gunk-dev/the-valley

policy_test.go

source860de91b1a12main's published tip history
16.3 KiB
1package main
2
3import (
4 "bytes"
5 "errors"
6 "fmt"
7 "io"
8 "os"
9 "path/filepath"
10 "slices"
11 "strings"
12 "testing"
13
14 "the-valley/note"
15 "the-valley/web/export"
16 "the-valley/web/export/exporttest"
17)
18
19// The authorization counter reads no clock and survives the process: each
20// publisher over one state directory allocates a sequence greater than
21// every one allocated before, a floor from the receiver raises it, and a
22// counter that cannot be read is an error, never a fresh start at one.
23func TestTheAuthorizationSequenceIsDurable(t *testing.T) {
24 state := t.TempDir()
25 next := func(floor int64) (int64, error) {
26 p := &publisher{cfg: config{state: state}, stdout: io.Discard, stderr: io.Discard}
27 return p.nextSequence(floor)
28 }
29 for i, c := range []struct{ floor, want int64 }{{0, 1}, {0, 2}, {10, 11}, {3, 12}, {0, 13}} {
30 got, err := next(c.floor)
31 if err != nil || got != c.want {
32 t.Fatalf("allocation %d with floor %d gave %d, %v; want %d", i+1, c.floor, got, err, c.want)
33 }
34 }
35 data, err := os.ReadFile(filepath.Join(state, authorizationSequenceFile))
36 if err != nil || string(data) != "13\n" {
37 t.Errorf("the counter holds %q, %v; want 13", data, err)
38 }
39 for _, bad := range []string{"", "x\n", "-4\n"} {
40 if err := os.WriteFile(filepath.Join(state, authorizationSequenceFile), []byte(bad), 0o600); err != nil {
41 t.Fatal(err)
42 }
43 if got, err := next(0); err == nil {
44 t.Errorf("a counter holding %q gave sequence %d", bad, got)
45 }
46 }
47}
48
49// An incomplete check keeps a project's access only from the authorization
50// the receiver last said it stored, and only while the receiver still
51// holds it. With app's policy unreadable, a pass keeps app, naming that
52// authorization as its basis. Then app's own policy withdraws anyone, and
53// the receiver stores the withdrawal. The publisher's state is then
54// restored from a copy taken before the withdrawal, and app's policy is
55// unreadable again. The restored record still lets anyone read app, but
56// the receiver refuses the authorization that keeps it, as replayed, or as
57// stale-basis when the restored counter is ahead, and the retry keeps
58// nothing it could not check.
59func TestARestoredStateRestoresNoWithdrawnAccess(t *testing.T) {
60 v := newValley(t)
61 rv := newReceiver(t, v)
62 app := filepath.Join(v.srv, "app.git")
63 stored := func() *export.Authorization {
64 t.Helper()
65 a, _, err := rv.store.Authorization()
66 if err != nil {
67 t.Fatal(err)
68 }
69 return a
70 }
71 unreadable := func(f func()) (string, error) {
72 t.Helper()
73 if err := os.Rename(app, app+".moved"); err != nil {
74 t.Fatal(err)
75 }
76 defer os.Rename(app+".moved", app)
77 _, stderr, err := v.tryPublish(nil, rv.flags()...)
78 if f != nil {
79 f()
80 }
81 return stderr, err
82 }
83
84 v.publish(rv.flags()...)
85 first := stored()
86 if !first.Allows(export.Anyone, "app", identities["app"]) {
87 t.Fatalf("the first authorization names %+v, want app", first.Projects)
88 }
89 backup := filepath.Join(t.TempDir(), "state")
90 v.run("", "cp", "-a", v.state, backup)
91
92 if _, err := unreadable(nil); !errors.Is(err, errIncomplete) {
93 t.Fatalf("a pass with app unreadable gave %v, want an incomplete check", err)
94 }
95 if kept := stored(); !kept.Allows(export.Anyone, "app", identities["app"]) || kept.Basis != first.Sequence {
96 t.Errorf("with app unreadable the receiver stored %+v with basis %d; want app kept on basis %d", kept.Projects, kept.Basis, first.Sequence)
97 }
98
99 v.declare("app", policy("app", "operator"))
100 v.publish(rv.flags()...)
101 if withdrawn := stored(); withdrawn.Allows(export.Anyone, "app", identities["app"]) {
102 t.Fatalf("the withdrawal stored %+v, which names app", withdrawn.Projects)
103 }
104
105 for _, c := range []struct {
106 name string
107 counter string // the restored counter, or "" to leave the copy's
108 refused export.Code
109 }{
110 {"behind", "", export.CodeReplayed},
111 {"ahead", "1000\n", export.CodeStaleBasis},
112 } {
113 t.Run(c.name, func(t *testing.T) {
114 if err := os.RemoveAll(v.state); err != nil {
115 t.Fatal(err)
116 }
117 v.run("", "cp", "-a", backup, v.state)
118 if c.counter != "" {
119 v.write(filepath.Join(v.state, authorizationSequenceFile), c.counter)
120 }
121 before := stored().Sequence
122 stderr, err := unreadable(nil)
123 if !errors.Is(err, errIncomplete) {
124 t.Fatalf("the restored pass gave %v, want an incomplete check", err)
125 }
126 mustSay(t, "the restored pass", stderr, "refused")
127 mustSay(t, "the restored pass", stderr, "as "+string(c.refused))
128 got := stored()
129 if got.Sequence <= before || got.Allows(export.Anyone, "app", identities["app"]) || got.Basis != 0 {
130 t.Errorf("after the restored pass the receiver holds %d naming %+v on basis %d; want a newer one that keeps nothing",
131 got.Sequence, got.Projects, got.Basis)
132 }
133 })
134 }
135}
136
137// A failure while the counter is written, at the file's sync, its rename
138// or the directory's sync, returns no sequence, and leaves no temporary
139// file behind. No later allocation hands out a sequence at or below one
140// handed out before: a failure at the directory's sync may have written
141// the counter, and the next allocation counts from it.
142func TestTheAuthorizationCounterSurvivesFailedWrites(t *testing.T) {
143 state := t.TempDir()
144 next := func() (int64, error) {
145 p := &publisher{cfg: config{state: state}, stdout: io.Discard, stderr: io.Discard}
146 return p.nextSequence(0)
147 }
148 handed := int64(0)
149 allocate := func() {
150 t.Helper()
151 seq, err := next()
152 if err != nil {
153 t.Fatal(err)
154 }
155 if seq <= handed {
156 t.Fatalf("allocated %d after %d", seq, handed)
157 }
158 handed = seq
159 }
160 allocate()
161 failed := errors.New("injected")
162 realSync, realRename := syncFile, renameFile
163 defer func() { syncFile, renameFile = realSync, realRename }()
164 dirSync := func(f *os.File) error {
165 if info, err := f.Stat(); err == nil && info.IsDir() {
166 return failed
167 }
168 return realSync(f)
169 }
170 for _, c := range []struct {
171 name string
172 sync func(*os.File) error
173 rename func(string, string) error
174 }{
175 {"the file's sync", func(*os.File) error { return failed }, realRename},
176 {"the rename", realSync, func(string, string) error { return failed }},
177 {"the directory's sync", dirSync, realRename},
178 } {
179 syncFile, renameFile = c.sync, c.rename
180 if seq, err := next(); !errors.Is(err, failed) {
181 t.Errorf("a failure at %s gave sequence %d, %v", c.name, seq, err)
182 }
183 syncFile, renameFile = realSync, realRename
184 entries, err := os.ReadDir(state)
185 if err != nil {
186 t.Fatal(err)
187 }
188 if len(entries) != 1 || entries[0].Name() != authorizationSequenceFile {
189 t.Errorf("after a failure at %s the state directory holds %v", c.name, entries)
190 }
191 allocate()
192 }
193}
194
195// A receiver that lost its state, as when its volume is replaced, holds no
196// authorization. With app's policy unreadable, the pass keeps app's access
197// on the basis of the authorization the receiver acknowledged before, and
198// the receiver refuses it as stale-basis. The retry keeps nothing it could
199// not check, and publishes the grant it could read: anyone may read site.
200func TestAReceiverThatLostItsStateGetsTheReadableGrants(t *testing.T) {
201 v := newValley(t)
202 rv := newReceiver(t, v)
203 v.declare("site", policy("site", "anyone"))
204 v.publish(rv.flags()...)
205 before, _, err := rv.store.Authorization()
206 if err != nil {
207 t.Fatal(err)
208 }
209 if !before.Allows(export.Anyone, "app", identities["app"]) || !before.Allows(export.Anyone, "site", identities["site"]) {
210 t.Fatalf("the first authorization names %+v, want app and site", before.Projects)
211 }
212
213 rv.replaceStore()
214 app := filepath.Join(v.srv, "app.git")
215 if err := os.Rename(app, app+".moved"); err != nil {
216 t.Fatal(err)
217 }
218 defer os.Rename(app+".moved", app)
219 _, stderr, err := v.tryPublish(nil, rv.flags()...)
220 if !errors.Is(err, errIncomplete) {
221 t.Fatalf("the pass gave %v, want an incomplete check", err)
222 }
223 mustSay(t, "the pass to a receiver that lost its state", stderr, "as "+string(export.CodeStaleBasis))
224 got, _, err := rv.store.Authorization()
225 if err != nil {
226 t.Fatalf("the receiver that lost its state stored no authorization: %v", err)
227 }
228 if !got.Allows(export.Anyone, "site", identities["site"]) || got.Allows(export.Anyone, "app", identities["app"]) || got.Basis != 0 {
229 t.Errorf("the receiver that lost its state holds %+v on basis %d; want site alone, on no basis", got.Projects, got.Basis)
230 }
231}
232
233// A bounded fallback is measured, never assumed to fit. The receiver holds
234// an authorization it admitted before a pass left room under the limit:
235// exactly 262,144 bytes signed, at sequence 99,999,999, on no basis. The
236// next check withdraws bob from app, which saves the 15 bytes of "reader
237// app bob", and keeps notes, whose policy it could not read, on the basis
238// of that authorization, which costs the 15 of "basis 99999999". Its
239// sequence, 100,000,000, is a digit longer, so its authorization and the
240// fallback narrowed from the stored one are a byte over the limit. The
241// fallback drops notes, kept only on the basis, and the basis with it, so
242// it fits, and the receiver admits the withdrawal of bob.
243func TestAFallbackOverTheLimitStillDeliversAWithdrawal(t *testing.T) {
244 p := &publisher{signer: exporttest.SignerName, limit: export.MaxAuthorization}
245 notes := strings.Repeat("4", 32)
246 prev := &export.Authorization{Instance: exporttest.Instance, Destination: exporttest.Destination, Sequence: 99_999_999,
247 Checked: exporttest.Collected,
248 Projects: []export.AuthorizedProject{
249 {Name: "app", Identity: identities["app"], Readers: []string{"anyone", "bob", "operator"}},
250 {Name: "notes", Identity: notes, Readers: []string{"alice"}},
251 }}
252 // Each further reader of app is "reader app " and a 9-character name,
253 // 21 bytes, and the last is as long as fills the limit exactly.
254 app := &prev.Projects[0]
255 size := prev.SignedSize(p.signer)
256 for i := 0; export.MaxAuthorization-size >= 21+25; i++ {
257 app.Readers = append(app.Readers, fmt.Sprintf("r%08d", i))
258 size += 21
259 }
260 app.Readers = append(app.Readers, "z"+strings.Repeat("0", export.MaxAuthorization-size-13))
261 if size := prev.SignedSize(p.signer); size != export.MaxAuthorization {
262 t.Fatalf("the stored authorization is %d bytes signed, want %d", size, export.MaxAuthorization)
263 }
264
265 full := &export.Authorization{Instance: prev.Instance, Destination: prev.Destination, Sequence: 100_000_000,
266 Checked: exporttest.SignedAt, Basis: prev.Sequence,
267 Projects: []export.AuthorizedProject{
268 {Name: "app", Identity: app.Identity, Readers: slices.DeleteFunc(slices.Clone(app.Readers), func(r string) bool { return r == "bob" })},
269 prev.Projects[1],
270 }}
271 size = full.SignedSize(p.signer)
272 if size != export.MaxAuthorization+1 {
273 t.Fatalf("the check's authorization is %d bytes signed, want a byte over %d", size, export.MaxAuthorization)
274 }
275 c := policyCheck{authorization: full, kept: []string{"notes"}}
276 p.fallBack(&c, prev, size)
277
278 signed, err := c.authorization.Sign(p.signer, exporttest.Key())
279 if err != nil {
280 t.Fatalf("the fallback is not signed: %v", err)
281 }
282 got, err := export.VerifyAuthorization(bytes.NewReader(signed), export.AuthorizationAdmission{
283 Verifiers: []note.VerifierKey{exporttest.Verifier()}, Instance: prev.Instance, Destination: prev.Destination,
284 HighWater: prev.Sequence})
285 if err != nil {
286 t.Fatalf("the receiver refuses the fallback: %v", err)
287 }
288 if got.Sequence != full.Sequence || got.Basis != 0 || got.Names("notes", notes) {
289 t.Errorf("the receiver admitted authorization %d on basis %d naming notes %v; want %d, on no basis, without notes",
290 got.Sequence, got.Basis, got.Names("notes", notes), full.Sequence)
291 }
292 if got.Allows("bob", "app", app.Identity) {
293 t.Errorf("the fallback still lets bob read app")
294 }
295 for _, r := range full.Projects[0].Readers {
296 if !got.Allows(r, "app", app.Identity) {
297 t.Errorf("the fallback dropped %s from app, which it had no need to drop", r)
298 break
299 }
300 }
301 if !errors.Is(c.overflow, errOverflow) || c.pending != "no access" || c.dropped != "notes to alice" {
302 t.Errorf("the check's overflow is %v, pending %q and dropped %q; want pending no access, and notes to alice dropped",
303 c.overflow, c.pending, c.dropped)
304 }
305 if !strings.Contains(c.overflow.Error(), "so to fit it also drops notes to alice; pending until an authorization fits: no access") {
306 t.Errorf("the overflow does not say what the fallback dropped and what is pending: %v", c.overflow)
307 }
308}
309
310// The last resort of a fallback over the limit is an authorization that
311// grants nothing, which always fits. With the limit lowered to exactly
312// that authorization's size, a pass that adds anyone to site's readers
313// sends it: the receiver stores an authorization that names no project,
314// and the pass fails, saying what is pending and what the fallback
315// dropped.
316func TestTheLastResortGrantsNothing(t *testing.T) {
317 v := newValley(t)
318 rv := newReceiver(t, v)
319 v.publish(rv.flags()...)
320 before, _, err := rv.store.Authorization()
321 if err != nil {
322 t.Fatal(err)
323 }
324 if !before.Allows(export.Anyone, "app", identities["app"]) {
325 t.Fatalf("the first authorization names %+v, want app", before.Projects)
326 }
327
328 v.declare("site", policy("site", "anyone"))
329 nothing := &export.Authorization{Instance: instanceName, Destination: destination, Sequence: before.Sequence + 1, Checked: before.Checked}
330 stdout, stderr, failed := v.tryPublish(func(p *publisher) { p.limit = nothing.SignedSize(p.signer) }, rv.flags()...)
331 if !errors.Is(failed, errOverflow) {
332 t.Fatalf("the pass gave %v, want an overflow\nstdout:\n%s\nstderr:\n%s", failed, stdout, stderr)
333 }
334 got, _, err := rv.store.Authorization()
335 if err != nil {
336 t.Fatal(err)
337 }
338 if got.Sequence != nothing.Sequence || len(got.Projects) != 0 || len(got.Bindings) != 0 || got.Basis != 0 {
339 t.Errorf("the receiver holds authorization %d naming %+v with %d bindings on basis %d; want %d, granting nothing",
340 got.Sequence, got.Projects, len(got.Bindings), got.Basis, nothing.Sequence)
341 }
342 mustSay(t, "the pass", stdout, fmt.Sprintf("the receiver stored authorization %d: no project may be read\n", nothing.Sequence))
343 mustSay(t, "the pass", stdout, "valley-web-publish: pending: site to anyone\n")
344 mustSay(t, "the pass", stdout, "valley-web-publish: dropped: app to anyone, operator")
345 mustSay(t, "the pass", failed.Error(), "so to fit it also drops app to anyone, operator")
346}
347
348// A fallback the receiver refuses is still reported when the retry fails.
349// With the limit lowered to the size of an authorization that grants
350// nothing, a pass that adds anyone to site's readers signs a fallback that
351// drops app to fit. The receiver refuses it as replayed, and the instance
352// repository is then unreadable, so the retry's policy check fails before
353// it signs. The pass prints what is pending and what the fallback dropped,
354// and its error names both beside the failure to read the instance.
355func TestARefusedFallbackIsReportedWhenTheRetryFails(t *testing.T) {
356 v := newValley(t)
357 rv := newReceiver(t, v)
358 v.publish(rv.flags()...)
359 before, _, err := rv.store.Authorization()
360 if err != nil {
361 t.Fatal(err)
362 }
363
364 v.declare("site", policy("site", "anyone"))
365 instance := filepath.Join(v.srv, "valley.git")
366 defer os.Rename(instance+".moved", instance)
367 rv.mu.Lock()
368 rv.refuse = func(kind string, _ int64) (*export.Error, int) {
369 if kind != "authorization" {
370 return nil, 0
371 }
372 if err := os.Rename(instance, instance+".moved"); err != nil {
373 t.Error(err)
374 }
375 rv.refuse = nil
376 return &export.Error{Code: export.CodeReplayed, Message: "refused by the test", HighWater: before.Sequence + 10}, 0
377 }
378 rv.mu.Unlock()
379 nothing := &export.Authorization{Instance: instanceName, Destination: destination, Sequence: before.Sequence + 1, Checked: before.Checked}
380 stdout, stderr, failed := v.tryPublish(func(p *publisher) { p.limit = nothing.SignedSize(p.signer) }, rv.flags()...)
381 if !errors.Is(failed, errOverflow) {
382 t.Fatalf("the pass gave %v, want an overflow\nstdout:\n%s\nstderr:\n%s", failed, stdout, stderr)
383 }
384 mustSay(t, "the pass", stderr, "as "+string(export.CodeReplayed))
385 mustSay(t, "the pass", stdout, "valley-web-publish: pending: site to anyone\n")
386 mustSay(t, "the pass", stdout, "valley-web-publish: dropped: app to anyone, operator\n")
387 mustSay(t, "the pass", failed.Error(), "in the instance repository")
388 mustSay(t, "the pass", failed.Error(), fmt.Sprintf("the receiver refused authorization %d as %s", nothing.Sequence, export.CodeReplayed))
389 mustSay(t, "the pass", failed.Error(), "so to fit it also drops app to anyone, operator; pending until an authorization fits: site to anyone")
390 if got, _, err := rv.store.Authorization(); err != nil || got.Sequence != before.Sequence {
391 t.Errorf("the receiver holds authorization %v, %v; want %d, as it stored nothing since", got, err, before.Sequence)
392 }
393}