gunk-dev/the-valley

exporttest.go

source9b709a18cb1fmain's published tip history
11.6 KiB
1// Package exporttest is the web UI's shared fixture: a complete, valid
2// export built from a small synthetic valley, with its signed manifest and
3// the verifier key that opens it. The publisher's, the receiver's and the
4// server's tests all build it, so they test against the same bytes.
5//
6// The synthetic valley has two projects. app is public; site is hidden.
7// Both belong to one group, whose identifier is core and whose name, which
8// its web URLs open with, is tools; t is its alias. Each project's web
9// name is its identifier, and its short alias too. app was renamed from
10// old-app, and site from old-site, which each keeps as a former name. The
11// export carries app's names alone.
12// app has a milestone with five children, among them a claimed knot, an
13// unclaimed knot in progress, a knot blocked by a local knot and by one of
14// site's, a bug whose body and comment hold HTML, and comments by mapped
15// and unmapped principals, one of them edited. It has one ready change, whose earlier version,
16// draft, branch and repository URL the export drops. Each project has a
17// real bare repository whose main has a few commits.
18//
19// The valley's JSON is literal, under valley/, in the shapes valley plan,
20// valley pending and valley knot show print. testdata/export.json is the
21// export built from it, kept as the contract's expected output.
22package exporttest
23
24import (
25 "bytes"
26 "context"
27 "crypto/ed25519"
28 "embed"
29 "fmt"
30 "io/fs"
31 "net/http/httptest"
32 "os"
33 "os/exec"
34 "path/filepath"
35 "sort"
36 "strings"
37 "testing"
38 "time"
39
40 "the-valley/note"
41 "the-valley/web/export"
42)
43
44//go:embed valley
45var valley embed.FS
46
47const (
48 // Instance and Destination are what the fixture's manifest is signed
49 // for, and what a receiver admitting it is configured with.
50 Instance = "valley-host"
51 Destination = "example.org"
52 // SignerName is the export key's name in the manifest's signature.
53 SignerName = "valley-host/web-export"
54)
55
56var (
57 // Collected is the synthetic valley's plan time, and SignedAt the
58 // manifest's signing time, whose Unix nanoseconds are its sequence.
59 Collected = time.Date(2026, 10, 25, 12, 0, 0, 0, time.UTC)
60 SignedAt = time.Date(2026, 10, 25, 12, 0, 30, 0, time.UTC)
61
62 // Principals is the publisher's display mapping. drive-by, who wrote
63 // a bug and a comment, is not in it.
64 Principals = export.Principals{"app-operator": "operator", "app-agent": "agent"}
65
66 // Visibility exports app alone.
67 Visibility = map[string]export.Visibility{"app": export.Public}
68
69 // Groups are the instance's one group, and Placements both projects'
70 // places in it.
71 Groups = []export.Group{{ID: "core", Name: "tools", Aliases: []string{"t"}}}
72 Placements = map[string]export.Placement{
73 "app": {Group: "core", Name: "app", FormerNames: []string{"old-app"}, Aliases: []string{"app"}},
74 "site": {Group: "core", Name: "site", FormerNames: []string{"old-site"}, Aliases: []string{"site"}},
75 }
76)
77
78// Key is the fixture's export key. It is derived from a fixed seed, so its
79// verifier is the same in every run.
80func Key() ed25519.PrivateKey {
81 return ed25519.NewKeyFromSeed([]byte("the-valley web export test key!!"))
82}
83
84// Verifier is the key a receiver pins to admit the fixture's manifest.
85func Verifier() note.VerifierKey {
86 return note.NewVerifierKey(SignerName, Key().Public().(ed25519.PublicKey))
87}
88
89// Fixture is the synthetic valley and everything built from it.
90type Fixture struct {
91 // Inputs are the synthetic valley's JSON, its visibility, its source
92 // tips and the display mapping: what the projection reads.
93 Inputs export.Inputs
94 // Repos are both projects' bare repositories, by project name.
95 Repos map[string]string
96
97 // Export is the export built from Inputs, and ExportJSON its bytes.
98 Export *export.Export
99 ExportJSON []byte
100 // Bundles are each exported project's bundle of main, by project.
101 Bundles map[string]string
102 // Manifest is the export's manifest, and Signed the manifest signed
103 // with Key.
104 Manifest *export.Manifest
105 Signed []byte
106
107 // Dir is a complete export directory, laid out as a generation is:
108 // export.json and repos/<project>.git.
109 Dir string
110}
111
112// New builds the fixture under a temporary directory of t's.
113func New(t testing.TB) *Fixture {
114 t.Helper()
115 root := t.TempDir()
116 f := &Fixture{Repos: map[string]string{}, Bundles: map[string]string{}}
117 ctx := context.Background()
118
119 in := export.Inputs{
120 Plan: read(t, "valley/plan.json"),
121 Pending: read(t, "valley/pending.json"),
122 Visibility: Visibility,
123 SourceTips: map[string]string{},
124 Principals: Principals,
125 Groups: Groups,
126 Placements: Placements,
127 }
128 details, err := fs.Glob(valley, "valley/details/*/*.json")
129 if err != nil {
130 t.Fatal(err)
131 }
132 for _, path := range details {
133 in.Details = append(in.Details, read(t, path))
134 }
135
136 for name, commits := range history {
137 repo := filepath.Join(root, "valley", name+".git")
138 git(t, "", nil, "init", "--quiet", "--bare", "--template=", "--initial-branch=main", repo)
139 git(t, repo, fastImport(commits), "fast-import", "--quiet")
140 f.Repos[name] = repo
141 in.SourceTips[name] = strings.TrimSpace(string(git(t, repo, nil, "rev-parse", "refs/heads/main")))
142 }
143 // The source tip of a project that is not exported is never read.
144 for name := range in.SourceTips {
145 if _, ok := Visibility[name]; !ok {
146 delete(in.SourceTips, name)
147 }
148 }
149 f.Inputs = in
150
151 f.Export, err = export.Build(in)
152 if err != nil {
153 t.Fatal(err)
154 }
155 f.ExportJSON, err = f.Export.Encode()
156 if err != nil {
157 t.Fatal(err)
158 }
159
160 bodies := map[string]export.Body{}
161 for _, p := range f.Export.Projects {
162 path := filepath.Join(root, "bundles", p.Name+".bundle")
163 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
164 t.Fatal(err)
165 }
166 git(t, f.Repos[p.Name], nil, "bundle", "create", "--quiet", path, "main")
167 f.Bundles[p.Name] = path
168 if bodies[p.Name], err = export.FileBody(p.Name, path); err != nil {
169 t.Fatal(err)
170 }
171 }
172 f.Manifest, err = export.NewManifest(Instance, Destination, SignedAt.UnixNano(), f.Export, f.ExportJSON, bodies)
173 if err != nil {
174 t.Fatal(err)
175 }
176 f.Signed = f.Sign(t, f.Manifest)
177
178 f.Dir = filepath.Join(root, "export")
179 if err := os.MkdirAll(filepath.Join(f.Dir, "repos"), 0o755); err != nil {
180 t.Fatal(err)
181 }
182 if err := os.WriteFile(filepath.Join(f.Dir, export.ExportFile), f.ExportJSON, 0o644); err != nil {
183 t.Fatal(err)
184 }
185 for _, p := range f.Export.Projects {
186 repo := filepath.Join(f.Dir, "repos", p.Name+".git")
187 if err := export.AcceptBundle(ctx, f.Bundles[p.Name], repo, p.SourceTip); err != nil {
188 t.Fatal(err)
189 }
190 }
191 return f
192}
193
194// Sign signs a manifest with the fixture's key, so a test can sign a
195// manifest it changed.
196func (f *Fixture) Sign(t testing.TB, m *export.Manifest) []byte {
197 t.Helper()
198 signed, err := m.Sign(SignerName, Key())
199 if err != nil {
200 t.Fatal(err)
201 }
202 return signed
203}
204
205// Admission is what a receiver admits the fixture's manifest with: the
206// pinned verifier, the instance and destination, no high-water mark, and a
207// clock a second past the signing time.
208func (f *Fixture) Admission() export.Admission {
209 return export.Admission{
210 Verifiers: []note.VerifierKey{Verifier()},
211 Instance: Instance,
212 Destination: Destination,
213 Now: SignedAt.Add(time.Second),
214 }
215}
216
217// BodyBytes is the content of the body the manifest declares under name:
218// export.json, or a project's bundle.
219func (f *Fixture) BodyBytes(t testing.TB, name string) []byte {
220 t.Helper()
221 if name == export.ExportFile {
222 return f.ExportJSON
223 }
224 path, ok := f.Bundles[name]
225 if !ok {
226 t.Fatalf("the fixture has no body %s", name)
227 }
228 data, err := os.ReadFile(path)
229 if err != nil {
230 t.Fatal(err)
231 }
232 return data
233}
234
235// Upload runs the upload's three steps against the store, as a receiver
236// does: it admits the signed manifest, stages it, stages every body the
237// inventory needs, and activates it. It returns the active generation.
238func (f *Fixture) Upload(t testing.TB, s *export.Store) export.Generation {
239 t.Helper()
240 hw, err := s.HighWater()
241 if err != nil {
242 t.Fatal(err)
243 }
244 a := f.Admission()
245 a.HighWater = hw
246 m, err := export.VerifyManifest(bytes.NewReader(f.Signed), a)
247 if err != nil {
248 t.Fatal(err)
249 }
250 st, err := s.Stage(context.Background(), m)
251 if err != nil {
252 t.Fatal(err)
253 }
254 inv, err := s.Inventory(st)
255 if err != nil {
256 t.Fatal(err)
257 }
258 for _, need := range inv.Needs {
259 body := f.BodyBytes(t, need.Name)
260 req := httptest.NewRequest("PUT", export.BodyPath(m.Sequence, need.SHA256), bytes.NewReader(body))
261 want := export.Body{Name: need.Name, SHA256: need.SHA256, Size: need.Size}
262 if _, err := export.StageBody(st.Bodies(), want, 64<<20, req); err != nil {
263 t.Fatal(err)
264 }
265 }
266 g, err := s.Activate(context.Background(), st)
267 if err != nil {
268 t.Fatal(err)
269 }
270 return g
271}
272
273func read(t testing.TB, path string) []byte {
274 t.Helper()
275 data, err := valley.ReadFile(path)
276 if err != nil {
277 t.Fatal(err)
278 }
279 return data
280}
281
282// commit is one commit of a fixture repository's main: its time, its
283// message, and the files it writes.
284type commit struct {
285 at time.Time
286 message string
287 files map[string]string
288}
289
290// history is each project's main, oldest commit first. Every commit's
291// author, committer and time are fixed, so the tips are the same in every
292// run.
293var history = map[string][]commit{
294 "app": {
295 {time.Date(2026, 10, 1, 9, 0, 0, 0, time.UTC), "app: the first README", map[string]string{
296 "README.md": "# app\n\nA synthetic project for the web UI's tests.\n",
297 }},
298 {time.Date(2026, 10, 2, 9, 0, 0, 0, time.UTC), "app: a program", map[string]string{
299 "src/main.go": "package main\n\nfunc main() {}\n",
300 }},
301 {time.Date(2026, 10, 3, 9, 0, 0, 0, time.UTC), "docs: a guide, and the README names it", map[string]string{
302 "README.md": "# app\n\nA synthetic project for the web UI's tests. See docs/guide.md.\n\n<script>alert(\"readme\")</script>\n",
303 "docs/guide.md": "# Guide\n\nRead the plan, then the source.\n",
304 }},
305 },
306 "site": {
307 {time.Date(2026, 10, 1, 9, 0, 0, 0, time.UTC), "site: hidden", map[string]string{
308 "README.md": "# site\n\nThis project is not exported.\n",
309 }},
310 },
311}
312
313// fastImport is the git fast-import stream that writes commits to main.
314func fastImport(commits []commit) []byte {
315 var b bytes.Buffer
316 data := func(s string) { fmt.Fprintf(&b, "data %d\n%s\n", len(s), s) }
317 for _, c := range commits {
318 who := fmt.Sprintf("Example Author <author@example.org> %d +0000", c.at.Unix())
319 fmt.Fprintf(&b, "commit refs/heads/main\nauthor %s\ncommitter %s\n", who, who)
320 data(c.message + "\n")
321 var paths []string
322 for path := range c.files {
323 paths = append(paths, path)
324 }
325 sort.Strings(paths)
326 for _, path := range paths {
327 fmt.Fprintf(&b, "M 100644 inline %s\n", path)
328 data(c.files[path])
329 }
330 }
331 return b.Bytes()
332}
333
334// gitTimeout is how long the fixture waits for one git command.
335const gitTimeout = 2 * time.Minute
336
337// git runs git as the export package does: in dir unless it is "", with no
338// GIT_ variable of the caller's and no system or global configuration. It
339// runs git with Run, so git and anything it started are killed once git
340// exits, or once gitTimeout has passed, which fails the test.
341func git(t testing.TB, dir string, stdin []byte, args ...string) []byte {
342 t.Helper()
343 if dir != "" {
344 args = append([]string{"-C", dir}, args...)
345 }
346 cmd := exec.Command(export.GitProgram, args...)
347 for _, kv := range os.Environ() {
348 if !strings.HasPrefix(kv, "GIT_") {
349 cmd.Env = append(cmd.Env, kv)
350 }
351 }
352 cmd.Env = append(cmd.Env, "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null")
353 if stdin != nil {
354 cmd.Stdin = bytes.NewReader(stdin)
355 }
356 var out, stderr bytes.Buffer
357 cmd.Stdout, cmd.Stderr = &out, &stderr
358 if err := Run(t, cmd, gitTimeout); err != nil {
359 t.Fatalf("git %s: %v: %s", strings.Join(args, " "), err, stderr.String())
360 }
361 return out.Bytes()
362}