package altacompat // Alta's engine against Home's real operator engine (internal/operator at // the pinned commit): the verifier, the canonical-bytes check, the stream, // the plan store and its windows, the provenance fence, owner-seed, // seed-team, provision, register (with the record verified under the // pinned provisioning key), verify, activate, disable and retire, and // both inspects. The HTTP transport below mirrors internal/home // operator_http.go's routing and fixed outcomes; Home's own tests cover // that transport, which needs the whole Home app to construct. import ( "bytes" "context" "crypto/hmac" "crypto/sha256" "database/sql" "encoding/base64" "encoding/hex" "errors" "io" "log/slog" "net/http" "net/http/httptest" "path/filepath" "strings" "testing" "time" "amadan.net/oficina/alta/console" "amadan.net/oficina/alta/console/fakeconsole" "amadan.net/oficina/alta/homeop" "amadan.net/oficina/alta/provision" sharedseal "amadan.net/oficina/home/handoff/seal" "amadan.net/oficina/home/internal/home/directorydata" "amadan.net/oficina/home/internal/operator" "amadan.net/oficina/home/roster" "amadan.net/rastrillo/rastrillo/assertion" family "amadan.net/rastrillo/rastrillo/crypto" rdb "amadan.net/rastrillo/rastrillo/db" "amadan.net/rastrillo/rastrillo/migrate" ) const ( credOrigin = "https://id.oficina.works" dirOrigin = "https://oficina.works" owner = "till-canary@lagged.test" account = "bds" ) var apps = []string{"docs", "sheets", "slides", "calendar", "calls", "memoria"} var adoptionApps = append(append([]string(nil), apps...), "equipo", "base") type home struct { now time.Time pepper []byte prefilter [32]byte dirPlans *operator.PlanStore credPlans *operator.PlanStore directory *operator.Directory credential *operator.CredentialHTTP dirV *operator.Verifier credV *operator.Verifier provPub string dirDB *sql.DB credDB *sql.DB } func open(t *testing.T, set *migrate.Set) *sql.DB { t.Helper() h, err := rdb.Open(filepath.Join(t.TempDir(), "role.db"), nil) if err != nil { t.Fatal(err) } t.Cleanup(func() { h.Close() }) if _, err := migrate.Apply(context.Background(), h, set); err != nil { t.Fatal(err) } return h.Writer() } // newHome builds both roles. extraEnv adds HOME_CONSUMERS entries (the // six canonical consumers, for adoption). func newHome(t *testing.T, alta *family.Keypair, prefilter string, installation, registry, device string, extraEnv map[string]string) *home { t.Helper() h := &home{now: time.Unix(2_000_000_000, 0), pepper: bytes.Repeat([]byte{9}, 32)} raw, _ := base64.RawURLEncoding.DecodeString(prefilter) h.prefilter = sha256.Sum256(raw) clock := func() time.Time { return h.now } sealer, err := sharedseal.New(bytes.Repeat([]byte{6}, 32), "oficina/operator") if err != nil { t.Fatal(err) } altaPub := base64.RawURLEncoding.EncodeToString(alta.SignPub()) ownerKey, _ := family.Generate() prov, _ := family.Generate() page, _ := family.Generate() browser, _ := family.Generate() h.provPub = base64.RawURLEncoding.EncodeToString(prov.SignPub()) // The directory role. // The directory's serving schema at the pinned commit // (internal/home runtime.go ServingSchema): since 7bdddfa it includes // the Team page's set, whose memberships.added_at seed-team writes. h.dirDB = open(t, migrate.Merge(directorydata.Schema, directorydata.RosterSchema, directorydata.OperatorSchema, operator.DirectorySchema, operator.DirectoryHTTPSchema, directorydata.TeamSchema)) h.dirV, err = operator.NewVerifier(operator.Pins{Role: "directory", Origin: dirOrigin, Installation: installation, Registry: registry, Device: device, PublicKey: altaPub, Actions: []string{"directory.inspect", "directory.initialize", "directory.seed-team", "directory.provision-consumer", "directory.verify-consumer", "directory.activate-consumer", "directory.disable-consumer"}}) if err != nil { t.Fatal(err) } de, err := operator.NewEngine(h.dirDB, h.dirV, sealer, bytes.Repeat([]byte{7}, 32), clock) if err != nil { t.Fatal(err) } ov, err := operator.NewOwnerVerifier(base64.RawURLEncoding.EncodeToString(ownerKey.SignPub()), credOrigin, dirOrigin) if err != nil { t.Fatal(err) } // internal/home directory_runtime.go directoryRouteAllowed: the reserved // label admits only the canonical binding; every other label its own host. route := func(r directorydata.Route) bool { if r.Label == "oficina" { return directorydata.CanonicalBinding(r.Label, r.App, r.ConsumerID, r.Origin) } return r.Origin == "https://"+r.Label+"."+r.App+".oficina.works" } h.directory, err = operator.NewDirectory(de, ov, prov, []roster.Key{{ID: "page1", Public: base64.RawURLEncoding.EncodeToString(page.SignPub())}}, directorydata.Config{Apps: adoptionApps, ValidateRoute: route}) if err != nil { t.Fatal(err) } if h.dirPlans, err = operator.NewPlanStore(h.dirDB, "directory", sealer); err != nil { t.Fatal(err) } // The credential role. h.credDB = open(t, migrate.Merge(operator.CredentialSchema, operator.CredentialHTTPSchema)) if _, err := h.credDB.Exec("CREATE TABLE people(person_ref TEXT PRIMARY KEY, blind_index TEXT UNIQUE)"); err != nil { t.Fatal(err) } if _, err := h.credDB.Exec("INSERT INTO people VALUES('pr_aaaaaaaaaaaaaaaaaaaaaaaaaa',?)", h.index(owner)); err != nil { t.Fatal(err) } h.credV, err = operator.NewVerifier(operator.Pins{Role: "credential", Origin: credOrigin, Installation: installation, Registry: registry, Device: device, PublicKey: altaPub, Actions: []string{"credential.inspect", "credential.owner-seed", "credential.register-consumer", "credential.retire-consumer"}}) if err != nil { t.Fatal(err) } ce, err := operator.NewEngine(h.credDB, h.credV, sealer, bytes.Repeat([]byte{8}, 32), clock) if err != nil { t.Fatal(err) } resolve := func(ctx context.Context, c *sql.Conn, address string, existing bool, _ time.Time) (string, bool, error) { var ref string err := c.QueryRowContext(ctx, "SELECT person_ref FROM people WHERE blind_index=?", h.index(address)).Scan(&ref) if errors.Is(err, sql.ErrNoRows) { return "", false, nil } return ref, err == nil, err } cred, err := operator.NewCredential(ce, dirOrigin, ownerKey, [][]byte{browser.SignPub()}, resolve) if err != nil { t.Fatal(err) } keys := map[string][]byte{"k1": browser.SignPub()} admit := func(id, origin string) bool { _, err := assertion.NewVerifier(credOrigin, origin, keys) return err == nil && id != "" } env := map[string]string{"directory": dirOrigin, "alta": "https://alta-x.bds.oncarlos.com"} for id, origin := range extraEnv { env[id] = origin } if h.credential, err = operator.NewCredentialHTTP(cred, h.provPub, env, adoptionApps, h.index, admit); err != nil { t.Fatal(err) } if h.credPlans, err = operator.NewPlanStore(h.credDB, "credential", sealer); err != nil { t.Fatal(err) } return h } func (h *home) index(address string) string { m := hmac.New(sha256.New, h.pepper) m.Write([]byte(strings.ToLower(address))) return hex.EncodeToString(m.Sum(nil)) } // handler mirrors internal/home operator_http.go's handleOperator. func (h *home) handler(role string) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { answer := func(status int, code string) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) _, _ = io.WriteString(w, `{"outcome":"`+code+`"}`) } if r.Method != http.MethodPost || (r.URL.Path != "/operator/v1" && r.URL.Path != "/operator/v1/plan") { answer(404, "not_found") return } if len(r.Header.Values("Cookie")) > 0 || len(r.Header.Values("Origin")) > 0 || r.Header.Get("Content-Type") != "application/json" { answer(403, "browser") return } tok, err := base64.RawURLEncoding.Strict().DecodeString(strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")) if err != nil || sha256.Sum256(tok) != h.prefilter { answer(401, "prefilter") return } body, _ := io.ReadAll(io.LimitReader(r.Body, operator.BodyLimit+1)) v, plans := h.dirV, h.dirPlans if role == "credential" { v, plans = h.credV, h.credPlans } result := func(out []byte, err error) { switch { case err == nil: w.Header().Set("Content-Type", "application/json") _, _ = w.Write(out) case errors.Is(err, operator.ErrRefused): answer(403, "refused") default: answer(503, "unavailable") } } if r.URL.Path == "/operator/v1/plan" { p, err := v.VerifyPlan(body, adoptionApps, h.now) if err != nil { answer(403, "refused") return } index := "" if role == "credential" && p.Owner != "" { index = h.index(p.Owner) var one int if h.credDB.QueryRow("SELECT 1 FROM people WHERE blind_index=?", index).Scan(&one) != nil { answer(403, "refused") return } } err = plans.Submit(context.Background(), p, index, h.now) if errors.Is(err, operator.ErrBusy) { answer(409, "busy") return } result([]byte(`{"outcome":"pending"}`), err) return } if _, err := v.Verify(body); err == nil { if role == "directory" { result(h.directory.ExecuteHTTP(r.Context(), body)) } else { result(h.credential.ExecuteHTTP(r.Context(), body)) } return } if role == "directory" { result(h.directory.InspectHTTP(r.Context(), body)) } else { result(h.credential.InspectHTTP(r.Context(), body)) } }) } // confirm is Paul on Home's confirm pages: Home's own copy of the pending // plan, the credential role comparing the typed owner's blind index. func (h *home) confirm(t *testing.T, role, typed string) operator.PlanView { t.Helper() plans := h.dirPlans if role == "credential" { plans = h.credPlans } p, err := plans.Pending(context.Background(), h.now) if err != nil { t.Fatalf("%s: no pending plan: %v", role, err) } v, err := plans.Open(context.Background(), p.ID, h.now, func(v operator.PlanView) bool { return role == "directory" || v.OwnerIndex == "" || hmac.Equal([]byte(v.OwnerIndex), []byte(h.index(typed))) }) if err != nil { t.Fatalf("%s: confirm: %v", role, err) } return v } type rig struct { home *home con *fakeconsole.Console engine *provision.Engine cfg provision.Config // engine's, for an engine with an Observer store *provision.Store client *homeop.Client } func newRig(t *testing.T) *rig { return newRigWith(t, nil, nil) } // newRigWith is newRig over a Home whose env manifest also holds // extraEnv, with the engine's AfterAct hook. func newRigWith(t *testing.T, extraEnv map[string]string, afterAct func(string) error) *rig { t.Helper() alta, _ := family.Generate() pre, inst, reg, dev := homeop.Token(), homeop.Token(), homeop.Token(), homeop.Token() h := newHome(t, alta, pre, inst, reg, dev, extraEnv) dir := httptest.NewServer(h.handler("directory")) cred := httptest.NewServer(h.handler("credential")) t.Cleanup(dir.Close) t.Cleanup(cred.Close) con := fakeconsole.New(account, "alta") t.Cleanup(con.Close) tokens := map[string]string{} for _, a := range provision.Apps { tokens[a.Slug] = con.Mint(a.Slug) // A git-describe stamp, as the apps' Makefiles write: Home // (0cee9ba) activates on an observed token, not only a commit. con.Versions[a.Slug] = "v0.1.7-3-gabc1234" con.MailPrefix[a.Slug] = a.MailPrefixes[0] } con.Relay["calls"] = true db, err := provision.OpenDB(filepath.Join(t.TempDir(), "alta.db")) if err != nil { t.Fatal(err) } t.Cleanup(func() { db.Close() }) clock := func() time.Time { return h.now } store, err := provision.NewStore(context.Background(), db, bytes.Repeat([]byte{4}, 32), clock) if err != nil { t.Fatal(err) } roles := map[string]homeop.Role{ "credential": {Name: "credential", Origin: credOrigin, URL: cred.URL, Installation: inst, Registry: reg, Device: dev}, "directory": {Name: "directory", Origin: dirOrigin, URL: dir.URL, Installation: inst, Registry: reg, Device: dev}, } client := &homeop.Client{Key: alta, Prefilter: pre, Roles: roles, Now: clock} cfg := provision.Config{Store: store, Home: client, Console: &console.Client{Base: con.URL(), Account: account, Tokens: tokens, Guard: provision.Guard{Store: store, Account: account}}, Public: &http.Client{Transport: con.Transport()}, HomeCfg: provision.HomeConfig{Issuer: credOrigin, Directory: dirOrigin, KeysBase64: "eyJrMSI6IkJBPT0ifQ==", Provisioner: h.provPub}, Account: account, Now: clock, Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), AfterAct: afterAct, Debug: func(err error) { t.Logf("transient: %v", err) }} return &rig{home: h, con: con, engine: provision.New(cfg), cfg: cfg, store: store, client: client} } func (r *rig) drive(t *testing.T, run int64) provision.Run { t.Helper() var out provision.Run for i := 0; i < 40; i++ { _ = r.engine.Advance(context.Background(), run) out, _ = r.store.Run(context.Background(), run) if out.State == "done" || out.State == "failed" { return out } r.con.Walk() r.home.now = r.home.now.Add(3 * time.Second) } return out } // TestAltaAgainstHomesRealOperator runs Alta's first production run and a // whole team through Home's real code: initialize; create-team for all // six apps (Docs through verify and activate); add-apps after the window // closes; then retire. func TestAltaAgainstHomesRealOperator(t *testing.T) { r := newRig(t) ctx := context.Background() run, err := r.engine.StartInitialize(ctx, provision.InitializeAttestation) if err != nil { t.Fatal(err) } r.home.confirm(t, "directory", "") if got := r.drive(t, run); got.State != "done" { t.Fatalf("initialize: %s %s", got.State, got.Code) } // Home keeps the initialize window open until it expires; a second // confirm before then is 409. r.home.now = r.home.now.Add(homeop.WindowLifetime * time.Second) run, err = r.engine.CreateTeam(ctx, provision.NewTeam{Label: "lagged", Name: "Lagged", Owner: owner, Apps: apps}) if err != nil { t.Fatal(err) } r1, _ := r.store.Run(ctx, run) dv := r.home.confirm(t, "directory", "") cv := r.home.confirm(t, "credential", owner) // Home's own copy, as Paul reads it on both pages. if dv.Prefix() != homeop.PlanPrefix(r1.PlanID) || cv.Prefix() != dv.Prefix() || dv.Label != "lagged" || dv.DisplayName != "Lagged" || len(dv.Apps) != 6 || cv.OwnerIndex != r.home.index(owner) { t.Fatalf("Home's copy: %+v / %+v", dv, cv) } if got := r.drive(t, run); got.State != "done" { steps, _ := r.store.Steps(ctx, "lagged") t.Fatalf("create-team: %s %s %+v", got.State, got.Code, steps) } var state string if err := r.home.dirDB.QueryRow("SELECT state FROM team_instances WHERE consumer_id='lagged-docs'").Scan(&state); err != nil || state != "live" { t.Fatalf("docs at the directory: %q %v", state, err) } if err := r.home.dirDB.QueryRow("SELECT state FROM team_instances WHERE consumer_id='lagged-sheets'").Scan(&state); err != nil || state != "live" { t.Fatalf("sheets at the directory: %q %v", state, err) } if err := r.home.dirDB.QueryRow("SELECT state FROM team_instances WHERE consumer_id='lagged-slides'").Scan(&state); err != nil || state != "live" { t.Fatalf("slides at the directory: %q %v", state, err) } if err := r.home.dirDB.QueryRow("SELECT state FROM team_instances WHERE consumer_id='lagged-memoria'").Scan(&state); err != nil || state != "live" { t.Fatalf("memoria at the directory: %q %v", state, err) } if err := r.home.dirDB.QueryRow("SELECT state FROM team_instances WHERE consumer_id='lagged-calendar'").Scan(&state); err != nil || state != "live" { t.Fatalf("calendar at the directory: %q %v", state, err) } // Every app has roster mode: all six are live at the directory. var live int if err := r.home.dirDB.QueryRow("SELECT count(*) FROM team_instances WHERE state='live'").Scan(&live); err != nil || live != 6 { t.Fatalf("live at the directory: %d %v", live, err) } var n int _ = r.home.credDB.QueryRow("SELECT count(*) FROM consumers WHERE state='active'").Scan(&n) if n != 6 { t.Fatalf("credential consumers %d", n) } // Alta's manifest digest is Home's. table, _ := operator.ActiveConsumers(ctx, r.home.credDB) union := map[string]string{"directory": dirOrigin, "alta": "https://alta-x.bds.oncarlos.com"} for id, o := range table { union[id] = o } want, _ := operator.ManifestDigest(union) if got := homeop.ManifestDigest(union); got != want { t.Fatalf("manifest digest %s, Home's %s", got, want) } // Docs' environment carries a record Docs itself would accept: the // one Home signed, under the key Alta pinned. vars, _, _ := r.con.Env("docs", "lagged") rec, _ := base64.StdEncoding.DecodeString(vars["DOCS_TEAM_PROVISIONING_BASE64"].Value) keys, _ := base64.StdEncoding.DecodeString(vars["DOCS_TEAM_OPERATOR_KEYS_BASE64"].Value) if _, err := roster.VerifyProvisioning(rec, provision.ProvisionerKeys(r.home.provPub), roster.Bindings{Issuer: credOrigin, Directory: dirOrigin, Consumer: "lagged-docs", App: "docs", Team: vars["DOCS_TEAM_ID"].Value, Audience: "https://lagged.docs.oficina.works"}); err != nil || !strings.Contains(string(keys), r.home.provPub) { t.Fatalf("docs record: %v", err) } // Alta's stream is Home's. for _, role := range []string{"directory", "credential"} { seq, head, _, _ := r.store.Stream(ctx, role) db := r.home.dirDB if role == "credential" { db = r.home.credDB } var hs int64 var hh string _ = db.QueryRow("SELECT sequence,head FROM "+role+"_operator_state WHERE singleton=1").Scan(&hs, &hh) if seq != hs || head != hh { t.Fatalf("%s stream: Alta %d/%s, Home %d/%s", role, seq, head, hs, hh) } } // Retire Calls: disable at the directory, retire at the credential // origin, detach, delete. r.home.now = r.home.now.Add(homeop.WindowLifetime * time.Second) run, err = r.engine.RetireApps(ctx, "lagged", []string{"calls"}, "lagged") if err != nil { t.Fatal(err) } r.home.confirm(t, "directory", "") r.home.confirm(t, "credential", "") if got := r.drive(t, run); got.State != "done" { t.Fatalf("retire: %s %s", got.State, got.Code) } if err := r.home.dirDB.QueryRow("SELECT state FROM team_instances WHERE consumer_id='lagged-calls'").Scan(&state); err != nil || state != "disabled" { t.Fatalf("calls at the directory: %q", state) } if err := r.home.credDB.QueryRow("SELECT state FROM consumers WHERE consumer_id='lagged-calls'").Scan(&state); err != nil || state != "retired" { t.Fatalf("calls at the credential origin: %q", state) } } // TestHomeRefusesWhatAltaMustNotDo checks the fences hold on Home's side // for requests Alta signs correctly: no window, a label outside the // window, an unknown owner. func TestHomeRefusesWhatAltaMustNotDo(t *testing.T) { r := newRig(t) ctx := context.Background() run, _ := r.engine.StartInitialize(ctx, provision.InitializeAttestation) // Not confirmed: no window, nothing happens at Home. if got := r.drive(t, run); got.State == "done" { t.Fatal("initialized without a window") } var n int _ = r.home.dirDB.QueryRow("SELECT count(*) FROM roster_generation").Scan(&n) if n != 0 { t.Fatal("generation written without a window") } r.home.confirm(t, "directory", "") if got := r.drive(t, run); got.State != "done" { t.Fatalf("initialize: %s %s", got.State, got.Code) } r.home.now = r.home.now.Add(homeop.WindowLifetime * time.Second) if _, err := r.engine.CreateTeam(ctx, provision.NewTeam{Label: "alpha", Name: "Alpha", Owner: "nobody@nowhere.test", Apps: []string{"docs"}}); err == nil { t.Fatal("Home accepted a plan for an owner who never signed in") } } // TestSeededAppsAgainstHomesRealOperator: an own team with Equipo and Base // (oficina/alta design/team-bundle) reaches live at Home's real directory. // The seeded apps carry no roster record; Home's activation takes Alta's // evidence for them as it does for a roster app (spec ยง1.2). func TestSeededAppsAgainstHomesRealOperator(t *testing.T) { r := newRig(t) ctx := context.Background() run, err := r.engine.StartInitialize(ctx, provision.InitializeAttestation) if err != nil { t.Fatal(err) } r.home.confirm(t, "directory", "") if got := r.drive(t, run); got.State != "done" { t.Fatalf("initialize: %s %s", got.State, got.Code) } r.home.now = r.home.now.Add(homeop.WindowLifetime * time.Second) bundle := append(append([]string{}, apps...), "equipo", "base") run, err = r.engine.CreateTeam(ctx, provision.NewTeam{Label: "campbells", Name: "Campbells", Owner: owner, Apps: bundle, Options: provision.RunOptions{Profile: provision.ProfileOwn}}) if err != nil { t.Fatal(err) } r.home.confirm(t, "directory", "") r.home.confirm(t, "credential", owner) if got := r.drive(t, run); got.State != "done" { steps, _ := r.store.Steps(ctx, "campbells") t.Fatalf("create-team: %s %s %+v", got.State, got.Code, steps) } for _, id := range []string{"campbells-equipo", "campbells-base"} { var state string if err := r.home.dirDB.QueryRow("SELECT state FROM team_instances WHERE consumer_id=?", id).Scan(&state); err != nil || state != "live" { t.Fatalf("%s at the directory: %q %v", id, state, err) } } var live int if err := r.home.dirDB.QueryRow("SELECT count(*) FROM team_instances WHERE state='live'").Scan(&live); err != nil || live != len(bundle) { t.Fatalf("live at the directory: %d %v", live, err) } }