// Package fakehome is an in-memory stand-in for Home's two operator // endpoints (POST /operator/v1 and /operator/v1/plan on each role), with // Paul's confirm ceremony as a method call. It keeps Home's rules that // Alta's state machine depends on: pinned signature, canonical bytes, // sequence = previous + 1, exact replay returning the stored result even // after expiry, refusals that never consume a sequence, one pending and // one open plan per role, windows that admit only their kind's verbs, the // provenance fence, owner receipts that expire, signed provisioning // records and the manifest digest. // // It is a fake: the homecompat module runs Alta against Home's real // engine. This one exists for speed, crash injection and fault paths // Home's real code makes awkward to reach (a lost answer after commit). package fakehome import ( "bytes" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/hex" "errors" "io" "net/http" "net/url" "regexp" "slices" "strings" "sync" "time" "amadan.net/oficina/alta/homeop" "amadan.net/oficina/home/roster" family "amadan.net/rastrillo/rastrillo/crypto" "github.com/go-json-experiment/json/jsontext" ) // observedVersion is Home's app_version rule (0cee9ba). var observedVersion = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$`) var registry = []string{"docs", "sheets", "slides", "calendar", "calls", "memoria", "equipo", "base"} type plan struct { id, kind, label, name, owner string // existing is an adoption plan's team SQID; empty for an ordinary one. existing string apps []string expires, window int64 } type stored struct { action, head string seq int64 mac [32]byte result []byte } type role struct { name, origin string installation, registry, device string seq int64 head string results map[string]stored pending, open *plan } type team struct { id int64 sqid string label string name string owner string epoch int64 viaHTTP bool ownerUsed map[string]bool } type instance struct { team int64 app, origin, consumer string state string // pending | live | disabled recordDigest [32]byte generation string attempt *attempt } type attempt struct { id string issued, expires int64 } type consumer struct{ origin, app, state string } // Home is both roles. type Home struct { mu sync.Mutex // Now is Home's clock. Now func() time.Time alta []byte altaKID string prefilter [32]byte roles map[string]*role // People are the addresses that have signed in at Home, with refs. People map[string]string owner, provisioning, rosterPage *family.Keypair generation *string teams map[string]*team // by sqid nextTeam int64 instances map[string]*instance // by consumer consumers map[string]consumer // credential table env map[string]string // HOME_CONSUMERS // Faults. LoseAnswer makes the next matching operation commit and then // drop the connection; Outage makes matching operations answer 503 // without committing. LoseAnswer func(action string) bool Outage func(action string) bool // Calls counts operations by action (committed or not). Calls map[string]int // requests is the committed operations in order; committedApp is the // app the operation in flight touched, set by mutate. requests []string committedApp string // RecordSigner, when set, signs provisioning records instead of the // directory's provisioning key; RecordAudience, when set, is the // audience records bind. Both make records Alta must refuse. RecordSigner *family.Keypair RecordAudience string } // Pins are what Alta needs to reach a role. type Pins struct { Installation, Registry, Device string } func token() string { return homeop.Token() } // New builds a Home that pins alta's public key and prefilter token. func New(altaPublic []byte, prefilter string, credentialOrigin, directoryOrigin string, now func() time.Time) *Home { owner, _ := family.Generate() prov, _ := family.Generate() page, _ := family.Generate() h := &Home{Now: now, alta: altaPublic, altaKID: homeop.KeyID(altaPublic), roles: map[string]*role{}, People: map[string]string{}, owner: owner, provisioning: prov, rosterPage: page, teams: map[string]*team{}, nextTeam: 1, instances: map[string]*instance{}, consumers: map[string]consumer{}, env: map[string]string{"directory": directoryOrigin, "alta": "https://alta.example.test"}, Calls: map[string]int{}} raw, _ := base64.RawURLEncoding.DecodeString(prefilter) h.prefilter = sha256.Sum256(raw) for name, origin := range map[string]string{homeop.Credential: credentialOrigin, homeop.Directory: directoryOrigin} { h.roles[name] = &role{name: name, origin: origin, installation: token(), registry: token(), device: token(), results: map[string]stored{}} } return h } // Pins returns the pins for role, as Alta's configuration carries them. func (h *Home) Pins(r string) Pins { x := h.roles[r] return Pins{x.installation, x.registry, x.device} } // SharePins gives both roles the credential role's pins, as production // holds them: Alta has one installation, registry and device on both // roles (one configuration, as alta-adopt's config file carries it). func (h *Home) SharePins() Pins { h.mu.Lock() defer h.mu.Unlock() c, d := h.roles[homeop.Credential], h.roles[homeop.Directory] d.installation, d.registry, d.device = c.installation, c.registry, c.device return Pins{c.installation, c.registry, c.device} } // ProvisioningPublic is the directory's provisioning key, base64url. func (h *Home) ProvisioningPublic() string { return base64.RawURLEncoding.EncodeToString(h.provisioning.SignPub()) } // AddPerson records that address has signed in at Home. func (h *Home) AddPerson(address string) string { h.mu.Lock() defer h.mu.Unlock() ref := "pr_" + strings.Repeat("a", 25) + string(rune('a'+len(h.People)%26)) h.People[address] = ref return ref } // AddEnvConsumer adds an entry to the credential role's immutable env // manifest (HOME_CONSUMERS), as an existing instance has. Adoption's // register verifies against it and inserts nothing. func (h *Home) AddEnvConsumer(id, origin string) { h.mu.Lock() defer h.mu.Unlock() h.env[id] = origin } // Requests is the committed operations in order, each as its action, with // ":" for the verbs that touch one app, for example // "directory.activate-consumer:calendar". A refused operation, an // operation that did not commit and an exact replay add nothing. func (h *Home) Requests() []string { h.mu.Lock() defer h.mu.Unlock() return slices.Clone(h.requests) } // Confirm is Paul on role's confirm page: it opens the pending plan's // window. owner is the typed address (credential role, create-team). func (h *Home) Confirm(r, owner string) error { h.mu.Lock() defer h.mu.Unlock() x := h.roles[r] now := h.Now().Unix() h.sweep(x, now) if x.pending == nil { return errors.New("fakehome: no pending plan") } if x.open != nil { return errors.New("fakehome: 409 a window is open") } if x.pending.owner != "" && x.pending.owner != owner { return errors.New("fakehome: typed owner does not match") } p := x.pending x.pending = nil p.window = now + homeop.WindowLifetime x.open = p return nil } // Team reports a seeded team's state for assertions. func (h *Home) Team(label string) (id int64, sqid string, ok bool) { h.mu.Lock() defer h.mu.Unlock() for _, t := range h.teams { if t.label == label { return t.id, t.sqid, true } } return 0, "", false } // TeamCount is how many teams exist. func (h *Home) TeamCount() int { h.mu.Lock() defer h.mu.Unlock() return len(h.teams) } // InstanceState is a directory consumer's state. func (h *Home) InstanceState(consumer string) string { h.mu.Lock() defer h.mu.Unlock() if i, ok := h.instances[consumer]; ok { return i.state } return "" } // ConsumerState is a credential consumer's state. func (h *Home) ConsumerState(id string) string { h.mu.Lock() defer h.mu.Unlock() return h.consumers[id].state } // ConsumerCount counts the credential table's rows. func (h *Home) ConsumerCount() int { h.mu.Lock() defer h.mu.Unlock() return len(h.consumers) } // Stream is a role's (sequence, head). func (h *Home) Stream(r string) (int64, string) { h.mu.Lock() defer h.mu.Unlock() return h.roles[r].seq, h.roles[r].head } func (h *Home) sweep(x *role, now int64) { if x.pending != nil && x.pending.expires <= now { x.pending = nil } if x.open != nil && x.open.window <= now { x.open = nil } } // Handler is role r's /operator/v1 and /operator/v1/plan. func (h *Home) Handler(r string) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { answer := func(status int, code string) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) _, _ = io.WriteString(w, `{"outcome":"`+code+`"}`) } if req.URL.Path != "/operator/v1" && req.URL.Path != "/operator/v1/plan" { answer(404, "not_found") return } if req.Method != http.MethodPost { answer(405, "method") return } if len(req.Header.Values("Cookie")) > 0 || len(req.Header.Values("Origin")) > 0 || req.Header.Get("Sec-Fetch-Mode") != "" { answer(403, "browser") return } if req.Header.Get("Content-Type") != "application/json" { answer(415, "media") return } auth := req.Header.Get("Authorization") tok, err := base64.RawURLEncoding.Strict().DecodeString(strings.TrimPrefix(auth, "Bearer ")) if !strings.HasPrefix(auth, "Bearer ") || err != nil || sha256.Sum256(tok) != h.prefilter { answer(401, "prefilter") return } body, err := io.ReadAll(io.LimitReader(req.Body, homeop.BodyLimit+1)) if err != nil || len(body) > homeop.BodyLimit { answer(413, "size") return } h.mu.Lock() defer h.mu.Unlock() x := h.roles[r] now := h.Now().Unix() h.sweep(x, now) if req.URL.Path == "/operator/v1/plan" { status := h.submit(x, body, now) switch status { case 200: w.Header().Set("Content-Type", "application/json") _, _ = io.WriteString(w, `{"outcome":"pending"}`) case 409: answer(409, "busy") default: answer(403, "refused") } return } if out, ok := h.inspect(x, body, now); ok { w.Header().Set("Content-Type", "application/json") _, _ = w.Write(out) return } out, status, action := h.execute(x, body, now) if action != "" { h.Calls[action]++ } if status == 200 && action != "" && h.LoseAnswer != nil && h.LoseAnswer(action) { // Committed; the answer is lost on the way back. if hj, ok := w.(http.Hijacker); ok { c, _, _ := hj.Hijack() c.Close() return } panic(http.ErrAbortHandler) } switch status { case 200: w.Header().Set("Content-Type", "application/json") _, _ = w.Write(out) case 503: answer(503, "unavailable") default: answer(403, "refused") } }) } // ---- envelopes ---- type envelope struct { Version int `json:"v"` KeyID string `json:"kid"` Payload string `json:"payload"` Signature string `json:"signature"` } // canonical decodes b strictly into v and requires b to be v's canonical // encoding, as Home's strictCanonical does. func canonical(b []byte, v any) bool { if homeop.Decode(b, v) != nil { return false } re, err := homeop.Encode(v) return err == nil && bytes.Equal(re, b) } func (h *Home) open(raw []byte, context string) ([]byte, bool) { var env envelope if !canonical(raw, &env) || env.Version != 1 || env.KeyID != h.altaKID { return nil, false } p, err := base64.RawURLEncoding.Strict().DecodeString(env.Payload) sig, err2 := base64.RawURLEncoding.Strict().DecodeString(env.Signature) if err != nil || err2 != nil || len(sig) != 64 || !family.Verify(h.alta, context, p, sig) { return nil, false } return p, true } func sign(k *family.Keypair, context string, v any) []byte { payload, _ := homeop.Encode(v) sig, _ := family.Sign(k, context, payload) out, _ := homeop.Encode(envelope{1, homeop.KeyID(k.SignPub()), base64.RawURLEncoding.EncodeToString(payload), base64.RawURLEncoding.EncodeToString(sig)}) return out } func validLabel(s string) bool { if len(s) == 0 || len(s) > 63 || s[0] == '-' || s[len(s)-1] == '-' { return false } for _, c := range s { if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-') { return false } } return true } // ---- plans ---- func (h *Home) submit(x *role, body []byte, now int64) int { payload, ok := h.open(body, homeop.PlanContext) if !ok { return 403 } var p homeop.Plan if !canonical(payload, &p) || p.Version != 1 || p.Purpose != "operator-plan" || p.Role != x.name || p.Origin != x.origin || p.Installation != x.installation || p.Registry != x.registry || p.Device != x.device || !homeop.CanonicalToken(p.PlanID) || p.Issued > now || now >= p.Expires || p.Expires-p.Issued > homeop.PlanLifetime { return 403 } // Home's Plan.valid: an adoption plan binds a team SQID, only on // create-team or add-apps, only under label oficina, only for the // canonical apps; and oficina is reserved against everything else. if p.ExistingTeam != "" { if !validSQID(p.ExistingTeam) || (p.Kind != homeop.KindCreateTeam && p.Kind != homeop.KindAddApps) || (x.name == homeop.Directory && p.Label != "oficina") { return 403 } for _, a := range p.Apps { if homeop.CanonicalOrigin(a) == "" { return 403 } } } else if x.name == homeop.Directory && p.Label == "oficina" && (p.Kind == homeop.KindCreateTeam || p.Kind == homeop.KindAddApps) { return 403 } if p.Kind == homeop.KindInitialize { if x.name != homeop.Directory || len(p.Apps) != 0 || p.Label != "" || p.DisplayName != "" || p.Owner != "" { return 403 } } else { if len(p.Apps) == 0 || len(p.Apps) > 8 { return 403 } seen := map[string]bool{} for _, a := range p.Apps { if !slices.Contains(registry, a) || seen[a] { return 403 } seen[a] = true } if x.name == homeop.Directory { if p.Owner != "" || !validLabel(p.Label) || (p.Kind == homeop.KindCreateTeam) != (p.DisplayName != "") { return 403 } } else { if p.Label != "" || p.DisplayName != "" || (p.Kind == homeop.KindCreateTeam) != (p.Owner != "") { return 403 } if p.Owner != "" { if _, ok := h.People[p.Owner]; !ok { return 403 } } } } if x.pending != nil || (x.open != nil && x.open.id == p.PlanID) { return 409 } x.pending = &plan{id: p.PlanID, kind: p.Kind, label: p.Label, name: p.DisplayName, owner: p.Owner, existing: p.ExistingTeam, apps: p.Apps, expires: p.Expires} return 200 } // ---- inspect ---- func (h *Home) inspect(x *role, body []byte, now int64) ([]byte, bool) { payload, ok := h.open(body, homeop.InspectContext) if !ok { return nil, false } var c homeop.InspectChallenge if !canonical(payload, &c) || c.Role != x.name || c.Origin != x.origin || c.Installation != x.installation || c.Registry != x.registry || c.Device != x.device || c.Issued > now || c.Expires <= now { return nil, false } out := homeop.Inspection{Version: 1, Role: x.name, Challenge: c.Challenge, Observed: now, Sequence: x.seq, Head: x.head} if x.pending != nil { out.PendingPlan, out.PendingExpires = x.pending.id, x.pending.expires } if x.open != nil { out.OpenPlan, out.WindowExpires = x.open.id, x.open.window } if x.name == homeop.Directory { out.Generation = h.generation out.TeamID = h.nextTeam out.TeamSQID = sqid(h.nextTeam) } b, _ := homeop.Encode(out) return b, true } // sqid is not Home's sqids encoding; the fake only needs a stable, // distinct token per id. func sqid(id int64) string { return "t" + strings.Repeat("x", int(id%5)+2) + string(rune('a'+id%26)) } var sqidShape = regexp.MustCompile(`^tx{2,6}[a-z]$`) // validSQID is Home's validTeamSQID for this fake's sqids: the shape sqid // produces. Home's decodes to exactly one positive id and re-encodes. func validSQID(s string) bool { return sqidShape.MatchString(s) } // routeScope is Home's routeScope (existing.go): an ordinary window never // touches the oficina label or a canonical origin; an adoption window // touches only the exact canonical tuple of the plan's team. func routeScope(existing, label, team, app, consumer, origin string) bool { if existing == "" { return label != "oficina" && origin != homeop.CanonicalOrigin(app) } return validSQID(existing) && team == existing && canonicalBinding(label, app, consumer, origin) } // canonicalBinding is directorydata.CanonicalBinding. func canonicalBinding(label, app, consumer, origin string) bool { return label == "oficina" && consumer == app && homeop.CanonicalOrigin(app) != "" && origin == homeop.CanonicalOrigin(app) } // ---- operations ---- type wrapper struct { Version int `json:"version"` Authorization jsontext.Value `json:"signed_authorization"` Input jsontext.Value `json:"operation_input"` } func (h *Home) execute(x *role, body []byte, now int64) ([]byte, int, string) { var w wrapper if !canonical(body, &w) || w.Version != 1 { return nil, 403, "" } payload, ok := h.open(w.Authorization, homeop.InputContext) if !ok { return nil, 403, "" } var a homeop.Authorization if !canonical(payload, &a) || a.Role != x.name || a.Origin != x.origin || a.Installation != x.installation || a.Registry != x.registry || a.Device != x.device || a.InputDigest != homeop.Digest(w.Input) || a.Initial != (a.Sequence == 1) || a.Expires-a.Issued > 300 { return nil, 403, "" } head := homeop.Digest(w.Authorization) mac := sha256.Sum256(w.Input) if s, ok := x.results[a.OperationID]; ok { if s.action != a.Action || s.seq != a.Sequence || s.head != head || s.mac != mac || x.seq < a.Sequence { return nil, 403, a.Action } return s.result, 200, a.Action } if h.Outage != nil && h.Outage(a.Action) { return nil, 503, a.Action } if !(a.Issued <= now && now < a.Expires) { return nil, 403, a.Action } if a.Sequence != x.seq+1 || a.Previous != x.head { return nil, 403, a.Action } w0 := x.open if w0 == nil || !admits(w0.kind, a.Action) { return nil, 403, a.Action } base := homeop.Result{Version: 1, OperationID: a.OperationID, Outcome: "committed"} h.committedApp = "" res, ok := h.mutate(x, w0, a, w.Input, head, now, base) if !ok { return nil, 403, a.Action } out, _ := homeop.Encode(res) x.results[a.OperationID] = stored{action: a.Action, seq: a.Sequence, head: head, mac: mac, result: out} x.seq, x.head = a.Sequence, head entry := a.Action if h.committedApp != "" { entry += ":" + h.committedApp } h.requests = append(h.requests, entry) return out, 200, a.Action } func admits(kind, action string) bool { switch action { case homeop.DirectoryInitialize: return kind == homeop.KindInitialize case homeop.DirectorySeedTeam, homeop.CredentialOwnerSeed: return kind == homeop.KindCreateTeam case homeop.DirectoryProvision, homeop.DirectoryVerify, homeop.DirectoryActivate, homeop.CredentialRegister: return kind == homeop.KindCreateTeam || kind == homeop.KindAddApps case homeop.DirectoryDisable, homeop.CredentialRetire: return kind == homeop.KindRetireApps } return false } func base(in homeop.InputBase, a homeop.Authorization) bool { return in.Version == 1 && in.Operation == a.Action && in.OperationID == a.OperationID } func (h *Home) fence(sq, label string) (*team, bool) { t, ok := h.teams[sq] return t, ok && t.viaHTTP && t.label == label } func (h *Home) mutate(x *role, w *plan, a homeop.Authorization, input []byte, head string, now int64, res homeop.Result) (homeop.Result, bool) { switch a.Action { case homeop.DirectoryInitialize: var in homeop.InitializeInput if !canonical(input, &in) || !base(in.InputBase, a) || !a.Initial || in.ExpectedGeneration != nil || !homeop.CanonicalToken(in.Generation) || in.Baseline != homeop.Baseline || h.generation != nil { return res, false } g := in.Generation h.generation = &g res.Generation = g return res, true case homeop.CredentialOwnerSeed: var in homeop.OwnerInput if !canonical(input, &in) || !base(in.InputBase, a) || !in.ExistingOnly || in.Address != w.owner || in.Directory != h.roles[homeop.Directory].origin { return res, false } if w.existing != "" && in.TeamSQID != w.existing { return res, false } ref, ok := h.People[in.Address] if !ok || in.TeamID <= 0 || in.TeamSQID != sqid(in.TeamID) { return res, false } res.Receipt = sign(h.owner, homeop.OwnerContext, homeop.OwnerReceipt{Version: 1, Purpose: "owner-seed", OperationID: a.OperationID, Issuer: x.origin, Directory: in.Directory, TeamID: in.TeamID, TeamSQID: in.TeamSQID, PersonRef: ref, Role: "owner", Issued: now, Expires: now + 300}) return res, true case homeop.DirectorySeedTeam: var in homeop.SeedInput if !canonical(input, &in) || !base(in.InputBase, a) || a.Initial || in.Label != w.label || in.Name != w.name || h.generation == nil || in.Generation != *h.generation { return res, false } // Home's seedTeamForWindow: oficina is seeded only by an adoption // window, and only at that window's SQID. if (in.Label == "oficina") != (w.existing != "") || (w.existing != "" && in.TeamSQID != w.existing) { return res, false } receipt, ok := h.verifyReceipt(in.Receipt, now) if !ok || receipt.TeamID != in.TeamID || receipt.TeamSQID != in.TeamSQID || in.TeamID != h.nextTeam || in.TeamSQID != sqid(h.nextTeam) { return res, false } for _, t := range h.teams { if t.label == in.Label || t.ownerUsed[receipt.OperationID] { return res, false } } t := &team{id: in.TeamID, sqid: in.TeamSQID, label: in.Label, name: in.Name, owner: receipt.PersonRef, epoch: 1, viaHTTP: true, ownerUsed: map[string]bool{receipt.OperationID: true}} h.teams[t.sqid] = t h.nextTeam++ res.Generation, res.TeamID, res.TeamSQID, res.Epoch = in.Generation, t.id, t.sqid, t.epoch return res, true case homeop.DirectoryProvision: var in homeop.ProvisionInput if !canonical(input, &in) || !base(in.InputBase, a) || a.Initial || in.Sequence != 0 || !slices.Contains(w.apps, in.App) || h.generation == nil || in.Generation != *h.generation { return res, false } t, ok := h.fence(in.TeamSQID, w.label) if !ok || !routeScope(w.existing, t.label, in.TeamSQID, in.App, in.Consumer, in.Audience) { return res, false } if w.existing == "" && in.Audience != "https://"+t.label+"."+in.App+".oficina.works" { return res, false } h.committedApp = in.App for c, i := range h.instances { if (i.team == t.id && i.app == in.App) || c == in.Consumer || i.origin == in.Audience { return res, false } } b := roster.Bindings{Issuer: h.roles[homeop.Credential].origin, Directory: x.origin, Consumer: in.Consumer, App: in.App, Team: in.TeamSQID, Audience: in.Audience} page := roster.Key{ID: "page1", Public: base64.RawURLEncoding.EncodeToString(h.rosterPage.SignPub())} signer := h.provisioning if h.RecordSigner != nil { signer = h.RecordSigner } if h.RecordAudience != "" { b.Audience = h.RecordAudience } record, err := roster.SignProvisioning(signer, homeop.KeyID(signer.SignPub()), roster.Provisioning{Version: 1, Operation: a.OperationID, Sequence: 1, Bindings: b, Generation: in.Generation, MinEpoch: t.epoch, Keys: []roster.Key{page}}) if err != nil { return res, false } bearer := make([]byte, 32) _, _ = rand.Read(bearer) h.instances[in.Consumer] = &instance{team: t.id, app: in.App, origin: in.Audience, consumer: in.Consumer, state: "pending", recordDigest: sha256.Sum256(record), generation: in.Generation} res.Generation, res.TeamID, res.TeamSQID, res.Epoch, res.Record, res.Bearer = in.Generation, t.id, t.sqid, t.epoch, record, base64.RawURLEncoding.EncodeToString(bearer) return res, true case homeop.CredentialRegister: var in homeop.RegisterInput if !canonical(input, &in) || !base(in.InputBase, a) || a.Initial { return res, false } claimed, ok := claimedBindings(in.Record) if !ok { return res, false } expected := claimed expected.Issuer, expected.Directory = x.origin, h.roles[homeop.Directory].origin v, err := roster.VerifyProvisioning(in.Record, []roster.Key{{ID: homeop.KeyID(h.provisioning.SignPub()), Public: h.ProvisioningPublic()}}, expected) if err != nil { return res, false } b := v.Bindings() if !slices.Contains(w.apps, b.App) { return res, false } h.committedApp = b.App if w.existing != "" { // Home's register under an adoption window: verify only. The // exact pair is already in the env manifest, no other env // entry has the origin, and the table has neither; nothing is // inserted, replaced or retired. if b.Team != w.existing || !canonicalBinding("oficina", b.App, b.Consumer, b.Audience) || h.env[b.Consumer] != b.Audience { return res, false } for id, origin := range h.env { if id != b.Consumer && origin == b.Audience { return res, false } } for id, c := range h.consumers { if id == b.Consumer || c.origin == b.Audience { return res, false } } res.Manifest = h.manifest() return res, true } for id, origin := range h.env { if id == b.Consumer || origin == b.Audience { return res, false } } for id, c := range h.consumers { if id == b.Consumer || c.origin == b.Audience { return res, false } } h.consumers[b.Consumer] = consumer{origin: b.Audience, app: b.App, state: "active"} res.Manifest = h.manifest() return res, true case homeop.CredentialRetire: var in homeop.RetireInput if !canonical(input, &in) || !base(in.InputBase, a) || a.Initial { return res, false } c, ok := h.consumers[in.Consumer] if !ok || c.state != "active" || !slices.Contains(w.apps, c.app) { return res, false } h.committedApp = c.app c.state = "retired" h.consumers[in.Consumer] = c res.Manifest = h.manifest() return res, true case homeop.DirectoryVerify: var in homeop.VerificationInput if !canonical(input, &in) || !base(in.InputBase, a) || a.Initial || !slices.Contains(w.apps, in.App) { return res, false } if _, ok := h.fence(in.TeamSQID, w.label); !ok || !routeScope(w.existing, w.label, in.TeamSQID, in.App, in.Consumer, in.Audience) { return res, false } h.committedApp = in.App i, ok := h.pendingBinding(in.Consumer, in.TeamSQID, in.App, in.Audience, in.Generation, in.RecordSequence, in.RecordDigest, in.Owner, in.Epoch) if !ok || in.Issued <= 0 || in.Issued > now || in.Expires <= now || in.Expires-in.Issued > 600 { return res, false } if i.attempt != nil && i.attempt.expires > now { return res, false } i.attempt = &attempt{a.OperationID, in.Issued, in.Expires} res.Attempt, res.Expires = a.OperationID, in.Expires return res, true case homeop.DirectoryActivate: var in homeop.ActivationInput if !canonical(input, &in) || !base(in.InputBase, a) || a.Initial { return res, false } p := in.Evidence // Home's activateForWindow: the window, not the evidence, picks // the policy. policy := homeop.ActivationPolicy if w.existing != "" { policy = homeop.ExistingActivationPolicy } u, err := url.Parse(p.Audience) if err != nil || !slices.Contains(w.apps, p.App) || p.Policy != policy || !observedVersion.MatchString(p.AppVersion) || !homeop.CanonicalToken(p.ArtifactDigest) || !homeop.CanonicalToken(p.EnvironmentBinding) || !homeop.CanonicalToken(p.ManifestDigest) || p.AliasHost != u.Host || p.Completed > now || now-p.Completed >= 300 { return res, false } if _, ok := h.fence(p.TeamSQID, w.label); !ok || !routeScope(w.existing, w.label, p.TeamSQID, p.App, p.Consumer, p.Audience) { return res, false } h.committedApp = p.App i, ok := h.pendingBinding(p.Consumer, p.TeamSQID, p.App, p.Audience, p.Generation, p.RecordSequence, p.RecordDigest, p.Owner, p.Epoch) if !ok || i.attempt == nil || i.attempt.id != p.Attempt || i.attempt.expires <= now || p.Started < i.attempt.issued || p.Completed >= i.attempt.expires { return res, false } i.state, i.attempt = "live", nil res.Attempt, res.Generation, res.TeamSQID, res.Epoch = p.Attempt, p.Generation, p.TeamSQID, p.Epoch return res, true case homeop.DirectoryDisable: var in homeop.DisableInput if !canonical(input, &in) || !base(in.InputBase, a) || a.Initial || !slices.Contains(w.apps, in.App) || h.generation == nil || in.Generation != *h.generation { return res, false } t, ok := h.fence(in.TeamSQID, w.label) i, ok2 := h.instances[in.Consumer] if !ok || !ok2 || i.team != t.id || i.app != in.App || i.state == "disabled" { return res, false } h.committedApp = in.App i.state = "disabled" res.Generation, res.TeamID, res.TeamSQID = in.Generation, t.id, t.sqid return res, true } return res, false } func (h *Home) pendingBinding(consumer, sq, app, audience, gen string, seq int64, digest, owner string, epoch int64) (*instance, bool) { i, ok := h.instances[consumer] if !ok || i.state != "pending" || i.app != app || i.origin != audience || i.generation != gen || seq != 1 { return nil, false } t, ok := h.teams[sq] if !ok || t.id != i.team || t.owner != owner || t.epoch != epoch { return nil, false } d, err := base64.RawURLEncoding.Strict().DecodeString(digest) if err != nil || !bytes.Equal(d, i.recordDigest[:]) { return nil, false } return i, true } func (h *Home) verifyReceipt(raw []byte, now int64) (homeop.OwnerReceipt, bool) { var env envelope if !canonical(raw, &env) || env.KeyID != homeop.KeyID(h.owner.SignPub()) { return homeop.OwnerReceipt{}, false } p, err := base64.RawURLEncoding.Strict().DecodeString(env.Payload) sig, err2 := base64.RawURLEncoding.Strict().DecodeString(env.Signature) if err != nil || err2 != nil || !family.Verify(h.owner.SignPub(), homeop.OwnerContext, p, sig) { return homeop.OwnerReceipt{}, false } var r homeop.OwnerReceipt if !canonical(p, &r) || now >= r.Expires || r.Issued > now { return homeop.OwnerReceipt{}, false } return r, true } func claimedBindings(record []byte) (roster.Bindings, bool) { p, err := homeop.EnvelopePayload(record) if err != nil { return roster.Bindings{}, false } var pr roster.Provisioning if homeop.Decode(p, &pr) != nil { return roster.Bindings{}, false } return pr.Bindings, true } func (h *Home) manifest() string { union := map[string]string{} for id, o := range h.env { union[id] = o } for id, c := range h.consumers { if c.state == "active" { union[id] = c.origin } } return homeop.ManifestDigest(union) } // KeyHex is a helper for tests that need a person ref. func KeyHex(b []byte) string { return hex.EncodeToString(b) }