gunk-dev/the-valley

authorization_test.go

source782170038f7fmain's published tip history
15.9 KiB
1package export_test
2
3import (
4 "bytes"
5 "context"
6 "crypto/ed25519"
7 "errors"
8 "os"
9 "path/filepath"
10 "strings"
11 "syscall"
12 "testing"
13 "time"
14
15 "the-valley/note"
16 "the-valley/web/export"
17 "the-valley/web/export/exporttest"
18)
19
20func authorizationAdmission(hw int64) export.AuthorizationAdmission {
21 return export.AuthorizationAdmission{Verifiers: []note.VerifierKey{exporttest.Verifier()},
22 Instance: exporttest.Instance, Destination: exporttest.Destination, HighWater: hw}
23}
24
25// VerifyAuthorization takes its steps in order, each with its own refusal,
26// and has no step for age: an authorization checked long ago, or dated
27// ahead of every clock, is admitted when its sequence is above the stored
28// one's.
29func TestVerifyAuthorizationSteps(t *testing.T) {
30 f := exporttest.New(t)
31 sign := func(a *export.Authorization) []byte { return exporttest.SignAuthorization(t, a) }
32 at := func(seq int64, checked time.Time) *export.Authorization {
33 a := exporttest.Authorization(seq, "app")
34 a.Checked = checked
35 return a
36 }
37 other := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{7}, 32))
38 foreign, err := at(5, exporttest.Collected).Sign(exporttest.SignerName, other)
39 if err != nil {
40 t.Fatal(err)
41 }
42 elsewhere := at(5, exporttest.Collected)
43 elsewhere.Destination = "elsewhere.example.org"
44 otherInstance := at(5, exporttest.Collected)
45 otherInstance.Instance = "other-valley"
46 for _, c := range []struct {
47 name string
48 signed []byte
49 want export.Code
50 }{
51 {"too large", bytes.Repeat([]byte("a"), export.MaxAuthorization+1), export.CodeTooLarge},
52 {"another key", foreign, export.CodeBadSignature},
53 {"a content manifest", f.Signed, export.CodeBadManifest},
54 {"another instance", sign(otherInstance), export.CodeWrongInstance},
55 {"another destination", sign(elsewhere), export.CodeWrongDestination},
56 {"the stored sequence", sign(at(4, exporttest.Collected)), export.CodeReplayed},
57 {"an older sequence", sign(at(3, exporttest.Collected)), export.CodeReplayed},
58 } {
59 t.Run(c.name, func(t *testing.T) {
60 _, err := export.VerifyAuthorization(bytes.NewReader(c.signed), authorizationAdmission(4))
61 wantCode(t, err, c.want)
62 if c.want == export.CodeReplayed {
63 var e *export.Error
64 if errors.As(err, &e) && e.HighWater != 4 {
65 t.Errorf("the replayed refusal gives high water %d, want 4", e.HighWater)
66 }
67 }
68 })
69 }
70 for _, checked := range []time.Time{time.Date(2001, 1, 1, 0, 0, 0, 0, time.UTC), time.Now().Add(1000 * time.Hour).Truncate(time.Second)} {
71 a, err := export.VerifyAuthorization(bytes.NewReader(sign(at(5, checked))), authorizationAdmission(4))
72 if err != nil {
73 t.Errorf("an authorization checked at %s was refused: %v", checked, err)
74 continue
75 }
76 if !a.Allows(export.Anyone, "app", exporttest.Identities["app"]) || a.Allows(export.Anyone, "app", strings.Repeat("0", 32)) {
77 t.Errorf("the authorization checked at %s allows %+v", checked, a.Projects)
78 }
79 }
80}
81
82// The authorization's text holds each record exactly as Text writes it.
83func TestParseAuthorizationRefuses(t *testing.T) {
84 text := string(exporttest.Authorization(1, "app").Text())
85 if _, err := export.ParseAuthorization([]byte(text)); err != nil {
86 t.Fatalf("the authorization's own text is refused: %v", err)
87 }
88 id := exporttest.Identities["app"]
89 for name, bad := range map[string]string{
90 "a content type line": strings.Replace(text, export.AuthorizationType, export.ManifestType, 1),
91 "no checked record": strings.Replace(text, "checked 2026-10-25T12:00:00Z\n", "", 1),
92 "a local checked time": strings.Replace(text, "2026-10-25T12:00:00Z", "2026-10-25T14:00:00+02:00", 1),
93 "a project no reader": strings.Replace(text, "reader app anyone\n", "", 1),
94 "a reader no project": text + "reader site anyone\n",
95 "a reader twice": text + "reader app anyone\n",
96 "a short identity": strings.Replace(text, id, id[:31], 1),
97 "a sequence of zero": strings.Replace(text, "sequence 1\n", "sequence 0\n", 1),
98 "an unknown record": text + "credential x\n",
99 "a principal with a /": strings.Replace(text, "reader app anyone", "reader app any/one", 1),
100 "no closing newline": strings.TrimSuffix(text, "\n"),
101 "a second destination": text + "destination example.org\n",
102 } {
103 t.Run(name, func(t *testing.T) {
104 _, err := export.ParseAuthorization([]byte(bad))
105 wantCode(t, err, export.CodeBadManifest)
106 })
107 }
108}
109
110// Authorize takes the authorization lock alone: while an activation, or a
111// process of its own, holds the activation lock, an authorization is
112// stored at once, and Stage waits. A stored sequence is durable across a
113// reopening, and nothing at or below it is stored again.
114func TestStoreAuthorizesWhileTheActivationLockIsHeld(t *testing.T) {
115 f := exporttest.New(t)
116 dir := payload(t)
117 s := openStore(t, dir)
118 lock, err := os.OpenFile(filepath.Join(dir, "lock"), os.O_RDWR, 0)
119 if err != nil {
120 t.Fatal(err)
121 }
122 defer lock.Close()
123 if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_EX); err != nil {
124 t.Fatal(err)
125 }
126 ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
127 defer cancel()
128 a := exporttest.Authorization(2)
129 if err := s.Authorize(ctx, a, exporttest.SignAuthorization(t, a)); err != nil {
130 t.Fatalf("an authorization was not stored while the activation lock was held: %v", err)
131 }
132 short, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
133 defer cancel()
134 if _, err := s.Stage(short, fixtureUpload(t, f).m); !errors.Is(err, context.DeadlineExceeded) {
135 t.Errorf("Stage gave %v while the activation lock was held, want it to wait", err)
136 }
137 lock.Close()
138
139 for _, seq := range []int64{2, 1} {
140 a := exporttest.Authorization(seq, "app")
141 wantCode(t, s.Authorize(context.Background(), a, exporttest.SignAuthorization(t, a)), export.CodeReplayed)
142 }
143 again := openStore(t, dir)
144 if hw, err := again.AuthorizationHighWater(); hw != 2 || err != nil {
145 t.Errorf("after reopening the stored authorization is %d, %v; want 2", hw, err)
146 }
147 if got, _, err := again.Authorization(); err != nil || len(got.Projects) != 0 {
148 t.Errorf("after reopening the stored authorization names %+v, %v; want nothing", got, err)
149 }
150}
151
152// The serving lock is never held under a context that is done: a server
153// whose deadline passed takes it, gives it back and fails, though it is
154// free, so it writes no response's headers past its deadline.
155func TestTheServingLockIsNotHeldPastADeadline(t *testing.T) {
156 s := openStore(t, payload(t))
157 done, cancel := context.WithCancel(context.Background())
158 cancel()
159 if release, err := s.HoldServing(done); !errors.Is(err, context.Canceled) {
160 if err == nil {
161 release()
162 }
163 t.Errorf("HoldServing under a done context gave %v", err)
164 }
165 release, err := s.HoldServing(context.Background())
166 if err != nil {
167 t.Fatalf("the serving lock was not given back: %v", err)
168 }
169 release()
170}
171
172// A store with no authorization builds no repository and needs no bundle,
173// and a stored authorization that cannot be read is no high-water mark of
174// zero: nothing is stored over it.
175func TestStoreBuildsOnlyWhatTheAuthorizationNames(t *testing.T) {
176 f := exporttest.New(t)
177 dir := payload(t)
178 s, err := export.OpenStore(descriptorOf(dir), func(err error) { t.Errorf("the store reported: %v", err) })
179 if err != nil {
180 t.Fatal(err)
181 }
182 a := exporttest.Authorization(1)
183 if err := s.Authorize(context.Background(), a, exporttest.SignAuthorization(t, a)); err != nil {
184 t.Fatal(err)
185 }
186 u := fixtureUpload(t, f)
187 st := stage(t, f, s, u)
188 inv, err := s.Inventory(st)
189 if err != nil {
190 t.Fatal(err)
191 }
192 if len(inv.Needs) != 1 || inv.Needs[0].Name != export.ExportFile {
193 t.Errorf("with app not named the inventory needs %+v, want export.json alone", inv.Needs)
194 }
195 putNeed(t, st, u, inv.Needs[0])
196 g, err := s.Activate(context.Background(), st)
197 if err != nil {
198 t.Fatal(err)
199 }
200 if got := entries(t, filepath.Join(g.Dir, "repos")); len(got) != 0 {
201 t.Errorf("the generation holds repositories %v of projects no authorization names", got)
202 }
203
204 if err := os.WriteFile(filepath.Join(dir, "authorization"), []byte("damaged"), 0o644); err != nil {
205 t.Fatal(err)
206 }
207 if _, err := s.AuthorizationHighWater(); err == nil {
208 t.Error("a damaged stored authorization gave a high-water mark")
209 }
210 next := exporttest.Authorization(9, "app")
211 if err := s.Authorize(context.Background(), next, exporttest.SignAuthorization(t, next)); err == nil {
212 t.Error("an authorization was stored over a damaged one")
213 }
214}
215
216// An authorization that withdraws a project hides it at once, and Prune
217// deletes its repository once no reader holds the generation, leaving
218// export.json as it was signed. Named again, the project is missing, and
219// the inventory needs its bundle.
220func TestStorePrunesAWithdrawnRepository(t *testing.T) {
221 f := exporttest.New(t)
222 s := openStore(t, payload(t))
223 g := f.Upload(t, s)
224 repo, _ := g.Repo("app")
225 before, err := os.ReadFile(g.ExportPath())
226 if err != nil {
227 t.Fatal(err)
228 }
229 exporttest.Authorize(t, s)
230 _, release, err := s.Open()
231 if err != nil {
232 t.Fatal(err)
233 }
234 if err := s.Prune(context.Background()); !errors.Is(err, export.ErrHeld) {
235 t.Errorf("Prune gave %v while a reader held the generation, want ErrHeld", err)
236 }
237 if _, err := os.Stat(repo); err != nil {
238 t.Errorf("Prune deleted the repository a reader held: %v", err)
239 }
240 release()
241 if err := s.Prune(context.Background()); err != nil {
242 t.Fatal(err)
243 }
244 if _, err := os.Stat(repo); !errors.Is(err, os.ErrNotExist) {
245 t.Errorf("Prune left the withdrawn repository: %v", err)
246 }
247 if after, err := os.ReadFile(g.ExportPath()); err != nil || !bytes.Equal(before, after) {
248 t.Errorf("Prune changed export.json: %v", err)
249 }
250
251 exporttest.Authorize(t, s, "app")
252 if missing, err := s.Missing(); err != nil || len(missing) != 1 || missing[0] != "app" {
253 t.Errorf("named again, the missing projects are %v, %v; want app", missing, err)
254 }
255 u := later(t, f, time.Minute)
256 st := stage(t, f, s, u)
257 inv, err := s.Inventory(st)
258 if err != nil {
259 t.Fatal(err)
260 }
261 if len(inv.Holds) != 0 || len(inv.Needs) != 2 {
262 t.Errorf("named again, the inventory holds %+v and needs %+v; want nothing held and both bodies", inv.Holds, inv.Needs)
263 }
264}
265
266// The store's entry point is a descriptor file. A directory, as the first
267// layout's state was, is refused by both openers, and nothing is created.
268// A new store beside the first layout's state deletes none of it, then or
269// on a later start: the receiver writes nothing outside its descriptor and
270// v2/, and the operator deletes the first layout by hand.
271func TestStoreDescriptorLeavesTheFirstLayout(t *testing.T) {
272 dir := t.TempDir()
273 if _, err := export.OpenStore(dir, nil); err == nil || !strings.Contains(err.Error(), "is a directory") {
274 t.Errorf("OpenStore of a directory gave %v", err)
275 }
276 if _, err := export.OpenReadOnly(dir); err == nil || !strings.Contains(err.Error(), "is a directory") {
277 t.Errorf("OpenReadOnly of a directory gave %v", err)
278 }
279 if got := entries(t, dir); len(got) != 0 {
280 t.Errorf("a refused directory holds %v", got)
281 }
282 firstLayout(t, dir)
283 want := "active exports high-water lock staging store trash v2"
284 for start := 1; start <= 2; start++ {
285 var r reports
286 if _, err := export.OpenStore(filepath.Join(dir, "store"), r.report); err != nil {
287 t.Fatal(err)
288 }
289 if got := entries(t, dir); strings.Join(got, " ") != want {
290 t.Errorf("after start %d the directory holds %v, want %s", start, got, want)
291 }
292 if data, err := os.ReadFile(filepath.Join(dir, "exports", "1", "export.json")); err != nil || string(data) != "{}" {
293 t.Errorf("after start %d the first layout's export.json holds %q, %v", start, data, err)
294 }
295 if target, err := os.Readlink(filepath.Join(dir, "active")); err != nil || target != "exports/1" {
296 t.Errorf("after start %d the first layout's active points at %q, %v", start, target, err)
297 }
298 if errs := r.all(); len(errs) != 0 {
299 t.Errorf("start %d reported %v", start, errs)
300 }
301 }
302 if err := os.WriteFile(filepath.Join(dir, "other"), []byte("the-valley/web-store/v1\n"), 0o644); err != nil {
303 t.Fatal(err)
304 }
305 if _, err := export.OpenReadOnly(filepath.Join(dir, "other")); err == nil {
306 t.Error("OpenReadOnly opened a file that is no store's descriptor")
307 }
308 if _, err := export.OpenReadOnly(filepath.Join(dir, "store")); err != nil {
309 t.Errorf("OpenReadOnly of the descriptor gave %v", err)
310 }
311}
312
313// An authorization with a basis is admitted only while the stored
314// authorization is the one it names, by VerifyAuthorization and again by
315// Store.Authorize under its lock, and its basis is less than its sequence.
316func TestAnAuthorizationWithABasisNeedsItStored(t *testing.T) {
317 based := func(seq, basis int64) *export.Authorization {
318 a := exporttest.Authorization(seq, "app")
319 a.Basis = basis
320 return a
321 }
322 if _, err := export.VerifyAuthorization(bytes.NewReader(exporttest.SignAuthorization(t, based(9, 4))), authorizationAdmission(4)); err != nil {
323 t.Errorf("an authorization on the stored basis was refused: %v", err)
324 }
325 _, err := export.VerifyAuthorization(bytes.NewReader(exporttest.SignAuthorization(t, based(9, 3))), authorizationAdmission(4))
326 wantCode(t, err, export.CodeStaleBasis)
327 var e *export.Error
328 if errors.As(err, &e) && e.HighWater != 4 {
329 t.Errorf("the stale-basis refusal gives high water %d, want 4", e.HighWater)
330 }
331 _, err = export.ParseAuthorization(based(4, 4).Text())
332 wantCode(t, err, export.CodeBadManifest)
333
334 s := openStore(t, payload(t))
335 stored, _, err := s.Authorization()
336 if err != nil {
337 t.Fatal(err)
338 }
339 stale := based(stored.Sequence+5, stored.Sequence+1)
340 wantCode(t, s.Authorize(context.Background(), stale, exporttest.SignAuthorization(t, stale)), export.CodeStaleBasis)
341 current := based(stored.Sequence+5, stored.Sequence)
342 if err := s.Authorize(context.Background(), current, exporttest.SignAuthorization(t, current)); err != nil {
343 t.Errorf("Authorize refused an authorization on the stored basis: %v", err)
344 }
345}
346
347// A prune that selected a withdrawn repository, and is paused before it
348// deletes it, deletes nothing once an authorization names the project
349// again: it reads the authorization again under the authorization lock.
350// The reply to that authorization says the receiver serves the export
351// whole, and the repository survives the prune.
352func TestAPruneKeepsWhatAnAuthorizationNamesAgain(t *testing.T) {
353 f := exporttest.New(t)
354 s := openStore(t, payload(t))
355 g := f.Upload(t, s)
356 repo, _ := g.Repo("app")
357 digest, err := f.Export.Digest()
358 if err != nil {
359 t.Fatal(err)
360 }
361 exporttest.Authorize(t, s)
362 paused, resume := make(chan struct{}), make(chan struct{})
363 *export.PruneSelected = func() {
364 close(paused)
365 <-resume
366 }
367 defer func() { *export.PruneSelected = nil }()
368 pruned := make(chan error, 1)
369 go func() { pruned <- s.Prune(context.Background()) }()
370 <-paused
371
372 exporttest.Authorize(t, s, "app")
373 reply := func() *export.AuthorizationReply {
374 active, _, err := s.Holdings()
375 if err != nil {
376 t.Fatal(err)
377 }
378 missing, err := s.Missing()
379 if err != nil {
380 t.Fatal(err)
381 }
382 return &export.AuthorizationReply{Active: active, Missing: missing}
383 }
384 if r := reply(); !r.Serves(digest) {
385 t.Errorf("named again while a prune was paused, the reply is %+v; want the export served whole", r)
386 }
387 close(resume)
388 if err := <-pruned; err != nil {
389 t.Fatal(err)
390 }
391 if _, err := os.Stat(repo); err != nil {
392 t.Errorf("the prune deleted the repository an authorization named again: %v", err)
393 }
394 if r := reply(); !r.Serves(digest) {
395 t.Errorf("after the prune the reply is %+v; want the export served whole", r)
396 }
397}
398
399// firstLayout makes, in dir, the state of the first store layout: active
400// pointing at a generation, high-water, exports/, staging/, trash/ and
401// lock.
402func firstLayout(t *testing.T, dir string) {
403 t.Helper()
404 for _, d := range []string{"exports/1/repos", "staging/2/bodies", "trash/old"} {
405 if err := os.MkdirAll(filepath.Join(dir, d), 0o755); err != nil {
406 t.Fatal(err)
407 }
408 }
409 for name, data := range map[string]string{"high-water": "1\n", "lock": "", "exports/1/export.json": "{}"} {
410 if err := os.WriteFile(filepath.Join(dir, name), []byte(data), 0o644); err != nil {
411 t.Fatal(err)
412 }
413 }
414 if err := os.Symlink("exports/1", filepath.Join(dir, "active")); err != nil {
415 t.Fatal(err)
416 }
417}