package fakehome import ( "bytes" "io" "net/http" "net/http/httptest" "slices" "testing" "time" "amadan.net/oficina/alta/homeop" family "amadan.net/rastrillo/rastrillo/crypto" ) const ( credOrigin = "https://id.oficina.works" dirOrigin = "https://oficina.works" ownerAddr = "paul@example.test" ) var canonicalApps = []string{"docs", "sheets", "slides", "calendar", "calls", "memoria"} // driver is Alta's side of the two operator streams, as little of it as // these tests need: it signs, sends and tracks each role's sequence. type driver struct { t *testing.T h *Home key *family.Keypair pre string now time.Time srv map[string]*httptest.Server seq map[string]int64 head map[string]string gen string } func newDriver(t *testing.T) *driver { t.Helper() 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{}} d.key, _ = family.Generate() d.pre = homeop.Token() d.h = New(d.key.SignPub(), d.pre, credOrigin, dirOrigin, func() time.Time { return d.now }) d.h.AddPerson(ownerAddr) for _, r := range []string{homeop.Credential, homeop.Directory} { d.srv[r] = httptest.NewServer(d.h.Handler(r)) t.Cleanup(d.srv[r].Close) } return d } func (d *driver) post(role, path string, body []byte) (int, []byte) { d.t.Helper() req, _ := http.NewRequest(http.MethodPost, d.srv[role].URL+path, bytes.NewReader(body)) req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer "+d.pre) resp, err := http.DefaultClient.Do(req) if err != nil { d.t.Fatalf("transport error: %v", err) } defer resp.Body.Close() out, err := io.ReadAll(resp.Body) if err != nil { d.t.Fatalf("reading the answer: %v", err) } return resp.StatusCode, out } func (d *driver) pins(role string) homeop.Authorization { p := d.h.Pins(role) origin := dirOrigin if role == homeop.Credential { origin = credOrigin } return homeop.Authorization{Role: role, Origin: origin, Installation: p.Installation, Registry: p.Registry, Device: p.Device} } // plan signs and submits a plan, returning the HTTP status. func (d *driver) plan(role string, p homeop.Plan) int { d.t.Helper() a := d.pins(role) p.Role, p.Origin, p.Installation, p.Registry, p.Device = role, a.Origin, a.Installation, a.Registry, a.Device p.PlanID, p.Issued, p.Expires = homeop.Token(), d.now.Unix()-homeop.Skew, d.now.Unix()-homeop.Skew+homeop.PlanLifetime raw, err := homeop.SignPlan(d.key, p) if err != nil { d.t.Fatal(err) } status, _ := d.post(role, "/operator/v1/plan", raw) return status } // sign builds the next request on role's stream without sending it. func (d *driver) sign(role, action string, input func(homeop.InputBase) any) homeop.Request { d.t.Helper() a := d.pins(role) a.Sequence, a.JournalSequence = d.seq[role]+1, d.seq[role]+1 a.Previous = d.head[role] a.OperationID, a.Action = homeop.Token(), action a.Issued, a.Expires = d.now.Unix()-homeop.Skew, d.now.Unix()-homeop.Skew+homeop.RequestLifetime req, err := homeop.SignRequest(d.key, a, input(homeop.InputBase{Version: 1, Operation: action, OperationID: a.OperationID})) if err != nil { d.t.Fatal(err) } return req } // send posts req; a committed operation advances the stream. ok is false // only for Home's explicit refusal (403); any other status fails the test, // so a negative assertion cannot pass on a server fault. func (d *driver) send(role string, req homeop.Request) (homeop.Result, bool) { d.t.Helper() status, body := d.post(role, "/operator/v1", req.Bytes) switch status { case 200: case 403: return homeop.Result{}, false default: d.t.Fatalf("operation answered %d, want 200 or 403", status) } var res homeop.Result if err := homeop.Decode(body, &res); err != nil { d.t.Fatal(err) } if req.Authorization.Sequence == d.seq[role]+1 { d.seq[role], d.head[role] = req.Authorization.Sequence, req.Head } return res, true } func (d *driver) op(role, action string, input func(homeop.InputBase) any) (homeop.Result, bool) { d.t.Helper() return d.send(role, d.sign(role, action, input)) } func (d *driver) must(role, action string, input func(homeop.InputBase) any) homeop.Result { d.t.Helper() res, ok := d.op(role, action, input) if !ok { d.t.Fatalf("%s refused", action) } return res } // proposed is the team id and sqid the directory proposes next. func (d *driver) proposed() (int64, string) { d.t.Helper() a := d.pins(homeop.Directory) 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}) if err != nil { d.t.Fatal(err) } status, body := d.post(homeop.Directory, "/operator/v1", raw) var in homeop.Inspection if status != 200 || homeop.Decode(body, &in) != nil { d.t.Fatalf("inspect %d", status) } return in.TeamID, in.TeamSQID } func (d *driver) initialize() { d.t.Helper() if d.plan(homeop.Directory, homeop.Plan{Kind: homeop.KindInitialize}) != 200 { d.t.Fatal("initialize plan") } if err := d.h.Confirm(homeop.Directory, ""); err != nil { d.t.Fatal(err) } d.gen = homeop.Token() d.must(homeop.Directory, homeop.DirectoryInitialize, func(b homeop.InputBase) any { return homeop.InitializeInput{InputBase: b, Generation: d.gen, Baseline: homeop.Baseline} }) // Let initialize's window lapse, as it does between Alta's phases. d.now = d.now.Add((homeop.WindowLifetime + 1) * time.Second) } // openCreate submits and confirms the two create-team adoption plans. func (d *driver) openCreate(existing string) { d.t.Helper() if s := d.plan(homeop.Credential, homeop.Plan{Kind: homeop.KindCreateTeam, Apps: canonicalApps, Owner: ownerAddr, ExistingTeam: existing}); s != 200 { d.t.Fatalf("credential plan %d", s) } if s := d.plan(homeop.Directory, homeop.Plan{Kind: homeop.KindCreateTeam, Apps: canonicalApps, Label: "oficina", DisplayName: "Oficina", ExistingTeam: existing}); s != 200 { d.t.Fatalf("directory plan %d", s) } if err := d.h.Confirm(homeop.Credential, ownerAddr); err != nil { d.t.Fatal(err) } if err := d.h.Confirm(homeop.Directory, ""); err != nil { d.t.Fatal(err) } } func (d *driver) ownerSeed(id int64, sq, address string) (homeop.Result, bool) { return d.op(homeop.Credential, homeop.CredentialOwnerSeed, func(b homeop.InputBase) any { return homeop.OwnerInput{InputBase: b, Directory: dirOrigin, TeamID: id, TeamSQID: sq, Address: address, ExistingOnly: true} }) } func (d *driver) seed(id int64, sq, label string, receipt []byte) (homeop.Result, bool) { return d.op(homeop.Directory, homeop.DirectorySeedTeam, func(b homeop.InputBase) any { return homeop.SeedInput{InputBase: b, Generation: d.gen, TeamID: id, TeamSQID: sq, Label: label, Name: "Oficina", Receipt: receipt} }) } func (d *driver) provision(sq, app, consumer, audience string) (homeop.Result, bool) { return d.op(homeop.Directory, homeop.DirectoryProvision, func(b homeop.InputBase) any { return homeop.ProvisionInput{InputBase: b, Generation: d.gen, TeamSQID: sq, App: app, Consumer: consumer, Audience: audience} }) } func (d *driver) register(record []byte) (homeop.Result, bool) { return d.op(homeop.Credential, homeop.CredentialRegister, func(b homeop.InputBase) any { return homeop.RegisterInput{InputBase: b, Record: record} }) } // seedTeam runs owner-seed and seed-team at the proposed sqid. func (d *driver) seedTeam() (id int64, sq string) { d.t.Helper() id, sq = d.proposed() d.openCreate(sq) res := d.must(homeop.Credential, homeop.CredentialOwnerSeed, func(b homeop.InputBase) any { return homeop.OwnerInput{InputBase: b, Directory: dirOrigin, TeamID: id, TeamSQID: sq, Address: ownerAddr, ExistingOnly: true} }) d.must(homeop.Directory, homeop.DirectorySeedTeam, func(b homeop.InputBase) any { return homeop.SeedInput{InputBase: b, Generation: d.gen, TeamID: id, TeamSQID: sq, Label: "oficina", Name: "Oficina", Receipt: res.Receipt} }) return id, sq } func (d *driver) canonicalEnv() { for _, a := range canonicalApps { d.h.AddEnvConsumer(a, homeop.CanonicalOrigin(a)) } } func TestFakeHomeAdoptionScope(t *testing.T) { t.Run("plans", func(t *testing.T) { d := newDriver(t) d.initialize() _, sq := d.proposed() dir := func(p homeop.Plan) int { return d.plan(homeop.Directory, p) } cases := map[string]homeop.Plan{ "ordinary create-team under oficina": {Kind: homeop.KindCreateTeam, Apps: canonicalApps, Label: "oficina", DisplayName: "Oficina"}, "ordinary add-apps under oficina": {Kind: homeop.KindAddApps, Apps: []string{"docs"}, Label: "oficina"}, "existing team under another label": {Kind: homeop.KindCreateTeam, Apps: canonicalApps, Label: "acme", DisplayName: "Acme", ExistingTeam: sq}, "existing team on retire-apps": {Kind: homeop.KindRetireApps, Apps: []string{"docs"}, Label: "oficina", ExistingTeam: sq}, "existing team that is not a sqid": {Kind: homeop.KindCreateTeam, Apps: canonicalApps, Label: "oficina", DisplayName: "Oficina", ExistingTeam: "not a sqid"}, } for name, p := range cases { if s := dir(p); s != 403 { t.Errorf("%s: plan answered %d, want 403", name, s) } } if s := dir(homeop.Plan{Kind: homeop.KindCreateTeam, Apps: canonicalApps, Label: "oficina", DisplayName: "Oficina", ExistingTeam: sq}); s != 200 { t.Errorf("adoption create-team plan answered %d, want 200", s) } }) t.Run("seed only at the proposed sqid", func(t *testing.T) { d := newDriver(t) d.initialize() id, sq := d.proposed() other := sqid(id + 1) d.openCreate(other) // a plan for a sqid Home did not propose // The owner receipt binds the proposed sqid, the plan another. if _, ok := d.ownerSeed(id, sq, ownerAddr); ok { t.Fatal("owner-seed at a sqid other than the plan's was committed") } res, ok := d.ownerSeed(id+1, other, ownerAddr) if !ok { t.Fatal("owner-seed at the plan's sqid refused") } if _, ok := d.seed(id+1, other, "oficina", res.Receipt); ok { t.Fatal("seed-team committed at a sqid Home did not propose") } if d.h.TeamCount() != 0 { t.Fatal("a team exists") } }) t.Run("seed at the proposed sqid", func(t *testing.T) { d := newDriver(t) d.initialize() id, sq := d.seedTeam() if got, gotSQ, ok := d.h.Team("oficina"); !ok || got != id || gotSQ != sq { t.Fatalf("team %v %v %v", got, gotSQ, ok) } }) t.Run("seed refuses a label other than oficina", func(t *testing.T) { d := newDriver(t) d.initialize() id, sq := d.proposed() d.openCreate(sq) res, _ := d.ownerSeed(id, sq, ownerAddr) if _, ok := d.seed(id, sq, "acme", res.Receipt); ok { t.Fatal("seed-team committed another label in an adoption window") } }) t.Run("provision admits only the canonical tuple", func(t *testing.T) { d := newDriver(t) d.initialize() d.canonicalEnv() _, sq := d.seedTeam() for name, c := range map[string][3]string{ "ordinary consumer id": {"docs", "oficina-docs", "https://docs.oficina.works"}, "ordinary origin": {"docs", "docs", "https://oficina.docs.oficina.works"}, "another app's origin": {"docs", "docs", "https://sheets.oficina.works"}, "another app's id": {"docs", "sheets", "https://docs.oficina.works"}, "foreign origin": {"docs", "docs", "https://docs.example.test"}, } { if _, ok := d.provision(sq, c[0], c[1], c[2]); ok { t.Errorf("%s: provisioned", name) } } if _, ok := d.provision("txxxa", "docs", "docs", "https://docs.oficina.works"); ok { t.Error("provisioned under a sqid other than the plan's team") } if _, ok := d.provision(sq, "docs", "docs", "https://docs.oficina.works"); !ok { t.Fatal("canonical provision refused") } if d.h.InstanceState("docs") != "pending" { t.Fatalf("state %q", d.h.InstanceState("docs")) } }) t.Run("register verifies and inserts nothing", func(t *testing.T) { d := newDriver(t) d.initialize() d.canonicalEnv() _, sq := d.seedTeam() res, ok := d.provision(sq, "docs", "docs", "https://docs.oficina.works") if !ok { t.Fatal("provision refused") } before := d.h.ConsumerCount() got, ok := d.register(res.Record) if !ok { t.Fatal("register of the canonical record refused") } if d.h.ConsumerCount() != before || d.h.ConsumerState("docs") != "" { t.Fatalf("register inserted a consumer: %d -> %d", before, d.h.ConsumerCount()) } if want := d.h.manifest(); got.Manifest != want { t.Fatalf("manifest %q, want the existing union %q", got.Manifest, want) } }) t.Run("register needs the env manifest entry", func(t *testing.T) { d := newDriver(t) d.initialize() _, sq := d.seedTeam() // no canonical env entries res, ok := d.provision(sq, "docs", "docs", "https://docs.oficina.works") if !ok { t.Fatal("provision refused") } if _, ok := d.register(res.Record); ok { t.Fatal("register without an env manifest entry committed") } d.h.AddEnvConsumer("docs", "https://elsewhere.oficina.works") if _, ok := d.register(res.Record); ok { t.Fatal("register against an env entry with another origin committed") } }) t.Run("activation policy", func(t *testing.T) { d := newDriver(t) d.initialize() d.canonicalEnv() _, sq := d.seedTeam() res, _ := d.provision(sq, "docs", "docs", "https://docs.oficina.works") owner := d.h.People[ownerAddr] d.must(homeop.Directory, homeop.DirectoryVerify, func(b homeop.InputBase) any { 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} }) // The attempt id is the verify operation's id: the last committed one. d.h.mu.Lock() attempt := d.h.instances["docs"].attempt.id d.h.mu.Unlock() activate := func(policy string) bool { _, ok := d.op(homeop.Directory, homeop.DirectoryActivate, func(b homeop.InputBase) any { 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}} }) return ok } if activate(homeop.ActivationPolicy) { t.Fatal("activation under oficina/team-activation/v1 committed in an adoption window") } if d.h.InstanceState("docs") != "pending" { t.Fatal("refused activation changed state") } if !activate(homeop.ExistingActivationPolicy) { t.Fatal("activation under the existing-app policy refused") } if d.h.InstanceState("docs") != "live" { t.Fatalf("state %q", d.h.InstanceState("docs")) } }) } // The window picks the policy both ways: an ordinary window keeps // oficina/team-activation/v1 and refuses the existing-app policy. func TestFakeHomeOrdinaryActivationPolicy(t *testing.T) { d := newDriver(t) d.initialize() id, sq := d.proposed() if s := d.plan(homeop.Credential, homeop.Plan{Kind: homeop.KindCreateTeam, Apps: []string{"docs"}, Owner: ownerAddr}); s != 200 { t.Fatalf("credential plan %d", s) } if s := d.plan(homeop.Directory, homeop.Plan{Kind: homeop.KindCreateTeam, Apps: []string{"docs"}, Label: "acme", DisplayName: "Oficina"}); s != 200 { t.Fatalf("directory plan %d", s) } if err := d.h.Confirm(homeop.Credential, ownerAddr); err != nil { t.Fatal(err) } if err := d.h.Confirm(homeop.Directory, ""); err != nil { t.Fatal(err) } owned, ok := d.ownerSeed(id, sq, ownerAddr) if !ok { t.Fatal("owner-seed") } if _, ok := d.seed(id, sq, "oficina", owned.Receipt); ok { t.Fatal("an ordinary window seeded the oficina label") } if _, ok := d.seed(id, sq, "acme", owned.Receipt); !ok { t.Fatal("seed") } if _, ok := d.provision(sq, "docs", "docs", "https://docs.oficina.works"); ok { t.Fatal("an ordinary window provisioned a canonical tuple") } res, ok := d.provision(sq, "docs", "acme-docs", "https://acme.docs.oficina.works") if !ok { t.Fatal("ordinary provision refused") } owner := d.h.People[ownerAddr] d.must(homeop.Directory, homeop.DirectoryVerify, func(b homeop.InputBase) any { 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} }) d.h.mu.Lock() attempt := d.h.instances["acme-docs"].attempt.id d.h.mu.Unlock() activate := func(policy string) bool { _, ok := d.op(homeop.Directory, homeop.DirectoryActivate, func(b homeop.InputBase) any { 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}} }) return ok } if activate(homeop.ExistingActivationPolicy) { t.Fatal("an ordinary window accepted oficina/existing-app-activation/v1") } if !activate(homeop.ActivationPolicy) { t.Fatal("an ordinary window refused oficina/team-activation/v1") } } func TestFakeHomeRequestsOrdered(t *testing.T) { d := newDriver(t) if got := d.h.Requests(); len(got) != 0 { t.Fatalf("fresh Home has requests %v", got) } d.initialize() d.canonicalEnv() _, sq := d.seedTeam() // A refused request is not a committed one. if _, ok := d.provision(sq, "docs", "oficina-docs", "https://docs.oficina.works"); ok { t.Fatal("non-canonical provision committed") } docs, ok := d.provision(sq, "docs", "docs", "https://docs.oficina.works") if !ok { t.Fatal("provision") } if _, ok := d.provision(sq, "calendar", "calendar", "https://calendar.oficina.works"); !ok { t.Fatal("provision") } if _, ok := d.register(docs.Record); !ok { t.Fatal("register") } // An exact replay returns the stored result and commits nothing new. replay := d.sign(homeop.Directory, homeop.DirectoryProvision, func(b homeop.InputBase) any { return homeop.ProvisionInput{InputBase: b, Generation: d.gen, TeamSQID: sq, App: "sheets", Consumer: "sheets", Audience: "https://sheets.oficina.works"} }) if _, ok := d.send(homeop.Directory, replay); !ok { t.Fatal("provision") } if _, ok := d.send(homeop.Directory, replay); !ok { t.Fatal("replay refused") } want := []string{ "directory.initialize", "credential.owner-seed", "directory.seed-team", "directory.provision-consumer:docs", "directory.provision-consumer:calendar", "credential.register-consumer:docs", "directory.provision-consumer:sheets", } got := d.h.Requests() if !slices.Equal(got, want) { t.Fatalf("requests\n got %v\nwant %v", got, want) } got[0] = "tampered" if d.h.Requests()[0] != "directory.initialize" { t.Fatal("Requests returned the Home's own slice") } }