oficina / alta Public

Clone
git clone https://amadan.net/oficina/alta

Plain git — no account needed to clone.

Download

Download this file

1package fakehome
2
3import (
4 "bytes"
5 "io"
6 "net/http"
7 "net/http/httptest"
8 "slices"
9 "testing"
10 "time"
11
12 "amadan.net/oficina/alta/homeop"
13 family "amadan.net/rastrillo/rastrillo/crypto"
14)
15
16const (
17 credOrigin = "https://id.oficina.works"
18 dirOrigin = "https://oficina.works"
19 ownerAddr = "paul@example.test"
20)
21
22var canonicalApps = []string{"docs", "sheets", "slides", "calendar", "calls", "memoria"}
23
24// driver is Alta's side of the two operator streams, as little of it as
25// these tests need: it signs, sends and tracks each role's sequence.
26type driver struct {
27 t *testing.T
28 h *Home
29 key *family.Keypair
30 pre string
31 now time.Time
32 srv map[string]*httptest.Server
33 seq map[string]int64
34 head map[string]string
35 gen string
36}
37
38func newDriver(t *testing.T) *driver {
39 t.Helper()
40 d := &driver{t: t, now: time.Unix(2_000_000_000, 0), srv: map[string]*httptest.Server{}, seq: map[string]int64{}, head: map[string]string{}}
41 d.key, _ = family.Generate()
42 d.pre = homeop.Token()
43 d.h = New(d.key.SignPub(), d.pre, credOrigin, dirOrigin, func() time.Time { return d.now })
44 d.h.AddPerson(ownerAddr)
45 for _, r := range []string{homeop.Credential, homeop.Directory} {
46 d.srv[r] = httptest.NewServer(d.h.Handler(r))
47 t.Cleanup(d.srv[r].Close)
48 }
49 return d
50}
51
52func (d *driver) post(role, path string, body []byte) (int, []byte) {
53 d.t.Helper()
54 req, _ := http.NewRequest(http.MethodPost, d.srv[role].URL+path, bytes.NewReader(body))
55 req.Header.Set("Content-Type", "application/json")
56 req.Header.Set("Authorization", "Bearer "+d.pre)
57 resp, err := http.DefaultClient.Do(req)
58 if err != nil {
59 d.t.Fatalf("transport error: %v", err)
60 }
61 defer resp.Body.Close()
62 out, err := io.ReadAll(resp.Body)
63 if err != nil {
64 d.t.Fatalf("reading the answer: %v", err)
65 }
66 return resp.StatusCode, out
67}
68
69func (d *driver) pins(role string) homeop.Authorization {
70 p := d.h.Pins(role)
71 origin := dirOrigin
72 if role == homeop.Credential {
73 origin = credOrigin
74 }
75 return homeop.Authorization{Role: role, Origin: origin, Installation: p.Installation, Registry: p.Registry, Device: p.Device}
76}
77
78// plan signs and submits a plan, returning the HTTP status.
79func (d *driver) plan(role string, p homeop.Plan) int {
80 d.t.Helper()
81 a := d.pins(role)
82 p.Role, p.Origin, p.Installation, p.Registry, p.Device = role, a.Origin, a.Installation, a.Registry, a.Device
83 p.PlanID, p.Issued, p.Expires = homeop.Token(), d.now.Unix()-homeop.Skew, d.now.Unix()-homeop.Skew+homeop.PlanLifetime
84 raw, err := homeop.SignPlan(d.key, p)
85 if err != nil {
86 d.t.Fatal(err)
87 }
88 status, _ := d.post(role, "/operator/v1/plan", raw)
89 return status
90}
91
92// sign builds the next request on role's stream without sending it.
93func (d *driver) sign(role, action string, input func(homeop.InputBase) any) homeop.Request {
94 d.t.Helper()
95 a := d.pins(role)
96 a.Sequence, a.JournalSequence = d.seq[role]+1, d.seq[role]+1
97 a.Previous = d.head[role]
98 a.OperationID, a.Action = homeop.Token(), action
99 a.Issued, a.Expires = d.now.Unix()-homeop.Skew, d.now.Unix()-homeop.Skew+homeop.RequestLifetime
100 req, err := homeop.SignRequest(d.key, a, input(homeop.InputBase{Version: 1, Operation: action, OperationID: a.OperationID}))
101 if err != nil {
102 d.t.Fatal(err)
103 }
104 return req
105}
106
107// send posts req; a committed operation advances the stream. ok is false
108// only for Home's explicit refusal (403); any other status fails the test,
109// so a negative assertion cannot pass on a server fault.
110func (d *driver) send(role string, req homeop.Request) (homeop.Result, bool) {
111 d.t.Helper()
112 status, body := d.post(role, "/operator/v1", req.Bytes)
113 switch status {
114 case 200:
115 case 403:
116 return homeop.Result{}, false
117 default:
118 d.t.Fatalf("operation answered %d, want 200 or 403", status)
119 }
120 var res homeop.Result
121 if err := homeop.Decode(body, &res); err != nil {
122 d.t.Fatal(err)
123 }
124 if req.Authorization.Sequence == d.seq[role]+1 {
125 d.seq[role], d.head[role] = req.Authorization.Sequence, req.Head
126 }
127 return res, true
128}
129
130func (d *driver) op(role, action string, input func(homeop.InputBase) any) (homeop.Result, bool) {
131 d.t.Helper()
132 return d.send(role, d.sign(role, action, input))
133}
134
135func (d *driver) must(role, action string, input func(homeop.InputBase) any) homeop.Result {
136 d.t.Helper()
137 res, ok := d.op(role, action, input)
138 if !ok {
139 d.t.Fatalf("%s refused", action)
140 }
141 return res
142}
143
144// proposed is the team id and sqid the directory proposes next.
145func (d *driver) proposed() (int64, string) {
146 d.t.Helper()
147 a := d.pins(homeop.Directory)
148 raw, err := homeop.SignInspect(d.key, homeop.InspectChallenge{Role: homeop.Directory, Origin: dirOrigin, Installation: a.Installation, Registry: a.Registry, Device: a.Device, Challenge: homeop.Token(), Issued: d.now.Unix() - homeop.Skew, Expires: d.now.Unix() - homeop.Skew + homeop.RequestLifetime})
149 if err != nil {
150 d.t.Fatal(err)
151 }
152 status, body := d.post(homeop.Directory, "/operator/v1", raw)
153 var in homeop.Inspection
154 if status != 200 || homeop.Decode(body, &in) != nil {
155 d.t.Fatalf("inspect %d", status)
156 }
157 return in.TeamID, in.TeamSQID
158}
159
160func (d *driver) initialize() {
161 d.t.Helper()
162 if d.plan(homeop.Directory, homeop.Plan{Kind: homeop.KindInitialize}) != 200 {
163 d.t.Fatal("initialize plan")
164 }
165 if err := d.h.Confirm(homeop.Directory, ""); err != nil {
166 d.t.Fatal(err)
167 }
168 d.gen = homeop.Token()
169 d.must(homeop.Directory, homeop.DirectoryInitialize, func(b homeop.InputBase) any {
170 return homeop.InitializeInput{InputBase: b, Generation: d.gen, Baseline: homeop.Baseline}
171 })
172 // Let initialize's window lapse, as it does between Alta's phases.
173 d.now = d.now.Add((homeop.WindowLifetime + 1) * time.Second)
174}
175
176// openCreate submits and confirms the two create-team adoption plans.
177func (d *driver) openCreate(existing string) {
178 d.t.Helper()
179 if s := d.plan(homeop.Credential, homeop.Plan{Kind: homeop.KindCreateTeam, Apps: canonicalApps, Owner: ownerAddr, ExistingTeam: existing}); s != 200 {
180 d.t.Fatalf("credential plan %d", s)
181 }
182 if s := d.plan(homeop.Directory, homeop.Plan{Kind: homeop.KindCreateTeam, Apps: canonicalApps, Label: "oficina", DisplayName: "Oficina", ExistingTeam: existing}); s != 200 {
183 d.t.Fatalf("directory plan %d", s)
184 }
185 if err := d.h.Confirm(homeop.Credential, ownerAddr); err != nil {
186 d.t.Fatal(err)
187 }
188 if err := d.h.Confirm(homeop.Directory, ""); err != nil {
189 d.t.Fatal(err)
190 }
191}
192
193func (d *driver) ownerSeed(id int64, sq, address string) (homeop.Result, bool) {
194 return d.op(homeop.Credential, homeop.CredentialOwnerSeed, func(b homeop.InputBase) any {
195 return homeop.OwnerInput{InputBase: b, Directory: dirOrigin, TeamID: id, TeamSQID: sq, Address: address, ExistingOnly: true}
196 })
197}
198
199func (d *driver) seed(id int64, sq, label string, receipt []byte) (homeop.Result, bool) {
200 return d.op(homeop.Directory, homeop.DirectorySeedTeam, func(b homeop.InputBase) any {
201 return homeop.SeedInput{InputBase: b, Generation: d.gen, TeamID: id, TeamSQID: sq, Label: label, Name: "Oficina", Receipt: receipt}
202 })
203}
204
205func (d *driver) provision(sq, app, consumer, audience string) (homeop.Result, bool) {
206 return d.op(homeop.Directory, homeop.DirectoryProvision, func(b homeop.InputBase) any {
207 return homeop.ProvisionInput{InputBase: b, Generation: d.gen, TeamSQID: sq, App: app, Consumer: consumer, Audience: audience}
208 })
209}
210
211func (d *driver) register(record []byte) (homeop.Result, bool) {
212 return d.op(homeop.Credential, homeop.CredentialRegister, func(b homeop.InputBase) any {
213 return homeop.RegisterInput{InputBase: b, Record: record}
214 })
215}
216
217// seedTeam runs owner-seed and seed-team at the proposed sqid.
218func (d *driver) seedTeam() (id int64, sq string) {
219 d.t.Helper()
220 id, sq = d.proposed()
221 d.openCreate(sq)
222 res := d.must(homeop.Credential, homeop.CredentialOwnerSeed, func(b homeop.InputBase) any {
223 return homeop.OwnerInput{InputBase: b, Directory: dirOrigin, TeamID: id, TeamSQID: sq, Address: ownerAddr, ExistingOnly: true}
224 })
225 d.must(homeop.Directory, homeop.DirectorySeedTeam, func(b homeop.InputBase) any {
226 return homeop.SeedInput{InputBase: b, Generation: d.gen, TeamID: id, TeamSQID: sq, Label: "oficina", Name: "Oficina", Receipt: res.Receipt}
227 })
228 return id, sq
229}
230
231func (d *driver) canonicalEnv() {
232 for _, a := range canonicalApps {
233 d.h.AddEnvConsumer(a, homeop.CanonicalOrigin(a))
234 }
235}
236
237func TestFakeHomeAdoptionScope(t *testing.T) {
238 t.Run("plans", func(t *testing.T) {
239 d := newDriver(t)
240 d.initialize()
241 _, sq := d.proposed()
242 dir := func(p homeop.Plan) int { return d.plan(homeop.Directory, p) }
243 cases := map[string]homeop.Plan{
244 "ordinary create-team under oficina": {Kind: homeop.KindCreateTeam, Apps: canonicalApps, Label: "oficina", DisplayName: "Oficina"},
245 "ordinary add-apps under oficina": {Kind: homeop.KindAddApps, Apps: []string{"docs"}, Label: "oficina"},
246 "existing team under another label": {Kind: homeop.KindCreateTeam, Apps: canonicalApps, Label: "acme", DisplayName: "Acme", ExistingTeam: sq},
247 "existing team on retire-apps": {Kind: homeop.KindRetireApps, Apps: []string{"docs"}, Label: "oficina", ExistingTeam: sq},
248 "existing team that is not a sqid": {Kind: homeop.KindCreateTeam, Apps: canonicalApps, Label: "oficina", DisplayName: "Oficina", ExistingTeam: "not a sqid"},
249 }
250 for name, p := range cases {
251 if s := dir(p); s != 403 {
252 t.Errorf("%s: plan answered %d, want 403", name, s)
253 }
254 }
255 if s := dir(homeop.Plan{Kind: homeop.KindCreateTeam, Apps: canonicalApps, Label: "oficina", DisplayName: "Oficina", ExistingTeam: sq}); s != 200 {
256 t.Errorf("adoption create-team plan answered %d, want 200", s)
257 }
258 })
259
260 t.Run("seed only at the proposed sqid", func(t *testing.T) {
261 d := newDriver(t)
262 d.initialize()
263 id, sq := d.proposed()
264 other := sqid(id + 1)
265 d.openCreate(other) // a plan for a sqid Home did not propose
266 // The owner receipt binds the proposed sqid, the plan another.
267 if _, ok := d.ownerSeed(id, sq, ownerAddr); ok {
268 t.Fatal("owner-seed at a sqid other than the plan's was committed")
269 }
270 res, ok := d.ownerSeed(id+1, other, ownerAddr)
271 if !ok {
272 t.Fatal("owner-seed at the plan's sqid refused")
273 }
274 if _, ok := d.seed(id+1, other, "oficina", res.Receipt); ok {
275 t.Fatal("seed-team committed at a sqid Home did not propose")
276 }
277 if d.h.TeamCount() != 0 {
278 t.Fatal("a team exists")
279 }
280 })
281
282 t.Run("seed at the proposed sqid", func(t *testing.T) {
283 d := newDriver(t)
284 d.initialize()
285 id, sq := d.seedTeam()
286 if got, gotSQ, ok := d.h.Team("oficina"); !ok || got != id || gotSQ != sq {
287 t.Fatalf("team %v %v %v", got, gotSQ, ok)
288 }
289 })
290
291 t.Run("seed refuses a label other than oficina", func(t *testing.T) {
292 d := newDriver(t)
293 d.initialize()
294 id, sq := d.proposed()
295 d.openCreate(sq)
296 res, _ := d.ownerSeed(id, sq, ownerAddr)
297 if _, ok := d.seed(id, sq, "acme", res.Receipt); ok {
298 t.Fatal("seed-team committed another label in an adoption window")
299 }
300 })
301
302 t.Run("provision admits only the canonical tuple", func(t *testing.T) {
303 d := newDriver(t)
304 d.initialize()
305 d.canonicalEnv()
306 _, sq := d.seedTeam()
307 for name, c := range map[string][3]string{
308 "ordinary consumer id": {"docs", "oficina-docs", "https://docs.oficina.works"},
309 "ordinary origin": {"docs", "docs", "https://oficina.docs.oficina.works"},
310 "another app's origin": {"docs", "docs", "https://sheets.oficina.works"},
311 "another app's id": {"docs", "sheets", "https://docs.oficina.works"},
312 "foreign origin": {"docs", "docs", "https://docs.example.test"},
313 } {
314 if _, ok := d.provision(sq, c[0], c[1], c[2]); ok {
315 t.Errorf("%s: provisioned", name)
316 }
317 }
318 if _, ok := d.provision("txxxa", "docs", "docs", "https://docs.oficina.works"); ok {
319 t.Error("provisioned under a sqid other than the plan's team")
320 }
321 if _, ok := d.provision(sq, "docs", "docs", "https://docs.oficina.works"); !ok {
322 t.Fatal("canonical provision refused")
323 }
324 if d.h.InstanceState("docs") != "pending" {
325 t.Fatalf("state %q", d.h.InstanceState("docs"))
326 }
327 })
328
329 t.Run("register verifies and inserts nothing", func(t *testing.T) {
330 d := newDriver(t)
331 d.initialize()
332 d.canonicalEnv()
333 _, sq := d.seedTeam()
334 res, ok := d.provision(sq, "docs", "docs", "https://docs.oficina.works")
335 if !ok {
336 t.Fatal("provision refused")
337 }
338 before := d.h.ConsumerCount()
339 got, ok := d.register(res.Record)
340 if !ok {
341 t.Fatal("register of the canonical record refused")
342 }
343 if d.h.ConsumerCount() != before || d.h.ConsumerState("docs") != "" {
344 t.Fatalf("register inserted a consumer: %d -> %d", before, d.h.ConsumerCount())
345 }
346 if want := d.h.manifest(); got.Manifest != want {
347 t.Fatalf("manifest %q, want the existing union %q", got.Manifest, want)
348 }
349 })
350
351 t.Run("register needs the env manifest entry", func(t *testing.T) {
352 d := newDriver(t)
353 d.initialize()
354 _, sq := d.seedTeam() // no canonical env entries
355 res, ok := d.provision(sq, "docs", "docs", "https://docs.oficina.works")
356 if !ok {
357 t.Fatal("provision refused")
358 }
359 if _, ok := d.register(res.Record); ok {
360 t.Fatal("register without an env manifest entry committed")
361 }
362 d.h.AddEnvConsumer("docs", "https://elsewhere.oficina.works")
363 if _, ok := d.register(res.Record); ok {
364 t.Fatal("register against an env entry with another origin committed")
365 }
366 })
367
368 t.Run("activation policy", func(t *testing.T) {
369 d := newDriver(t)
370 d.initialize()
371 d.canonicalEnv()
372 _, sq := d.seedTeam()
373 res, _ := d.provision(sq, "docs", "docs", "https://docs.oficina.works")
374 owner := d.h.People[ownerAddr]
375 d.must(homeop.Directory, homeop.DirectoryVerify, func(b homeop.InputBase) any {
376 return homeop.VerificationInput{InputBase: b, Consumer: "docs", TeamSQID: sq, App: "docs", Audience: "https://docs.oficina.works", Generation: d.gen, RecordSequence: 1, RecordDigest: homeop.Digest(res.Record), Epoch: res.Epoch, Owner: owner, Issued: d.now.Unix() - 60, Expires: d.now.Unix() + 300}
377 })
378 // The attempt id is the verify operation's id: the last committed one.
379 d.h.mu.Lock()
380 attempt := d.h.instances["docs"].attempt.id
381 d.h.mu.Unlock()
382 activate := func(policy string) bool {
383 _, ok := d.op(homeop.Directory, homeop.DirectoryActivate, func(b homeop.InputBase) any {
384 return homeop.ActivationInput{InputBase: b, Evidence: homeop.ActivationEvidence{Version: 1, Policy: policy, Attempt: attempt, Consumer: "docs", TeamSQID: sq, App: "docs", Audience: "https://docs.oficina.works", Generation: d.gen, RecordSequence: 1, RecordDigest: homeop.Digest(res.Record), Epoch: res.Epoch, Owner: owner, AppVersion: "v1", ArtifactDigest: homeop.Token(), EnvironmentBinding: homeop.Token(), ManifestDigest: homeop.Token(), AliasHost: "docs.oficina.works", Started: d.now.Unix() - 50, Completed: d.now.Unix() - 5}}
385 })
386 return ok
387 }
388 if activate(homeop.ActivationPolicy) {
389 t.Fatal("activation under oficina/team-activation/v1 committed in an adoption window")
390 }
391 if d.h.InstanceState("docs") != "pending" {
392 t.Fatal("refused activation changed state")
393 }
394 if !activate(homeop.ExistingActivationPolicy) {
395 t.Fatal("activation under the existing-app policy refused")
396 }
397 if d.h.InstanceState("docs") != "live" {
398 t.Fatalf("state %q", d.h.InstanceState("docs"))
399 }
400 })
401}
402
403// The window picks the policy both ways: an ordinary window keeps
404// oficina/team-activation/v1 and refuses the existing-app policy.
405func TestFakeHomeOrdinaryActivationPolicy(t *testing.T) {
406 d := newDriver(t)
407 d.initialize()
408 id, sq := d.proposed()
409 if s := d.plan(homeop.Credential, homeop.Plan{Kind: homeop.KindCreateTeam, Apps: []string{"docs"}, Owner: ownerAddr}); s != 200 {
410 t.Fatalf("credential plan %d", s)
411 }
412 if s := d.plan(homeop.Directory, homeop.Plan{Kind: homeop.KindCreateTeam, Apps: []string{"docs"}, Label: "acme", DisplayName: "Oficina"}); s != 200 {
413 t.Fatalf("directory plan %d", s)
414 }
415 if err := d.h.Confirm(homeop.Credential, ownerAddr); err != nil {
416 t.Fatal(err)
417 }
418 if err := d.h.Confirm(homeop.Directory, ""); err != nil {
419 t.Fatal(err)
420 }
421 owned, ok := d.ownerSeed(id, sq, ownerAddr)
422 if !ok {
423 t.Fatal("owner-seed")
424 }
425 if _, ok := d.seed(id, sq, "oficina", owned.Receipt); ok {
426 t.Fatal("an ordinary window seeded the oficina label")
427 }
428 if _, ok := d.seed(id, sq, "acme", owned.Receipt); !ok {
429 t.Fatal("seed")
430 }
431 if _, ok := d.provision(sq, "docs", "docs", "https://docs.oficina.works"); ok {
432 t.Fatal("an ordinary window provisioned a canonical tuple")
433 }
434 res, ok := d.provision(sq, "docs", "acme-docs", "https://acme.docs.oficina.works")
435 if !ok {
436 t.Fatal("ordinary provision refused")
437 }
438 owner := d.h.People[ownerAddr]
439 d.must(homeop.Directory, homeop.DirectoryVerify, func(b homeop.InputBase) any {
440 return homeop.VerificationInput{InputBase: b, Consumer: "acme-docs", TeamSQID: sq, App: "docs", Audience: "https://acme.docs.oficina.works", Generation: d.gen, RecordSequence: 1, RecordDigest: homeop.Digest(res.Record), Epoch: res.Epoch, Owner: owner, Issued: d.now.Unix() - 60, Expires: d.now.Unix() + 300}
441 })
442 d.h.mu.Lock()
443 attempt := d.h.instances["acme-docs"].attempt.id
444 d.h.mu.Unlock()
445 activate := func(policy string) bool {
446 _, ok := d.op(homeop.Directory, homeop.DirectoryActivate, func(b homeop.InputBase) any {
447 return homeop.ActivationInput{InputBase: b, Evidence: homeop.ActivationEvidence{Version: 1, Policy: policy, Attempt: attempt, Consumer: "acme-docs", TeamSQID: sq, App: "docs", Audience: "https://acme.docs.oficina.works", Generation: d.gen, RecordSequence: 1, RecordDigest: homeop.Digest(res.Record), Epoch: res.Epoch, Owner: owner, AppVersion: "v1", ArtifactDigest: homeop.Token(), EnvironmentBinding: homeop.Token(), ManifestDigest: homeop.Token(), AliasHost: "acme.docs.oficina.works", Started: d.now.Unix() - 50, Completed: d.now.Unix() - 5}}
448 })
449 return ok
450 }
451 if activate(homeop.ExistingActivationPolicy) {
452 t.Fatal("an ordinary window accepted oficina/existing-app-activation/v1")
453 }
454 if !activate(homeop.ActivationPolicy) {
455 t.Fatal("an ordinary window refused oficina/team-activation/v1")
456 }
457}
458
459func TestFakeHomeRequestsOrdered(t *testing.T) {
460 d := newDriver(t)
461 if got := d.h.Requests(); len(got) != 0 {
462 t.Fatalf("fresh Home has requests %v", got)
463 }
464 d.initialize()
465 d.canonicalEnv()
466 _, sq := d.seedTeam()
467 // A refused request is not a committed one.
468 if _, ok := d.provision(sq, "docs", "oficina-docs", "https://docs.oficina.works"); ok {
469 t.Fatal("non-canonical provision committed")
470 }
471 docs, ok := d.provision(sq, "docs", "docs", "https://docs.oficina.works")
472 if !ok {
473 t.Fatal("provision")
474 }
475 if _, ok := d.provision(sq, "calendar", "calendar", "https://calendar.oficina.works"); !ok {
476 t.Fatal("provision")
477 }
478 if _, ok := d.register(docs.Record); !ok {
479 t.Fatal("register")
480 }
481 // An exact replay returns the stored result and commits nothing new.
482 replay := d.sign(homeop.Directory, homeop.DirectoryProvision, func(b homeop.InputBase) any {
483 return homeop.ProvisionInput{InputBase: b, Generation: d.gen, TeamSQID: sq, App: "sheets", Consumer: "sheets", Audience: "https://sheets.oficina.works"}
484 })
485 if _, ok := d.send(homeop.Directory, replay); !ok {
486 t.Fatal("provision")
487 }
488 if _, ok := d.send(homeop.Directory, replay); !ok {
489 t.Fatal("replay refused")
490 }
491 want := []string{
492 "directory.initialize",
493 "credential.owner-seed",
494 "directory.seed-team",
495 "directory.provision-consumer:docs",
496 "directory.provision-consumer:calendar",
497 "credential.register-consumer:docs",
498 "directory.provision-consumer:sheets",
499 }
500 got := d.h.Requests()
501 if !slices.Equal(got, want) {
502 t.Fatalf("requests\n got %v\nwant %v", got, want)
503 }
504 got[0] = "tampered"
505 if d.h.Requests()[0] != "directory.initialize" {
506 t.Fatal("Requests returned the Home's own slice")
507 }
508}
509