gunk-dev/the-valley

exporttest.go

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