gunk-dev/the-valley

authorization_test.go

source4dc8a2218c87main's published tip history
17.1 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// A store with no authorization builds no repository and needs no bundle,
153// and a stored authorization that cannot be read is no high-water mark of
154// zero: nothing is stored over it.
155func TestStoreBuildsOnlyWhatTheAuthorizationNames(t *testing.T) {
156 f := exporttest.New(t)
157 dir := payload(t)
158 s, err := export.OpenStore(descriptorOf(dir), func(err error) { t.Errorf("the store reported: %v", err) })
159 if err != nil {
160 t.Fatal(err)
161 }
162 a := exporttest.Authorization(1)
163 if err := s.Authorize(context.Background(), a, exporttest.SignAuthorization(t, a)); err != nil {
164 t.Fatal(err)
165 }
166 u := fixtureUpload(t, f)
167 st := stage(t, f, s, u)
168 inv, err := s.Inventory(st)
169 if err != nil {
170 t.Fatal(err)
171 }
172 if len(inv.Needs) != 1 || inv.Needs[0].Name != export.ExportFile {
173 t.Errorf("with app not named the inventory needs %+v, want export.json alone", inv.Needs)
174 }
175 putNeed(t, st, u, inv.Needs[0])
176 g, err := s.Activate(context.Background(), st)
177 if err != nil {
178 t.Fatal(err)
179 }
180 if got := entries(t, filepath.Join(g.Dir, "repos")); len(got) != 0 {
181 t.Errorf("the generation holds repositories %v of projects no authorization names", got)
182 }
183
184 if err := os.WriteFile(filepath.Join(dir, "authorization"), []byte("damaged"), 0o644); err != nil {
185 t.Fatal(err)
186 }
187 if _, err := s.AuthorizationHighWater(); err == nil {
188 t.Error("a damaged stored authorization gave a high-water mark")
189 }
190 next := exporttest.Authorization(9, "app")
191 if err := s.Authorize(context.Background(), next, exporttest.SignAuthorization(t, next)); err == nil {
192 t.Error("an authorization was stored over a damaged one")
193 }
194}
195
196// An authorization that withdraws a project hides it at once, and Prune
197// deletes its repository once no reader holds the generation, leaving
198// export.json as it was signed. Named again, the project is missing, and
199// the inventory needs its bundle.
200func TestStorePrunesAWithdrawnRepository(t *testing.T) {
201 f := exporttest.New(t)
202 s := openStore(t, payload(t))
203 g := f.Upload(t, s)
204 repo, _ := g.Repo("app")
205 before, err := os.ReadFile(g.ExportPath())
206 if err != nil {
207 t.Fatal(err)
208 }
209 exporttest.Authorize(t, s)
210 _, release, err := s.Open()
211 if err != nil {
212 t.Fatal(err)
213 }
214 if err := s.Prune(context.Background()); !errors.Is(err, export.ErrHeld) {
215 t.Errorf("Prune gave %v while a reader held the generation, want ErrHeld", err)
216 }
217 if _, err := os.Stat(repo); err != nil {
218 t.Errorf("Prune deleted the repository a reader held: %v", err)
219 }
220 release()
221 if err := s.Prune(context.Background()); err != nil {
222 t.Fatal(err)
223 }
224 if _, err := os.Stat(repo); !errors.Is(err, os.ErrNotExist) {
225 t.Errorf("Prune left the withdrawn repository: %v", err)
226 }
227 if after, err := os.ReadFile(g.ExportPath()); err != nil || !bytes.Equal(before, after) {
228 t.Errorf("Prune changed export.json: %v", err)
229 }
230
231 exporttest.Authorize(t, s, "app")
232 if missing, err := s.Missing(); err != nil || len(missing) != 1 || missing[0] != "app" {
233 t.Errorf("named again, the missing projects are %v, %v; want app", missing, err)
234 }
235 u := later(t, f, time.Minute)
236 st := stage(t, f, s, u)
237 inv, err := s.Inventory(st)
238 if err != nil {
239 t.Fatal(err)
240 }
241 if len(inv.Holds) != 0 || len(inv.Needs) != 2 {
242 t.Errorf("named again, the inventory holds %+v and needs %+v; want nothing held and both bodies", inv.Holds, inv.Needs)
243 }
244}
245
246// The store's entry point is a descriptor file. A directory, as the first
247// layout's state was, is refused by both openers. A new store retires the
248// first layout's state from the descriptor's directory, active first, so a
249// binary of that layout serves nothing there.
250func TestStoreDescriptorRetiresTheFirstLayout(t *testing.T) {
251 dir := t.TempDir()
252 if _, err := export.OpenStore(dir, nil); err == nil || !strings.Contains(err.Error(), "is a directory") {
253 t.Errorf("OpenStore of a directory gave %v", err)
254 }
255 if _, err := export.OpenReadOnly(dir); err == nil || !strings.Contains(err.Error(), "is a directory") {
256 t.Errorf("OpenReadOnly of a directory gave %v", err)
257 }
258 if err := os.MkdirAll(filepath.Join(dir, "exports", "1", "repos"), 0o755); err != nil {
259 t.Fatal(err)
260 }
261 for name, data := range map[string]string{"high-water": "1\n", "lock": "", "exports/1/export.json": "{}"} {
262 if err := os.WriteFile(filepath.Join(dir, name), []byte(data), 0o644); err != nil {
263 t.Fatal(err)
264 }
265 }
266 if err := os.Symlink("exports/1", filepath.Join(dir, "active")); err != nil {
267 t.Fatal(err)
268 }
269 var r reports
270 if _, err := export.OpenStore(filepath.Join(dir, "store"), r.report); err != nil {
271 t.Fatal(err)
272 }
273 if got := entries(t, dir); strings.Join(got, " ") != "store v2" {
274 t.Errorf("after the first layout was retired the directory holds %v", got)
275 }
276 if errs := r.all(); len(errs) != 1 || !strings.Contains(errs[0].Error(), "retired") {
277 t.Errorf("the store reported %v, want the retired layout", errs)
278 }
279 if err := os.WriteFile(filepath.Join(dir, "other"), []byte("the-valley/web-store/v1\n"), 0o644); err != nil {
280 t.Fatal(err)
281 }
282 if _, err := export.OpenReadOnly(filepath.Join(dir, "other")); err == nil {
283 t.Error("OpenReadOnly opened a file that is no store's descriptor")
284 }
285 if _, err := export.OpenReadOnly(filepath.Join(dir, "store")); err != nil {
286 t.Errorf("OpenReadOnly of the descriptor gave %v", err)
287 }
288}
289
290// An authorization with a basis is admitted only while the stored
291// authorization is the one it names, by VerifyAuthorization and again by
292// Store.Authorize under its lock, and its basis is less than its sequence.
293func TestAnAuthorizationWithABasisNeedsItStored(t *testing.T) {
294 based := func(seq, basis int64) *export.Authorization {
295 a := exporttest.Authorization(seq, "app")
296 a.Basis = basis
297 return a
298 }
299 if _, err := export.VerifyAuthorization(bytes.NewReader(exporttest.SignAuthorization(t, based(9, 4))), authorizationAdmission(4)); err != nil {
300 t.Errorf("an authorization on the stored basis was refused: %v", err)
301 }
302 _, err := export.VerifyAuthorization(bytes.NewReader(exporttest.SignAuthorization(t, based(9, 3))), authorizationAdmission(4))
303 wantCode(t, err, export.CodeStaleBasis)
304 var e *export.Error
305 if errors.As(err, &e) && e.HighWater != 4 {
306 t.Errorf("the stale-basis refusal gives high water %d, want 4", e.HighWater)
307 }
308 _, err = export.ParseAuthorization(based(4, 4).Text())
309 wantCode(t, err, export.CodeBadManifest)
310
311 s := openStore(t, payload(t))
312 stored, _, err := s.Authorization()
313 if err != nil {
314 t.Fatal(err)
315 }
316 stale := based(stored.Sequence+5, stored.Sequence+1)
317 wantCode(t, s.Authorize(context.Background(), stale, exporttest.SignAuthorization(t, stale)), export.CodeStaleBasis)
318 current := based(stored.Sequence+5, stored.Sequence)
319 if err := s.Authorize(context.Background(), current, exporttest.SignAuthorization(t, current)); err != nil {
320 t.Errorf("Authorize refused an authorization on the stored basis: %v", err)
321 }
322}
323
324// A prune that selected a withdrawn repository, and is paused before it
325// deletes it, deletes nothing once an authorization names the project
326// again: it reads the authorization again under the authorization lock.
327// The reply to that authorization says the receiver serves the export
328// whole, and the repository survives the prune.
329func TestAPruneKeepsWhatAnAuthorizationNamesAgain(t *testing.T) {
330 f := exporttest.New(t)
331 s := openStore(t, payload(t))
332 g := f.Upload(t, s)
333 repo, _ := g.Repo("app")
334 digest, err := f.Export.Digest()
335 if err != nil {
336 t.Fatal(err)
337 }
338 exporttest.Authorize(t, s)
339 paused, resume := make(chan struct{}), make(chan struct{})
340 *export.PruneSelected = func() {
341 close(paused)
342 <-resume
343 }
344 defer func() { *export.PruneSelected = nil }()
345 pruned := make(chan error, 1)
346 go func() { pruned <- s.Prune(context.Background()) }()
347 <-paused
348
349 exporttest.Authorize(t, s, "app")
350 reply := func() *export.AuthorizationReply {
351 active, _, err := s.Holdings()
352 if err != nil {
353 t.Fatal(err)
354 }
355 missing, err := s.Missing()
356 if err != nil {
357 t.Fatal(err)
358 }
359 return &export.AuthorizationReply{Active: active, Missing: missing}
360 }
361 if r := reply(); !r.Serves(digest) {
362 t.Errorf("named again while a prune was paused, the reply is %+v; want the export served whole", r)
363 }
364 close(resume)
365 if err := <-pruned; err != nil {
366 t.Fatal(err)
367 }
368 if _, err := os.Stat(repo); err != nil {
369 t.Errorf("the prune deleted the repository an authorization named again: %v", err)
370 }
371 if r := reply(); !r.Serves(digest) {
372 t.Errorf("after the prune the reply is %+v; want the export served whole", r)
373 }
374}
375
376// firstLayout makes, in dir, the state of the first store layout: active
377// pointing at a generation, high-water, exports/, staging/, trash/ and
378// lock.
379func firstLayout(t *testing.T, dir string) {
380 t.Helper()
381 for _, d := range []string{"exports/1/repos", "staging/2/bodies", "trash/old"} {
382 if err := os.MkdirAll(filepath.Join(dir, d), 0o755); err != nil {
383 t.Fatal(err)
384 }
385 }
386 for name, data := range map[string]string{"high-water": "1\n", "lock": "", "exports/1/export.json": "{}"} {
387 if err := os.WriteFile(filepath.Join(dir, name), []byte(data), 0o644); err != nil {
388 t.Fatal(err)
389 }
390 }
391 if err := os.Symlink("exports/1", filepath.Join(dir, "active")); err != nil {
392 t.Fatal(err)
393 }
394}
395
396// A retirement stopped before any of its steps, as by a crash, is
397// finished by the next start, whatever of the first layout is left: the
398// next start finds it by any of its names. A process holding the first
399// layout's lock stops the retirement before it deletes anything.
400func TestRetiringTheFirstLayoutResumes(t *testing.T) {
401 steps := []string{"active", "high-water", "exports", "staging", "trash", "lock"}
402 for _, step := range steps {
403 t.Run(step, func(t *testing.T) {
404 dir := t.TempDir()
405 firstLayout(t, dir)
406 stopped := errors.New("stopped")
407 *export.RetireStep = func(name string) error {
408 if name == step {
409 return stopped
410 }
411 return nil
412 }
413 _, err := export.OpenStore(filepath.Join(dir, "store"), nil)
414 *export.RetireStep = nil
415 if !errors.Is(err, stopped) {
416 t.Fatalf("OpenStore gave %v, want the retirement stopped at %s", err, step)
417 }
418 if _, err := os.Lstat(filepath.Join(dir, step)); err != nil {
419 t.Errorf("the retirement stopped at %s deleted it: %v", step, err)
420 }
421 var r reports
422 if _, err := export.OpenStore(filepath.Join(dir, "store"), r.report); err != nil {
423 t.Fatal(err)
424 }
425 if got := entries(t, dir); strings.Join(got, " ") != "store v2" {
426 t.Errorf("after the retirement resumed the directory holds %v", got)
427 }
428 if errs := r.all(); len(errs) != 1 || !strings.Contains(errs[0].Error(), "retired") {
429 t.Errorf("the store reported %v, want the retired layout", errs)
430 }
431 })
432 }
433
434 t.Run("lock held", func(t *testing.T) {
435 dir := t.TempDir()
436 firstLayout(t, dir)
437 lock, err := os.OpenFile(filepath.Join(dir, "lock"), os.O_RDWR, 0)
438 if err != nil {
439 t.Fatal(err)
440 }
441 defer lock.Close()
442 if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_EX); err != nil {
443 t.Fatal(err)
444 }
445 _, err = export.OpenStore(filepath.Join(dir, "store"), nil)
446 if err == nil || !strings.Contains(err.Error(), "stop the receiver of the first layout") {
447 t.Errorf("OpenStore beside a held first-layout lock gave %v", err)
448 }
449 if got := entries(t, dir); strings.Join(got, " ") != "active exports high-water lock staging trash" {
450 t.Errorf("a refused retirement left %v", got)
451 }
452 })
453}