gunk-dev/the-valley

exporttest.go

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