provision: sealed state, recipes and the §6 state machine
Alta's SQLite state (§4): every label ever used, the sealed display name, the sealed owner address, runs, per-team steps so a later add-apps run continues where one parked, the sealed exact bytes of every signed Home request (a lost result is recovered by exact replay, and the roster bearer re-fetched that way, never stored), and each role's stream position, re-read through a signed inspect when Alta's is missing or behind. secure_delete is on. The recipes port provision-team.py into GENERATED / SET / PLATFORM (§5) for an owned, standalone environment: Home's consumer values, fresh keys never regenerated, the owner allowlist until roster mode, Docs' team mode, AI off for Memoria, no uploads for Slides, quality reports off for Calls; PLATFORM keys are only ever waited for, never written. The engine: preflight, one shared plan id across both roles, windows read through inspect, owner-seed and seed-team (an expired receipt takes a new owner-seed), then per app provision, register, environment, instance, domain (state, never status), serving (/api/version against the box's rollout report), verify and activate with §7's evidence for roster-mode apps, and the exact-keys audit, after which the address-bearing rows are deleted. Deprovision is disable, retire, detach, delete. One run at a time; logs carry step keys and fixed codes only. Tests run against fakehome and fakeconsole: the whole lagged run, a crash after each of its 40 acts with a fresh engine resuming to the same end state, a lost answer after commit for every verb, an expired receipt, a lost stream, a closed window resumed under add-apps, the §8 guards, a wrong mail prefix, a fork with Track 1 keys, deprovisioning, and a scan of the database files for the owner and platform canaries.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
9 files changed,
+4,713
−0
homeop/fakehome/fakehome.go+761 −0provision/apps.go+310 −0provision/engine.go+785 −0provision/engine_test.go+522 −0provision/guard_test.go+147 −0provision/harness_test.go+204 −0provision/migrations/0001_init.sql+130 −0provision/steps.go+1,029 −0provision/store.go+825 −0
diff --git a/homeop/fakehome/fakehome.go b/homeop/fakehome/fakehome.go| new file mode 100644 |
| index 0000000..2d7bd22 |
| --- /dev/null |
| +++ b/homeop/fakehome/fakehome.go |
| @@ -0,0 +1,761 @@ |
| +// 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" |
| + "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" |
| +) |
| + |
| +var registry = []string{"docs", "sheets", "slides", "calendar", "calls", "memoria"} |
| + |
| +type plan struct { |
| + id, kind, label, name, owner 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 |
| +} |
| + |
| +// 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} |
| +} |
| + |
| +// 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 |
| +} |
| + |
| +// 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 |
| + } |
| + 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, 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)) } |
| + |
| +// ---- 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"} |
| + 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 |
| + 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 |
| + } |
| + 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 |
| + } |
| + 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 || in.Audience != "https://"+t.label+"."+in.App+".oficina.works" { |
| + return res, false |
| + } |
| + 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())} |
| + record, err := roster.SignProvisioning(h.provisioning, homeop.KeyID(h.provisioning.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 |
| + } |
| + 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 |
| + } |
| + 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 { |
| + return res, false |
| + } |
| + 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 |
| + u, err := url.Parse(p.Audience) |
| + if err != nil || !slices.Contains(w.apps, p.App) || p.Policy != homeop.ActivationPolicy || len(p.AppVersion) != 40 || !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 { |
| + return res, false |
| + } |
| + 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 |
| + } |
| + 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) } |
diff --git a/provision/apps.go b/provision/apps.go| new file mode 100644 |
| index 0000000..2c3ae6e |
| --- /dev/null |
| +++ b/provision/apps.go |
| @@ -0,0 +1,310 @@ |
| +package provision |
| + |
| +import ( |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "encoding/hex" |
| + stdjson "encoding/json" |
| + "fmt" |
| + "regexp" |
| + "slices" |
| + "strings" |
| + |
| + "amadan.net/oficina/home/roster" |
| +) |
| + |
| +// LabelPattern is Alta's label rule (§5): deliberately tighter than |
| +// Home's ValidLabel, so every derived host stays well inside DNS limits. |
| +var LabelPattern = regexp.MustCompile(`^[a-z][a-z0-9-]{1,30}[a-z0-9]$`) |
| + |
| +// PublicDomain is the only public suffix Home's directory admits for a |
| +// team instance (internal/home directoryRouteAllowed). |
| +const PublicDomain = "oficina.works" |
| + |
| +// App is one Oficina app as Alta provisions it: the env prefix it reads, |
| +// whether it has roster mode, which SMTP prefixes its binary reads, and |
| +// whether it needs the platform relay. |
| +type App struct { |
| + Slug string |
| + Name string |
| + Prefix string |
| + // Roster is true for an app with team (roster) mode on main. Only |
| + // those reach steps 11–12; the rest stop at 10 with their directory |
| + // row pending (§6). |
| + Roster bool |
| + // MailPrefixes are the <PREFIX>_SMTP_* sets the binary reads, in its |
| + // own order. The mail walk writes the set the app declared; a set the |
| + // binary does not read leaves it without mail, which step 7 refuses. |
| + MailPrefixes []string |
| + // Relay is true when CARLOS_RELAY is a PLATFORM key (Calls). |
| + Relay bool |
| +} |
| + |
| +// Apps is the compiled registry, in Home's order (directory_runtime.go). |
| +var Apps = []App{ |
| + {Slug: "docs", Name: "Docs", Prefix: "DOCS", Roster: true, MailPrefixes: []string{"DOCS_SMTP"}}, |
| + {Slug: "sheets", Name: "Sheets", Prefix: "SHEETS", MailPrefixes: []string{"CARLOS_SMTP"}}, |
| + {Slug: "slides", Name: "Slides", Prefix: "SLIDES", MailPrefixes: []string{"SLIDES_SMTP", "CARLOS_SMTP"}}, |
| + {Slug: "calendar", Name: "Calendar", Prefix: "CALENDAR", MailPrefixes: []string{"CALENDAR_SMTP", "CARLOS_SMTP"}}, |
| + {Slug: "calls", Name: "Calls", Prefix: "CALLS", MailPrefixes: []string{"CALLS_SMTP", "CARLOS_SMTP"}, Relay: true}, |
| + {Slug: "memoria", Name: "Memoria", Prefix: "MEMORIA", MailPrefixes: []string{"CARLOS_SMTP"}}, |
| +} |
| + |
| +// AppBySlug finds a registry app. |
| +func AppBySlug(slug string) (App, bool) { |
| + for _, a := range Apps { |
| + if a.Slug == slug { |
| + return a, true |
| + } |
| + } |
| + return App{}, false |
| +} |
| + |
| +// Slugs is the registry's slugs. |
| +func Slugs() []string { |
| + out := make([]string, len(Apps)) |
| + for i, a := range Apps { |
| + out[i] = a.Slug |
| + } |
| + return out |
| +} |
| + |
| +// SortApps orders apps as the registry does and drops unknowns. |
| +func SortApps(apps []string) []string { |
| + var out []string |
| + for _, a := range Apps { |
| + if slices.Contains(apps, a.Slug) { |
| + out = append(out, a.Slug) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// Hosts derives a team instance's two hostnames. |
| +func RouteHost(label, app, account string) string { |
| + return label + "-" + app + "." + account + ".oncarlos.com" |
| +} |
| +func PublicHost(label, app string) string { return label + "." + app + "." + PublicDomain } |
| +func PublicOrigin(label, app string) string { |
| + return "https://" + PublicHost(label, app) |
| +} |
| +func ConsumerID(label, app string) string { return label + "-" + app } |
| + |
| +// Class is a recipe key's treatment (§5). |
| +type Class string |
| + |
| +const ( |
| + Generated Class = "generated" |
| + Set Class = "set" |
| + Platform Class = "platform" |
| +) |
| + |
| +// Key is one recipe key. Value is known for SET keys only; a GENERATED |
| +// key's value exists only on its way to the console, sealed. |
| +type Key struct { |
| + Name string |
| + Class Class |
| + Value string |
| + Secret bool |
| + // OwnerAddress marks a SET key whose value is the owner's address |
| + // (the stopgap allowlist). After step 13 Alta no longer knows it. |
| + OwnerAddress bool |
| + // FromHome marks a GENERATED key whose value Home minted (the roster |
| + // bearer), fetched by exact replay of step 5. |
| + FromHome bool |
| +} |
| + |
| +// HomeConfig is the Home material every recipe carries: Alta's pinned |
| +// copies, none of them secret. |
| +type HomeConfig struct { |
| + Issuer string // credential origin, https://id.oficina.works |
| + Directory string // https://oficina.works |
| + KeysBase64 string // the assertion keys manifest, as ALTA_HOME_KEYS_BASE64 |
| + Provisioner string // the directory's provisioning public key, base64url |
| +} |
| + |
| +// Inputs is what a recipe is built from. |
| +type Inputs struct { |
| + Label string |
| + Owner string // empty once deleted (§4) |
| + TeamSQID string |
| + Record []byte // step 5's signed record (Docs) |
| + Home HomeConfig |
| + CallsZone string |
| +} |
| + |
| +// Recipe is one app's GENERATED and SET keys. PLATFORM keys are added by |
| +// PlatformKeys once the walks have delivered them. |
| +func Recipe(app App, in Inputs) []Key { |
| + p := app.Prefix |
| + keys := []Key{ |
| + {Name: p + "_ORIGIN", Class: Set, Value: PublicOrigin(in.Label, app.Slug)}, |
| + {Name: p + "_INSTANCE_KEY", Class: Generated, Secret: true}, |
| + {Name: p + "_HOME_ISSUER", Class: Set, Value: in.Home.Issuer}, |
| + {Name: p + "_HOME_CONSUMER_ID", Class: Set, Value: ConsumerID(in.Label, app.Slug)}, |
| + {Name: p + "_HOME_KEYS_BASE64", Class: Set, Value: in.Home.KeysBase64}, |
| + {Name: p + "_HOME_DEK_BASE64", Class: Generated, Secret: true}, |
| + {Name: "HOME_DIRECTORY_ORIGIN", Class: Set, Value: in.Home.Directory}, |
| + } |
| + owner := func(name string) Key { return Key{Name: name, Class: Set, Value: in.Owner, OwnerAddress: true} } |
| + switch app.Slug { |
| + case "docs": |
| + keys = append(keys, |
| + Key{Name: "DOCS_CONTENT_KEY", Class: Generated, Secret: true}, |
| + Key{Name: "DOCS_TEAM_ROSTER_TOKEN", Class: Generated, Secret: true, FromHome: true}, |
| + Key{Name: "DOCS_ALLOWED_ADDRESSES", Class: Set, Value: ""}, |
| + Key{Name: "DOCS_TEAM_ID", Class: Set, Value: in.TeamSQID}, |
| + Key{Name: "DOCS_TEAM_DIRECTORY_ORIGIN", Class: Set, Value: in.Home.Directory}, |
| + Key{Name: "DOCS_TEAM_PROVISIONING_BASE64", Class: Set, Value: base64.StdEncoding.EncodeToString(in.Record)}, |
| + Key{Name: "DOCS_TEAM_OPERATOR_KEYS_BASE64", Class: Set, Value: operatorKeys(in.Home.Provisioner)}, |
| + ) |
| + case "sheets": |
| + keys = append(keys, Key{Name: "SHEETS_DEK", Class: Generated, Secret: true}, owner("SHEETS_OWNERS")) |
| + case "slides": |
| + // No uploads (Paul): no CARLOS_STORE_*, so uploads answer 503. |
| + keys = append(keys, owner("SLIDES_ALLOWED_ADDRESSES")) |
| + case "calendar": |
| + keys = append(keys, Key{Name: "CALENDAR_DEK", Class: Generated, Secret: true}, owner("CALENDAR_ALLOWED_ADDRESSES")) |
| + case "calls": |
| + keys = append(keys, |
| + Key{Name: "CALLS_DEK", Class: Generated, Secret: true}, |
| + owner("CALLS_ALLOWED_ADDRESSES"), |
| + Key{Name: "CALLS_ZONE", Class: Set, Value: in.CallsZone}, |
| + // A team's call-quality logs would land in the operator's |
| + // `carlos logs`; off until that team's owner and Paul agree. |
| + Key{Name: "CALLS_QUALITY_REPORTS", Class: Set, Value: "off"}, |
| + ) |
| + case "memoria": |
| + // AI off: MEMORIA_AI, _TENSORX_KEY, _SIBLINGS, _SIBLING_TOKEN_* |
| + // and _ALLOW_LOGGED_MAIL are simply absent. |
| + keys = append(keys, |
| + Key{Name: "MEMORIA_DEK", Class: Generated, Secret: true}, |
| + owner("MEMORIA_OWNERS"), |
| + Key{Name: "MEMORIA_TEAM", Class: Set, Value: in.Label}, |
| + ) |
| + } |
| + return keys |
| +} |
| + |
| +// operatorKeys is DOCS_TEAM_OPERATOR_KEYS_BASE64: the directory's |
| +// provisioning key as a one-entry []roster.Key, JSON, standard base64. |
| +func operatorKeys(public string) string { |
| + if public == "" { |
| + return "" |
| + } |
| + raw, err := base64.RawURLEncoding.DecodeString(public) |
| + if err != nil { |
| + return "" |
| + } |
| + sum := sha256.Sum256(raw) |
| + b, _ := stdjson.Marshal([]roster.Key{{ID: hex.EncodeToString(sum[:]), Public: public}}) |
| + return base64.StdEncoding.EncodeToString(b) |
| +} |
| + |
| +// ProvisionerKeys is the same key for roster.VerifyProvisioning. |
| +func ProvisionerKeys(public string) []roster.Key { |
| + raw, err := base64.RawURLEncoding.DecodeString(public) |
| + if err != nil { |
| + return nil |
| + } |
| + sum := sha256.Sum256(raw) |
| + return []roster.Key{{ID: hex.EncodeToString(sum[:]), Public: public}} |
| +} |
| + |
| +var smtpSuffixes = []string{"HOST", "PORT", "USER", "PASS", "FROM"} |
| + |
| +// SMTPKeys is a prefix's five. |
| +func SMTPKeys(prefix string) []string { |
| + out := make([]string, len(smtpSuffixes)) |
| + for i, s := range smtpSuffixes { |
| + out[i] = prefix + "_" + s |
| + } |
| + return out |
| +} |
| + |
| +var smtpKey = regexp.MustCompile(`^([A-Z][A-Z0-9_]*_SMTP)_(HOST|PORT|USER|PASS|FROM)$`) |
| + |
| +// PlatformState is what the walks have delivered into one environment. |
| +type PlatformState struct { |
| + // Keys are the PLATFORM keys present that this app reads. |
| + Keys []string |
| + // Missing is the PLATFORM keys still to arrive. |
| + Missing []string |
| + // WrongPrefix names an SMTP prefix delivered that the binary does not |
| + // read: a declaration under the wrong prefix (§5, §6 step 0). |
| + WrongPrefix string |
| +} |
| + |
| +// PlatformKeys classifies an environment's present key names against |
| +// app's PLATFORM expectations. |
| +func PlatformKeys(app App, present map[string]bool) PlatformState { |
| + var st PlatformState |
| + prefixes := map[string]int{} |
| + for k := range present { |
| + if m := smtpKey.FindStringSubmatch(k); m != nil { |
| + prefixes[m[1]]++ |
| + } |
| + } |
| + chosen := "" |
| + for _, p := range app.MailPrefixes { |
| + if prefixes[p] > 0 { |
| + chosen = p |
| + break |
| + } |
| + } |
| + for p := range prefixes { |
| + if !slices.Contains(app.MailPrefixes, p) { |
| + st.WrongPrefix = p |
| + } |
| + } |
| + if chosen == "" { |
| + chosen = app.MailPrefixes[0] |
| + } |
| + want := SMTPKeys(chosen) |
| + if app.Relay { |
| + want = append(want, "CARLOS_RELAY") |
| + } |
| + for _, k := range want { |
| + if present[k] { |
| + st.Keys = append(st.Keys, k) |
| + } else { |
| + st.Missing = append(st.Missing, k) |
| + } |
| + } |
| + return st |
| +} |
| + |
| +// EnvironmentBinding is §7's environment_binding: base64url(SHA-256) of |
| +// Alta's canonical recipe JSON for this instance — sorted names, each with |
| +// its class and, for a SET key, the SHA-256 of its value. GENERATED and |
| +// PLATFORM keys contribute name and class only. |
| +func EnvironmentBinding(env string, keys []Key, platform []string) string { |
| + type row = [3]string |
| + var rows []row |
| + for _, k := range keys { |
| + h := "" |
| + if k.Class == Set { |
| + s := sha256.Sum256([]byte(k.Value)) |
| + h = hex.EncodeToString(s[:]) |
| + } |
| + rows = append(rows, row{k.Name, string(k.Class), h}) |
| + } |
| + for _, k := range platform { |
| + rows = append(rows, row{k, string(Platform), ""}) |
| + } |
| + slices.SortFunc(rows, func(a, b row) int { return strings.Compare(a[0], b[0]) }) |
| + b, _ := stdjson.Marshal([]any{"oficina/alta/environment-binding/v1", env, rows}) |
| + sum := sha256.Sum256(b) |
| + return base64.RawURLEncoding.EncodeToString(sum[:]) |
| +} |
| + |
| +// freshKey is a GENERATED value: 32 random bytes, standard base64, the |
| +// shape every DEK and instance key in the suite takes. |
| +func freshKey() string { |
| + b := make([]byte, 32) |
| + if _, err := rand.Read(b); err != nil { |
| + panic(fmt.Sprintf("provision: no randomness: %v", err)) |
| + } |
| + return base64.StdEncoding.EncodeToString(b) |
| +} |
diff --git a/provision/engine.go b/provision/engine.go| new file mode 100644 |
| index 0000000..33822d1 |
| --- /dev/null |
| +++ b/provision/engine.go |
| @@ -0,0 +1,785 @@ |
| +package provision |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "log/slog" |
| + "net/http" |
| + "net/mail" |
| + "slices" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/alta/console" |
| + "amadan.net/oficina/alta/homeop" |
| +) |
| + |
| +// Config is everything the engine reaches. |
| +type Config struct { |
| + Store *Store |
| + Home *homeop.Client |
| + Console *console.Client |
| + // Public is the client for the team instances' own origins |
| + // (/api/version, /api/team). |
| + Public *http.Client |
| + HomeCfg HomeConfig |
| + Account string |
| + // CallsZone is CALLS_ZONE for a team's Calls. |
| + CallsZone string |
| + Now func() time.Time |
| + Logger *slog.Logger |
| + // AfterAct, when set, runs after every act has taken effect remotely |
| + // and before Alta records it. A test returns an error from it to |
| + // simulate a crash at exactly that point (§12). |
| + AfterAct func(key string) error |
| + // Debug, when set, sees errors that are neither a park nor a fail |
| + // (tests only: they may carry text the logs must not). |
| + Debug func(error) |
| +} |
| + |
| +// Engine runs §6's state machine. Every step is probe → act → verify → |
| +// record; a crash resumes by probing; nothing is inferred from a timeout; |
| +// nothing is deleted to "clean up". |
| +type Engine struct{ cfg Config } |
| + |
| +func New(cfg Config) *Engine { |
| + if cfg.Now == nil { |
| + cfg.Now = time.Now |
| + } |
| + if cfg.Logger == nil { |
| + cfg.Logger = slog.Default() |
| + } |
| + if cfg.Public == nil { |
| + cfg.Public = &http.Client{Timeout: 15 * time.Second} |
| + } |
| + if cfg.CallsZone == "" { |
| + cfg.CallsZone = "UTC" |
| + } |
| + return &Engine{cfg} |
| +} |
| + |
| +func (e *Engine) Store() *Store { return e.cfg.Store } |
| +func (e *Engine) now() time.Time { return e.cfg.Now() } |
| + |
| +// Park is a step that cannot finish yet: it will be retried. Code is a |
| +// fixed word, safe for logs and pages. |
| +type Park struct{ Code string } |
| + |
| +func (p *Park) Error() string { return "parked: " + p.Code } |
| + |
| +// Fail is a step that needs Paul: Alta will not retry it on its own. |
| +type Fail struct{ Code string } |
| + |
| +func (f *Fail) Error() string { return "failed: " + f.Code } |
| + |
| +func park(code string) error { return &Park{code} } |
| +func fail(code string) error { return &Fail{code} } |
| + |
| +// errCrash marks an AfterAct hook's simulated crash. |
| +var errCrash = errors.New("provision: simulated crash") |
| + |
| +func (e *Engine) acted(key string) error { |
| + if e.cfg.AfterAct != nil { |
| + if err := e.cfg.AfterAct(key); err != nil { |
| + return fmt.Errorf("%w at %s: %v", errCrash, key, err) |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// log carries step keys and fixed codes only (§8): never a label, an |
| +// address, a key or a platform value. App slugs are compiled constants. |
| +func (e *Engine) log(run int64, app, step, outcome string) { |
| + e.cfg.Logger.Info("alta step", "run", run, "app", app, "step", step, "outcome", outcome) |
| +} |
| + |
| +// ---- starting runs (§6 steps 0 and 2) ---- |
| + |
| +// InitializeAttestation is the sentence Paul types to give amendment |
| +// §12's baseline confirmation. Alta then signs Home's fixed |
| +// baseline_attestation value in directory.initialize. |
| +const InitializeAttestation = "This directory has never issued a roster generation or consumer record" |
| + |
| +// StartInitialize opens Alta's first production run: a directory-only |
| +// initialize plan (§6 step 1). |
| +func (e *Engine) StartInitialize(ctx context.Context, typed string) (int64, error) { |
| + if strings.TrimSpace(typed) != InitializeAttestation { |
| + return 0, fail("attestation-mismatch") |
| + } |
| + ins, o, _ := e.cfg.Home.Inspect(ctx, homeop.Directory) |
| + if o != homeop.OK { |
| + return 0, fail("home-" + o.String()) |
| + } |
| + if ins.Generation != nil { |
| + return 0, fail("already-initialized") |
| + } |
| + id, err := e.cfg.Store.NewRun(ctx, homeop.KindInitialize, "", nil) |
| + if err != nil { |
| + return 0, err |
| + } |
| + e.cfg.Store.Audit(ctx, id, "", "", "run-start", homeop.KindInitialize) |
| + return id, e.submitPlans(ctx, id, "", "", "", homeop.KindInitialize, nil) |
| +} |
| + |
| +// NewTeam is the New team form. |
| +type NewTeam struct { |
| + Label, Name, Owner string |
| + Apps []string |
| + // Forked: the team moves an existing stopgap whose environments Paul |
| + // forked to <label>-team (§6, "Moving the lagged stopgap"). |
| + Forked bool |
| +} |
| + |
| +// EnvironmentName is a team's owned environment's name. |
| +func EnvironmentName(label string, forked bool) string { |
| + if forked { |
| + return label + "-team" |
| + } |
| + return label |
| +} |
| + |
| +// validEnvironment is CARLOS's environment name rule. |
| +func validEnvironment(s string) bool { |
| + if len(s) == 0 || len(s) > 32 || s == "default" { |
| + return false |
| + } |
| + for _, c := range s { |
| + if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-') { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// CreateTeam runs step 0 for a new team and, if it passes, records the |
| +// label (for good) and submits the plans. |
| +func (e *Engine) CreateTeam(ctx context.Context, in NewTeam) (int64, error) { |
| + in.Apps = SortApps(in.Apps) |
| + env := EnvironmentName(in.Label, in.Forked) |
| + switch { |
| + case !LabelPattern.MatchString(in.Label): |
| + return 0, fail("label-shape") |
| + case !homeop.TeamName(in.Name): |
| + return 0, fail("name-shape") |
| + case !homeop.OwnerAddress(in.Owner): |
| + return 0, fail("owner-shape") |
| + case len(in.Apps) == 0: |
| + return 0, fail("no-apps") |
| + case !validEnvironment(env): |
| + return 0, fail("environment-shape") |
| + } |
| + if a, err := mail.ParseAddress(in.Owner); err != nil || a.Address != in.Owner { |
| + return 0, fail("owner-shape") |
| + } |
| + used, err := e.cfg.Store.LabelUsed(ctx, in.Label) |
| + if err != nil { |
| + return 0, err |
| + } |
| + if used { |
| + return 0, fail("label-used") |
| + } |
| + if err := e.preflight(withProposal(ctx, in.Label, env, in.Apps), in.Label, env, in.Forked, in.Apps, true); err != nil { |
| + return 0, err |
| + } |
| + if err := e.cfg.Store.CreateTeam(ctx, in.Label, in.Name, env, in.Forked, in.Owner, in.Apps); err != nil { |
| + return 0, err |
| + } |
| + id, err := e.cfg.Store.NewRun(ctx, homeop.KindCreateTeam, in.Label, in.Apps) |
| + if err != nil { |
| + return 0, err |
| + } |
| + e.cfg.Store.Audit(ctx, id, in.Label, "", "run-start", homeop.KindCreateTeam) |
| + return id, e.submitPlans(ctx, id, in.Label, in.Name, in.Owner, homeop.KindCreateTeam, in.Apps) |
| +} |
| + |
| +// AddApps starts an add-apps run: new apps for a team, or a parked run's |
| +// apps resumed under a fresh plan (§6: "A run that parks resumes under a |
| +// new plan of kind add-apps"). |
| +func (e *Engine) AddApps(ctx context.Context, label string, apps []string) (int64, error) { |
| + apps = SortApps(apps) |
| + t, err := e.cfg.Store.Team(ctx, label) |
| + if err != nil { |
| + return 0, fail("no-team") |
| + } |
| + if t.TeamSQID == "" { |
| + // The team was never seeded: only a create-team plan admits |
| + // owner-seed and seed-team. Resume that instead. |
| + return e.resumeCreate(ctx, t, apps) |
| + } |
| + if len(apps) == 0 { |
| + return 0, fail("no-apps") |
| + } |
| + var fresh []string |
| + for _, a := range apps { |
| + switch t.Apps[a] { |
| + case "retired": |
| + return 0, fail("app-retired") |
| + case "": |
| + fresh = append(fresh, a) |
| + } |
| + } |
| + if err := e.preflight(withProposal(ctx, label, t.Environment, fresh), label, t.Environment, t.Forked, apps, false); err != nil { |
| + return 0, err |
| + } |
| + if err := e.cfg.Store.AddApps(ctx, label, fresh); err != nil { |
| + return 0, err |
| + } |
| + id, err := e.cfg.Store.NewRun(ctx, homeop.KindAddApps, label, apps) |
| + if err != nil { |
| + return 0, err |
| + } |
| + e.cfg.Store.Audit(ctx, id, label, "", "run-start", homeop.KindAddApps) |
| + return id, e.submitPlans(ctx, id, label, "", "", homeop.KindAddApps, apps) |
| +} |
| + |
| +// resumeCreate is a fresh create-team plan for a team whose seed has not |
| +// committed: its owner must still be held (it is, until step 13). |
| +func (e *Engine) resumeCreate(ctx context.Context, t Team, apps []string) (int64, error) { |
| + owner, ok, err := e.cfg.Store.Owner(ctx, t.Label) |
| + if err != nil { |
| + return 0, err |
| + } |
| + if !ok { |
| + return 0, fail("owner-needed") |
| + } |
| + if len(apps) == 0 { |
| + for a, st := range t.Apps { |
| + if st == "active" { |
| + apps = append(apps, a) |
| + } |
| + } |
| + apps = SortApps(apps) |
| + } |
| + id, err := e.cfg.Store.NewRun(ctx, homeop.KindCreateTeam, t.Label, apps) |
| + if err != nil { |
| + return 0, err |
| + } |
| + e.cfg.Store.Audit(ctx, id, t.Label, "", "run-start", homeop.KindCreateTeam) |
| + return id, e.submitPlans(ctx, id, t.Label, t.Name, owner, homeop.KindCreateTeam, apps) |
| +} |
| + |
| +// RetireApps starts a deprovision run (§9). typed must equal the label. |
| +func (e *Engine) RetireApps(ctx context.Context, label string, apps []string, typed string) (int64, error) { |
| + apps = SortApps(apps) |
| + if typed != label { |
| + return 0, fail("label-mismatch") |
| + } |
| + t, err := e.cfg.Store.Team(ctx, label) |
| + if err != nil { |
| + return 0, fail("no-team") |
| + } |
| + if t.TeamSQID == "" { |
| + return 0, fail("team-not-seeded") |
| + } |
| + if len(apps) == 0 { |
| + return 0, fail("no-apps") |
| + } |
| + for _, a := range apps { |
| + if t.Apps[a] != "active" { |
| + return 0, fail("app-not-active") |
| + } |
| + } |
| + id, err := e.cfg.Store.NewRun(ctx, homeop.KindRetireApps, label, apps) |
| + if err != nil { |
| + return 0, err |
| + } |
| + e.cfg.Store.Audit(ctx, id, label, "", "run-start", homeop.KindRetireApps) |
| + return id, e.submitPlans(ctx, id, label, "", "", homeop.KindRetireApps, apps) |
| +} |
| + |
| +// Resubmit signs a fresh plan for a run whose plan expired unconfirmed. |
| +func (e *Engine) Resubmit(ctx context.Context, runID int64) error { |
| + r, err := e.cfg.Store.Run(ctx, runID) |
| + if err != nil { |
| + return err |
| + } |
| + if r.State == "done" || r.State == "superseded" || r.State == "failed" { |
| + return fail("run-finished") |
| + } |
| + name, owner := "", "" |
| + if r.Kind == homeop.KindCreateTeam { |
| + t, err := e.cfg.Store.Team(ctx, r.Label) |
| + if err != nil { |
| + return err |
| + } |
| + if t.TeamSQID != "" { |
| + return fail("use-add-apps") |
| + } |
| + name = t.Name |
| + var ok bool |
| + if owner, ok, err = e.cfg.Store.Owner(ctx, r.Label); err != nil || !ok { |
| + return fail("owner-needed") |
| + } |
| + } |
| + return e.submitPlans(ctx, runID, r.Label, name, owner, r.Kind, r.Apps) |
| +} |
| + |
| +// preflight is §6 step 0's console and Home half. |
| +func (e *Engine) preflight(ctx context.Context, label, env string, forked bool, apps []string, creating bool) error { |
| + for _, a := range apps { |
| + if _, ok := AppBySlug(a); !ok { |
| + return fail("unknown-app") |
| + } |
| + if e.cfg.Console.Tokens[a] == "" { |
| + return fail("no-credential-" + a) |
| + } |
| + } |
| + for _, role := range []string{homeop.Directory, homeop.Credential} { |
| + ins, o, _ := e.cfg.Home.Inspect(ctx, role) |
| + if o != homeop.OK { |
| + return fail("home-" + role + "-" + o.String()) |
| + } |
| + if role == homeop.Directory && ins.Generation == nil { |
| + return fail("home-not-initialized") |
| + } |
| + } |
| + for _, a := range apps { |
| + app, _ := AppBySlug(a) |
| + cfg, found, err := e.cfg.Console.GetConfig(ctx, a, env) |
| + if err != nil { |
| + return fail("console-" + a) |
| + } |
| + if found { |
| + if creating && !forked { |
| + // Owned by scope alta already, but not a fork Paul made for |
| + // this label: a name Alta does not hold. Refuse rather than |
| + // adopt it. |
| + return fail("environment-exists-" + a) |
| + } |
| + present := map[string]bool{} |
| + for _, v := range cfg.Vars { |
| + present[v.Key] = true |
| + } |
| + if st := PlatformKeys(app, present); st.WrongPrefix != "" { |
| + return fail("mail-prefix-" + a) |
| + } |
| + } else if forked { |
| + return fail("fork-missing-" + a) |
| + } |
| + inst, found, err := e.cfg.Console.GetInstance(ctx, a, RouteHost(label, a, e.cfg.Account)) |
| + if err != nil { |
| + return fail("console-" + a) |
| + } |
| + if found && inst.Environment != env { |
| + return fail("instance-bound-elsewhere-" + a) |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// submitPlans is §6 step 2: one plan per role with one shared plan_id. |
| +// The directory's carries the label and display name, the credential's |
| +// the owner; Home keeps its own copy and Paul confirms that copy. |
| +func (e *Engine) submitPlans(ctx context.Context, runID int64, label, name, owner, kind string, apps []string) error { |
| + planID := homeop.Token() |
| + issued := e.now() |
| + roles := []string{homeop.Directory, homeop.Credential} |
| + if kind == homeop.KindInitialize { |
| + roles = roles[:1] |
| + } |
| + signed := map[string][]byte{} |
| + var expires int64 |
| + for _, role := range roles { |
| + p, err := e.cfg.Home.NewPlan(role, planID, kind, apps, issued) |
| + if err != nil { |
| + return err |
| + } |
| + if role == homeop.Directory && kind != homeop.KindInitialize { |
| + p.Label = label |
| + if kind == homeop.KindCreateTeam { |
| + p.DisplayName = name |
| + } |
| + } |
| + if role == homeop.Credential && kind == homeop.KindCreateTeam { |
| + p.Owner = owner |
| + } |
| + raw, err := homeop.SignPlan(e.cfg.Home.Key, p) |
| + if err != nil { |
| + return err |
| + } |
| + if err := e.cfg.Store.SavePlan(ctx, planID, role, raw, p.Expires); err != nil { |
| + return err |
| + } |
| + signed[role], expires = raw, p.Expires |
| + } |
| + if err := e.cfg.Store.SetRunPlan(ctx, runID, planID, expires); err != nil { |
| + return err |
| + } |
| + e.cfg.Store.Audit(ctx, runID, label, "", "plan-signed", homeop.PlanPrefix(planID)) |
| + for _, role := range roles { |
| + switch o := e.cfg.Home.SubmitPlan(ctx, role, signed[role]); o { |
| + case homeop.OK: |
| + _ = e.cfg.Store.MarkPlan(ctx, planID, role, "pending", 0) |
| + e.cfg.Store.Audit(ctx, runID, label, "", "plan-pending", role) |
| + case homeop.Refused: |
| + _ = e.cfg.Store.SetRunState(ctx, runID, "failed", "plan-refused-"+role) |
| + e.cfg.Store.Audit(ctx, runID, label, "", "plan-refused", role) |
| + return fail("plan-refused-" + role) |
| + default: |
| + // Busy, unavailable or lost: Advance retries with the same |
| + // signed plan until it expires. |
| + e.cfg.Store.Audit(ctx, runID, label, "", "plan-"+o.String(), role) |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// ---- advancing ---- |
| + |
| +// pass is one Advance's view of Home. |
| +type pass struct { |
| + run Run |
| + team Team |
| + ins map[string]homeop.Inspection |
| + open map[string]int64 // role -> window expiry, when this run's window is open |
| + closed map[string]string |
| +} |
| + |
| +func (p *pass) windowOpen(role string, now time.Time) bool { |
| + return p.open[role] > now.Unix()+20 |
| +} |
| + |
| +// Advance takes run as far as it can go now. Only one run advances at a |
| +// time (§8). |
| +func (e *Engine) Advance(ctx context.Context, runID int64) error { |
| + st := e.cfg.Store |
| + if err := st.Lock(ctx, runID, 10*time.Minute); err != nil { |
| + return err |
| + } |
| + defer st.Unlock(ctx, runID) |
| + r, err := st.Run(ctx, runID) |
| + if err != nil { |
| + return err |
| + } |
| + if r.State == "done" || r.State == "superseded" || r.State == "failed" { |
| + return nil |
| + } |
| + _ = st.DropExpiredPlans(ctx) |
| + p := &pass{run: r, ins: map[string]homeop.Inspection{}, open: map[string]int64{}, closed: map[string]string{}} |
| + if r.Label != "" { |
| + if p.team, err = st.Team(ctx, r.Label); err != nil { |
| + return err |
| + } |
| + } |
| + if err := e.windows(ctx, p); err != nil { |
| + return e.settle(ctx, p, err) |
| + } |
| + switch r.Kind { |
| + case homeop.KindInitialize: |
| + return e.settle(ctx, p, e.initialize(ctx, p)) |
| + case homeop.KindRetireApps: |
| + return e.settle(ctx, p, e.retire(ctx, p)) |
| + default: |
| + return e.settle(ctx, p, e.provision(ctx, p)) |
| + } |
| +} |
| + |
| +// settle records the run's state from the pass's outcome. |
| +func (e *Engine) settle(ctx context.Context, p *pass, err error) error { |
| + st := e.cfg.Store |
| + var pk *Park |
| + var fl *Fail |
| + switch { |
| + case err == nil: |
| + _ = st.SetRunState(ctx, p.run.ID, "done", "") |
| + st.Audit(ctx, p.run.ID, p.run.Label, "", "run-done", p.run.Kind) |
| + return nil |
| + case errors.Is(err, errCrash): |
| + return err |
| + case errors.As(err, &fl): |
| + _ = st.SetRunState(ctx, p.run.ID, "failed", fl.Code) |
| + st.Audit(ctx, p.run.ID, p.run.Label, "", "run-failed", fl.Code) |
| + return err |
| + case errors.As(err, &pk): |
| + state := "parked" |
| + if pk.Code == "awaiting-confirm" { |
| + state = "planned" |
| + } |
| + _ = st.SetRunState(ctx, p.run.ID, state, pk.Code) |
| + return nil |
| + default: |
| + if errors.Is(err, console.ErrGuard) { |
| + _ = st.SetRunState(ctx, p.run.ID, "failed", "guard") |
| + st.Audit(ctx, p.run.ID, p.run.Label, "", "guard-refused", "") |
| + return err |
| + } |
| + _ = st.SetRunState(ctx, p.run.ID, "parked", "transient") |
| + e.cfg.Logger.Warn("alta advance", "run", p.run.ID, "outcome", "transient") |
| + if e.cfg.Debug != nil { |
| + e.cfg.Debug(err) |
| + } |
| + return nil |
| + } |
| +} |
| + |
| +// windows reads both roles' plan state for this run: open, pending, or |
| +// gone. A busy role is retried with the same signed plan while it lives. |
| +func (e *Engine) windows(ctx context.Context, p *pass) error { |
| + st := e.cfg.Store |
| + if p.run.PlanID == "" { |
| + return fail("no-plan") |
| + } |
| + subs, err := st.Plans(ctx, p.run.PlanID) |
| + if err != nil { |
| + return err |
| + } |
| + now := e.now().Unix() |
| + pending := false |
| + for role, sub := range subs { |
| + ins, o, _ := e.cfg.Home.Inspect(ctx, role) |
| + if o != homeop.OK { |
| + return park("home-unavailable") |
| + } |
| + p.ins[role] = ins |
| + switch { |
| + case ins.OpenPlan == p.run.PlanID && ins.WindowExpires > now: |
| + p.open[role] = ins.WindowExpires |
| + if sub.State != "open" { |
| + _ = st.MarkPlan(ctx, p.run.PlanID, role, "open", ins.WindowExpires) |
| + st.Audit(ctx, p.run.ID, p.run.Label, "", "window-open", role) |
| + } |
| + case ins.PendingPlan == p.run.PlanID: |
| + pending = true |
| + if sub.State == "signed" { |
| + _ = st.MarkPlan(ctx, p.run.PlanID, role, "pending", 0) |
| + } |
| + case sub.State == "signed" && now < sub.Expires && sub.Signed != nil: |
| + switch e.cfg.Home.SubmitPlan(ctx, role, sub.Signed) { |
| + case homeop.OK: |
| + _ = st.MarkPlan(ctx, p.run.PlanID, role, "pending", 0) |
| + pending = true |
| + case homeop.Refused: |
| + return fail("plan-refused-" + role) |
| + default: |
| + p.closed[role] = "home-busy" |
| + pending = true |
| + } |
| + default: |
| + if sub.State != "closed" { |
| + _ = st.MarkPlan(ctx, p.run.PlanID, role, "closed", 0) |
| + } |
| + if sub.State == "open" || sub.Window > 0 { |
| + p.closed[role] = "window-expired" |
| + } else { |
| + p.closed[role] = "plan-expired" |
| + } |
| + } |
| + } |
| + // Nothing open yet and something still waiting on Paul: the run is |
| + // planned, not parked. |
| + if len(p.open) == 0 && pending { |
| + return park("awaiting-confirm") |
| + } |
| + return nil |
| +} |
| + |
| +func (e *Engine) needWindow(p *pass, role string) error { |
| + if p.windowOpen(role, e.now()) { |
| + return nil |
| + } |
| + if c := p.closed[role]; c != "" { |
| + return park(c) |
| + } |
| + return park("awaiting-confirm-" + role) |
| +} |
| + |
| +// ---- the operator stream ---- |
| + |
| +type opSpec struct { |
| + role, action, label, app, purpose string |
| + // reuse: replay a committed request for this purpose instead of |
| + // signing a new one (its result is the step's result). |
| + reuse bool |
| + build func(base homeop.InputBase) any |
| +} |
| + |
| +var errOpRefused = errors.New("provision: Home refused the operation") |
| + |
| +// replayHeld replays the request Alta holds for s's purpose, if any: a |
| +// signed one whose answer was lost, or (with reuse) a committed one whose |
| +// result the step needs again. handled is false when there is nothing to |
| +// replay, or the held request never committed (then it is marked refused |
| +// and a new one may be signed). |
| +func (e *Engine) replayHeld(ctx context.Context, s opSpec) (homeop.Result, bool, error) { |
| + st := e.cfg.Store |
| + prev, ok, err := st.LastRequest(ctx, s.label, s.app, s.purpose) |
| + if err != nil { |
| + return homeop.Result{}, true, err |
| + } |
| + if !ok || !(prev.State == "signed" || (prev.State == "committed" && s.reuse)) { |
| + return homeop.Result{}, false, nil |
| + } |
| + res, _, o := e.cfg.Home.Execute(ctx, s.role, prev.Bytes) |
| + switch o { |
| + case homeop.OK: |
| + if prev.State == "signed" { |
| + if err := e.acted(s.purpose + "/replayed"); err != nil { |
| + return homeop.Result{}, true, err |
| + } |
| + if err := st.Commit(ctx, prev); err != nil { |
| + return homeop.Result{}, true, err |
| + } |
| + st.Audit(ctx, 0, s.label, s.app, "home-recovered", s.action) |
| + } |
| + return res, true, nil |
| + case homeop.Refused: |
| + if prev.State == "committed" { |
| + return homeop.Result{}, true, fail("replay-refused") |
| + } |
| + // Never committed: it expired before Home saw it, or was refused. |
| + _ = st.MarkRequest(ctx, prev.ID, "refused") |
| + return homeop.Result{}, false, nil |
| + default: |
| + return homeop.Result{}, true, park("home-unavailable") |
| + } |
| +} |
| + |
| +// op runs one Home operation: replay what Alta already signed for this |
| +// purpose (a lost result is recovered by exact replay), else sign the |
| +// next sequence, store it sealed, send it, and record it. |
| +func (e *Engine) op(ctx context.Context, s opSpec) (homeop.Result, error) { |
| + if res, handled, err := e.replayHeld(ctx, s); handled { |
| + return res, err |
| + } |
| + for attempt := 0; attempt < 2; attempt++ { |
| + res, err := e.signAndSend(ctx, s) |
| + if !errors.Is(err, errResync) { |
| + return res, err |
| + } |
| + } |
| + return homeop.Result{}, fail("stream-diverged") |
| +} |
| + |
| +var errResync = errors.New("provision: stream resynchronised") |
| + |
| +func (e *Engine) signAndSend(ctx context.Context, s opSpec) (homeop.Result, error) { |
| + st := e.cfg.Store |
| + seq, head, ok, err := st.Stream(ctx, s.role) |
| + if err != nil { |
| + return homeop.Result{}, err |
| + } |
| + if !ok { |
| + // No stream on record (a fresh Alta, or a lost DB): Home's head is |
| + // the arbiter; read it through a signed inspect. |
| + ins, o, _ := e.cfg.Home.Inspect(ctx, s.role) |
| + if o != homeop.OK { |
| + return homeop.Result{}, park("home-unavailable") |
| + } |
| + if err := st.SetStream(ctx, s.role, ins.Sequence, ins.Head); err != nil { |
| + return homeop.Result{}, err |
| + } |
| + st.Audit(ctx, 0, s.label, s.app, "stream-adopted", s.role) |
| + seq, head = ins.Sequence, ins.Head |
| + } |
| + a, err := e.cfg.Home.NewAuthorization(s.role) |
| + if err != nil { |
| + return homeop.Result{}, err |
| + } |
| + journal, err := st.NextJournal(ctx) |
| + if err != nil { |
| + return homeop.Result{}, err |
| + } |
| + now := e.now().Unix() |
| + a.Sequence, a.Previous, a.JournalSequence = seq+1, head, journal |
| + a.OperationID, a.Action = homeop.Token(), s.action |
| + a.Issued, a.Expires = now, now+homeop.RequestLifetime |
| + req, err := homeop.SignRequest(e.cfg.Home.Key, a, s.build(homeop.InputBase{Version: 1, Operation: s.action, OperationID: a.OperationID})) |
| + if err != nil { |
| + return homeop.Result{}, err |
| + } |
| + row := OpRequest{ID: journal, Role: s.role, Sequence: a.Sequence, OperationID: a.OperationID, Action: s.action, Label: s.label, App: s.app, Purpose: s.purpose, Head: req.Head, Expires: a.Expires, Bytes: req.Bytes} |
| + // Stored before it is sent: whatever happens next, a resume holds the |
| + // exact bytes to replay. |
| + if err := st.SaveRequest(ctx, row); err != nil { |
| + return homeop.Result{}, err |
| + } |
| + res, _, o := e.cfg.Home.Execute(ctx, s.role, req.Bytes) |
| + switch o { |
| + case homeop.OK: |
| + if err := e.acted(s.purpose); err != nil { |
| + return homeop.Result{}, err |
| + } |
| + if err := st.Commit(ctx, row); err != nil { |
| + return homeop.Result{}, err |
| + } |
| + st.Audit(ctx, 0, s.label, s.app, "home-committed", s.action) |
| + return res, nil |
| + case homeop.Refused: |
| + _ = st.MarkRequest(ctx, row.ID, "refused") |
| + ins, io, _ := e.cfg.Home.Inspect(ctx, s.role) |
| + if io != homeop.OK { |
| + return homeop.Result{}, park("home-unavailable") |
| + } |
| + if ins.Sequence != seq || ins.Head != head { |
| + // Home's head moved without Alta: Alta's DB is behind (lost, |
| + // or restored). Adopt Home's position; if Home's head is a |
| + // request Alta holds, that request committed. |
| + if held, ok, _ := st.RequestByHead(ctx, s.role, ins.Head); ok { |
| + _ = st.Commit(ctx, held) |
| + } |
| + if err := st.SetStream(ctx, s.role, ins.Sequence, ins.Head); err != nil { |
| + return homeop.Result{}, err |
| + } |
| + st.Audit(ctx, 0, s.label, s.app, "stream-resync", s.role) |
| + return homeop.Result{}, errResync |
| + } |
| + st.Audit(ctx, 0, s.label, s.app, "home-refused", s.action) |
| + return homeop.Result{}, errOpRefused |
| + default: |
| + // Unavailable or lost: the request may have committed. Only an |
| + // exact replay says; the row stays "signed" for the next pass. |
| + return homeop.Result{}, park("home-unavailable") |
| + } |
| +} |
| + |
| +// ---- initialize ---- |
| + |
| +func (e *Engine) initialize(ctx context.Context, p *pass) error { |
| + if _, ok, _ := e.cfg.Store.Done(ctx, "", "", "initialize"); ok { |
| + return nil |
| + } |
| + if ins := p.ins[homeop.Directory]; ins.Generation != nil { |
| + // Initialized: by this run (a result lost to a crash, recovered by |
| + // replay below), or by nobody Alta knows of. |
| + if _, held, _ := e.cfg.Store.LastRequest(ctx, "", "", "initialize"); !held { |
| + return fail("initialized-elsewhere") |
| + } |
| + } else if err := e.needWindow(p, homeop.Directory); err != nil { |
| + return err |
| + } |
| + gen := homeop.Token() |
| + res, err := e.op(ctx, opSpec{role: homeop.Directory, action: homeop.DirectoryInitialize, purpose: "initialize", reuse: true, |
| + build: func(b homeop.InputBase) any { |
| + return homeop.InitializeInput{InputBase: b, Generation: gen, Baseline: homeop.Baseline} |
| + }}) |
| + if errors.Is(err, errOpRefused) { |
| + return fail("initialize-refused") |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + e.log(p.run.ID, "", "initialize", "done") |
| + return e.cfg.Store.SetStep(ctx, "", "", "initialize", "done", "", map[string]any{"generation": res.Generation}) |
| +} |
| + |
| +// ---- helpers ---- |
| + |
| +func str(d map[string]any, k string) string { |
| + s, _ := d[k].(string) |
| + return s |
| +} |
| + |
| +func num(d map[string]any, k string) int64 { |
| + switch v := d[k].(type) { |
| + case float64: |
| + return int64(v) |
| + case int64: |
| + return v |
| + case int: |
| + return int64(v) |
| + } |
| + return 0 |
| +} |
| + |
| +func contains(list []string, s string) bool { return slices.Contains(list, s) } |
diff --git a/provision/engine_test.go b/provision/engine_test.go| new file mode 100644 |
| index 0000000..6da9812 |
| --- /dev/null |
| +++ b/provision/engine_test.go |
| @@ -0,0 +1,522 @@ |
| +package provision |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/alta/console" |
| + "amadan.net/oficina/alta/homeop" |
| +) |
| + |
| +// checkEndState is what every successful lagged run must leave, however |
| +// it got there: one team, six consumers, six instances bound to the owned |
| +// environment, environments exactly the recipe, no key regenerated, no |
| +// address and no platform value left in Alta. |
| +func checkEndState(t *testing.T, h *harness) { |
| + t.Helper() |
| + if n := h.home.TeamCount(); n != 1 { |
| + t.Fatalf("teams at Home = %d, want 1", n) |
| + } |
| + if n := h.home.ConsumerCount(); n != len(allApps) { |
| + t.Fatalf("credential consumers = %d, want %d", n, len(allApps)) |
| + } |
| + if n := h.con.InstanceCount(); n != len(allApps) { |
| + t.Fatalf("instances = %d, want %d", n, len(allApps)) |
| + } |
| + e := h.engine(nil) |
| + for _, slug := range allApps { |
| + app, _ := AppBySlug(slug) |
| + env, _, ok := h.con.Instance(RouteHost("lagged", slug, account)) |
| + if !ok || env != "lagged" { |
| + t.Fatalf("%s instance bound to %q", slug, env) |
| + } |
| + if _, state, ok := h.con.Claim(PublicHost("lagged", slug)); !ok || state != "live" { |
| + t.Fatalf("%s claim %q", slug, state) |
| + } |
| + if err := e.AuditEnvironment(h.ctx(), "lagged", app); err != nil { |
| + t.Fatalf("%s audit: %v", slug, err) |
| + } |
| + vars, owner, _ := h.con.Env(slug, "lagged") |
| + if owner != "alta" { |
| + t.Fatalf("%s environment owner %q", slug, owner) |
| + } |
| + for k, v := range vars { |
| + if v.Kind == "secret" && !console.PlatformManaged(k) && h.con.SecretWrites[slug+"/lagged/"+k] != 1 { |
| + t.Fatalf("%s %s written %d times: a generated key was regenerated", slug, k, h.con.SecretWrites[slug+"/lagged/"+k]) |
| + } |
| + } |
| + want := "pending" |
| + if app.Roster { |
| + want = "live" |
| + } |
| + if got := h.home.InstanceState(ConsumerID("lagged", slug)); got != want { |
| + t.Fatalf("%s directory row %q, want %q", slug, got, want) |
| + } |
| + } |
| + // The roster bearer reached Docs, sealed, and is Home's. |
| + if v, err := h.con.Open("docs", "lagged", "DOCS_TEAM_ROSTER_TOKEN"); err != nil || len(v) != 43 { |
| + t.Fatalf("roster token: %q %v", v, err) |
| + } |
| + // Generated keys are 32 random bytes. |
| + if v, err := h.con.Open("calls", "lagged", "CALLS_DEK"); err != nil || len(b64(v)) != 32 { |
| + t.Fatalf("CALLS_DEK: %v", err) |
| + } |
| + // Privacy (§12): no address after step 13 anywhere in Alta's DB, and |
| + // no platform value ever. |
| + var n int |
| + _ = h.store.DB().QueryRow("SELECT count(*) FROM owner_inputs").Scan(&n) |
| + if n != 0 { |
| + t.Fatal("owner input survives step 13") |
| + } |
| + _ = h.store.DB().QueryRow("SELECT count(*) FROM operator_requests WHERE action='credential.owner-seed'").Scan(&n) |
| + if n != 0 { |
| + t.Fatal("owner-seed request survives step 13") |
| + } |
| + _ = h.store.DB().QueryRow("SELECT count(*) FROM plan_submissions WHERE role='credential' AND sealed_plan IS NOT NULL").Scan(&n) |
| + if n != 0 { |
| + t.Fatal("credential plan survives step 13") |
| + } |
| + _, _ = h.store.DB().Exec("PRAGMA wal_checkpoint(TRUNCATE)") |
| + for _, needle := range []string{ownerCanary, "fakeconsole", "PLATFORM-VALUE-CANARY", "lagged.test"} { |
| + if h.scan(needle) { |
| + t.Fatalf("%q found in Alta's database files", needle) |
| + } |
| + } |
| + for _, needle := range []string{ownerCanary, "lagged", "PLATFORM-VALUE-CANARY"} { |
| + if strings.Contains(h.logs.String(), needle) { |
| + t.Fatalf("%q in Alta's logs", needle) |
| + } |
| + } |
| +} |
| + |
| +func TestCreateTeamEndToEnd(t *testing.T) { |
| + h := newHarness(t) |
| + h.initialized() |
| + e := h.engine(nil) |
| + run := h.createLagged(e) |
| + r := h.drive(e, run, 40) |
| + if r.State != "done" { |
| + steps, _ := h.store.Steps(h.ctx(), "lagged") |
| + t.Fatalf("run %s %s; steps %+v", r.State, r.Code, steps) |
| + } |
| + checkEndState(t, h) |
| + // Every Home write was under the one plan id Paul confirmed. |
| + if h.home.Calls[homeop.CredentialOwnerSeed] != 1 || h.home.Calls[homeop.DirectorySeedTeam] != 1 { |
| + t.Fatalf("owner-seed %d, seed-team %d", h.home.Calls[homeop.CredentialOwnerSeed], h.home.Calls[homeop.DirectorySeedTeam]) |
| + } |
| +} |
| + |
| +// countActs runs a whole create-team and returns its acts in order. |
| +func countActs(t *testing.T) []string { |
| + h := newHarness(t) |
| + h.initialized() |
| + var acts []string |
| + e := h.engine(func(k string) error { acts = append(acts, k); return nil }) |
| + run := h.createLagged(e) |
| + if r := h.drive(e, run, 40); r.State != "done" { |
| + t.Fatalf("clean run %s %s", r.State, r.Code) |
| + } |
| + return acts |
| +} |
| + |
| +// TestCrashAfterEveryAct is §12's crash injection: after every act (the |
| +// remote effect has happened, Alta has not recorded it) the process dies; |
| +// a fresh engine over the same database resumes by probing and reaches |
| +// the same end state with no duplicate instance, consumer or team. |
| +func TestCrashAfterEveryAct(t *testing.T) { |
| + acts := countActs(t) |
| + if len(acts) < 20 { |
| + t.Fatalf("only %d acts: %v", len(acts), acts) |
| + } |
| + for i := range acts { |
| + t.Run(fmt.Sprintf("%02d-%s", i, strings.ReplaceAll(acts[i], "/", "-")), func(t *testing.T) { |
| + h := newHarness(t) |
| + h.initialized() |
| + n := 0 |
| + crashed := false |
| + e := h.engine(func(k string) error { |
| + if n == i && !crashed { |
| + crashed = true |
| + return errors.New("kill -9") |
| + } |
| + n++ |
| + return nil |
| + }) |
| + run := h.createLagged(e) |
| + for j := 0; j < 40 && !crashed; j++ { |
| + _ = e.Advance(h.ctx(), run) |
| + h.con.Walk() |
| + h.tick(5 * time.Second) |
| + } |
| + if !crashed { |
| + t.Fatalf("act %d never reached", i) |
| + } |
| + // The crashed process's lock is stale on restart. |
| + h.tick(11 * time.Minute) |
| + if r, _ := h.store.Run(h.ctx(), run); r.State != "done" { |
| + // The window may have closed during the restart: Paul |
| + // confirms a fresh plan for the same apps. |
| + if r2 := h.drive(h.engine(nil), run, 40); r2.State != "done" { |
| + next, err := h.engine(nil).AddApps(h.ctx(), "lagged", allApps) |
| + if err != nil { |
| + t.Fatalf("resume plan: %v (run %s %s)", err, r2.State, r2.Code) |
| + } |
| + kind := homeop.KindAddApps |
| + if _, _, seeded := h.home.Team("lagged"); !seeded { |
| + kind = homeop.KindCreateTeam |
| + } |
| + h.confirm(kind) |
| + if r3 := h.drive(h.engine(nil), next, 40); r3.State != "done" { |
| + t.Fatalf("after crash at %s: %s %s", acts[i], r3.State, r3.Code) |
| + } |
| + } |
| + } |
| + checkEndState(t, h) |
| + }) |
| + } |
| +} |
| + |
| +// TestLostAnswersAreRecoveredByReplay: Home commits and the answer is |
| +// lost on the way back, for every verb. Nothing is inferred from it; the |
| +// exact replay returns the stored result. |
| +func TestLostAnswersAreRecoveredByReplay(t *testing.T) { |
| + for _, action := range []string{homeop.CredentialOwnerSeed, homeop.DirectorySeedTeam, homeop.DirectoryProvision, homeop.CredentialRegister, homeop.DirectoryVerify, homeop.DirectoryActivate} { |
| + t.Run(action, func(t *testing.T) { |
| + h := newHarness(t) |
| + h.initialized() |
| + lost := false |
| + h.home.LoseAnswer = func(a string) bool { |
| + if a == action && !lost { |
| + lost = true |
| + return true |
| + } |
| + return false |
| + } |
| + e := h.engine(nil) |
| + run := h.createLagged(e) |
| + if r := h.drive(e, run, 40); r.State != "done" { |
| + t.Fatalf("%s %s", r.State, r.Code) |
| + } |
| + if !lost { |
| + t.Fatal("no answer was lost") |
| + } |
| + checkEndState(t, h) |
| + }) |
| + } |
| +} |
| + |
| +// TestExpiredReceiptTakesANewOwnerSeed: replay returns the same expired |
| +// receipt by design, so an expired one leads to a new owner-seed, not a |
| +// stuck step 4. |
| +func TestExpiredReceiptTakesANewOwnerSeed(t *testing.T) { |
| + h := newHarness(t) |
| + h.initialized() |
| + down := true |
| + h.home.Outage = func(a string) bool { return down && a == homeop.DirectorySeedTeam } |
| + e := h.engine(nil) |
| + run := h.createLagged(e) |
| + _ = e.Advance(h.ctx(), run) |
| + if h.home.Calls[homeop.CredentialOwnerSeed] != 1 { |
| + t.Fatalf("owner-seed calls %d", h.home.Calls[homeop.CredentialOwnerSeed]) |
| + } |
| + h.tick(6 * time.Minute) // the receipt (300 s) and the signed seed-team expire |
| + down = false |
| + if r := h.drive(e, run, 40); r.State != "done" { |
| + t.Fatalf("%s %s", r.State, r.Code) |
| + } |
| + if h.home.Calls[homeop.CredentialOwnerSeed] != 2 { |
| + t.Fatalf("owner-seed calls %d, want a second for the expired receipt", h.home.Calls[homeop.CredentialOwnerSeed]) |
| + } |
| + checkEndState(t, h) |
| +} |
| + |
| +// TestStreamResyncAfterLostDatabase: Alta's stream rows are gone (a DB |
| +// restored from before its last operations). Home refuses the stale |
| +// sequence; Alta re-reads Home's head through a signed inspect and goes on. |
| +func TestStreamResyncAfterLostDatabase(t *testing.T) { |
| + h := newHarness(t) |
| + h.initialized() |
| + e := h.engine(nil) |
| + run := h.createLagged(e) |
| + _ = e.Advance(h.ctx(), run) |
| + seq, _ := h.home.Stream(homeop.Directory) |
| + if seq < 3 { |
| + t.Fatalf("directory sequence %d", seq) |
| + } |
| + // Roll Alta's view back to sequence 1, as a restored backup would. |
| + var oldHead string |
| + if err := h.store.DB().QueryRow("SELECT head FROM operator_requests WHERE role='directory' AND sequence=1").Scan(&oldHead); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := h.store.SetStream(h.ctx(), homeop.Directory, 1, oldHead); err != nil { |
| + t.Fatal(err) |
| + } |
| + if r := h.drive(e, run, 40); r.State != "done" { |
| + t.Fatalf("%s %s", r.State, r.Code) |
| + } |
| + got, head := h.home.Stream(homeop.Directory) |
| + if s, hd, _, _ := h.store.Stream(h.ctx(), homeop.Directory); s != got || hd != head { |
| + t.Fatalf("Alta's stream %d/%s, Home's %d/%s", s, hd, got, head) |
| + } |
| + audit, _ := h.store.AuditLog(h.ctx(), "lagged", 500) |
| + found := false |
| + for _, a := range audit { |
| + found = found || a.Event == "stream-resync" |
| + } |
| + if !found { |
| + t.Fatal("no stream-resync in the audit") |
| + } |
| +} |
| + |
| +func TestWindowExpiryParksAndAddAppsResumes(t *testing.T) { |
| + h := newHarness(t) |
| + h.initialized() |
| + h.con.DomainPolls = 1000 // domains do not issue within the window |
| + e := h.engine(nil) |
| + run := h.createLagged(e) |
| + r := h.drive(e, run, 5) |
| + if r.State != "parked" { |
| + t.Fatalf("%s %s", r.State, r.Code) |
| + } |
| + h.tick(homeop.WindowLifetime * time.Second) |
| + for _, a := range allApps { |
| + h.con.SetDomainState(PublicHost("lagged", a), "live") |
| + } |
| + if r = h.drive(e, run, 10); r.State != "parked" || r.Code != "window-expired" { |
| + t.Fatalf("after window: %s %s", r.State, r.Code) |
| + } |
| + next, err := e.AddApps(h.ctx(), "lagged", allApps) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + h.confirm(homeop.KindAddApps) |
| + if r = h.drive(e, next, 40); r.State != "done" { |
| + t.Fatalf("add-apps: %s %s", r.State, r.Code) |
| + } |
| + checkEndState(t, h) |
| +} |
| + |
| +func TestLabelsAreNeverReused(t *testing.T) { |
| + h := newHarness(t) |
| + h.initialized() |
| + e := h.engine(nil) |
| + run := h.createLagged(e) |
| + h.drive(e, run, 40) |
| + _, err := e.CreateTeam(h.ctx(), NewTeam{Label: "lagged", Name: "Again", Owner: ownerCanary, Apps: []string{"docs"}}) |
| + var fl *Fail |
| + if !errors.As(err, &fl) || fl.Code != "label-used" { |
| + t.Fatalf("reused label: %v", err) |
| + } |
| + // Alta's label rule is tighter than Home's. |
| + for _, bad := range []string{"a", "Lagged", "-lag", "lag-", strings.Repeat("a", 33), "la_g"} { |
| + if _, err := e.CreateTeam(h.ctx(), NewTeam{Label: bad, Name: "x", Owner: ownerCanary, Apps: []string{"docs"}}); !errors.As(err, &fl) || fl.Code != "label-shape" { |
| + t.Fatalf("label %q: %v", bad, err) |
| + } |
| + } |
| +} |
| + |
| +func TestOwnerMustAlreadyExist(t *testing.T) { |
| + h := newHarness(t) |
| + h.initialized() |
| + e := h.engine(nil) |
| + _, err := e.CreateTeam(h.ctx(), NewTeam{Label: "alpha", Name: "Alpha", Owner: "nobody@nowhere.test", Apps: []string{"docs"}}) |
| + var fl *Fail |
| + if !errors.As(err, &fl) || fl.Code != "plan-refused-credential" { |
| + t.Fatalf("unknown owner: %v", err) |
| + } |
| +} |
| + |
| +func TestDocsMailUnderTheWrongPrefixRefuses(t *testing.T) { |
| + h := newHarness(t) |
| + h.initialized() |
| + h.con.MailPrefix["docs"] = "CARLOS_SMTP" // Docs reads DOCS_SMTP_* only |
| + e := h.engine(nil) |
| + run := h.createLagged(e) |
| + r := h.drive(e, run, 10) |
| + if r.State != "failed" || r.Code != "mail-prefix-docs" { |
| + t.Fatalf("%s %s", r.State, r.Code) |
| + } |
| +} |
| + |
| +func TestPlatformKeysAwaitTheWalk(t *testing.T) { |
| + h := newHarness(t) |
| + h.initialized() |
| + e := h.engine(nil) |
| + run, err := e.CreateTeam(h.ctx(), NewTeam{Label: "beta", Name: "Beta", Owner: ownerCanary, Apps: []string{"calls"}}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + h.confirm(homeop.KindCreateTeam) |
| + _ = e.Advance(h.ctx(), run) |
| + st, _, _ := h.store.Step(h.ctx(), "beta", "calls", StepEnv) |
| + if st.Code != "awaiting-platform-keys" { |
| + t.Fatalf("env step %s %s", st.State, st.Code) |
| + } |
| + // No instance before PLATFORM keys are there (§6). |
| + if h.con.InstanceCount() != 0 { |
| + t.Fatal("instance created before the platform keys arrived") |
| + } |
| + h.con.Walk() |
| + if r := h.drive(e, run, 20); r.State != "done" { |
| + t.Fatalf("%s %s", r.State, r.Code) |
| + } |
| + vars, _, _ := h.con.Env("calls", "beta") |
| + if _, ok := vars["CARLOS_RELAY"]; !ok { |
| + t.Fatal("no relay identity") |
| + } |
| +} |
| + |
| +func TestForkedEnvironmentKeepsKeysAndDropsTrack1Extras(t *testing.T) { |
| + h := newHarness(t) |
| + h.initialized() |
| + // Paul: carlos env fork --from lagged --to lagged-team --scope alta, |
| + // then the rebind. The fork carries lagged's own keys only. |
| + h.con.SetEnv("memoria", "lagged-team", "alta", map[string]fakeVar{ |
| + "MEMORIA_DEK": {Kind: "secret", Envelope: sealFor(t, h, "memoria", "till-data-key")}, |
| + "MEMORIA_INSTANCE_KEY": {Kind: "secret", Envelope: sealFor(t, h, "memoria", "instance")}, |
| + "MEMORIA_ORIGIN": {Kind: "env", Value: "https://lagged.memoria.oficina.works"}, |
| + "MEMORIA_OWNERS": {Kind: "env", Value: ownerCanary}, |
| + "MEMORIA_AI": {Kind: "env", Value: ""}, |
| + "OFICINA_DASHBOARD_TEAM": {Kind: "env", Value: ""}, |
| + }) |
| + h.con.AddInstance("memoria", RouteHost("lagged", "memoria", account), "lagged-team") |
| + h.con.AddClaim("memoria", PublicHost("lagged", "memoria"), RouteHost("lagged", "memoria", account), "live") |
| + e := h.engine(nil) |
| + run, err := e.CreateTeam(h.ctx(), NewTeam{Label: "lagged", Name: "Lagged", Owner: ownerCanary, Apps: []string{"memoria"}, Forked: true}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + h.confirm(homeop.KindCreateTeam) |
| + if r := h.drive(e, run, 20); r.State != "done" { |
| + t.Fatalf("%s %s", r.State, r.Code) |
| + } |
| + vars, _, _ := h.con.Env("memoria", "lagged-team") |
| + for _, k := range []string{"MEMORIA_AI", "OFICINA_DASHBOARD_TEAM"} { |
| + if _, ok := vars[k]; ok { |
| + t.Fatalf("%s survived the fork", k) |
| + } |
| + } |
| + if v, _ := h.con.Open("memoria", "lagged-team", "MEMORIA_DEK"); v != "till-data-key" { |
| + t.Fatal("the forked DEK was regenerated: Till's data would be unreadable") |
| + } |
| + if _, restarts, _ := h.con.Instance(RouteHost("lagged", "memoria", account)); restarts == 0 { |
| + t.Fatal("config changed under a running instance without a restart") |
| + } |
| +} |
| + |
| +func TestExtraKeyInAnUnforkedEnvironmentRefuses(t *testing.T) { |
| + h := newHarness(t) |
| + h.initialized() |
| + e := h.engine(nil) |
| + run, err := e.CreateTeam(h.ctx(), NewTeam{Label: "gamma", Name: "Gamma", Owner: ownerCanary, Apps: []string{"sheets"}}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + h.confirm(homeop.KindCreateTeam) |
| + if r := h.drive(e, run, 20); r.State != "done" { |
| + t.Fatalf("%s %s", r.State, r.Code) |
| + } |
| + vars, _, _ := h.con.Env("sheets", "gamma") |
| + vars["SNEAKY"] = fakeVar{Kind: "env", Value: "x"} |
| + h.con.SetEnv("sheets", "gamma", "alta", vars) |
| + app, _ := AppBySlug("sheets") |
| + var fl *Fail |
| + if err := e.AuditEnvironment(h.ctx(), "gamma", app); !errors.As(err, &fl) || fl.Code != "audit-extra-key" { |
| + t.Fatalf("audit with an extra key: %v", err) |
| + } |
| +} |
| + |
| +func TestDeprovision(t *testing.T) { |
| + h := newHarness(t) |
| + h.initialized() |
| + e := h.engine(nil) |
| + run := h.createLagged(e) |
| + h.drive(e, run, 40) |
| + h.tick(homeop.WindowLifetime * time.Second) |
| + var fl *Fail |
| + if _, err := e.RetireApps(h.ctx(), "lagged", []string{"calls"}, "laged"); !errors.As(err, &fl) || fl.Code != "label-mismatch" { |
| + t.Fatalf("mistyped label: %v", err) |
| + } |
| + ret, err := e.RetireApps(h.ctx(), "lagged", []string{"docs", "calls"}, "lagged") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + h.confirm(homeop.KindRetireApps) |
| + if r := h.drive(e, ret, 10); r.State != "done" { |
| + t.Fatalf("%s %s", r.State, r.Code) |
| + } |
| + for _, a := range []string{"docs", "calls"} { |
| + if got := h.home.InstanceState(ConsumerID("lagged", a)); got != "disabled" { |
| + t.Fatalf("%s directory %q", a, got) |
| + } |
| + if got := h.home.ConsumerState(ConsumerID("lagged", a)); got != "retired" { |
| + t.Fatalf("%s credential %q", a, got) |
| + } |
| + if _, _, ok := h.con.Claim(PublicHost("lagged", a)); ok { |
| + t.Fatalf("%s claim survives", a) |
| + } |
| + if _, _, ok := h.con.Instance(RouteHost("lagged", a, account)); ok { |
| + t.Fatalf("%s instance survives", a) |
| + } |
| + // The owned environment survives (no delete verb exists). |
| + if _, _, ok := h.con.Env(a, "lagged"); !ok { |
| + t.Fatalf("%s environment gone", a) |
| + } |
| + } |
| + // Retired hostnames are never reused. |
| + h.tick(homeop.WindowLifetime * time.Second) |
| + if _, err := e.AddApps(h.ctx(), "lagged", []string{"calls"}); !errors.As(err, &fl) || fl.Code != "app-retired" { |
| + t.Fatalf("re-adding a retired app: %v", err) |
| + } |
| + // Untouched apps keep running. |
| + if _, _, ok := h.con.Instance(RouteHost("lagged", "sheets", account)); !ok { |
| + t.Fatal("sheets went with them") |
| + } |
| +} |
| + |
| +func TestInitializeNeedsTheTypedAttestation(t *testing.T) { |
| + h := newHarness(t) |
| + e := h.engine(nil) |
| + var fl *Fail |
| + if _, err := e.StartInitialize(h.ctx(), "yes"); !errors.As(err, &fl) || fl.Code != "attestation-mismatch" { |
| + t.Fatalf("%v", err) |
| + } |
| + // Before initialize, no team can be created. |
| + if _, err := e.CreateTeam(h.ctx(), NewTeam{Label: "alpha", Name: "Alpha", Owner: ownerCanary, Apps: []string{"docs"}}); !errors.As(err, &fl) || fl.Code != "home-not-initialized" { |
| + t.Fatalf("%v", err) |
| + } |
| + h.initialized() |
| + if _, err := e.StartInitialize(h.ctx(), InitializeAttestation); !errors.As(err, &fl) || fl.Code != "already-initialized" { |
| + t.Fatalf("%v", err) |
| + } |
| +} |
| + |
| +func TestPlanIsTheSameOnBothRoles(t *testing.T) { |
| + h := newHarness(t) |
| + h.initialized() |
| + e := h.engine(nil) |
| + run := h.createLagged(e) |
| + r, _ := h.store.Run(h.ctx(), run) |
| + plans, _ := h.store.Plans(h.ctx(), r.PlanID) |
| + if len(plans) != 2 { |
| + t.Fatalf("plans %d", len(plans)) |
| + } |
| + for role, p := range plans { |
| + raw, _ := homeop.EnvelopePayload(p.Signed) |
| + var plan homeop.Plan |
| + if err := homeop.Decode(raw, &plan); err != nil || plan.PlanID != r.PlanID { |
| + t.Fatalf("%s plan %v", role, err) |
| + } |
| + if role == homeop.Directory && (plan.Label != "lagged" || plan.DisplayName != "Lagged" || plan.Owner != "") { |
| + t.Fatalf("directory plan %+v", plan) |
| + } |
| + if role == homeop.Credential && (plan.Owner != ownerCanary || plan.Label != "" || plan.DisplayName != "") { |
| + t.Fatalf("credential plan carries %+v", plan) |
| + } |
| + } |
| + _ = context.Background |
| +} |
diff --git a/provision/guard_test.go b/provision/guard_test.go| new file mode 100644 |
| index 0000000..cb73817 |
| --- /dev/null |
| +++ b/provision/guard_test.go |
| @@ -0,0 +1,147 @@ |
| +package provision |
| + |
| +import ( |
| + "errors" |
| + "testing" |
| + |
| + "amadan.net/oficina/alta/console" |
| + "amadan.net/oficina/alta/homeop" |
| +) |
| + |
| +// The §8 guards, each with a test that fails if the guard is removed. |
| +// Every refusal must happen before a request leaves the process: the fake |
| +// console's request log is checked unchanged. |
| + |
| +func guardHarness(t *testing.T) (*harness, *Engine) { |
| + h := newHarness(t) |
| + h.initialized() |
| + e := h.engine(nil) |
| + run, err := e.CreateTeam(h.ctx(), NewTeam{Label: "alpha", Name: "Alpha", Owner: ownerCanary, Apps: []string{"sheets", "calls"}}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + h.confirm(homeop.KindCreateTeam) |
| + h.drive(e, run, 20) |
| + return h, e |
| +} |
| + |
| +func refusedLocally(t *testing.T, h *harness, what string, err error) { |
| + t.Helper() |
| + if !errors.Is(err, console.ErrGuard) { |
| + t.Fatalf("%s: want Alta's guard to refuse, got %v", what, err) |
| + } |
| +} |
| + |
| +func TestGuardRefusesEmptyEnvironment(t *testing.T) { |
| + h, e := guardHarness(t) |
| + before := len(h.con.Requests) |
| + _, err := e.cfg.Console.PutConfig(h.ctx(), "sheets", "", map[string]console.SetVar{"X": {Kind: "env", Value: "1"}}, nil, "") |
| + refusedLocally(t, h, "empty environment", err) |
| + _, _, err = e.cfg.Console.GetConfig(h.ctx(), "sheets", "") |
| + refusedLocally(t, h, "empty environment read", err) |
| + if len(h.con.Requests) != before { |
| + t.Fatal("a refused request reached the console") |
| + } |
| +} |
| + |
| +func TestGuardRefusesEnvironmentNotInAltasRecords(t *testing.T) { |
| + h, e := guardHarness(t) |
| + before := len(h.con.Requests) |
| + // "default" and Paul's own named environments are never Alta's. |
| + for _, env := range []string{"default", "slice2", "lagged", "beta"} { |
| + _, err := e.cfg.Console.PutConfig(h.ctx(), "sheets", env, map[string]console.SetVar{"X": {Kind: "env", Value: "1"}}, nil, "") |
| + refusedLocally(t, h, env, err) |
| + } |
| + // alpha's environment is Alta's for sheets and calls, not for docs. |
| + _, err := e.cfg.Console.PutConfig(h.ctx(), "docs", "alpha", map[string]console.SetVar{"X": {Kind: "env", Value: "1"}}, nil, "") |
| + refusedLocally(t, h, "alpha for docs", err) |
| + if len(h.con.Requests) != before { |
| + t.Fatal("a refused request reached the console") |
| + } |
| +} |
| + |
| +func TestGuardRefusesHostsOutsideAltasShapes(t *testing.T) { |
| + h, e := guardHarness(t) |
| + before := len(h.con.Requests) |
| + for _, host := range []string{ |
| + "sheets.oficina.works", // Paul's own |
| + "sheets.bds.oncarlos.com", // Paul's route |
| + "beta-sheets.bds.oncarlos.com", // a label Alta does not hold |
| + "alpha-sheets.other.oncarlos.com", // another account |
| + "alpha.sheets.example.com", // another domain |
| + "alpha-docs.bds.oncarlos.com", // an app the team does not have |
| + "x.alpha.sheets.oficina.works", // a deeper name |
| + } { |
| + err := e.cfg.Console.CreateInstance(h.ctx(), "sheets", host, "alpha", "") |
| + refusedLocally(t, h, host, err) |
| + err = e.cfg.Console.AttachDomain(h.ctx(), "sheets", host, RouteHost("alpha", "sheets", account), "") |
| + refusedLocally(t, h, host+" attach", err) |
| + err = e.cfg.Console.RestartHost(h.ctx(), "sheets", host, "") |
| + refusedLocally(t, h, host+" restart", err) |
| + } |
| + if len(h.con.Requests) != before { |
| + t.Fatal("a refused request reached the console") |
| + } |
| +} |
| + |
| +func TestGuardRefusesDeleteOutsideADeprovisionRun(t *testing.T) { |
| + h, e := guardHarness(t) |
| + before := len(h.con.Requests) |
| + refusedLocally(t, h, "delete instance", e.cfg.Console.DeleteInstance(h.ctx(), "sheets", RouteHost("alpha", "sheets", account))) |
| + refusedLocally(t, h, "detach domain", e.cfg.Console.DetachDomain(h.ctx(), "sheets", PublicHost("alpha", "sheets"))) |
| + // A deprovision run for calls does not admit a DELETE for sheets. |
| + h.tick(homeop.WindowLifetime * 1e9) |
| + run, err := e.RetireApps(h.ctx(), "alpha", []string{"calls"}, "alpha") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx := WithDeprovision(h.ctx(), run) |
| + refusedLocally(t, h, "delete for an app the run does not name", e.cfg.Console.DeleteInstance(ctx, "sheets", RouteHost("alpha", "sheets", account))) |
| + // A create-team run id is not a deprovision run. |
| + refusedLocally(t, h, "delete under a create run", e.cfg.Console.DeleteInstance(WithDeprovision(h.ctx(), 1), "calls", RouteHost("alpha", "calls", account))) |
| + if len(h.con.Requests) != before { |
| + t.Fatal("a refused request reached the console") |
| + } |
| + if _, _, ok := h.con.Instance(RouteHost("alpha", "sheets", account)); !ok { |
| + t.Fatal("sheets instance deleted") |
| + } |
| +} |
| + |
| +func TestGuardRefusesPlatformManagedKeys(t *testing.T) { |
| + h, e := guardHarness(t) |
| + before := len(h.con.Requests) |
| + for _, k := range []string{"CARLOS_SMTP_PASS", "DOCS_SMTP_USER", "SHEETS_SMTP_HOST", "CARLOS_RELAY", "CARLOS_MAIL_EVENTS_KEY", "SLIDES_SCAN_CALLBACK_SECRET", "CARLOS_STORE_BUCKET"} { |
| + _, err := e.cfg.Console.PutConfig(h.ctx(), "sheets", "alpha", map[string]console.SetVar{k: {Kind: "env", Value: "x"}}, nil, "") |
| + refusedLocally(t, h, "set "+k, err) |
| + _, err = e.cfg.Console.PutConfig(h.ctx(), "sheets", "alpha", nil, []string{k}, "") |
| + refusedLocally(t, h, "unset "+k, err) |
| + } |
| + if len(h.con.Requests) != before { |
| + t.Fatal("a refused request reached the console") |
| + } |
| + // And the recipe never names one. |
| + for _, a := range Apps { |
| + for _, k := range Recipe(a, Inputs{Label: "alpha"}) { |
| + if console.PlatformManaged(k.Name) { |
| + t.Fatalf("%s recipe names platform-managed %s", a.Slug, k.Name) |
| + } |
| + } |
| + } |
| +} |
| + |
| +// TestGuardAllowsPreflightReadsOnly: a preflight may read a proposed |
| +// label's hosts and environment (checking a label must not burn it), but |
| +// never write them. |
| +func TestGuardAllowsPreflightReadsOnly(t *testing.T) { |
| + h, e := guardHarness(t) |
| + ctx := withProposal(h.ctx(), "delta", "delta", []string{"docs"}) |
| + if _, _, err := e.cfg.Console.GetConfig(ctx, "docs", "delta"); err != nil { |
| + t.Fatalf("preflight read: %v", err) |
| + } |
| + if _, _, err := e.cfg.Console.GetInstance(ctx, "docs", RouteHost("delta", "docs", account)); err != nil { |
| + t.Fatalf("preflight read: %v", err) |
| + } |
| + _, err := e.cfg.Console.PutConfig(ctx, "docs", "delta", map[string]console.SetVar{"X": {Kind: "env", Value: "1"}}, nil, "") |
| + refusedLocally(t, h, "preflight write", err) |
| + refusedLocally(t, h, "preflight create", e.cfg.Console.CreateInstance(ctx, "docs", RouteHost("delta", "docs", account), "delta", "")) |
| +} |
diff --git a/provision/harness_test.go b/provision/harness_test.go| new file mode 100644 |
| index 0000000..3a23e5e |
| --- /dev/null |
| +++ b/provision/harness_test.go |
| @@ -0,0 +1,204 @@ |
| +package provision |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/base64" |
| + "errors" |
| + "io" |
| + "log/slog" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/alta/console" |
| + "amadan.net/oficina/alta/console/fakeconsole" |
| + "amadan.net/oficina/alta/homeop" |
| + "amadan.net/oficina/alta/homeop/fakehome" |
| + family "amadan.net/rastrillo/rastrillo/crypto" |
| +) |
| + |
| +const ( |
| + ownerCanary = "till-owner-canary@lagged.test" |
| + credOrigin = "https://id.oficina.works" |
| + dirOrigin = "https://oficina.works" |
| + account = "bds" |
| +) |
| + |
| +type harness struct { |
| + t *testing.T |
| + now time.Time |
| + home *fakehome.Home |
| + dir *httptest.Server |
| + cred *httptest.Server |
| + con *fakeconsole.Console |
| + key *family.Keypair |
| + pre string |
| + path string |
| + store *Store |
| + tokens map[string]string |
| + logs *bytes.Buffer |
| +} |
| + |
| +func newHarness(t *testing.T) *harness { |
| + t.Helper() |
| + h := &harness{t: t, now: time.Unix(2_000_000_000, 0), logs: &bytes.Buffer{}} |
| + var err error |
| + if h.key, err = family.Generate(); err != nil { |
| + t.Fatal(err) |
| + } |
| + h.pre = homeop.Token() |
| + h.home = fakehome.New(h.key.SignPub(), h.pre, credOrigin, dirOrigin, h.clock) |
| + h.home.AddPerson(ownerCanary) |
| + h.dir = httptest.NewServer(h.home.Handler(homeop.Directory)) |
| + h.cred = httptest.NewServer(h.home.Handler(homeop.Credential)) |
| + t.Cleanup(h.dir.Close) |
| + t.Cleanup(h.cred.Close) |
| + h.con = fakeconsole.New(account, "alta") |
| + t.Cleanup(h.con.Close) |
| + h.tokens = map[string]string{} |
| + for _, a := range Apps { |
| + h.tokens[a.Slug] = h.con.Mint(a.Slug) |
| + h.con.Versions[a.Slug] = "0123456789abcdef0123456789abcdef01234567" |
| + h.con.MailPrefix[a.Slug] = a.MailPrefixes[0] |
| + } |
| + h.con.Relay["calls"] = true |
| + h.path = filepath.Join(t.TempDir(), "alta.db") |
| + db, err := OpenDB(h.path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { db.Close() }) |
| + if h.store, err = NewStore(context.Background(), db, bytes.Repeat([]byte{4}, 32), h.clock); err != nil { |
| + t.Fatal(err) |
| + } |
| + return h |
| +} |
| + |
| +func (h *harness) clock() time.Time { return h.now } |
| +func (h *harness) tick(d time.Duration) { h.now = h.now.Add(d) } |
| +func (h *harness) ctx() context.Context { return context.Background() } |
| + |
| +func (h *harness) engine(hook func(string) error) *Engine { |
| + roles := map[string]homeop.Role{} |
| + for _, r := range []string{homeop.Credential, homeop.Directory} { |
| + p := h.home.Pins(r) |
| + origin, url := credOrigin, h.cred.URL |
| + if r == homeop.Directory { |
| + origin, url = dirOrigin, h.dir.URL |
| + } |
| + roles[r] = homeop.Role{Name: r, Origin: origin, URL: url, Installation: p.Installation, Registry: p.Registry, Device: p.Device} |
| + } |
| + hc := &homeop.Client{Key: h.key, Prefilter: h.pre, Roles: roles, Now: h.clock} |
| + cc := &console.Client{Base: h.con.URL(), Account: account, Tokens: h.tokens, Guard: Guard{Store: h.store, Account: account}} |
| + return New(Config{Store: h.store, Home: hc, Console: cc, Public: &http.Client{Transport: h.con.Transport()}, |
| + HomeCfg: HomeConfig{Issuer: credOrigin, Directory: dirOrigin, KeysBase64: "eyJrMSI6IkJBPT0ifQ==", Provisioner: h.home.ProvisioningPublic()}, |
| + Account: account, Now: h.clock, Logger: slog.New(slog.NewTextHandler(h.logs, nil)), AfterAct: hook, Debug: func(err error) { h.t.Logf("transient: %v", err) }}) |
| +} |
| + |
| +// confirm is Paul on Home's confirm pages, directory first. |
| +func (h *harness) confirm(kind string) { |
| + h.t.Helper() |
| + if err := h.home.Confirm(homeop.Directory, ""); err != nil { |
| + h.t.Fatal(err) |
| + } |
| + if kind == homeop.KindInitialize { |
| + return |
| + } |
| + owner := "" |
| + if kind == homeop.KindCreateTeam { |
| + owner = ownerCanary |
| + } |
| + if err := h.home.Confirm(homeop.Credential, owner); err != nil { |
| + h.t.Fatal(err) |
| + } |
| +} |
| + |
| +// drive advances run until it is done, failed, or stuck for rounds, |
| +// letting the walks run and time pass a little between passes. |
| +func (h *harness) drive(e *Engine, run int64, rounds int) Run { |
| + h.t.Helper() |
| + var r Run |
| + for i := 0; i < rounds; i++ { |
| + if err := e.Advance(h.ctx(), run); err != nil && !errors.Is(err, errCrash) { |
| + var fl *Fail |
| + if !errors.As(err, &fl) { |
| + h.t.Fatalf("advance: %v", err) |
| + } |
| + } |
| + var err error |
| + if r, err = h.store.Run(h.ctx(), run); err != nil { |
| + h.t.Fatal(err) |
| + } |
| + if r.State == "done" || r.State == "failed" { |
| + return r |
| + } |
| + h.con.Walk() |
| + h.tick(5 * time.Second) |
| + } |
| + return r |
| +} |
| + |
| +// initialized runs the first production run, initialize, and lets its |
| +// window expire so the next plan can be confirmed. |
| +func (h *harness) initialized() { |
| + h.t.Helper() |
| + e := h.engine(nil) |
| + run, err := e.StartInitialize(h.ctx(), InitializeAttestation) |
| + if err != nil { |
| + h.t.Fatal(err) |
| + } |
| + h.confirm(homeop.KindInitialize) |
| + if r := h.drive(e, run, 3); r.State != "done" { |
| + h.t.Fatalf("initialize: %s %s", r.State, r.Code) |
| + } |
| + h.tick(homeop.WindowLifetime * time.Second) |
| +} |
| + |
| +var allApps = []string{"docs", "sheets", "slides", "calendar", "calls", "memoria"} |
| + |
| +func (h *harness) createLagged(e *Engine) int64 { |
| + h.t.Helper() |
| + run, err := e.CreateTeam(h.ctx(), NewTeam{Label: "lagged", Name: "Lagged", Owner: ownerCanary, Apps: allApps}) |
| + if err != nil { |
| + h.t.Fatal(err) |
| + } |
| + h.confirm(homeop.KindCreateTeam) |
| + return run |
| +} |
| + |
| +// scan reports whether needle is anywhere in Alta's database files. |
| +func (h *harness) scan(needle string) bool { |
| + h.t.Helper() |
| + for _, suffix := range []string{"", "-wal", "-shm"} { |
| + f, err := os.Open(h.path + suffix) |
| + if err != nil { |
| + continue |
| + } |
| + b, _ := io.ReadAll(f) |
| + f.Close() |
| + if bytes.Contains(b, []byte(needle)) { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +func b64(s string) []byte { |
| + b, _ := base64.StdEncoding.DecodeString(s) |
| + return b |
| +} |
| + |
| +type fakeVar = fakeconsole.Var |
| + |
| +func sealFor(t *testing.T, h *harness, app, value string) string { |
| + t.Helper() |
| + e, err := console.Seal(h.con.SecretsPub(), "", app, []byte(value)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return e |
| +} |
diff --git a/provision/migrations/0001_init.sql b/provision/migrations/0001_init.sql| new file mode 100644 |
| index 0000000..2e190ba |
| --- /dev/null |
| +++ b/provision/migrations/0001_init.sql |
| @@ -0,0 +1,130 @@ |
| +-- Alta's state (team-provisioning-app.md §4). Sealed columns are AEAD |
| +-- under ALTA_DEK with a per-row purpose; nothing here is an app key, a |
| +-- CARLOS token, a roster bearer or team content. |
| + |
| +-- Every label ever used stays: labels are never reused (Paul, 2026-10-27). |
| +CREATE TABLE teams ( |
| + label TEXT PRIMARY KEY, |
| + sealed_name BLOB NOT NULL, |
| + environment TEXT NOT NULL, |
| + forked INTEGER NOT NULL DEFAULT 0 CHECK (forked IN (0, 1)), |
| + team_id INTEGER, |
| + team_sqid TEXT, |
| + epoch INTEGER, |
| + generation TEXT, |
| + owner_ref TEXT, |
| + created_at INTEGER NOT NULL |
| +) STRICT; |
| + |
| +-- An app once in a team stays; a retired app's hostnames are dead for good. |
| +CREATE TABLE team_apps ( |
| + label TEXT NOT NULL REFERENCES teams(label), |
| + app TEXT NOT NULL, |
| + state TEXT NOT NULL CHECK (state IN ('active', 'retired')), |
| + PRIMARY KEY (label, app) |
| +) STRICT; |
| + |
| +-- The owner's address, sealed; deleted at step 13 (§4). |
| +CREATE TABLE owner_inputs ( |
| + label TEXT PRIMARY KEY REFERENCES teams(label), |
| + sealed_address BLOB NOT NULL |
| +) STRICT; |
| + |
| +CREATE TABLE runs ( |
| + id INTEGER PRIMARY KEY, |
| + label TEXT NOT NULL DEFAULT '', |
| + kind TEXT NOT NULL CHECK (kind IN ('initialize', 'create-team', 'add-apps', 'retire-apps')), |
| + apps TEXT NOT NULL DEFAULT '', |
| + plan_id TEXT, |
| + plan_expires_at INTEGER, |
| + state TEXT NOT NULL CHECK (state IN ('planned', 'running', 'parked', 'done', 'superseded', 'failed')), |
| + code TEXT NOT NULL DEFAULT '', |
| + created_at INTEGER NOT NULL, |
| + updated_at INTEGER NOT NULL |
| +) STRICT; |
| +CREATE INDEX runs_label ON runs(label, id); |
| + |
| +-- One row per (plan, role). The signed bytes are kept, sealed, only so a |
| +-- role that answered busy can be retried with the same plan until it |
| +-- expires; the credential role's carry the owner and go at step 13. |
| +CREATE TABLE plan_submissions ( |
| + plan_id TEXT NOT NULL, |
| + role TEXT NOT NULL CHECK (role IN ('credential', 'directory')), |
| + sealed_plan BLOB, |
| + state TEXT NOT NULL CHECK (state IN ('signed', 'pending', 'open', 'closed')), |
| + expires_at INTEGER NOT NULL, |
| + window_expires_at INTEGER, |
| + PRIMARY KEY (plan_id, role) |
| +) STRICT; |
| + |
| +-- The state machine (§6), per team and app ('' for team-level steps), so |
| +-- a later add-apps run continues where an earlier one parked. |
| +CREATE TABLE steps ( |
| + label TEXT NOT NULL, |
| + app TEXT NOT NULL, |
| + step TEXT NOT NULL, |
| + state TEXT NOT NULL CHECK (state IN ('done', 'parked', 'failed')), |
| + code TEXT NOT NULL DEFAULT '', |
| + data TEXT NOT NULL DEFAULT '{}', |
| + updated_at INTEGER NOT NULL, |
| + PRIMARY KEY (label, app, step) |
| +) STRICT; |
| + |
| +-- Exact signed request bytes, sealed, so a lost result is recovered by |
| +-- exact replay (and the roster bearer re-fetched, never stored). |
| +CREATE TABLE operator_requests ( |
| + id INTEGER PRIMARY KEY, |
| + role TEXT NOT NULL CHECK (role IN ('credential', 'directory')), |
| + sequence INTEGER NOT NULL, |
| + operation_id TEXT NOT NULL UNIQUE, |
| + action TEXT NOT NULL, |
| + label TEXT NOT NULL DEFAULT '', |
| + app TEXT NOT NULL DEFAULT '', |
| + purpose TEXT NOT NULL, |
| + head TEXT NOT NULL, |
| + sealed_request BLOB NOT NULL, |
| + state TEXT NOT NULL CHECK (state IN ('signed', 'committed', 'refused')), |
| + expires_at INTEGER NOT NULL, |
| + created_at INTEGER NOT NULL |
| +) STRICT; |
| +CREATE INDEX operator_requests_purpose ON operator_requests(label, app, purpose, id); |
| + |
| +-- Per Home role: the stream position Home will accept next (§5). |
| +CREATE TABLE operator_streams ( |
| + role TEXT PRIMARY KEY CHECK (role IN ('credential', 'directory')), |
| + sequence INTEGER NOT NULL, |
| + head TEXT NOT NULL, |
| + updated_at INTEGER NOT NULL |
| +) STRICT; |
| + |
| +-- The environments Alta owns, per its own records (§8's guard). |
| +CREATE TABLE environments ( |
| + app TEXT NOT NULL, |
| + environment TEXT NOT NULL, |
| + label TEXT NOT NULL REFERENCES teams(label), |
| + PRIMARY KEY (app, environment) |
| +) STRICT; |
| + |
| +-- The audit: fixed event codes, never an address, key or platform value. |
| +CREATE TABLE audit ( |
| + id INTEGER PRIMARY KEY, |
| + at INTEGER NOT NULL, |
| + run_id INTEGER NOT NULL DEFAULT 0, |
| + label TEXT NOT NULL DEFAULT '', |
| + app TEXT NOT NULL DEFAULT '', |
| + event TEXT NOT NULL, |
| + detail TEXT NOT NULL DEFAULT '' |
| +) STRICT; |
| + |
| +-- One run at a time (§8). |
| +CREATE TABLE run_lock ( |
| + singleton INTEGER PRIMARY KEY CHECK (singleton = 1), |
| + run_id INTEGER NOT NULL, |
| + acquired_at INTEGER NOT NULL |
| +) STRICT; |
| + |
| +-- Alta's session idle clock (30 minutes; sessions' TTL is the absolute 12 h). |
| +CREATE TABLE session_seen ( |
| + token_hash TEXT PRIMARY KEY, |
| + seen_at INTEGER NOT NULL |
| +) STRICT; |
diff --git a/provision/steps.go b/provision/steps.go| new file mode 100644 |
| index 0000000..c1f505c |
| --- /dev/null |
| +++ b/provision/steps.go |
| @@ -0,0 +1,1029 @@ |
| +package provision |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "net/http" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/alta/console" |
| + "amadan.net/oficina/alta/homeop" |
| + "amadan.net/oficina/home/roster" |
| +) |
| + |
| +// Step names, in order. Team-level steps have app "". |
| +const ( |
| + StepOwner = "owner" // 3 |
| + StepTeam = "team" // 4 |
| + StepConsumer = "consumer" // 5 |
| + StepRegister = "register" // 6 |
| + StepEnv = "env" // 7 |
| + StepInstance = "instance" // 8 |
| + StepDomain = "domain" // 9 |
| + StepServing = "serving" // 10 |
| + StepVerify = "verify" // 11 |
| + StepActivate = "activate" // 12 |
| + StepAudit = "audit" // 13 |
| + |
| + StepDisable = "disable" // §9 |
| + StepRetire = "retire" |
| + StepDetach = "detach" |
| + StepDelete = "delete" |
| +) |
| + |
| +// AppSteps is the pipeline for app, in order. |
| +func AppSteps(app App) []string { |
| + s := []string{StepConsumer, StepRegister, StepEnv, StepInstance, StepDomain, StepServing} |
| + if app.Roster { |
| + s = append(s, StepVerify, StepActivate) |
| + } |
| + return append(s, StepAudit) |
| +} |
| + |
| +// RetireSteps is §9's order. |
| +var RetireSteps = []string{StepDisable, StepRetire, StepDetach, StepDelete} |
| + |
| +// DomainPatience is how long step 9 polls before it says so (§6: ≤ 30 |
| +// min, then park). |
| +const DomainPatience = 30 * time.Minute |
| + |
| +func (e *Engine) record(ctx context.Context, p *pass, app, step string, data map[string]any) error { |
| + e.log(p.run.ID, app, step, "done") |
| + e.cfg.Store.Audit(ctx, p.run.ID, p.run.Label, app, "step-done", step) |
| + return e.cfg.Store.SetStep(ctx, p.run.Label, app, step, "done", "", data) |
| +} |
| + |
| +func (e *Engine) note(ctx context.Context, p *pass, app, step string, err error, data map[string]any) { |
| + var pk *Park |
| + var fl *Fail |
| + state, code := "parked", "transient" |
| + switch { |
| + case errors.As(err, &pk): |
| + code = pk.Code |
| + case errors.As(err, &fl): |
| + state, code = "failed", fl.Code |
| + case errors.Is(err, console.ErrGuard): |
| + state, code = "failed", "guard" |
| + } |
| + prev, ok, _ := e.cfg.Store.Step(ctx, p.run.Label, app, step) |
| + if ok && prev.State == state && prev.Code == code && data == nil { |
| + return |
| + } |
| + if data == nil && ok { |
| + data = prev.Data |
| + } |
| + e.log(p.run.ID, app, step, state+":"+code) |
| + _ = e.cfg.Store.SetStep(ctx, p.run.Label, app, step, state, code, data) |
| +} |
| + |
| +// provision is a create-team or add-apps run: steps 3–4 for the team, |
| +// then each app's pipeline. A parked app does not hold the others back: |
| +// domains issue and instances start in parallel. |
| +func (e *Engine) provision(ctx context.Context, p *pass) error { |
| + if p.team.TeamSQID == "" { |
| + if err := e.seed(ctx, p); err != nil { |
| + return err |
| + } |
| + t, err := e.cfg.Store.Team(ctx, p.run.Label) |
| + if err != nil { |
| + return err |
| + } |
| + p.team = t |
| + } |
| + var first error |
| + for _, slug := range p.run.Apps { |
| + app, _ := AppBySlug(slug) |
| + if err := e.appPipeline(ctx, p, app); err != nil { |
| + if errors.Is(err, errCrash) { |
| + return err |
| + } |
| + var fl *Fail |
| + if errors.As(err, &fl) || errors.Is(err, console.ErrGuard) { |
| + return err |
| + } |
| + if first == nil { |
| + first = err |
| + } |
| + } |
| + } |
| + if first != nil { |
| + return first |
| + } |
| + return e.forgetOwnerWhenWritten(ctx, p) |
| +} |
| + |
| +func (e *Engine) appPipeline(ctx context.Context, p *pass, app App) error { |
| + for _, step := range AppSteps(app) { |
| + if _, ok, err := e.cfg.Store.Done(ctx, p.run.Label, app.Slug, step); err != nil { |
| + return err |
| + } else if ok { |
| + continue |
| + } |
| + err := e.runStep(ctx, p, app, step) |
| + if err != nil { |
| + if !errors.Is(err, errCrash) { |
| + e.note(ctx, p, app.Slug, step, err, nil) |
| + } |
| + return err |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +func (e *Engine) runStep(ctx context.Context, p *pass, app App, step string) error { |
| + switch step { |
| + case StepConsumer: |
| + return e.stepConsumer(ctx, p, app) |
| + case StepRegister: |
| + return e.stepRegister(ctx, p, app) |
| + case StepEnv: |
| + return e.stepEnv(ctx, p, app) |
| + case StepInstance: |
| + return e.stepInstance(ctx, p, app) |
| + case StepDomain: |
| + return e.stepDomain(ctx, p, app) |
| + case StepServing: |
| + return e.stepServing(ctx, p, app) |
| + case StepVerify: |
| + return e.stepVerify(ctx, p, app) |
| + case StepActivate: |
| + return e.stepActivate(ctx, p, app) |
| + case StepAudit: |
| + return e.stepAudit(ctx, p, app) |
| + } |
| + return fail("unknown-step") |
| +} |
| + |
| +// ---- steps 3 and 4: owner and team ---- |
| + |
| +func (e *Engine) seed(ctx context.Context, p *pass) error { |
| + if p.run.Kind != homeop.KindCreateTeam { |
| + return fail("team-not-seeded") |
| + } |
| + label := p.run.Label |
| + // A seed that committed and whose result was lost: replay recovers |
| + // it, no window needed. |
| + if res, handled, err := e.replayHeld(ctx, opSpec{role: homeop.Directory, action: homeop.DirectorySeedTeam, label: label, purpose: "seed-team", reuse: true}); handled { |
| + if err != nil { |
| + return err |
| + } |
| + return e.seeded(ctx, p, res) |
| + } |
| + for _, role := range []string{homeop.Credential, homeop.Directory} { |
| + if err := e.needWindow(p, role); err != nil { |
| + e.note(ctx, p, "", StepTeam, err, nil) |
| + return err |
| + } |
| + } |
| + gen := p.ins[homeop.Directory].Generation |
| + if gen == nil { |
| + return fail("home-not-initialized") |
| + } |
| + receipt, owner, err := e.ownerReceipt(ctx, p) |
| + if err != nil { |
| + e.note(ctx, p, "", StepOwner, err, nil) |
| + return err |
| + } |
| + res, err := e.op(ctx, opSpec{role: homeop.Directory, action: homeop.DirectorySeedTeam, label: label, purpose: "seed-team", |
| + build: func(b homeop.InputBase) any { |
| + return homeop.SeedInput{InputBase: b, Generation: *gen, TeamID: owner.TeamID, TeamSQID: owner.TeamSQID, Label: label, Name: p.team.Name, Receipt: receipt} |
| + }}) |
| + if errors.Is(err, errOpRefused) { |
| + // The receipt may have aged out or another team taken the |
| + // proposed id: both mean a new owner-seed next pass. Otherwise |
| + // the label is taken at Home, or the name differs from the plan. |
| + ins, o, _ := e.cfg.Home.Inspect(ctx, homeop.Directory) |
| + if o == homeop.OK && (ins.TeamID != owner.TeamID || owner.Expires <= e.now().Unix()+5) { |
| + _ = e.cfg.Store.SetStep(ctx, label, "", StepOwner, "parked", "receipt-stale", nil) |
| + return park("receipt-stale") |
| + } |
| + err = fail("seed-refused") |
| + } |
| + if err != nil { |
| + e.note(ctx, p, "", StepTeam, err, nil) |
| + return err |
| + } |
| + return e.seeded(ctx, p, res) |
| +} |
| + |
| +func (e *Engine) seeded(ctx context.Context, p *pass, res homeop.Result) error { |
| + if res.TeamID <= 0 || res.TeamSQID == "" || res.Epoch <= 0 { |
| + return fail("seed-result") |
| + } |
| + owner := str(mustDone(ctx, e.cfg.Store, p.run.Label, "", StepOwner), "owner_ref") |
| + if owner == "" { |
| + return fail("seed-owner-unknown") |
| + } |
| + if err := e.cfg.Store.SetSeeded(ctx, p.run.Label, res.TeamID, res.TeamSQID, res.Epoch, res.Generation, owner); err != nil { |
| + return err |
| + } |
| + return e.record(ctx, p, "", StepTeam, map[string]any{"team_sqid": res.TeamSQID, "epoch": res.Epoch}) |
| +} |
| + |
| +func mustDone(ctx context.Context, s *Store, label, app, step string) map[string]any { |
| + st, ok, _ := s.Step(ctx, label, app, step) |
| + if !ok { |
| + return map[string]any{} |
| + } |
| + return st.Data |
| +} |
| + |
| +// ownerReceipt is step 3: a receipt whose expiry is still ahead, for the |
| +// team id the directory proposes now. An expired receipt is never renewed |
| +// by replay (Home returns the same expired receipt by design): it takes a |
| +// new owner-seed operation. |
| +func (e *Engine) ownerReceipt(ctx context.Context, p *pass) ([]byte, homeop.OwnerReceipt, error) { |
| + label := p.run.Label |
| + proposed := p.ins[homeop.Directory] |
| + now := e.now().Unix() |
| + if d, ok, _ := e.cfg.Store.Done(ctx, label, "", StepOwner); ok { |
| + raw, _ := base64.RawURLEncoding.DecodeString(str(d, "receipt")) |
| + if r, err := homeop.ReadReceipt(raw); err == nil && r.Expires > now+30 && r.TeamID == proposed.TeamID { |
| + return raw, r, nil |
| + } |
| + } |
| + addr, ok, err := e.cfg.Store.Owner(ctx, label) |
| + if err != nil { |
| + return nil, homeop.OwnerReceipt{}, err |
| + } |
| + if !ok { |
| + return nil, homeop.OwnerReceipt{}, fail("owner-needed") |
| + } |
| + // A request signed but never answered may still hold a live receipt; |
| + // a committed one is never replayed here (its receipt may be dead). |
| + res, err := e.op(ctx, opSpec{role: homeop.Credential, action: homeop.CredentialOwnerSeed, label: label, purpose: "owner-seed", |
| + build: func(b homeop.InputBase) any { |
| + return homeop.OwnerInput{InputBase: b, Directory: e.cfg.HomeCfg.Directory, TeamID: proposed.TeamID, TeamSQID: proposed.TeamSQID, Address: addr, ExistingOnly: true} |
| + }}) |
| + if errors.Is(err, errOpRefused) { |
| + return nil, homeop.OwnerReceipt{}, fail("owner-refused") |
| + } |
| + if err != nil { |
| + return nil, homeop.OwnerReceipt{}, err |
| + } |
| + r, err := homeop.ReadReceipt(res.Receipt) |
| + if err != nil { |
| + return nil, homeop.OwnerReceipt{}, fail("receipt-unreadable") |
| + } |
| + if r.Expires <= e.now().Unix()+5 || r.TeamID != proposed.TeamID { |
| + return nil, homeop.OwnerReceipt{}, park("receipt-stale") |
| + } |
| + if err := e.record(ctx, p, "", StepOwner, map[string]any{"receipt": base64.RawURLEncoding.EncodeToString(res.Receipt), "owner_ref": r.PersonRef, "expires_at": r.Expires}); err != nil { |
| + return nil, homeop.OwnerReceipt{}, err |
| + } |
| + return res.Receipt, r, nil |
| +} |
| + |
| +// ---- step 5: directory consumer ---- |
| + |
| +func (e *Engine) expectedBindings(p *pass, app App) roster.Bindings { |
| + return roster.Bindings{Issuer: e.cfg.HomeCfg.Issuer, Directory: e.cfg.HomeCfg.Directory, Consumer: ConsumerID(p.run.Label, app.Slug), App: app.Slug, Team: p.team.TeamSQID, Audience: PublicOrigin(p.run.Label, app.Slug)} |
| +} |
| + |
| +func (e *Engine) provisionSpec(p *pass, app App) opSpec { |
| + return opSpec{role: homeop.Directory, action: homeop.DirectoryProvision, label: p.run.Label, app: app.Slug, purpose: "provision", reuse: true, |
| + build: func(b homeop.InputBase) any { |
| + return homeop.ProvisionInput{InputBase: b, Generation: p.team.Generation, TeamSQID: p.team.TeamSQID, App: app.Slug, Consumer: ConsumerID(p.run.Label, app.Slug), Audience: PublicOrigin(p.run.Label, app.Slug)} |
| + }} |
| +} |
| + |
| +func (e *Engine) stepConsumer(ctx context.Context, p *pass, app App) error { |
| + if _, held, _ := e.cfg.Store.LastRequest(ctx, p.run.Label, app.Slug, "provision"); !held { |
| + if err := e.needWindow(p, homeop.Directory); err != nil { |
| + return err |
| + } |
| + } |
| + res, err := e.op(ctx, e.provisionSpec(p, app)) |
| + if errors.Is(err, errOpRefused) { |
| + return fail("provision-refused") |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + // Alta checks the record against the directory's pinned provisioning |
| + // key and the bindings it asked for before it is written anywhere. |
| + if _, err := roster.VerifyProvisioning(res.Record, ProvisionerKeys(e.cfg.HomeCfg.Provisioner), e.expectedBindings(p, app)); err != nil { |
| + return fail("record-unverified") |
| + } |
| + return e.record(ctx, p, app.Slug, StepConsumer, map[string]any{ |
| + "record": base64.RawURLEncoding.EncodeToString(res.Record), |
| + "record_digest": homeop.Digest(res.Record), |
| + "epoch": res.Epoch, |
| + "generation": res.Generation, |
| + }) |
| +} |
| + |
| +func (e *Engine) consumerData(ctx context.Context, p *pass, app App) ([]byte, map[string]any, error) { |
| + d, ok, err := e.cfg.Store.Done(ctx, p.run.Label, app.Slug, StepConsumer) |
| + if err != nil || !ok { |
| + return nil, nil, fail("consumer-missing") |
| + } |
| + rec, err := base64.RawURLEncoding.DecodeString(str(d, "record")) |
| + if err != nil { |
| + return nil, nil, fail("consumer-missing") |
| + } |
| + return rec, d, nil |
| +} |
| + |
| +// bearer re-fetches the roster bearer by exact replay of step 5: Alta |
| +// never stores it (§4). |
| +func (e *Engine) bearer(ctx context.Context, p *pass, app App) (string, error) { |
| + prev, ok, err := e.cfg.Store.LastRequest(ctx, p.run.Label, app.Slug, "provision") |
| + if err != nil || !ok || prev.State != "committed" { |
| + return "", fail("bearer-unrecoverable") |
| + } |
| + res, _, o := e.cfg.Home.Execute(ctx, homeop.Directory, prev.Bytes) |
| + if o != homeop.OK { |
| + return "", park("home-unavailable") |
| + } |
| + if res.Bearer == "" { |
| + return "", fail("bearer-unrecoverable") |
| + } |
| + return res.Bearer, nil |
| +} |
| + |
| +// ---- step 6: credential consumer ---- |
| + |
| +func (e *Engine) stepRegister(ctx context.Context, p *pass, app App) error { |
| + rec, _, err := e.consumerData(ctx, p, app) |
| + if err != nil { |
| + return err |
| + } |
| + if _, held, _ := e.cfg.Store.LastRequest(ctx, p.run.Label, app.Slug, "register"); !held { |
| + if err := e.needWindow(p, homeop.Credential); err != nil { |
| + return err |
| + } |
| + } |
| + res, err := e.op(ctx, opSpec{role: homeop.Credential, action: homeop.CredentialRegister, label: p.run.Label, app: app.Slug, purpose: "register", reuse: true, |
| + build: func(b homeop.InputBase) any { return homeop.RegisterInput{InputBase: b, Record: rec} }}) |
| + if errors.Is(err, errOpRefused) { |
| + return fail("register-refused") |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + if !homeop.CanonicalToken(res.Manifest) { |
| + return fail("manifest-digest") |
| + } |
| + return e.record(ctx, p, app.Slug, StepRegister, map[string]any{"manifest_digest": res.Manifest}) |
| +} |
| + |
| +// ---- step 7: environment ---- |
| + |
| +func (e *Engine) inputs(ctx context.Context, p *pass, app App) (Inputs, error) { |
| + in := Inputs{Label: p.run.Label, TeamSQID: p.team.TeamSQID, Home: e.cfg.HomeCfg, CallsZone: e.cfg.CallsZone} |
| + if owner, ok, err := e.cfg.Store.Owner(ctx, p.run.Label); err != nil { |
| + return in, err |
| + } else if ok { |
| + in.Owner = owner |
| + } |
| + if app.Roster { |
| + rec, _, err := e.consumerData(ctx, p, app) |
| + if err != nil { |
| + return in, err |
| + } |
| + in.Record = rec |
| + } |
| + return in, nil |
| +} |
| + |
| +func (e *Engine) stepEnv(ctx context.Context, p *pass, app App) error { |
| + env := p.team.Environment |
| + in, err := e.inputs(ctx, p, app) |
| + if err != nil { |
| + return err |
| + } |
| + keys := Recipe(app, in) |
| + cfg, found, err := e.cfg.Console.GetConfig(ctx, app.Slug, env) |
| + if err != nil { |
| + return park("console-unavailable") |
| + } |
| + present := cfg.Keys() |
| + set := map[string]console.SetVar{} |
| + var unset []string |
| + recipe := map[string]bool{} |
| + running := false // a write landed on an instance already running |
| + for _, k := range keys { |
| + recipe[k.Name] = true |
| + if k.Class != Set { |
| + continue |
| + } |
| + have, ok := present[k.Name] |
| + if k.OwnerAddress && in.Owner == "" { |
| + if ok && have.Kind == "env" && have.Value != "" { |
| + continue |
| + } |
| + return park("owner-retype-needed") |
| + } |
| + if !ok || have.Kind != "env" || have.Value != k.Value { |
| + set[k.Name] = console.SetVar{Kind: "env", Value: k.Value} |
| + } |
| + } |
| + for name := range present { |
| + if recipe[name] || console.PlatformManaged(name) { |
| + continue |
| + } |
| + if !p.team.Forked { |
| + return fail("extra-key") |
| + } |
| + // A forked environment carries Track 1's own keys: anything the |
| + // recipe does not name goes (OFICINA_DASHBOARD_TEAM, MEMORIA_AI…). |
| + unset = append(unset, name) |
| + } |
| + if len(set) > 0 || len(unset) > 0 { |
| + put, err := e.cfg.Console.PutConfig(ctx, app.Slug, env, set, unset, "alta: team environment") |
| + if err != nil { |
| + if errors.Is(err, console.ErrGuard) { |
| + return err |
| + } |
| + return park("console-write") |
| + } |
| + running = running || put.RestartsHosts() |
| + if err := e.acted("env-set/" + app.Slug); err != nil { |
| + return err |
| + } |
| + if cfg, found, err = e.cfg.Console.GetConfig(ctx, app.Slug, env); err != nil || !found { |
| + return park("console-unavailable") |
| + } |
| + present = cfg.Keys() |
| + } |
| + if !found { |
| + return park("environment-absent") |
| + } |
| + // GENERATED keys: existence is checked by name; an existing key is |
| + // never regenerated (a DEK that changes under a database makes it |
| + // unreadable). Values are sealed to the console's key and forgotten. |
| + gen := map[string]console.SetVar{} |
| + for _, k := range keys { |
| + if k.Class != Generated { |
| + continue |
| + } |
| + if _, ok := present[k.Name]; ok { |
| + continue |
| + } |
| + value := "" |
| + if k.FromHome { |
| + if value, err = e.bearer(ctx, p, app); err != nil { |
| + return err |
| + } |
| + } else { |
| + value = freshKey() |
| + } |
| + if cfg.SecretsPubKey == "" { |
| + return fail("no-secrets-pubkey") |
| + } |
| + envelope, err := console.Seal(cfg.SecretsPubKey, cfg.SecretsAccount, app.Slug, []byte(value)) |
| + if err != nil { |
| + return fail("seal") |
| + } |
| + gen[k.Name] = console.SetVar{Kind: "secret", Envelope: envelope} |
| + } |
| + if len(gen) > 0 { |
| + put, err := e.cfg.Console.PutConfig(ctx, app.Slug, env, gen, nil, "alta: team keys") |
| + if err != nil { |
| + if errors.Is(err, console.ErrGuard) { |
| + return err |
| + } |
| + return park("console-write") |
| + } |
| + running = running || put.RestartsHosts() |
| + if err := e.acted("env-generate/" + app.Slug); err != nil { |
| + return err |
| + } |
| + if cfg, found, err = e.cfg.Console.GetConfig(ctx, app.Slug, env); err != nil || !found { |
| + return park("console-unavailable") |
| + } |
| + present = cfg.Keys() |
| + } |
| + if running { |
| + // Config written under a running instance needs a restart (step |
| + // 10 does it): a forked environment's instance, or a re-run. |
| + _ = e.cfg.Store.SetStep(ctx, p.run.Label, app.Slug, "restart", "parked", "config-changed", map[string]any{"at": e.now().Unix()}) |
| + } |
| + names := map[string]bool{} |
| + for k := range present { |
| + names[k] = true |
| + } |
| + // PLATFORM keys arrive on the walks' cadence, not at PUT /config. |
| + ps := PlatformKeys(app, names) |
| + if ps.WrongPrefix != "" { |
| + return fail("mail-prefix-" + app.Slug) |
| + } |
| + if len(ps.Missing) > 0 { |
| + return park("awaiting-platform-keys") |
| + } |
| + return e.record(ctx, p, app.Slug, StepEnv, map[string]any{"platform": ps.Keys, "binding": EnvironmentBinding(env, keys, ps.Keys)}) |
| +} |
| + |
| +// ---- step 8: instance ---- |
| + |
| +func (e *Engine) stepInstance(ctx context.Context, p *pass, app App) error { |
| + env, host := p.team.Environment, RouteHost(p.run.Label, app.Slug, e.cfg.Account) |
| + inst, found, err := e.cfg.Console.GetInstance(ctx, app.Slug, host) |
| + if err != nil { |
| + return park("console-unavailable") |
| + } |
| + if !found { |
| + err := e.cfg.Console.CreateInstance(ctx, app.Slug, host, env, "alta: team instance") |
| + if err != nil && !console.IsConflict(err) { |
| + if errors.Is(err, console.ErrGuard) { |
| + return err |
| + } |
| + return park("console-write") |
| + } |
| + if err == nil { |
| + if err := e.acted("instance/" + app.Slug); err != nil { |
| + return err |
| + } |
| + } |
| + if inst, found, err = e.cfg.Console.GetInstance(ctx, app.Slug, host); err != nil { |
| + return park("console-unavailable") |
| + } |
| + if !found { |
| + // 409 and still not ours: the host is held outside the scope. |
| + return fail("host-held") |
| + } |
| + } |
| + if inst.Environment != env { |
| + return fail("instance-bound-elsewhere") |
| + } |
| + return e.record(ctx, p, app.Slug, StepInstance, map[string]any{"route": host, "created_at": e.now().Unix()}) |
| +} |
| + |
| +// ---- step 9: domain ---- |
| + |
| +func (e *Engine) stepDomain(ctx context.Context, p *pass, app App) error { |
| + host, route := PublicHost(p.run.Label, app.Slug), RouteHost(p.run.Label, app.Slug, e.cfg.Account) |
| + d, found, err := e.cfg.Console.GetDomain(ctx, app.Slug, host) |
| + if err != nil { |
| + return park("console-unavailable") |
| + } |
| + prev, _, _ := e.cfg.Store.Step(ctx, p.run.Label, app.Slug, StepDomain) |
| + since := num(prev.Data, "attached_at") |
| + if !found { |
| + if err := e.cfg.Console.AttachDomain(ctx, app.Slug, host, route, "alta: team hostname"); err != nil && !console.IsConflict(err) { |
| + if errors.Is(err, console.ErrGuard) { |
| + return err |
| + } |
| + return park("console-write") |
| + } |
| + if err := e.acted("domain/" + app.Slug); err != nil { |
| + return err |
| + } |
| + since = e.now().Unix() |
| + if d, found, err = e.cfg.Console.GetDomain(ctx, app.Slug, host); err != nil || !found { |
| + _ = e.cfg.Store.SetStep(ctx, p.run.Label, app.Slug, StepDomain, "parked", "domain-attaching", map[string]any{"attached_at": since}) |
| + return park("domain-attaching") |
| + } |
| + } |
| + if since == 0 { |
| + since = e.now().Unix() |
| + } |
| + if d.Route != route { |
| + return fail("domain-route") |
| + } |
| + if d.State == "live" { |
| + return e.record(ctx, p, app.Slug, StepDomain, map[string]any{"host": host}) |
| + } |
| + code := "domain-" + d.State |
| + if e.now().Sub(time.Unix(since, 0)) > DomainPatience { |
| + code = "domain-slow-" + d.State |
| + } |
| + _ = e.cfg.Store.SetStep(ctx, p.run.Label, app.Slug, StepDomain, "parked", code, map[string]any{"attached_at": since, "reason": d.Reason}) |
| + return park(code) |
| +} |
| + |
| +// ---- step 10: serving ---- |
| + |
| +func (e *Engine) get(ctx context.Context, url string) (int, []byte, error) { |
| + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) |
| + if err != nil { |
| + return 0, nil, err |
| + } |
| + resp, err := e.cfg.Public.Do(req) |
| + if err != nil { |
| + return 0, nil, err |
| + } |
| + defer resp.Body.Close() |
| + b, err := io.ReadAll(io.LimitReader(resp.Body, 4096)) |
| + return resp.StatusCode, b, err |
| +} |
| + |
| +func (e *Engine) stepServing(ctx context.Context, p *pass, app App) error { |
| + route := RouteHost(p.run.Label, app.Slug, e.cfg.Account) |
| + row, found, err := e.cfg.Console.ListedHost(ctx, app.Slug, route) |
| + if err != nil || !found { |
| + return park("console-unavailable") |
| + } |
| + restart, needs, _ := e.cfg.Store.Step(ctx, p.run.Label, app.Slug, "restart") |
| + if (needs && restart.State == "parked") || (row.Rollout != nil && row.Rollout.ConfigPending) { |
| + if err := e.cfg.Console.RestartHost(ctx, app.Slug, route, "alta: config changed"); err != nil { |
| + if errors.Is(err, console.ErrGuard) { |
| + return err |
| + } |
| + return park("console-write") |
| + } |
| + if err := e.acted("restart/" + app.Slug); err != nil { |
| + return err |
| + } |
| + _ = e.cfg.Store.SetStep(ctx, p.run.Label, app.Slug, "restart", "done", "", map[string]any{"at": e.now().Unix()}) |
| + return park("restarting") |
| + } |
| + status, body, err := e.get(ctx, PublicOrigin(p.run.Label, app.Slug)+"/api/version") |
| + if err != nil || status != http.StatusOK { |
| + return park("version-unreachable") |
| + } |
| + version := strings.TrimSpace(string(body)) |
| + if version == "" || version == "dev" { |
| + return park("version-unstamped") |
| + } |
| + if row.Rollout == nil || row.Rollout.Serving == "" { |
| + return park("awaiting-box-report") |
| + } |
| + if row.Rollout.Serving != version { |
| + return park("serving-disagrees") |
| + } |
| + return e.record(ctx, p, app.Slug, StepServing, map[string]any{"app_version": version, "serving": row.Rollout.Serving}) |
| +} |
| + |
| +// ---- steps 11 and 12: verify and activate (roster-mode apps) ---- |
| + |
| +// TeamProbe is GET /api/team's readiness answer (team-members.md §7). |
| +type TeamProbe struct { |
| + TeamMode bool `json:"team_mode"` |
| + Consumer string `json:"consumer"` |
| + Roster string `json:"roster"` |
| +} |
| + |
| +func (e *Engine) stepVerify(ctx context.Context, p *pass, app App) error { |
| + now := e.now().Unix() |
| + prev, _, _ := e.cfg.Store.Step(ctx, p.run.Label, app.Slug, StepVerify) |
| + attempt, expires := str(prev.Data, "attempt"), num(prev.Data, "expires_at") |
| + if attempt == "" || expires <= now+60 { |
| + if err := e.needWindow(p, homeop.Directory); err != nil { |
| + return err |
| + } |
| + _, cd, err := e.consumerData(ctx, p, app) |
| + if err != nil { |
| + return err |
| + } |
| + issued := now |
| + // A new attempt each time: one whose expiry passed is replaced at |
| + // Home by the next verify, never renewed. |
| + res, err := e.op(ctx, opSpec{role: homeop.Directory, action: homeop.DirectoryVerify, label: p.run.Label, app: app.Slug, purpose: "verify", |
| + build: func(b homeop.InputBase) any { |
| + return homeop.VerificationInput{InputBase: b, Consumer: ConsumerID(p.run.Label, app.Slug), TeamSQID: p.team.TeamSQID, App: app.Slug, Audience: PublicOrigin(p.run.Label, app.Slug), |
| + Generation: str(cd, "generation"), RecordSequence: 1, RecordDigest: str(cd, "record_digest"), Epoch: num(cd, "epoch"), Owner: p.team.OwnerRef, Issued: issued, Expires: issued + 600} |
| + }}) |
| + if errors.Is(err, errOpRefused) { |
| + return fail("verify-refused") |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + attempt, expires = res.Attempt, res.Expires |
| + _ = e.cfg.Store.SetStep(ctx, p.run.Label, app.Slug, StepVerify, "parked", "awaiting-roster", map[string]any{"attempt": attempt, "issued_at": issued, "expires_at": expires}) |
| + prev.Data = map[string]any{"attempt": attempt, "issued_at": issued, "expires_at": expires} |
| + } |
| + status, body, err := e.get(ctx, PublicOrigin(p.run.Label, app.Slug)+"/api/team") |
| + if err != nil { |
| + return park("roster-unreachable") |
| + } |
| + if status == http.StatusNotFound { |
| + return park("no-readiness-probe") |
| + } |
| + var probe TeamProbe |
| + if status != http.StatusOK || json.Unmarshal(body, &probe) != nil { |
| + return park("roster-unreadable") |
| + } |
| + if !probe.TeamMode || probe.Consumer != ConsumerID(p.run.Label, app.Slug) { |
| + return park("not-team-mode") |
| + } |
| + if probe.Roster != "ok" { |
| + return park("roster-" + probe.Roster) |
| + } |
| + return e.record(ctx, p, app.Slug, StepVerify, prev.Data) |
| +} |
| + |
| +func artifactDigest(serving string) string { |
| + s := sha256.Sum256([]byte(serving)) |
| + return base64.RawURLEncoding.EncodeToString(s[:]) |
| +} |
| + |
| +func commit40(s string) bool { |
| + if len(s) != 40 { |
| + return false |
| + } |
| + for _, c := range s { |
| + if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +func (e *Engine) stepActivate(ctx context.Context, p *pass, app App) error { |
| + st := e.cfg.Store |
| + label := p.run.Label |
| + if prev, ok, _ := st.LastRequest(ctx, label, app.Slug, "activate"); !ok || prev.State != "committed" { |
| + if err := e.needWindow(p, homeop.Directory); err != nil { |
| + return err |
| + } |
| + } |
| + v, _, _ := st.Done(ctx, label, app.Slug, StepVerify) |
| + sv, _, _ := st.Done(ctx, label, app.Slug, StepServing) |
| + envd, _, _ := st.Done(ctx, label, app.Slug, StepEnv) |
| + reg, _, _ := st.Done(ctx, label, app.Slug, StepRegister) |
| + _, cd, err := e.consumerData(ctx, p, app) |
| + if err != nil { |
| + return err |
| + } |
| + now := e.now().Unix() |
| + if _, committed, _ := st.LastRequest(ctx, label, app.Slug, "activate"); !committed && num(v, "expires_at") <= now+10 { |
| + // The attempt lapsed: verify again. |
| + _ = st.SetStep(ctx, label, app.Slug, StepVerify, "parked", "attempt-expired", nil) |
| + return park("attempt-expired") |
| + } |
| + version := str(sv, "app_version") |
| + if !commit40(version) { |
| + return park("version-not-commit") |
| + } |
| + ev := homeop.ActivationEvidence{Version: 1, Policy: homeop.ActivationPolicy, Attempt: str(v, "attempt"), Consumer: ConsumerID(label, app.Slug), TeamSQID: p.team.TeamSQID, App: app.Slug, |
| + Audience: PublicOrigin(label, app.Slug), Generation: str(cd, "generation"), RecordSequence: 1, RecordDigest: str(cd, "record_digest"), Epoch: num(cd, "epoch"), Owner: p.team.OwnerRef, |
| + AppVersion: version, ArtifactDigest: artifactDigest(str(sv, "serving")), EnvironmentBinding: str(envd, "binding"), ManifestDigest: str(reg, "manifest_digest"), |
| + AliasHost: PublicHost(label, app.Slug), Started: num(v, "issued_at"), Completed: now} |
| + _, err = e.op(ctx, opSpec{role: homeop.Directory, action: homeop.DirectoryActivate, label: label, app: app.Slug, purpose: "activate", reuse: true, |
| + build: func(b homeop.InputBase) any { return homeop.ActivationInput{InputBase: b, Evidence: ev} }}) |
| + if errors.Is(err, errOpRefused) { |
| + return fail("activate-refused") |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + return e.record(ctx, p, app.Slug, StepActivate, map[string]any{"app_version": version}) |
| +} |
| + |
| +// ---- step 13: audit ---- |
| + |
| +// AuditEnvironment is §5's exact-keys rule for one app: the environment |
| +// holds GENERATED ∪ SET ∪ PLATFORM and nothing else, SET values as the |
| +// recipe says (owner-address values only checked present once Alta has |
| +// forgotten the address). |
| +func (e *Engine) AuditEnvironment(ctx context.Context, label string, app App) error { |
| + t, err := e.cfg.Store.Team(ctx, label) |
| + if err != nil { |
| + return err |
| + } |
| + p := &pass{run: Run{Label: label}, team: t} |
| + in, err := e.inputs(ctx, p, app) |
| + if err != nil { |
| + return err |
| + } |
| + keys := Recipe(app, in) |
| + cfg, found, err := e.cfg.Console.GetConfig(ctx, app.Slug, t.Environment) |
| + if err != nil { |
| + return park("console-unavailable") |
| + } |
| + if !found { |
| + return fail("audit-environment-absent") |
| + } |
| + present := cfg.Keys() |
| + names := map[string]bool{} |
| + for k := range present { |
| + names[k] = true |
| + } |
| + ps := PlatformKeys(app, names) |
| + if ps.WrongPrefix != "" { |
| + return fail("mail-prefix-" + app.Slug) |
| + } |
| + want := map[string]Key{} |
| + for _, k := range keys { |
| + want[k.Name] = k |
| + } |
| + for _, k := range ps.Keys { |
| + want[k] = Key{Name: k, Class: Platform} |
| + } |
| + for name := range present { |
| + if _, ok := want[name]; !ok { |
| + return fail("audit-extra-key") |
| + } |
| + } |
| + for name, k := range want { |
| + have, ok := present[name] |
| + if !ok { |
| + if k.Class == Platform { |
| + return park("awaiting-platform-keys") |
| + } |
| + return fail("audit-missing-key") |
| + } |
| + switch k.Class { |
| + case Generated: |
| + if have.Kind != "secret" { |
| + return fail("audit-kind") |
| + } |
| + case Set: |
| + if have.Kind != "env" { |
| + return fail("audit-kind") |
| + } |
| + if k.OwnerAddress && in.Owner == "" { |
| + if have.Value == "" { |
| + return fail("audit-allowlist-empty") |
| + } |
| + continue |
| + } |
| + if have.Value != k.Value { |
| + return fail("audit-value") |
| + } |
| + } |
| + } |
| + if len(ps.Missing) > 0 { |
| + return park("awaiting-platform-keys") |
| + } |
| + return nil |
| +} |
| + |
| +func (e *Engine) stepAudit(ctx context.Context, p *pass, app App) error { |
| + if err := e.AuditEnvironment(ctx, p.run.Label, app); err != nil { |
| + return err |
| + } |
| + pending := !app.Roster |
| + return e.record(ctx, p, app.Slug, StepAudit, map[string]any{"directory_pending": pending}) |
| +} |
| + |
| +// forgetOwnerWhenWritten deletes §4's address-bearing rows once the seed |
| +// has committed and every active app's stopgap allowlist is written. |
| +func (e *Engine) forgetOwnerWhenWritten(ctx context.Context, p *pass) error { |
| + st := e.cfg.Store |
| + if _, held, _ := st.Owner(ctx, p.run.Label); !held { |
| + return nil |
| + } |
| + if _, ok, _ := st.Done(ctx, p.run.Label, "", StepTeam); !ok { |
| + return nil |
| + } |
| + t, err := st.Team(ctx, p.run.Label) |
| + if err != nil { |
| + return err |
| + } |
| + for app, state := range t.Apps { |
| + if state != "active" { |
| + continue |
| + } |
| + if _, ok, _ := st.Done(ctx, p.run.Label, app, StepEnv); !ok { |
| + return nil |
| + } |
| + } |
| + if err := st.ForgetOwner(ctx, p.run.Label); err != nil { |
| + return err |
| + } |
| + st.Audit(ctx, p.run.ID, p.run.Label, "", "owner-forgotten", "") |
| + return nil |
| +} |
| + |
| +// ---- deprovision (§9) ---- |
| + |
| +func (e *Engine) retire(ctx context.Context, p *pass) error { |
| + ctx = WithDeprovision(ctx, p.run.ID) |
| + var first error |
| + for _, slug := range p.run.Apps { |
| + app, _ := AppBySlug(slug) |
| + err := e.retireApp(ctx, p, app) |
| + if errors.Is(err, errCrash) { |
| + return err |
| + } |
| + var fl *Fail |
| + if errors.As(err, &fl) || errors.Is(err, console.ErrGuard) { |
| + return err |
| + } |
| + if err != nil && first == nil { |
| + first = err |
| + } |
| + } |
| + return first |
| +} |
| + |
| +func (e *Engine) retireApp(ctx context.Context, p *pass, app App) error { |
| + st := e.cfg.Store |
| + label := p.run.Label |
| + for _, step := range RetireSteps { |
| + if _, ok, err := st.Done(ctx, label, app.Slug, step); err != nil { |
| + return err |
| + } else if ok { |
| + continue |
| + } |
| + var err error |
| + switch step { |
| + case StepDisable: |
| + err = e.stepDisable(ctx, p, app) |
| + case StepRetire: |
| + err = e.stepRetireConsumer(ctx, p, app) |
| + case StepDetach: |
| + err = e.stepDetach(ctx, p, app) |
| + case StepDelete: |
| + err = e.stepDelete(ctx, p, app) |
| + } |
| + if err != nil { |
| + if !errors.Is(err, errCrash) { |
| + e.note(ctx, p, app.Slug, step, err, nil) |
| + } |
| + return err |
| + } |
| + } |
| + if err := st.RetireApp(ctx, label, app.Slug); err != nil { |
| + return err |
| + } |
| + st.Audit(ctx, p.run.ID, label, app.Slug, "app-retired", "") |
| + return nil |
| +} |
| + |
| +func (e *Engine) stepDisable(ctx context.Context, p *pass, app App) error { |
| + if _, ok, _ := e.cfg.Store.Done(ctx, p.run.Label, app.Slug, StepConsumer); !ok { |
| + return e.record(ctx, p, app.Slug, StepDisable, map[string]any{"skipped": "never-provisioned"}) |
| + } |
| + if _, held, _ := e.cfg.Store.LastRequest(ctx, p.run.Label, app.Slug, "disable"); !held { |
| + if err := e.needWindow(p, homeop.Directory); err != nil { |
| + return err |
| + } |
| + } |
| + _, err := e.op(ctx, opSpec{role: homeop.Directory, action: homeop.DirectoryDisable, label: p.run.Label, app: app.Slug, purpose: "disable", reuse: true, |
| + build: func(b homeop.InputBase) any { |
| + return homeop.DisableInput{InputBase: b, Generation: p.team.Generation, TeamSQID: p.team.TeamSQID, App: app.Slug, Consumer: ConsumerID(p.run.Label, app.Slug)} |
| + }}) |
| + if errors.Is(err, errOpRefused) { |
| + return fail("disable-refused") |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + return e.record(ctx, p, app.Slug, StepDisable, nil) |
| +} |
| + |
| +func (e *Engine) stepRetireConsumer(ctx context.Context, p *pass, app App) error { |
| + if _, ok, _ := e.cfg.Store.Done(ctx, p.run.Label, app.Slug, StepRegister); !ok { |
| + return e.record(ctx, p, app.Slug, StepRetire, map[string]any{"skipped": "never-registered"}) |
| + } |
| + if _, held, _ := e.cfg.Store.LastRequest(ctx, p.run.Label, app.Slug, "retire"); !held { |
| + if err := e.needWindow(p, homeop.Credential); err != nil { |
| + return err |
| + } |
| + } |
| + _, err := e.op(ctx, opSpec{role: homeop.Credential, action: homeop.CredentialRetire, label: p.run.Label, app: app.Slug, purpose: "retire", reuse: true, |
| + build: func(b homeop.InputBase) any { |
| + return homeop.RetireInput{InputBase: b, Consumer: ConsumerID(p.run.Label, app.Slug)} |
| + }}) |
| + if errors.Is(err, errOpRefused) { |
| + return fail("retire-refused") |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + return e.record(ctx, p, app.Slug, StepRetire, nil) |
| +} |
| + |
| +// stepDetach removes the claim: CARLOS does not detach a claim when its |
| +// instance goes. |
| +func (e *Engine) stepDetach(ctx context.Context, p *pass, app App) error { |
| + host := PublicHost(p.run.Label, app.Slug) |
| + if _, found, err := e.cfg.Console.GetDomain(ctx, app.Slug, host); err != nil { |
| + return park("console-unavailable") |
| + } else if found { |
| + if err := e.cfg.Console.DetachDomain(ctx, app.Slug, host); err != nil { |
| + if errors.Is(err, console.ErrGuard) { |
| + return err |
| + } |
| + return park("console-write") |
| + } |
| + if err := e.acted("detach/" + app.Slug); err != nil { |
| + return err |
| + } |
| + if _, found, err = e.cfg.Console.GetDomain(ctx, app.Slug, host); err != nil || found { |
| + return park("detach-pending") |
| + } |
| + } |
| + return e.record(ctx, p, app.Slug, StepDetach, nil) |
| +} |
| + |
| +func (e *Engine) stepDelete(ctx context.Context, p *pass, app App) error { |
| + host := RouteHost(p.run.Label, app.Slug, e.cfg.Account) |
| + if _, found, err := e.cfg.Console.GetInstance(ctx, app.Slug, host); err != nil { |
| + return park("console-unavailable") |
| + } else if found { |
| + if err := e.cfg.Console.DeleteInstance(ctx, app.Slug, host); err != nil { |
| + if errors.Is(err, console.ErrGuard) { |
| + return err |
| + } |
| + return park("console-write") |
| + } |
| + if err := e.acted("delete/" + app.Slug); err != nil { |
| + return err |
| + } |
| + if _, found, err = e.cfg.Console.GetInstance(ctx, app.Slug, host); err != nil || found { |
| + return park("delete-pending") |
| + } |
| + } |
| + return e.record(ctx, p, app.Slug, StepDelete, nil) |
| +} |
diff --git a/provision/store.go b/provision/store.go| new file mode 100644 |
| index 0000000..9fa2836 |
| --- /dev/null |
| +++ b/provision/store.go |
| @@ -0,0 +1,825 @@ |
| +package provision |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "embed" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/home/handoff/seal" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| + _ "modernc.org/sqlite" |
| +) |
| + |
| +//go:embed migrations/*.sql |
| +var migrationFS embed.FS |
| + |
| +// Schema is Alta's own migration set. |
| +var Schema = migrate.MustFromFS(migrationFS, "alta") |
| + |
| +// ErrBusy is the run lock already held. |
| +var ErrBusy = errors.New("provision: another run is advancing") |
| + |
| +// Store is Alta's sealed SQLite state. |
| +type Store struct { |
| + db *sql.DB |
| + sealer *seal.Sealer |
| + now func() time.Time |
| +} |
| + |
| +// OpenDB opens path with the pragmas Alta's privacy rule needs: |
| +// secure_delete, so a deleted address is overwritten, not left in a free |
| +// page. One writer connection, as SQLite allows one. |
| +func OpenDB(path string) (*sql.DB, error) { |
| + dsn := "file:" + path + "?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)&_pragma=foreign_keys(1)&_pragma=secure_delete(1)&_time_format=sqlite&_timezone=UTC" |
| + db, err := sql.Open("sqlite", dsn) |
| + if err != nil { |
| + return nil, err |
| + } |
| + db.SetMaxOpenConns(1) |
| + if err := db.Ping(); err != nil { |
| + db.Close() |
| + return nil, err |
| + } |
| + return db, nil |
| +} |
| + |
| +// NewStore applies extra (sessions, handoff) and Alta's schema and seals |
| +// with dek (ALTA_DEK, 32 bytes). |
| +func NewStore(ctx context.Context, db *sql.DB, dek []byte, now func() time.Time, extra ...*migrate.Set) (*Store, error) { |
| + if len(dek) != 32 { |
| + return nil, errors.New("provision: ALTA_DEK must be 32 bytes") |
| + } |
| + s, err := seal.New(dek, "oficina/alta") |
| + if err != nil { |
| + return nil, err |
| + } |
| + sets := append([]*migrate.Set{Schema}, extra...) |
| + if _, err := migrate.Apply(ctx, migrate.Pool(db), migrate.Merge(sets...)); err != nil { |
| + return nil, fmt.Errorf("provision: migrate: %w", err) |
| + } |
| + if now == nil { |
| + now = time.Now |
| + } |
| + return &Store{db: db, sealer: s, now: now}, nil |
| +} |
| + |
| +func (s *Store) DB() *sql.DB { return s.db } |
| + |
| +func (s *Store) seal(purpose string, b []byte) ([]byte, error) { return s.sealer.Seal(purpose, b) } |
| +func (s *Store) open(purpose string, b []byte) ([]byte, error) { return s.sealer.Open(purpose, b) } |
| + |
| +// ---- teams ---- |
| + |
| +// Team is one team as Alta holds it. No address. |
| +type Team struct { |
| + Label, Name, Environment string |
| + Forked bool |
| + TeamID int64 |
| + TeamSQID string |
| + Epoch int64 |
| + Generation string |
| + OwnerRef string |
| + CreatedAt time.Time |
| + Apps map[string]string // app -> active|retired |
| +} |
| + |
| +func namePurpose(label string) string { return "alta/team-name/" + label } |
| +func ownerPurpose(label string) string { return "alta/owner/" + label } |
| + |
| +// LabelUsed reports whether label was ever used. |
| +func (s *Store) LabelUsed(ctx context.Context, label string) (bool, error) { |
| + var n int |
| + err := s.db.QueryRowContext(ctx, "SELECT count(*) FROM teams WHERE label=?", label).Scan(&n) |
| + return n > 0, err |
| +} |
| + |
| +// CreateTeam records a new label, its sealed name, its environment and |
| +// the owner's sealed address, in one transaction. |
| +func (s *Store) CreateTeam(ctx context.Context, label, name, env string, forked bool, owner string, apps []string) error { |
| + sealed, err := s.seal(namePurpose(label), []byte(name)) |
| + if err != nil { |
| + return err |
| + } |
| + addr, err := s.seal(ownerPurpose(label), []byte(owner)) |
| + if err != nil { |
| + return err |
| + } |
| + tx, err := s.db.BeginTx(ctx, nil) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + f := 0 |
| + if forked { |
| + f = 1 |
| + } |
| + if _, err := tx.ExecContext(ctx, "INSERT INTO teams(label,sealed_name,environment,forked,created_at) VALUES(?,?,?,?,?)", label, sealed, env, f, s.now().Unix()); err != nil { |
| + return fmt.Errorf("provision: label taken: %w", err) |
| + } |
| + if _, err := tx.ExecContext(ctx, "INSERT INTO owner_inputs(label,sealed_address) VALUES(?,?)", label, addr); err != nil { |
| + return err |
| + } |
| + for _, app := range apps { |
| + if _, err := tx.ExecContext(ctx, "INSERT INTO environments(app,environment,label) VALUES(?,?,?)", app, env, label); err != nil { |
| + return fmt.Errorf("provision: environment %s already Alta's for %s: %w", env, app, err) |
| + } |
| + if _, err := tx.ExecContext(ctx, "INSERT INTO team_apps(label,app,state) VALUES(?,?,'active')", label, app); err != nil { |
| + return err |
| + } |
| + } |
| + return tx.Commit() |
| +} |
| + |
| +// AddApps records apps joining a team (an add-apps run). A retired app is |
| +// refused: its hostnames are dead for good. |
| +func (s *Store) AddApps(ctx context.Context, label string, apps []string) error { |
| + t, err := s.Team(ctx, label) |
| + if err != nil { |
| + return err |
| + } |
| + tx, err := s.db.BeginTx(ctx, nil) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + for _, app := range apps { |
| + switch t.Apps[app] { |
| + case "retired": |
| + return fmt.Errorf("provision: %s was retired from this team and is never re-added", app) |
| + case "active": |
| + continue |
| + } |
| + if _, err := tx.ExecContext(ctx, "INSERT INTO environments(app,environment,label) VALUES(?,?,?)", app, t.Environment, label); err != nil { |
| + return err |
| + } |
| + if _, err := tx.ExecContext(ctx, "INSERT INTO team_apps(label,app,state) VALUES(?,?,'active')", label, app); err != nil { |
| + return err |
| + } |
| + } |
| + return tx.Commit() |
| +} |
| + |
| +// RetireApp marks an app retired. |
| +func (s *Store) RetireApp(ctx context.Context, label, app string) error { |
| + _, err := s.db.ExecContext(ctx, "UPDATE team_apps SET state='retired' WHERE label=? AND app=?", label, app) |
| + return err |
| +} |
| + |
| +// Team reads one team. |
| +func (s *Store) Team(ctx context.Context, label string) (Team, error) { |
| + var t Team |
| + var sealed []byte |
| + var forked int |
| + var id, epoch sql.NullInt64 |
| + var sqid, gen, owner sql.NullString |
| + var created int64 |
| + err := s.db.QueryRowContext(ctx, "SELECT label,sealed_name,environment,forked,team_id,team_sqid,epoch,generation,owner_ref,created_at FROM teams WHERE label=?", label).Scan(&t.Label, &sealed, &t.Environment, &forked, &id, &sqid, &epoch, &gen, &owner, &created) |
| + if err != nil { |
| + return Team{}, err |
| + } |
| + name, err := s.open(namePurpose(label), sealed) |
| + if err != nil { |
| + return Team{}, err |
| + } |
| + t.Name, t.Forked, t.TeamID, t.TeamSQID, t.Epoch, t.Generation, t.OwnerRef = string(name), forked == 1, id.Int64, sqid.String, epoch.Int64, gen.String, owner.String |
| + t.CreatedAt = time.Unix(created, 0) |
| + t.Apps = map[string]string{} |
| + rows, err := s.db.QueryContext(ctx, "SELECT app,state FROM team_apps WHERE label=?", label) |
| + if err != nil { |
| + return Team{}, err |
| + } |
| + defer rows.Close() |
| + for rows.Next() { |
| + var app, state string |
| + if err := rows.Scan(&app, &state); err != nil { |
| + return Team{}, err |
| + } |
| + t.Apps[app] = state |
| + } |
| + return t, rows.Err() |
| +} |
| + |
| +// Teams lists every label, newest first. |
| +func (s *Store) Teams(ctx context.Context) ([]Team, error) { |
| + rows, err := s.db.QueryContext(ctx, "SELECT label FROM teams ORDER BY created_at DESC, label") |
| + if err != nil { |
| + return nil, err |
| + } |
| + var labels []string |
| + for rows.Next() { |
| + var l string |
| + if err := rows.Scan(&l); err != nil { |
| + rows.Close() |
| + return nil, err |
| + } |
| + labels = append(labels, l) |
| + } |
| + rows.Close() |
| + var out []Team |
| + for _, l := range labels { |
| + t, err := s.Team(ctx, l) |
| + if err != nil { |
| + return nil, err |
| + } |
| + out = append(out, t) |
| + } |
| + return out, nil |
| +} |
| + |
| +// SetSeeded records what seed-team committed. |
| +func (s *Store) SetSeeded(ctx context.Context, label string, id int64, sqid string, epoch int64, generation, ownerRef string) error { |
| + _, err := s.db.ExecContext(ctx, "UPDATE teams SET team_id=?,team_sqid=?,epoch=?,generation=?,owner_ref=? WHERE label=?", id, sqid, epoch, generation, ownerRef, label) |
| + return err |
| +} |
| + |
| +// ---- owner input ---- |
| + |
| +// Owner returns the sealed owner address, if Alta still holds it. |
| +func (s *Store) Owner(ctx context.Context, label string) (string, bool, error) { |
| + var sealed []byte |
| + err := s.db.QueryRowContext(ctx, "SELECT sealed_address FROM owner_inputs WHERE label=?", label).Scan(&sealed) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return "", false, nil |
| + } |
| + if err != nil { |
| + return "", false, err |
| + } |
| + b, err := s.open(ownerPurpose(label), sealed) |
| + if err != nil { |
| + return "", false, err |
| + } |
| + return string(b), true, nil |
| +} |
| + |
| +// SetOwner stores a retyped owner address (§4: the stopgap allowlist edit |
| +// after step 13 has Paul retype it, and Alta deletes it again once |
| +// written). |
| +func (s *Store) SetOwner(ctx context.Context, label, addr string) error { |
| + sealed, err := s.seal(ownerPurpose(label), []byte(addr)) |
| + if err != nil { |
| + return err |
| + } |
| + _, err = s.db.ExecContext(ctx, "INSERT INTO owner_inputs(label,sealed_address) VALUES(?,?) ON CONFLICT(label) DO UPDATE SET sealed_address=excluded.sealed_address", label, sealed) |
| + return err |
| +} |
| + |
| +// ForgetOwner deletes every row that carries the owner's address: the |
| +// owner input, the credential role's plan bytes and every owner-seed |
| +// request (§4, step 13). secure_delete overwrites them. |
| +func (s *Store) ForgetOwner(ctx context.Context, label string) error { |
| + tx, err := s.db.BeginTx(ctx, nil) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + if _, err := tx.ExecContext(ctx, "DELETE FROM owner_inputs WHERE label=?", label); err != nil { |
| + return err |
| + } |
| + if _, err := tx.ExecContext(ctx, "DELETE FROM operator_requests WHERE label=? AND action='credential.owner-seed'", label); err != nil { |
| + return err |
| + } |
| + if _, err := tx.ExecContext(ctx, "UPDATE plan_submissions SET sealed_plan=NULL WHERE role='credential' AND plan_id IN (SELECT plan_id FROM runs WHERE label=? AND plan_id IS NOT NULL)", label); err != nil { |
| + return err |
| + } |
| + return tx.Commit() |
| +} |
| + |
| +// ---- runs ---- |
| + |
| +// Run is one (team, plan) run. |
| +type Run struct { |
| + ID int64 |
| + Label string |
| + Kind string |
| + Apps []string |
| + PlanID string |
| + PlanExpires int64 |
| + State, Code string |
| + Created, Upd time.Time |
| +} |
| + |
| +// NewRun starts a run. Any unfinished run for the same label is |
| +// superseded: one live plan per team. |
| +func (s *Store) NewRun(ctx context.Context, kind, label string, apps []string) (int64, error) { |
| + now := s.now().Unix() |
| + tx, err := s.db.BeginTx(ctx, nil) |
| + if err != nil { |
| + return 0, err |
| + } |
| + defer tx.Rollback() |
| + if _, err := tx.ExecContext(ctx, "UPDATE runs SET state='superseded',updated_at=? WHERE label=? AND kind<>'initialize' AND state IN ('planned','running','parked')", now, label); err != nil { |
| + return 0, err |
| + } |
| + if kind == "initialize" { |
| + if _, err := tx.ExecContext(ctx, "UPDATE runs SET state='superseded',updated_at=? WHERE kind='initialize' AND state IN ('planned','running','parked')", now); err != nil { |
| + return 0, err |
| + } |
| + } |
| + res, err := tx.ExecContext(ctx, "INSERT INTO runs(label,kind,apps,state,created_at,updated_at) VALUES(?,?,?,'planned',?,?)", label, kind, strings.Join(apps, ","), now, now) |
| + if err != nil { |
| + return 0, err |
| + } |
| + id, err := res.LastInsertId() |
| + if err != nil { |
| + return 0, err |
| + } |
| + return id, tx.Commit() |
| +} |
| + |
| +func scanRun(sc interface{ Scan(...any) error }) (Run, error) { |
| + var r Run |
| + var apps string |
| + var plan sql.NullString |
| + var exp sql.NullInt64 |
| + var c, u int64 |
| + if err := sc.Scan(&r.ID, &r.Label, &r.Kind, &apps, &plan, &exp, &r.State, &r.Code, &c, &u); err != nil { |
| + return Run{}, err |
| + } |
| + if apps != "" { |
| + r.Apps = strings.Split(apps, ",") |
| + } |
| + r.PlanID, r.PlanExpires, r.Created, r.Upd = plan.String, exp.Int64, time.Unix(c, 0), time.Unix(u, 0) |
| + return r, nil |
| +} |
| + |
| +const runCols = "id,label,kind,apps,plan_id,plan_expires_at,state,code,created_at,updated_at" |
| + |
| +func (s *Store) Run(ctx context.Context, id int64) (Run, error) { |
| + return scanRun(s.db.QueryRowContext(ctx, "SELECT "+runCols+" FROM runs WHERE id=?", id)) |
| +} |
| + |
| +// Runs lists a label's runs, newest first ("" lists initialize runs). |
| +func (s *Store) Runs(ctx context.Context, label string) ([]Run, error) { |
| + rows, err := s.db.QueryContext(ctx, "SELECT "+runCols+" FROM runs WHERE label=? ORDER BY id DESC LIMIT 50", label) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + var out []Run |
| + for rows.Next() { |
| + r, err := scanRun(rows) |
| + if err != nil { |
| + return nil, err |
| + } |
| + out = append(out, r) |
| + } |
| + return out, rows.Err() |
| +} |
| + |
| +// LiveRuns lists every run not finished. |
| +func (s *Store) LiveRuns(ctx context.Context) ([]Run, error) { |
| + rows, err := s.db.QueryContext(ctx, "SELECT "+runCols+" FROM runs WHERE state IN ('planned','running','parked') ORDER BY id") |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + var out []Run |
| + for rows.Next() { |
| + r, err := scanRun(rows) |
| + if err != nil { |
| + return nil, err |
| + } |
| + out = append(out, r) |
| + } |
| + return out, rows.Err() |
| +} |
| + |
| +func (s *Store) SetRunState(ctx context.Context, id int64, state, code string) error { |
| + _, err := s.db.ExecContext(ctx, "UPDATE runs SET state=?,code=?,updated_at=? WHERE id=?", state, code, s.now().Unix(), id) |
| + return err |
| +} |
| + |
| +func (s *Store) SetRunPlan(ctx context.Context, id int64, planID string, expires int64) error { |
| + _, err := s.db.ExecContext(ctx, "UPDATE runs SET plan_id=?,plan_expires_at=?,state='planned',code='',updated_at=? WHERE id=?", planID, expires, s.now().Unix(), id) |
| + return err |
| +} |
| + |
| +// ---- plans ---- |
| + |
| +// PlanSubmission is one role's copy of a plan. |
| +type PlanSubmission struct { |
| + PlanID, Role, State string |
| + Expires, Window int64 |
| + Signed []byte |
| +} |
| + |
| +func planPurpose(id, role string) string { return "alta/plan/" + id + "/" + role } |
| + |
| +func (s *Store) SavePlan(ctx context.Context, id, role string, signed []byte, expires int64) error { |
| + sealed, err := s.seal(planPurpose(id, role), signed) |
| + if err != nil { |
| + return err |
| + } |
| + _, err = s.db.ExecContext(ctx, "INSERT INTO plan_submissions(plan_id,role,sealed_plan,state,expires_at) VALUES(?,?,?,'signed',?)", id, role, sealed, expires) |
| + return err |
| +} |
| + |
| +func (s *Store) Plans(ctx context.Context, id string) (map[string]PlanSubmission, error) { |
| + rows, err := s.db.QueryContext(ctx, "SELECT plan_id,role,sealed_plan,state,expires_at,window_expires_at FROM plan_submissions WHERE plan_id=?", id) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + out := map[string]PlanSubmission{} |
| + for rows.Next() { |
| + var p PlanSubmission |
| + var sealed []byte |
| + var w sql.NullInt64 |
| + if err := rows.Scan(&p.PlanID, &p.Role, &sealed, &p.State, &p.Expires, &w); err != nil { |
| + return nil, err |
| + } |
| + p.Window = w.Int64 |
| + if sealed != nil { |
| + if p.Signed, err = s.open(planPurpose(p.PlanID, p.Role), sealed); err != nil { |
| + return nil, err |
| + } |
| + } |
| + out[p.Role] = p |
| + } |
| + return out, rows.Err() |
| +} |
| + |
| +func (s *Store) MarkPlan(ctx context.Context, id, role, state string, window int64) error { |
| + var w any |
| + if window > 0 { |
| + w = window |
| + } |
| + _, err := s.db.ExecContext(ctx, "UPDATE plan_submissions SET state=?,window_expires_at=coalesce(?,window_expires_at) WHERE plan_id=? AND role=?", state, w, id, role) |
| + return err |
| +} |
| + |
| +// DropExpiredPlans deletes the signed bytes of every plan past its expiry |
| +// and window: they are kept only to retry a busy role. |
| +func (s *Store) DropExpiredPlans(ctx context.Context) error { |
| + now := s.now().Unix() |
| + _, err := s.db.ExecContext(ctx, "UPDATE plan_submissions SET sealed_plan=NULL WHERE expires_at<=? AND (window_expires_at IS NULL OR window_expires_at<=?)", now, now) |
| + return err |
| +} |
| + |
| +// ---- steps ---- |
| + |
| +// Step is one recorded step. Data is non-secret JSON. |
| +type Step struct { |
| + Label, App, Name, State, Code string |
| + Data map[string]any |
| + Updated time.Time |
| +} |
| + |
| +func (s *Store) Step(ctx context.Context, label, app, name string) (Step, bool, error) { |
| + st := Step{Label: label, App: app, Name: name} |
| + var data string |
| + var u int64 |
| + err := s.db.QueryRowContext(ctx, "SELECT state,code,data,updated_at FROM steps WHERE label=? AND app=? AND step=?", label, app, name).Scan(&st.State, &st.Code, &data, &u) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return st, false, nil |
| + } |
| + if err != nil { |
| + return st, false, err |
| + } |
| + st.Updated = time.Unix(u, 0) |
| + if err := json.Unmarshal([]byte(data), &st.Data); err != nil { |
| + return st, false, err |
| + } |
| + return st, true, nil |
| +} |
| + |
| +// Done reports whether a step is done, and its data. |
| +func (s *Store) Done(ctx context.Context, label, app, name string) (map[string]any, bool, error) { |
| + st, ok, err := s.Step(ctx, label, app, name) |
| + if err != nil || !ok || st.State != "done" { |
| + return nil, false, err |
| + } |
| + return st.Data, true, nil |
| +} |
| + |
| +func (s *Store) SetStep(ctx context.Context, label, app, name, state, code string, data map[string]any) error { |
| + if data == nil { |
| + data = map[string]any{} |
| + } |
| + b, err := json.Marshal(data) |
| + if err != nil { |
| + return err |
| + } |
| + _, err = s.db.ExecContext(ctx, "INSERT INTO steps(label,app,step,state,code,data,updated_at) VALUES(?,?,?,?,?,?,?) ON CONFLICT(label,app,step) DO UPDATE SET state=excluded.state,code=excluded.code,data=excluded.data,updated_at=excluded.updated_at", label, app, name, state, code, string(b), s.now().Unix()) |
| + return err |
| +} |
| + |
| +// Steps lists a team's steps. |
| +func (s *Store) Steps(ctx context.Context, label string) ([]Step, error) { |
| + rows, err := s.db.QueryContext(ctx, "SELECT app,step,state,code,data,updated_at FROM steps WHERE label=? ORDER BY app,step", label) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + var out []Step |
| + for rows.Next() { |
| + st := Step{Label: label} |
| + var data string |
| + var u int64 |
| + if err := rows.Scan(&st.App, &st.Name, &st.State, &st.Code, &data, &u); err != nil { |
| + return nil, err |
| + } |
| + _ = json.Unmarshal([]byte(data), &st.Data) |
| + st.Updated = time.Unix(u, 0) |
| + out = append(out, st) |
| + } |
| + return out, rows.Err() |
| +} |
| + |
| +// ---- operator requests and streams ---- |
| + |
| +// OpRequest is one signed operation Alta holds. |
| +type OpRequest struct { |
| + ID int64 |
| + Role, OperationID, Action string |
| + Label, App, Purpose, Head string |
| + Sequence, Expires int64 |
| + State string |
| + Bytes []byte |
| +} |
| + |
| +func requestPurpose(opID string) string { return "alta/request/" + opID } |
| + |
| +// NextJournal reserves a journal sequence for a request about to be |
| +// signed (Home requires journal_sequence > 0; it is Alta's own counter). |
| +func (s *Store) NextJournal(ctx context.Context) (int64, error) { |
| + var n sql.NullInt64 |
| + err := s.db.QueryRowContext(ctx, "SELECT max(id) FROM operator_requests").Scan(&n) |
| + return n.Int64 + 1, err |
| +} |
| + |
| +// SaveRequest stores a signed request, sealed, before it is sent. |
| +func (s *Store) SaveRequest(ctx context.Context, r OpRequest) error { |
| + sealed, err := s.seal(requestPurpose(r.OperationID), r.Bytes) |
| + if err != nil { |
| + return err |
| + } |
| + _, err = s.db.ExecContext(ctx, "INSERT INTO operator_requests(id,role,sequence,operation_id,action,label,app,purpose,head,sealed_request,state,expires_at,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,'signed',?,?)", r.ID, r.Role, r.Sequence, r.OperationID, r.Action, r.Label, r.App, r.Purpose, r.Head, sealed, r.Expires, s.now().Unix()) |
| + return err |
| +} |
| + |
| +func (s *Store) scanRequest(sc interface{ Scan(...any) error }) (OpRequest, error) { |
| + var r OpRequest |
| + var sealed []byte |
| + if err := sc.Scan(&r.ID, &r.Role, &r.Sequence, &r.OperationID, &r.Action, &r.Label, &r.App, &r.Purpose, &r.Head, &sealed, &r.State, &r.Expires); err != nil { |
| + return OpRequest{}, err |
| + } |
| + b, err := s.open(requestPurpose(r.OperationID), sealed) |
| + if err != nil { |
| + return OpRequest{}, err |
| + } |
| + r.Bytes = b |
| + return r, nil |
| +} |
| + |
| +const reqCols = "id,role,sequence,operation_id,action,label,app,purpose,head,sealed_request,state,expires_at" |
| + |
| +// LastRequest is the newest request for (label, app, purpose) that is |
| +// not refused: the one to replay. |
| +func (s *Store) LastRequest(ctx context.Context, label, app, purpose string) (OpRequest, bool, error) { |
| + r, err := s.scanRequest(s.db.QueryRowContext(ctx, "SELECT "+reqCols+" FROM operator_requests WHERE label=? AND app=? AND purpose=? AND state<>'refused' ORDER BY id DESC LIMIT 1", label, app, purpose)) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return OpRequest{}, false, nil |
| + } |
| + return r, err == nil, err |
| +} |
| + |
| +// RequestByHead finds the request Alta signed whose authorization hashes |
| +// to head on role, if it holds one. |
| +func (s *Store) RequestByHead(ctx context.Context, role, head string) (OpRequest, bool, error) { |
| + r, err := s.scanRequest(s.db.QueryRowContext(ctx, "SELECT "+reqCols+" FROM operator_requests WHERE role=? AND head=?", role, head)) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return OpRequest{}, false, nil |
| + } |
| + return r, err == nil, err |
| +} |
| + |
| +func (s *Store) MarkRequest(ctx context.Context, id int64, state string) error { |
| + _, err := s.db.ExecContext(ctx, "UPDATE operator_requests SET state=? WHERE id=?", state, id) |
| + return err |
| +} |
| + |
| +// Commit records a committed request and advances the role's stream in |
| +// one transaction. |
| +func (s *Store) Commit(ctx context.Context, r OpRequest) error { |
| + tx, err := s.db.BeginTx(ctx, nil) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + if _, err := tx.ExecContext(ctx, "UPDATE operator_requests SET state='committed' WHERE id=?", r.ID); err != nil { |
| + return err |
| + } |
| + if _, err := tx.ExecContext(ctx, "INSERT INTO operator_streams(role,sequence,head,updated_at) VALUES(?,?,?,?) ON CONFLICT(role) DO UPDATE SET sequence=excluded.sequence,head=excluded.head,updated_at=excluded.updated_at WHERE excluded.sequence>operator_streams.sequence", r.Role, r.Sequence, r.Head, s.now().Unix()); err != nil { |
| + return err |
| + } |
| + return tx.Commit() |
| +} |
| + |
| +// Stream is a role's position: the last committed sequence and head. |
| +func (s *Store) Stream(ctx context.Context, role string) (int64, string, bool, error) { |
| + var seq int64 |
| + var head string |
| + err := s.db.QueryRowContext(ctx, "SELECT sequence,head FROM operator_streams WHERE role=?", role).Scan(&seq, &head) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return 0, "", false, nil |
| + } |
| + return seq, head, err == nil, err |
| +} |
| + |
| +// SetStream adopts Home's position (resync through inspect). |
| +func (s *Store) SetStream(ctx context.Context, role string, seq int64, head string) error { |
| + _, err := s.db.ExecContext(ctx, "INSERT INTO operator_streams(role,sequence,head,updated_at) VALUES(?,?,?,?) ON CONFLICT(role) DO UPDATE SET sequence=excluded.sequence,head=excluded.head,updated_at=excluded.updated_at", role, seq, head, s.now().Unix()) |
| + return err |
| +} |
| + |
| +// ---- audit ---- |
| + |
| +// AuditEntry is one audit row. |
| +type AuditEntry struct { |
| + At time.Time |
| + RunID int64 |
| + Label, App, Event, Detail string |
| +} |
| + |
| +func (s *Store) Audit(ctx context.Context, runID int64, label, app, event, detail string) { |
| + _, _ = s.db.ExecContext(ctx, "INSERT INTO audit(at,run_id,label,app,event,detail) VALUES(?,?,?,?,?,?)", s.now().Unix(), runID, label, app, event, detail) |
| +} |
| + |
| +func (s *Store) AuditLog(ctx context.Context, label string, limit int) ([]AuditEntry, error) { |
| + rows, err := s.db.QueryContext(ctx, "SELECT at,run_id,label,app,event,detail FROM audit WHERE label=? ORDER BY id DESC LIMIT ?", label, limit) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + var out []AuditEntry |
| + for rows.Next() { |
| + var e AuditEntry |
| + var at int64 |
| + if err := rows.Scan(&at, &e.RunID, &e.Label, &e.App, &e.Event, &e.Detail); err != nil { |
| + return nil, err |
| + } |
| + e.At = time.Unix(at, 0) |
| + out = append(out, e) |
| + } |
| + return out, rows.Err() |
| +} |
| + |
| +// ---- lock ---- |
| + |
| +// Lock takes the one-run-at-a-time lock. A lock older than stale is |
| +// taken over: its holder crashed (a run resumes by probing, so taking |
| +// over a dead holder's run is safe). |
| +func (s *Store) Lock(ctx context.Context, runID int64, stale time.Duration) error { |
| + now := s.now().Unix() |
| + res, err := s.db.ExecContext(ctx, "INSERT INTO run_lock(singleton,run_id,acquired_at) VALUES(1,?,?) ON CONFLICT(singleton) DO UPDATE SET run_id=excluded.run_id,acquired_at=excluded.acquired_at WHERE run_lock.acquired_at<?", runID, now, now-int64(stale.Seconds())) |
| + if err != nil { |
| + return err |
| + } |
| + if n, _ := res.RowsAffected(); n == 0 { |
| + return ErrBusy |
| + } |
| + return nil |
| +} |
| + |
| +func (s *Store) Unlock(ctx context.Context, runID int64) { |
| + _, _ = s.db.ExecContext(context.WithoutCancel(ctx), "DELETE FROM run_lock WHERE run_id=?", runID) |
| +} |
| + |
| +// ---- the §8 guard ---- |
| + |
| +type deprovisionKey struct{} |
| +type proposalKey struct{} |
| + |
| +// WithDeprovision marks ctx as inside retire-apps run id: the only |
| +// context in which the console client may send a DELETE. |
| +func WithDeprovision(ctx context.Context, runID int64) context.Context { |
| + return context.WithValue(ctx, deprovisionKey{}, runID) |
| +} |
| + |
| +// proposal is a team not yet recorded, whose hosts and environment a |
| +// preflight may READ (never write): checking a label must not burn it. |
| +type proposal struct { |
| + label, env string |
| + apps []string |
| +} |
| + |
| +func withProposal(ctx context.Context, label, env string, apps []string) context.Context { |
| + return context.WithValue(ctx, proposalKey{}, proposal{label, env, apps}) |
| +} |
| + |
| +// Guard implements console.Guard from Alta's records. |
| +type Guard struct { |
| + Store *Store |
| + Account string |
| +} |
| + |
| +func (g Guard) proposed(ctx context.Context, app string) (proposal, bool) { |
| + p, ok := ctx.Value(proposalKey{}).(proposal) |
| + if !ok { |
| + return proposal{}, false |
| + } |
| + for _, a := range p.apps { |
| + if a == app { |
| + return p, true |
| + } |
| + } |
| + return proposal{}, false |
| +} |
| + |
| +// Environment admits env for app only if Alta's records own it (or, for |
| +// a read, a preflight proposes it). |
| +func (g Guard) Environment(ctx context.Context, app, env string, write bool) error { |
| + if env == "" { |
| + return errors.New("empty environment") |
| + } |
| + if p, ok := g.proposed(ctx, app); ok && !write && p.env == env { |
| + return nil |
| + } |
| + var n int |
| + if err := g.Store.db.QueryRowContext(ctx, "SELECT count(*) FROM environments WHERE app=? AND environment=?", app, env).Scan(&n); err != nil { |
| + return err |
| + } |
| + if n == 0 { |
| + return errors.New("environment not Alta's") |
| + } |
| + return nil |
| +} |
| + |
| +// Host admits only <label>-<app>.<account>.oncarlos.com and |
| +// <label>.<app>.oficina.works for a label Alta holds with that app. |
| +func (g Guard) Host(ctx context.Context, app, host string, write bool) error { |
| + label := "" |
| + switch { |
| + case strings.HasSuffix(host, "-"+app+"."+g.Account+".oncarlos.com"): |
| + label = strings.TrimSuffix(host, "-"+app+"."+g.Account+".oncarlos.com") |
| + case strings.HasSuffix(host, "."+app+"."+PublicDomain): |
| + label = strings.TrimSuffix(host, "."+app+"."+PublicDomain) |
| + default: |
| + return errors.New("host outside Alta's shapes") |
| + } |
| + if !LabelPattern.MatchString(label) { |
| + return errors.New("host label outside Alta's shapes") |
| + } |
| + if p, ok := g.proposed(ctx, app); ok && !write && p.label == label { |
| + return nil |
| + } |
| + var n int |
| + if err := g.Store.db.QueryRowContext(ctx, "SELECT count(*) FROM team_apps WHERE label=? AND app=?", label, app).Scan(&n); err != nil { |
| + return err |
| + } |
| + if n == 0 { |
| + return errors.New("host for a team or app Alta does not hold") |
| + } |
| + return nil |
| +} |
| + |
| +// Delete admits a DELETE only inside a live retire-apps run naming app. |
| +func (g Guard) Delete(ctx context.Context, app, host string) error { |
| + id, ok := ctx.Value(deprovisionKey{}).(int64) |
| + if !ok { |
| + return errors.New("delete outside a deprovision run") |
| + } |
| + r, err := g.Store.Run(ctx, id) |
| + if err != nil { |
| + return err |
| + } |
| + if r.Kind != "retire-apps" || (r.State != "running" && r.State != "parked" && r.State != "planned") { |
| + return errors.New("delete outside a live deprovision run") |
| + } |
| + for _, a := range r.Apps { |
| + if a == app { |
| + return nil |
| + } |
| + } |
| + return errors.New("delete for an app the deprovision run does not name") |
| +} |
| + |
| +// ---- sessions' idle clock ---- |
| + |
| +// Seen records a session's activity and reports whether it was idle |
| +// longer than idle (then the caller signs it out). |
| +func (s *Store) Seen(ctx context.Context, tokenHash string, idle time.Duration) (expired bool, err error) { |
| + now := s.now().Unix() |
| + var last int64 |
| + err = s.db.QueryRowContext(ctx, "SELECT seen_at FROM session_seen WHERE token_hash=?", tokenHash).Scan(&last) |
| + if err == nil && now-last > int64(idle.Seconds()) { |
| + _, err = s.db.ExecContext(ctx, "DELETE FROM session_seen WHERE token_hash=?", tokenHash) |
| + return true, err |
| + } |
| + if err != nil && !errors.Is(err, sql.ErrNoRows) { |
| + return false, err |
| + } |
| + _, err = s.db.ExecContext(ctx, "INSERT INTO session_seen(token_hash,seen_at) VALUES(?,?) ON CONFLICT(token_hash) DO UPDATE SET seen_at=excluded.seen_at", tokenHash, now) |
| + return false, err |
| +} |
| + |
| +// SweepSeen drops idle-clock rows older than a session can live. |
| +func (s *Store) SweepSeen(ctx context.Context, older time.Duration) { |
| + _, _ = s.db.ExecContext(ctx, "DELETE FROM session_seen WHERE seen_at<?", s.now().Add(-older).Unix()) |
| +} |