gunk-dev/the-valley

authorization_test.go

sourcefefe7833f700main's published tip history
15.2 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, and nothing is created.
248// A new store beside the first layout's state deletes none of it, then or
249// on a later start: the receiver writes nothing outside its descriptor and
250// v2/, and the operator deletes the first layout by hand.
251func TestStoreDescriptorLeavesTheFirstLayout(t *testing.T) {
252 dir := t.TempDir()
253 if _, err := export.OpenStore(dir, nil); err == nil || !strings.Contains(err.Error(), "is a directory") {
254 t.Errorf("OpenStore of a directory gave %v", err)
255 }
256 if _, err := export.OpenReadOnly(dir); err == nil || !strings.Contains(err.Error(), "is a directory") {
257 t.Errorf("OpenReadOnly of a directory gave %v", err)
258 }
259 if got := entries(t, dir); len(got) != 0 {
260 t.Errorf("a refused directory holds %v", got)
261 }
262 firstLayout(t, dir)
263 want := "active exports high-water lock staging store trash v2"
264 for start := 1; start <= 2; start++ {
265 var r reports
266 if _, err := export.OpenStore(filepath.Join(dir, "store"), r.report); err != nil {
267 t.Fatal(err)
268 }
269 if got := entries(t, dir); strings.Join(got, " ") != want {
270 t.Errorf("after start %d the directory holds %v, want %s", start, got, want)
271 }
272 if data, err := os.ReadFile(filepath.Join(dir, "exports", "1", "export.json")); err != nil || string(data) != "{}" {
273 t.Errorf("after start %d the first layout's export.json holds %q, %v", start, data, err)
274 }
275 if target, err := os.Readlink(filepath.Join(dir, "active")); err != nil || target != "exports/1" {
276 t.Errorf("after start %d the first layout's active points at %q, %v", start, target, err)
277 }
278 if errs := r.all(); len(errs) != 0 {
279 t.Errorf("start %d reported %v", start, errs)
280 }
281 }
282 if err := os.WriteFile(filepath.Join(dir, "other"), []byte("the-valley/web-store/v1\n"), 0o644); err != nil {
283 t.Fatal(err)
284 }
285 if _, err := export.OpenReadOnly(filepath.Join(dir, "other")); err == nil {
286 t.Error("OpenReadOnly opened a file that is no store's descriptor")
287 }
288 if _, err := export.OpenReadOnly(filepath.Join(dir, "store")); err != nil {
289 t.Errorf("OpenReadOnly of the descriptor gave %v", err)
290 }
291}
292
293// An authorization with a basis is admitted only while the stored
294// authorization is the one it names, by VerifyAuthorization and again by
295// Store.Authorize under its lock, and its basis is less than its sequence.
296func TestAnAuthorizationWithABasisNeedsItStored(t *testing.T) {
297 based := func(seq, basis int64) *export.Authorization {
298 a := exporttest.Authorization(seq, "app")
299 a.Basis = basis
300 return a
301 }
302 if _, err := export.VerifyAuthorization(bytes.NewReader(exporttest.SignAuthorization(t, based(9, 4))), authorizationAdmission(4)); err != nil {
303 t.Errorf("an authorization on the stored basis was refused: %v", err)
304 }
305 _, err := export.VerifyAuthorization(bytes.NewReader(exporttest.SignAuthorization(t, based(9, 3))), authorizationAdmission(4))
306 wantCode(t, err, export.CodeStaleBasis)
307 var e *export.Error
308 if errors.As(err, &e) && e.HighWater != 4 {
309 t.Errorf("the stale-basis refusal gives high water %d, want 4", e.HighWater)
310 }
311 _, err = export.ParseAuthorization(based(4, 4).Text())
312 wantCode(t, err, export.CodeBadManifest)
313
314 s := openStore(t, payload(t))
315 stored, _, err := s.Authorization()
316 if err != nil {
317 t.Fatal(err)
318 }
319 stale := based(stored.Sequence+5, stored.Sequence+1)
320 wantCode(t, s.Authorize(context.Background(), stale, exporttest.SignAuthorization(t, stale)), export.CodeStaleBasis)
321 current := based(stored.Sequence+5, stored.Sequence)
322 if err := s.Authorize(context.Background(), current, exporttest.SignAuthorization(t, current)); err != nil {
323 t.Errorf("Authorize refused an authorization on the stored basis: %v", err)
324 }
325}
326
327// A prune that selected a withdrawn repository, and is paused before it
328// deletes it, deletes nothing once an authorization names the project
329// again: it reads the authorization again under the authorization lock.
330// The reply to that authorization says the receiver serves the export
331// whole, and the repository survives the prune.
332func TestAPruneKeepsWhatAnAuthorizationNamesAgain(t *testing.T) {
333 f := exporttest.New(t)
334 s := openStore(t, payload(t))
335 g := f.Upload(t, s)
336 repo, _ := g.Repo("app")
337 digest, err := f.Export.Digest()
338 if err != nil {
339 t.Fatal(err)
340 }
341 exporttest.Authorize(t, s)
342 paused, resume := make(chan struct{}), make(chan struct{})
343 *export.PruneSelected = func() {
344 close(paused)
345 <-resume
346 }
347 defer func() { *export.PruneSelected = nil }()
348 pruned := make(chan error, 1)
349 go func() { pruned <- s.Prune(context.Background()) }()
350 <-paused
351
352 exporttest.Authorize(t, s, "app")
353 reply := func() *export.AuthorizationReply {
354 active, _, err := s.Holdings()
355 if err != nil {
356 t.Fatal(err)
357 }
358 missing, err := s.Missing()
359 if err != nil {
360 t.Fatal(err)
361 }
362 return &export.AuthorizationReply{Active: active, Missing: missing}
363 }
364 if r := reply(); !r.Serves(digest) {
365 t.Errorf("named again while a prune was paused, the reply is %+v; want the export served whole", r)
366 }
367 close(resume)
368 if err := <-pruned; err != nil {
369 t.Fatal(err)
370 }
371 if _, err := os.Stat(repo); err != nil {
372 t.Errorf("the prune deleted the repository an authorization named again: %v", err)
373 }
374 if r := reply(); !r.Serves(digest) {
375 t.Errorf("after the prune the reply is %+v; want the export served whole", r)
376 }
377}
378
379// firstLayout makes, in dir, the state of the first store layout: active
380// pointing at a generation, high-water, exports/, staging/, trash/ and
381// lock.
382func firstLayout(t *testing.T, dir string) {
383 t.Helper()
384 for _, d := range []string{"exports/1/repos", "staging/2/bodies", "trash/old"} {
385 if err := os.MkdirAll(filepath.Join(dir, d), 0o755); err != nil {
386 t.Fatal(err)
387 }
388 }
389 for name, data := range map[string]string{"high-water": "1\n", "lock": "", "exports/1/export.json": "{}"} {
390 if err := os.WriteFile(filepath.Join(dir, name), []byte(data), 0o644); err != nil {
391 t.Fatal(err)
392 }
393 }
394 if err := os.Symlink("exports/1", filepath.Join(dir, "active")); err != nil {
395 t.Fatal(err)
396 }
397}