gunk-dev/the-valley

exporttest.go

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