gunk-dev/the-valley

authorization_test.go

sourceb9df3fe59e29main's published tip history
23.5 KiB
1package export_test
2
3import (
4 "bytes"
5 "context"
6 "crypto/ed25519"
7 "errors"
8 "fmt"
9 "math"
10 "os"
11 "path/filepath"
12 "slices"
13 "strings"
14 "syscall"
15 "testing"
16 "time"
17
18 "the-valley/note"
19 "the-valley/web/export"
20 "the-valley/web/export/exporttest"
21)
22
23func authorizationAdmission(hw int64) export.AuthorizationAdmission {
24 return export.AuthorizationAdmission{Verifiers: []note.VerifierKey{exporttest.Verifier()},
25 Instance: exporttest.Instance, Destination: exporttest.Destination, HighWater: hw}
26}
27
28// VerifyAuthorization takes its steps in order, each with its own refusal,
29// and has no step for age: an authorization checked long ago, or dated
30// ahead of every clock, is admitted when its sequence is above the stored
31// one's.
32func TestVerifyAuthorizationSteps(t *testing.T) {
33 f := exporttest.New(t)
34 sign := func(a *export.Authorization) []byte { return exporttest.SignAuthorization(t, a) }
35 at := func(seq int64, checked time.Time) *export.Authorization {
36 a := exporttest.Authorization(seq, "app")
37 a.Checked = checked
38 return a
39 }
40 other := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{7}, 32))
41 foreign, err := at(5, exporttest.Collected).Sign(exporttest.SignerName, other)
42 if err != nil {
43 t.Fatal(err)
44 }
45 elsewhere := at(5, exporttest.Collected)
46 elsewhere.Destination = "elsewhere.example.org"
47 otherInstance := at(5, exporttest.Collected)
48 otherInstance.Instance = "other-valley"
49 for _, c := range []struct {
50 name string
51 signed []byte
52 want export.Code
53 }{
54 {"too large", bytes.Repeat([]byte("a"), export.MaxAuthorization+1), export.CodeTooLarge},
55 {"another key", foreign, export.CodeBadSignature},
56 {"a content manifest", f.Signed, export.CodeBadManifest},
57 {"another instance", sign(otherInstance), export.CodeWrongInstance},
58 {"another destination", sign(elsewhere), export.CodeWrongDestination},
59 {"the stored sequence", sign(at(4, exporttest.Collected)), export.CodeReplayed},
60 {"an older sequence", sign(at(3, exporttest.Collected)), export.CodeReplayed},
61 } {
62 t.Run(c.name, func(t *testing.T) {
63 _, err := export.VerifyAuthorization(bytes.NewReader(c.signed), authorizationAdmission(4))
64 wantCode(t, err, c.want)
65 if c.want == export.CodeReplayed {
66 var e *export.Error
67 if errors.As(err, &e) && e.HighWater != 4 {
68 t.Errorf("the replayed refusal gives high water %d, want 4", e.HighWater)
69 }
70 }
71 })
72 }
73 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)} {
74 a, err := export.VerifyAuthorization(bytes.NewReader(sign(at(5, checked))), authorizationAdmission(4))
75 if err != nil {
76 t.Errorf("an authorization checked at %s was refused: %v", checked, err)
77 continue
78 }
79 if !a.Allows(export.Anyone, "app", exporttest.Identities["app"]) || a.Allows(export.Anyone, "app", strings.Repeat("0", 32)) {
80 t.Errorf("the authorization checked at %s allows %+v", checked, a.Projects)
81 }
82 }
83}
84
85// The authorization's text holds each record exactly as Text writes it.
86func TestParseAuthorizationRefuses(t *testing.T) {
87 text := string(exporttest.Authorization(1, "app").Text())
88 if _, err := export.ParseAuthorization([]byte(text)); err != nil {
89 t.Fatalf("the authorization's own text is refused: %v", err)
90 }
91 id := exporttest.Identities["app"]
92 for name, bad := range map[string]string{
93 "a content type line": strings.Replace(text, export.AuthorizationType, export.ManifestType, 1),
94 "no checked record": strings.Replace(text, "checked 2026-10-25T12:00:00Z\n", "", 1),
95 "a local checked time": strings.Replace(text, "2026-10-25T12:00:00Z", "2026-10-25T14:00:00+02:00", 1),
96 "a project no reader": strings.Replace(text, "reader app anyone\n", "", 1),
97 "a reader no project": text + "reader site anyone\n",
98 "a reader twice": text + "reader app anyone\n",
99 "a short identity": strings.Replace(text, id, id[:31], 1),
100 "a sequence of zero": strings.Replace(text, "sequence 1\n", "sequence 0\n", 1),
101 "an unknown record": text + "credential x\n",
102 "a principal with a /": strings.Replace(text, "reader app anyone", "reader app any/one", 1),
103 "no closing newline": strings.TrimSuffix(text, "\n"),
104 "a second destination": text + "destination example.org\n",
105 } {
106 t.Run(name, func(t *testing.T) {
107 _, err := export.ParseAuthorization([]byte(bad))
108 wantCode(t, err, export.CodeBadManifest)
109 })
110 }
111}
112
113// Sign signs nothing a receiver would refuse for its size: SignedSize is
114// what it writes, and one byte over MaxAuthorization is refused as too
115// large, before any signature.
116func TestSignRefusesAnAuthorizationOverTheLimit(t *testing.T) {
117 a := exporttest.Authorization(1, "app")
118 signed, err := a.Sign(exporttest.SignerName, exporttest.Key())
119 if err != nil || len(signed) != a.SignedSize(exporttest.SignerName) {
120 t.Fatalf("signed %d bytes, %v; SignedSize says %d", len(signed), err, a.SignedSize(exporttest.SignerName))
121 }
122 // Each reader record of app is "reader app " and a 9-character name:
123 // 21 bytes.
124 p := &a.Projects[0]
125 for i := 0; a.SignedSize(exporttest.SignerName) < export.MaxAuthorization; i++ {
126 p.Readers = append(p.Readers, fmt.Sprintf("r%08d", i))
127 }
128 for a.SignedSize(exporttest.SignerName) > export.MaxAuthorization {
129 p.Readers = p.Readers[:len(p.Readers)-1]
130 }
131 pad := export.MaxAuthorization - a.SignedSize(exporttest.SignerName)
132 a.Instance += strings.Repeat("x", pad)
133 if signed, err := a.Sign(exporttest.SignerName, exporttest.Key()); err != nil || len(signed) != export.MaxAuthorization {
134 t.Fatalf("an authorization of exactly %d bytes signed as %d bytes, %v", export.MaxAuthorization, len(signed), err)
135 }
136 a.Instance += "x"
137 _, err = a.Sign(exporttest.SignerName, exporttest.Key())
138 wantCode(t, err, export.CodeTooLarge)
139}
140
141// The bounded fallback is the last acknowledged authorization less every
142// access the current check no longer gives, and never more. Here the
143// check withdraws anyone and the operator from app and adds bob, gives
144// site a new publication identity, withdraws docs, adds notes, reissues
145// the operator's link under its ID with a new verifier, and adds a link.
146// The fallback keeps app for alice alone, and alice's link, under the
147// check's sequence, checked time and basis.
148func TestNarrowKeepsOnlyWhatBothAllow(t *testing.T) {
149 hex := func(c string) string { return strings.Repeat(c, 64) }
150 prev := &export.Authorization{Instance: exporttest.Instance, Destination: exporttest.Destination, Sequence: 5,
151 Checked: exporttest.Collected,
152 Projects: []export.AuthorizedProject{
153 {Name: "app", Identity: strings.Repeat("1", 32), Readers: []string{"alice", "anyone", "operator"}},
154 {Name: "docs", Identity: strings.Repeat("3", 32), Readers: []string{"alice"}},
155 {Name: "site", Identity: strings.Repeat("2", 32), Readers: []string{"anyone"}},
156 },
157 Bindings: []export.Binding{
158 {ID: "lk-0000000000000001", Principal: "alice", Verifier: hex("a")},
159 {ID: "lk-0000000000000002", Principal: "operator", Verifier: hex("b")},
160 }}
161 cur := &export.Authorization{Instance: exporttest.Instance, Destination: exporttest.Destination, Sequence: 9,
162 Checked: exporttest.SignedAt, Basis: 5,
163 Projects: []export.AuthorizedProject{
164 {Name: "app", Identity: strings.Repeat("1", 32), Readers: []string{"alice", "bob"}},
165 {Name: "notes", Identity: strings.Repeat("4", 32), Readers: []string{"carol"}},
166 {Name: "site", Identity: strings.Repeat("5", 32), Readers: []string{"anyone"}},
167 },
168 Bindings: []export.Binding{
169 {ID: "lk-0000000000000001", Principal: "alice", Verifier: hex("a")},
170 {ID: "lk-0000000000000002", Principal: "operator", Verifier: hex("c")},
171 {ID: "lk-0000000000000003", Principal: "bob", Verifier: hex("d")},
172 }}
173 n := export.Narrow(prev, cur)
174 want := &export.Authorization{Instance: exporttest.Instance, Destination: exporttest.Destination, Sequence: 9,
175 Checked: exporttest.SignedAt, Basis: 5,
176 Projects: []export.AuthorizedProject{{Name: "app", Identity: strings.Repeat("1", 32), Readers: []string{"alice"}}},
177 Bindings: []export.Binding{{ID: "lk-0000000000000001", Principal: "alice", Verifier: hex("a")}}}
178 if !bytes.Equal(n.Text(), want.Text()) {
179 t.Fatalf("the fallback is\n%s\nwant\n%s", n.Text(), want.Text())
180 }
181 for _, p := range append(append([]export.AuthorizedProject{}, prev.Projects...), cur.Projects...) {
182 for _, r := range append([]string{"anyone", "alice", "bob", "carol", "operator"}, p.Readers...) {
183 if n.Allows(r, p.Name, p.Identity) && !(prev.Allows(r, p.Name, p.Identity) && cur.Allows(r, p.Name, p.Identity)) {
184 t.Errorf("the fallback lets %s read %s under %s, which prev and cur do not both allow", r, p.Name, p.Identity)
185 }
186 }
187 }
188 if empty := export.Narrow(nil, cur); len(empty.Projects) != 0 || len(empty.Bindings) != 0 || empty.Sequence != 9 {
189 t.Errorf("the fallback from no acknowledged authorization is\n%s", empty.Text())
190 }
191
192 // However far its sequence and basis grow, the fallback of an
193 // authorization the check still allows in full is within FallbackRoom
194 // of it.
195 cur = &export.Authorization{Instance: prev.Instance, Destination: prev.Destination, Sequence: math.MaxInt64,
196 Checked: prev.Checked, Basis: math.MaxInt64 - 1, Projects: prev.Projects, Bindings: prev.Bindings}
197 grown := export.Narrow(prev, cur).SignedSize(exporttest.SignerName) - prev.SignedSize(exporttest.SignerName)
198 if grown > export.FallbackRoom {
199 t.Errorf("the fallback is %d bytes larger than the authorization it narrows, more than FallbackRoom, %d", grown, export.FallbackRoom)
200 }
201}
202
203// Fit restricts an authorization over the limit one access at a time, in
204// its order, and stops at the first step that fits. docs, kept on the
205// basis, goes first, whole, and the basis with it. Then a reader at a
206// time goes, the last by sort of the project with the most readers left,
207// app before site when they have as many, so each project goes with its
208// last reader. Then the bindings go in ID order, and at last nothing is
209// granted. An authorization that fits is returned as it is.
210func TestFitDropsAccessInItsOrder(t *testing.T) {
211 hex := func(c string) string { return strings.Repeat(c, 64) }
212 ids := map[string]string{"app": strings.Repeat("1", 32), "site": strings.Repeat("2", 32), "docs": strings.Repeat("3", 32)}
213 // state is the authorization with the basis, the last links of the
214 // bindings in ID order, and the projects given, each name:readers.
215 state := func(basis int64, links int, projects ...string) *export.Authorization {
216 a := &export.Authorization{Instance: exporttest.Instance, Destination: exporttest.Destination, Sequence: 9,
217 Checked: exporttest.SignedAt, Basis: basis}
218 for _, p := range projects {
219 name, readers, _ := strings.Cut(p, ":")
220 a.Projects = append(a.Projects, export.AuthorizedProject{Name: name, Identity: ids[name], Readers: strings.Split(readers, ",")})
221 }
222 bindings := []export.Binding{
223 {ID: "lk-0000000000000001", Principal: "bob", Verifier: hex("b")},
224 {ID: "lk-0000000000000002", Principal: "alice", Verifier: hex("a")},
225 }
226 a.Bindings = bindings[len(bindings)-links:]
227 return a
228 }
229 a := state(4, 2, "app:alice,anyone,bob", "docs:carol", "site:carol,dave")
230 slices.Reverse(a.Bindings)
231 steps := []*export.Authorization{
232 state(0, 2, "app:alice,anyone,bob", "site:carol,dave"),
233 state(0, 2, "app:alice,anyone", "site:carol,dave"),
234 state(0, 2, "app:alice", "site:carol,dave"),
235 state(0, 2, "app:alice", "site:carol"),
236 state(0, 2, "site:carol"),
237 state(0, 2),
238 state(0, 1),
239 state(0, 0),
240 }
241 onBasis := []string{"docs"}
242 if got := export.Fit(a, onBasis, exporttest.SignerName, a.SignedSize(exporttest.SignerName)); got != a {
243 t.Errorf("an authorization that fits became\n%s", got.Text())
244 }
245 for i, want := range steps {
246 got := export.Fit(a, onBasis, exporttest.SignerName, want.SignedSize(exporttest.SignerName))
247 if !bytes.Equal(got.Text(), want.Text()) {
248 t.Errorf("step %d of the restriction is\n%s\nwant\n%s", i+1, got.Text(), want.Text())
249 }
250 }
251 if got := export.Fit(a, onBasis, exporttest.SignerName, 1); !bytes.Equal(got.Text(), steps[len(steps)-1].Text()) {
252 t.Errorf("under a limit nothing fits, the restriction is\n%s\nwant the authorization that grants nothing", got.Text())
253 }
254}
255
256// Authorize takes the authorization lock alone: while an activation, or a
257// process of its own, holds the activation lock, an authorization is
258// stored at once, and Stage waits. A stored sequence is durable across a
259// reopening, and nothing at or below it is stored again.
260func TestStoreAuthorizesWhileTheActivationLockIsHeld(t *testing.T) {
261 f := exporttest.New(t)
262 dir := payload(t)
263 s := openStore(t, dir)
264 lock, err := os.OpenFile(filepath.Join(dir, "lock"), os.O_RDWR, 0)
265 if err != nil {
266 t.Fatal(err)
267 }
268 defer lock.Close()
269 if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_EX); err != nil {
270 t.Fatal(err)
271 }
272 ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
273 defer cancel()
274 a := exporttest.Authorization(2)
275 if err := s.Authorize(ctx, a, exporttest.SignAuthorization(t, a)); err != nil {
276 t.Fatalf("an authorization was not stored while the activation lock was held: %v", err)
277 }
278 short, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
279 defer cancel()
280 if _, err := s.Stage(short, fixtureUpload(t, f).m); !errors.Is(err, context.DeadlineExceeded) {
281 t.Errorf("Stage gave %v while the activation lock was held, want it to wait", err)
282 }
283 lock.Close()
284
285 for _, seq := range []int64{2, 1} {
286 a := exporttest.Authorization(seq, "app")
287 wantCode(t, s.Authorize(context.Background(), a, exporttest.SignAuthorization(t, a)), export.CodeReplayed)
288 }
289 again := openStore(t, dir)
290 if hw, err := again.AuthorizationHighWater(); hw != 2 || err != nil {
291 t.Errorf("after reopening the stored authorization is %d, %v; want 2", hw, err)
292 }
293 if got, _, err := again.Authorization(); err != nil || len(got.Projects) != 0 {
294 t.Errorf("after reopening the stored authorization names %+v, %v; want nothing", got, err)
295 }
296}
297
298// The serving lock is never held under a context that is done: a server
299// whose deadline passed takes it, gives it back and fails, though it is
300// free, so it writes no response's headers past its deadline.
301func TestTheServingLockIsNotHeldPastADeadline(t *testing.T) {
302 s := openStore(t, payload(t))
303 done, cancel := context.WithCancel(context.Background())
304 cancel()
305 if release, err := s.HoldServing(done); !errors.Is(err, context.Canceled) {
306 if err == nil {
307 release()
308 }
309 t.Errorf("HoldServing under a done context gave %v", err)
310 }
311 release, err := s.HoldServing(context.Background())
312 if err != nil {
313 t.Fatalf("the serving lock was not given back: %v", err)
314 }
315 release()
316}
317
318// A store with no authorization builds no repository and needs no bundle,
319// and a stored authorization that cannot be read is no high-water mark of
320// zero: nothing is stored over it.
321func TestStoreBuildsOnlyWhatTheAuthorizationNames(t *testing.T) {
322 f := exporttest.New(t)
323 dir := payload(t)
324 s, err := export.OpenStore(descriptorOf(dir), func(err error) { t.Errorf("the store reported: %v", err) })
325 if err != nil {
326 t.Fatal(err)
327 }
328 a := exporttest.Authorization(1)
329 if err := s.Authorize(context.Background(), a, exporttest.SignAuthorization(t, a)); err != nil {
330 t.Fatal(err)
331 }
332 u := fixtureUpload(t, f)
333 st := stage(t, f, s, u)
334 inv, err := s.Inventory(st)
335 if err != nil {
336 t.Fatal(err)
337 }
338 if len(inv.Needs) != 1 || inv.Needs[0].Name != export.ExportFile {
339 t.Errorf("with app not named the inventory needs %+v, want export.json alone", inv.Needs)
340 }
341 putNeed(t, st, u, inv.Needs[0])
342 g, err := s.Activate(context.Background(), st)
343 if err != nil {
344 t.Fatal(err)
345 }
346 if got := entries(t, filepath.Join(g.Dir, "repos")); len(got) != 0 {
347 t.Errorf("the generation holds repositories %v of projects no authorization names", got)
348 }
349
350 if err := os.WriteFile(filepath.Join(dir, "authorization"), []byte("damaged"), 0o644); err != nil {
351 t.Fatal(err)
352 }
353 if _, err := s.AuthorizationHighWater(); err == nil {
354 t.Error("a damaged stored authorization gave a high-water mark")
355 }
356 next := exporttest.Authorization(9, "app")
357 if err := s.Authorize(context.Background(), next, exporttest.SignAuthorization(t, next)); err == nil {
358 t.Error("an authorization was stored over a damaged one")
359 }
360}
361
362// An authorization that withdraws a project hides it at once, and Prune
363// deletes its repository once no reader holds the generation, leaving
364// export.json as it was signed. Named again, the project is missing, and
365// the inventory needs its bundle.
366func TestStorePrunesAWithdrawnRepository(t *testing.T) {
367 f := exporttest.New(t)
368 s := openStore(t, payload(t))
369 g := f.Upload(t, s)
370 repo, _ := g.Repo("app")
371 before, err := os.ReadFile(g.ExportPath())
372 if err != nil {
373 t.Fatal(err)
374 }
375 exporttest.Authorize(t, s)
376 _, release, err := s.Open()
377 if err != nil {
378 t.Fatal(err)
379 }
380 if err := s.Prune(context.Background()); !errors.Is(err, export.ErrHeld) {
381 t.Errorf("Prune gave %v while a reader held the generation, want ErrHeld", err)
382 }
383 if _, err := os.Stat(repo); err != nil {
384 t.Errorf("Prune deleted the repository a reader held: %v", err)
385 }
386 release()
387 if err := s.Prune(context.Background()); err != nil {
388 t.Fatal(err)
389 }
390 if _, err := os.Stat(repo); !errors.Is(err, os.ErrNotExist) {
391 t.Errorf("Prune left the withdrawn repository: %v", err)
392 }
393 if after, err := os.ReadFile(g.ExportPath()); err != nil || !bytes.Equal(before, after) {
394 t.Errorf("Prune changed export.json: %v", err)
395 }
396
397 exporttest.Authorize(t, s, "app")
398 if missing, err := s.Missing(); err != nil || len(missing) != 1 || missing[0] != "app" {
399 t.Errorf("named again, the missing projects are %v, %v; want app", missing, err)
400 }
401 u := later(t, f, time.Minute)
402 st := stage(t, f, s, u)
403 inv, err := s.Inventory(st)
404 if err != nil {
405 t.Fatal(err)
406 }
407 if len(inv.Holds) != 0 || len(inv.Needs) != 2 {
408 t.Errorf("named again, the inventory holds %+v and needs %+v; want nothing held and both bodies", inv.Holds, inv.Needs)
409 }
410}
411
412// The store's entry point is a descriptor file. A directory, as the first
413// layout's state was, is refused by both openers, and nothing is created.
414// A new store beside the first layout's state deletes none of it, then or
415// on a later start: the receiver writes nothing outside its descriptor and
416// v2/, and the operator deletes the first layout by hand.
417func TestStoreDescriptorLeavesTheFirstLayout(t *testing.T) {
418 dir := t.TempDir()
419 if _, err := export.OpenStore(dir, nil); err == nil || !strings.Contains(err.Error(), "is a directory") {
420 t.Errorf("OpenStore of a directory gave %v", err)
421 }
422 if _, err := export.OpenReadOnly(dir); err == nil || !strings.Contains(err.Error(), "is a directory") {
423 t.Errorf("OpenReadOnly of a directory gave %v", err)
424 }
425 if got := entries(t, dir); len(got) != 0 {
426 t.Errorf("a refused directory holds %v", got)
427 }
428 firstLayout(t, dir)
429 want := "active exports high-water lock staging store trash v2"
430 for start := 1; start <= 2; start++ {
431 var r reports
432 if _, err := export.OpenStore(filepath.Join(dir, "store"), r.report); err != nil {
433 t.Fatal(err)
434 }
435 if got := entries(t, dir); strings.Join(got, " ") != want {
436 t.Errorf("after start %d the directory holds %v, want %s", start, got, want)
437 }
438 if data, err := os.ReadFile(filepath.Join(dir, "exports", "1", "export.json")); err != nil || string(data) != "{}" {
439 t.Errorf("after start %d the first layout's export.json holds %q, %v", start, data, err)
440 }
441 if target, err := os.Readlink(filepath.Join(dir, "active")); err != nil || target != "exports/1" {
442 t.Errorf("after start %d the first layout's active points at %q, %v", start, target, err)
443 }
444 if errs := r.all(); len(errs) != 0 {
445 t.Errorf("start %d reported %v", start, errs)
446 }
447 }
448 if err := os.WriteFile(filepath.Join(dir, "other"), []byte("the-valley/web-store/v1\n"), 0o644); err != nil {
449 t.Fatal(err)
450 }
451 if _, err := export.OpenReadOnly(filepath.Join(dir, "other")); err == nil {
452 t.Error("OpenReadOnly opened a file that is no store's descriptor")
453 }
454 if _, err := export.OpenReadOnly(filepath.Join(dir, "store")); err != nil {
455 t.Errorf("OpenReadOnly of the descriptor gave %v", err)
456 }
457}
458
459// An authorization with a basis is admitted only while the stored
460// authorization is the one it names, by VerifyAuthorization and again by
461// Store.Authorize under its lock, and its basis is less than its sequence.
462func TestAnAuthorizationWithABasisNeedsItStored(t *testing.T) {
463 based := func(seq, basis int64) *export.Authorization {
464 a := exporttest.Authorization(seq, "app")
465 a.Basis = basis
466 return a
467 }
468 if _, err := export.VerifyAuthorization(bytes.NewReader(exporttest.SignAuthorization(t, based(9, 4))), authorizationAdmission(4)); err != nil {
469 t.Errorf("an authorization on the stored basis was refused: %v", err)
470 }
471 _, err := export.VerifyAuthorization(bytes.NewReader(exporttest.SignAuthorization(t, based(9, 3))), authorizationAdmission(4))
472 wantCode(t, err, export.CodeStaleBasis)
473 var e *export.Error
474 if errors.As(err, &e) && e.HighWater != 4 {
475 t.Errorf("the stale-basis refusal gives high water %d, want 4", e.HighWater)
476 }
477 _, err = export.ParseAuthorization(based(4, 4).Text())
478 wantCode(t, err, export.CodeBadManifest)
479
480 s := openStore(t, payload(t))
481 stored, _, err := s.Authorization()
482 if err != nil {
483 t.Fatal(err)
484 }
485 stale := based(stored.Sequence+5, stored.Sequence+1)
486 wantCode(t, s.Authorize(context.Background(), stale, exporttest.SignAuthorization(t, stale)), export.CodeStaleBasis)
487 current := based(stored.Sequence+5, stored.Sequence)
488 if err := s.Authorize(context.Background(), current, exporttest.SignAuthorization(t, current)); err != nil {
489 t.Errorf("Authorize refused an authorization on the stored basis: %v", err)
490 }
491}
492
493// A prune that selected a withdrawn repository, and is paused before it
494// deletes it, deletes nothing once an authorization names the project
495// again: it reads the authorization again under the authorization lock.
496// The reply to that authorization says the receiver serves the export
497// whole, and the repository survives the prune.
498func TestAPruneKeepsWhatAnAuthorizationNamesAgain(t *testing.T) {
499 f := exporttest.New(t)
500 s := openStore(t, payload(t))
501 g := f.Upload(t, s)
502 repo, _ := g.Repo("app")
503 digest, err := f.Export.Digest()
504 if err != nil {
505 t.Fatal(err)
506 }
507 exporttest.Authorize(t, s)
508 paused, resume := make(chan struct{}), make(chan struct{})
509 *export.PruneSelected = func() {
510 close(paused)
511 <-resume
512 }
513 defer func() { *export.PruneSelected = nil }()
514 pruned := make(chan error, 1)
515 go func() { pruned <- s.Prune(context.Background()) }()
516 <-paused
517
518 exporttest.Authorize(t, s, "app")
519 reply := func() *export.AuthorizationReply {
520 active, _, err := s.Holdings()
521 if err != nil {
522 t.Fatal(err)
523 }
524 missing, err := s.Missing()
525 if err != nil {
526 t.Fatal(err)
527 }
528 return &export.AuthorizationReply{Active: active, Missing: missing}
529 }
530 if r := reply(); !r.Serves(digest) {
531 t.Errorf("named again while a prune was paused, the reply is %+v; want the export served whole", r)
532 }
533 close(resume)
534 if err := <-pruned; err != nil {
535 t.Fatal(err)
536 }
537 if _, err := os.Stat(repo); err != nil {
538 t.Errorf("the prune deleted the repository an authorization named again: %v", err)
539 }
540 if r := reply(); !r.Serves(digest) {
541 t.Errorf("after the prune the reply is %+v; want the export served whole", r)
542 }
543}
544
545// firstLayout makes, in dir, the state of the first store layout: active
546// pointing at a generation, high-water, exports/, staging/, trash/ and
547// lock.
548func firstLayout(t *testing.T, dir string) {
549 t.Helper()
550 for _, d := range []string{"exports/1/repos", "staging/2/bodies", "trash/old"} {
551 if err := os.MkdirAll(filepath.Join(dir, d), 0o755); err != nil {
552 t.Fatal(err)
553 }
554 }
555 for name, data := range map[string]string{"high-water": "1\n", "lock": "", "exports/1/export.json": "{}"} {
556 if err := os.WriteFile(filepath.Join(dir, name), []byte(data), 0o644); err != nil {
557 t.Fatal(err)
558 }
559 }
560 if err := os.Symlink("exports/1", filepath.Join(dir, "active")); err != nil {
561 t.Fatal(err)
562 }
563}