oficina / alta Public

provision: adoption runs for the canonical apps

StartAdoption (Plan A: existing_team on both roles, seed at the
proposed SQID, consumer and register, ends awaiting-configuration),
ActivateAdopted (Plans B/C: verify without the team probe, activate
under the existing-app policy with the Observer's evidence, held
requests replayed exactly) and DisableAdopted (directory-only
disable). No console or instance calls.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev f6d1e6819d834f0922019a077bdfdc42acd799fe parent bb9a82a
6 files changed, +1,307 −15
  • adopt/observer.go +6 −0
  • adopt/observer_test.go +18 −0
  • provision/adopt.go +302 −1
  • provision/adopt_test.go +910 −0
  • provision/engine.go +41 −13
  • provision/steps.go +30 −1
diff --git a/adopt/observer.go b/adopt/observer.go
index 20ed829..f65cc7b 100644
--- a/adopt/observer.go
+++ b/adopt/observer.go
@@ -26,6 +26,12 @@ func (r *Refusal) Error() string {
return "adopt: observation refused: " + strings.Join(r.Codes, ", ")
}
+// RefusalCodes answers the codes to provision's engine, which parks an
+// adopted app's activation with them (provision.ObserverRefusal).
+func (r *Refusal) RefusalCodes() []string { return append([]string(nil), r.Codes...) }
+
+var _ provision.ObserverRefusal = (*Refusal)(nil)
+
func refuse(codes ...string) error { return &Refusal{Codes: sortedSet(codes)} }
// appVersion is the app_version Home's directory.activate-consumer
diff --git a/adopt/observer_test.go b/adopt/observer_test.go
index 5c9d370..767675d 100644
--- a/adopt/observer_test.go
+++ b/adopt/observer_test.go
@@ -402,3 +402,21 @@ func setupOK(t *testing.T, err error) {
t.Fatalf("setup: %v", err)
}
}
+
+// provision's engine parks an activation with the gate's own codes: it
+// reads them through provision.ObserverRefusal, as a copy.
+func TestObserverRefusalReachesTheEngine(t *testing.T) {
+ err := error(refuse("witness-superseded", "missing-witness"))
+ var r provision.ObserverRefusal
+ if !errors.As(err, &r) {
+ t.Fatal("a refusal is not a provision.ObserverRefusal")
+ }
+ codes := r.RefusalCodes()
+ if !slices.Equal(codes, []string{"missing-witness", "witness-superseded"}) {
+ t.Fatalf("codes %v", codes)
+ }
+ codes[0] = "edited"
+ if r.RefusalCodes()[0] != "missing-witness" {
+ t.Fatal("the engine can edit the refusal's codes")
+ }
+}
diff --git a/provision/adopt.go b/provision/adopt.go
index c2926b9..0b73704 100644
--- a/provision/adopt.go
+++ b/provision/adopt.go
@@ -1,6 +1,12 @@
package provision
-import "context"
+import (
+ "context"
+ "errors"
+ "strings"
+
+ "amadan.net/oficina/alta/homeop"
+)
// Observation is what an adopted app's activation evidence takes from the
// CARLOS half: the delivered version, the reviewed artifact's digest and
@@ -15,3 +21,298 @@ type Observation struct {
type Observer interface {
Observe(ctx context.Context, app, teamSQID string) (Observation, error)
}
+
+// ObserverRefusal is an Observer's refusal (adopt.Refusal): fixed codes,
+// which the activation parks with. Any other Observer error is a failed
+// read, retried on the next pass.
+type ObserverRefusal interface {
+ error
+ RefusalCodes() []string
+}
+
+// adoptionName is the existing team's display name (Paul, 2026-11-16).
+const adoptionName = "Oficina"
+
+// Existing-team adoption (Home implementation/existing-team-adoption.md)
+// runs in three plans, all under label oficina and the canonical tuple
+// (ConsumerID, PublicOrigin and PublicHost answer it for AdoptionLabel):
+//
+// - Plan A (StartAdoption): create-team with existing_team, owner-seed
+// and seed-team at that SQID, then each app's provision and register
+// (verified, nothing inserted). It ends done, awaiting-configuration.
+// - Plans B and C (ActivateAdopted): add-apps with existing_team, each
+// app's verify and activate under the existing-app policy, its
+// evidence from the Observer.
+// - DisableAdopted: an ordinary retire-apps window on the directory
+// alone, directory.disable-consumer and nothing else.
+//
+// None of them touches the console or an instance: the six instances,
+// their environments and their keys are not Alta's.
+
+// adoptionSteps is an adoption run's per-app pipeline: Plan A, a
+// disable, or Plans B and C.
+func adoptionSteps(kind string) []string {
+ switch kind {
+ case homeop.KindCreateTeam:
+ return []string{StepConsumer, StepRegister}
+ case homeop.KindRetireApps:
+ return []string{StepDisable}
+ }
+ return []string{StepVerify, StepActivate}
+}
+
+// StartAdoption opens Plan A for the six canonical apps. existing_team is
+// the SQID the directory proposes now, read here; Home seeds the team at
+// it or not at all.
+func (e *Engine) StartAdoption(ctx context.Context, name, owner string) (int64, error) {
+ if name != adoptionName {
+ return 0, fail("name-not-oficina")
+ }
+ if !homeop.OwnerAddress(owner) {
+ return 0, fail("owner-shape")
+ }
+ used, err := e.cfg.Store.LabelUsed(ctx, AdoptionLabel)
+ if err != nil {
+ return 0, err
+ }
+ if used {
+ return 0, fail("label-used")
+ }
+ if _, o, _ := e.cfg.Home.Inspect(ctx, homeop.Credential); o != homeop.OK {
+ return 0, fail("home-" + homeop.Credential + "-" + o.String())
+ }
+ ins, o, _ := e.cfg.Home.Inspect(ctx, homeop.Directory)
+ if o != homeop.OK {
+ return 0, fail("home-" + homeop.Directory + "-" + o.String())
+ }
+ if ins.Generation == nil || ins.TeamSQID == "" {
+ return 0, fail("home-not-initialized")
+ }
+ apps := Slugs()
+ if err := e.cfg.Store.CreateAdoption(ctx, name, owner, apps); err != nil {
+ return 0, err
+ }
+ id, err := e.cfg.Store.NewAdoptionRun(ctx, homeop.KindCreateTeam, apps)
+ if err != nil {
+ return 0, err
+ }
+ e.cfg.Store.Audit(ctx, id, AdoptionLabel, "", "run-start", homeop.KindCreateTeam)
+ return id, e.submitPlans(ctx, id, AdoptionLabel, name, owner, homeop.KindCreateTeam, apps, ins.TeamSQID)
+}
+
+// ActivateAdopted opens Plan B or C: add-apps on both roles for apps
+// whose Plan A is done, existing_team the seeded team's SQID, no owner.
+func (e *Engine) ActivateAdopted(ctx context.Context, apps []string) (int64, error) {
+ if e.cfg.Observer == nil {
+ return 0, fail("no-observer")
+ }
+ if len(apps) == 0 {
+ return 0, fail("no-apps")
+ }
+ sorted := SortApps(apps)
+ if len(sorted) != len(apps) {
+ return 0, fail("unknown-app")
+ }
+ t, err := e.cfg.Store.Team(ctx, AdoptionLabel)
+ if err != nil {
+ return 0, fail("no-team")
+ }
+ if t.TeamSQID == "" {
+ return 0, fail("team-not-seeded")
+ }
+ for _, a := range sorted {
+ if _, ok, err := e.cfg.Store.Done(ctx, AdoptionLabel, a, StepRegister); err != nil {
+ return 0, err
+ } else if !ok {
+ return 0, fail("not-registered")
+ }
+ if _, ok, err := e.cfg.Store.Done(ctx, AdoptionLabel, a, StepDisable); err != nil {
+ return 0, err
+ } else if ok {
+ return 0, fail("app-disabled")
+ }
+ if _, ok, err := e.cfg.Store.Done(ctx, AdoptionLabel, a, StepActivate); err != nil {
+ return 0, err
+ } else if ok {
+ return 0, fail("app-active")
+ }
+ }
+ id, err := e.cfg.Store.NewAdoptionRun(ctx, homeop.KindAddApps, sorted)
+ if err != nil {
+ return 0, err
+ }
+ e.cfg.Store.Audit(ctx, id, AdoptionLabel, "", "run-start", homeop.KindAddApps)
+ return id, e.submitPlans(ctx, id, AdoptionLabel, "", "", homeop.KindAddApps, sorted, t.TeamSQID)
+}
+
+// DisableAdopted opens a retire-apps window on the directory alone for one
+// adopted app: directory.disable-consumer, the immediate incident response.
+// Its env-manifest consumer, instance and environment are untouched.
+// typed must equal the label.
+func (e *Engine) DisableAdopted(ctx context.Context, app, typed string) (int64, error) {
+ if typed != AdoptionLabel {
+ return 0, fail("label-mismatch")
+ }
+ if _, ok := AppBySlug(app); !ok {
+ return 0, fail("unknown-app")
+ }
+ t, err := e.cfg.Store.Team(ctx, AdoptionLabel)
+ if err != nil {
+ return 0, fail("no-team")
+ }
+ if t.TeamSQID == "" {
+ return 0, fail("team-not-seeded")
+ }
+ if _, ok, err := e.cfg.Store.Done(ctx, AdoptionLabel, app, StepConsumer); err != nil {
+ return 0, err
+ } else if !ok {
+ return 0, fail("not-provisioned")
+ }
+ // Marked an adoption, so Advance takes it to the disable step alone,
+ // never §9's retire, detach and delete.
+ id, err := e.cfg.Store.newRun(ctx, homeop.KindRetireApps, AdoptionLabel, []string{app}, RunOptions{Profile: ProfileOutside}, true)
+ if err != nil {
+ return 0, err
+ }
+ e.cfg.Store.Audit(ctx, id, AdoptionLabel, "", "run-start", homeop.KindRetireApps)
+ return id, e.submitPlans(ctx, id, AdoptionLabel, "", "", homeop.KindRetireApps, []string{app}, "")
+}
+
+// adoptedTeam is the SQID a fresh plan for adoption run r binds: the
+// directory's proposal for Plan A (unseeded), the seeded team's for
+// Plans B and C, none for a disable.
+func (e *Engine) adoptedTeam(ctx context.Context, r Run) (string, error) {
+ switch r.Kind {
+ case homeop.KindCreateTeam:
+ ins, o, _ := e.cfg.Home.Inspect(ctx, homeop.Directory)
+ if o != homeop.OK || ins.TeamSQID == "" {
+ return "", fail("no-proposed-team")
+ }
+ return ins.TeamSQID, nil
+ case homeop.KindAddApps:
+ t, err := e.cfg.Store.Team(ctx, AdoptionLabel)
+ return t.TeamSQID, err
+ }
+ return "", nil
+}
+
+// planExisting is the existing_team of the plan this run's window opened
+// for, from Alta's own signed copy of the directory's plan.
+func (e *Engine) planExisting(ctx context.Context, p *pass) (string, error) {
+ subs, err := e.cfg.Store.Plans(ctx, p.run.PlanID)
+ if err != nil {
+ return "", err
+ }
+ // An absent row or dropped bytes read as no payload.
+ raw, err := homeop.EnvelopePayload(subs[homeop.Directory].Signed)
+ var plan homeop.Plan
+ if err != nil || homeop.Decode(raw, &plan) != nil {
+ return "", fail("plan-unreadable")
+ }
+ return plan.ExistingTeam, nil
+}
+
+// adoption is one Advance of an adoption run: the team's seed (Plan A
+// only), then each app's steps. A parked app does not hold the others
+// back; a failed one stops the run.
+func (e *Engine) adoption(ctx context.Context, p *pass) error {
+ st := e.cfg.Store
+ if p.team.TeamSQID == "" {
+ // seed admits create-team only: Plans B and C need a seeded team.
+ if err := e.seed(ctx, p); err != nil {
+ return err
+ }
+ t, err := st.Team(ctx, p.run.Label)
+ if err != nil {
+ return err
+ }
+ p.team = t
+ }
+ // No recipe ever holds the owner here: the seed was the address's
+ // last use.
+ if _, held, err := st.Owner(ctx, p.run.Label); err != nil {
+ return err
+ } else if held {
+ if err := st.ForgetOwner(ctx, p.run.Label); err != nil {
+ return err
+ }
+ st.Audit(ctx, p.run.ID, p.run.Label, "", "owner-forgotten", "")
+ }
+ var first error
+ for _, slug := range p.run.Apps {
+ app, _ := AppBySlug(slug)
+ if err := e.pipeline(ctx, p, app, adoptionSteps(p.run.Kind)); err != nil {
+ if errors.Is(err, errCrash) {
+ return err
+ }
+ var fl *Fail
+ if errors.As(err, &fl) {
+ return err
+ }
+ if first == nil {
+ first = err
+ }
+ }
+ }
+ return first
+}
+
+// stepActivateAdopted is step 12 for an adopted app: the existing-app
+// policy, the canonical consumer and audience, the Observer's evidence,
+// started_at the recorded issued_at and completed_at now − Skew. A
+// request Alta already signed is replayed exactly and never rebuilt: its
+// observation was made once.
+func (e *Engine) stepActivateAdopted(ctx context.Context, p *pass, app App) error {
+ st, label := e.cfg.Store, p.run.Label
+ if e.cfg.Observer == nil {
+ return fail("no-observer")
+ }
+ spec := opSpec{role: homeop.Directory, action: homeop.DirectoryActivate, label: label, app: app.Slug, purpose: "activate", reuse: true}
+ if _, handled, err := e.replayHeld(ctx, spec); handled {
+ if err != nil {
+ return err
+ }
+ return e.record(ctx, p, app.Slug, StepActivate, map[string]any{"replayed": true})
+ }
+ if err := e.needWindow(p, homeop.Directory); err != nil {
+ return err
+ }
+ v, _, _ := st.Done(ctx, label, app.Slug, StepVerify)
+ reg, _, _ := st.Done(ctx, label, app.Slug, StepRegister)
+ _, cd, err := e.consumerData(ctx, p, app)
+ if err != nil {
+ return err
+ }
+ if num(v, "expires_at") <= e.now().Unix()+10 {
+ // The attempt lapsed: verify again.
+ _ = st.SetStep(ctx, label, app.Slug, StepVerify, "parked", "attempt-expired", nil)
+ return park("attempt-expired")
+ }
+ obs, err := e.cfg.Observer.Observe(ctx, app.Slug, p.team.TeamSQID)
+ if err != nil {
+ var r ObserverRefusal
+ if errors.As(err, &r) {
+ return park("observe-" + strings.Join(r.RefusalCodes(), ","))
+ }
+ if e.cfg.Debug != nil {
+ e.cfg.Debug(err)
+ }
+ return park("observer-unavailable")
+ }
+ // What Home would refuse is never signed.
+ if !activationVersion.MatchString(obs.AppVersion) || !homeop.CanonicalToken(obs.ArtifactDigest) || !homeop.CanonicalToken(obs.EnvironmentBinding) {
+ return fail("observation-shape")
+ }
+ ev := homeop.ActivationEvidence{Version: 1, Policy: homeop.ExistingActivationPolicy, 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: obs.AppVersion, ArtifactDigest: obs.ArtifactDigest, EnvironmentBinding: obs.EnvironmentBinding, ManifestDigest: str(reg, "manifest_digest"),
+ AliasHost: PublicHost(label, app.Slug), Started: num(v, "issued_at"), Completed: e.now().Unix() - homeop.Skew}
+ spec.build = func(b homeop.InputBase) any { return homeop.ActivationInput{InputBase: b, Evidence: ev} }
+ if _, err := e.op(ctx, spec); err != nil {
+ if errors.Is(err, errOpRefused) {
+ return fail("activate-refused")
+ }
+ return err
+ }
+ return e.record(ctx, p, app.Slug, StepActivate, map[string]any{"app_version": obs.AppVersion})
+}
diff --git a/provision/adopt_test.go b/provision/adopt_test.go
new file mode 100644
index 0000000..2520a49
--- /dev/null
+++ b/provision/adopt_test.go
@@ -0,0 +1,910 @@
+package provision
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "slices"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/alta/console"
+ "amadan.net/oficina/alta/homeop"
+ "github.com/go-json-experiment/json/jsontext"
+)
+
+// fakeObserver is the CARLOS half as the engine meets it: it answers a
+// fixed observation, or refuses.
+type fakeObserver struct {
+ mu sync.Mutex
+ obs Observation
+ err error
+ calls []string
+}
+
+func (f *fakeObserver) Observe(_ context.Context, app, team string) (Observation, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.calls = append(f.calls, app+"/"+team)
+ if f.err != nil {
+ return Observation{}, f.err
+ }
+ return f.obs, nil
+}
+
+func (f *fakeObserver) set(err error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.err = err
+}
+
+func (f *fakeObserver) count() int {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return len(f.calls)
+}
+
+// testRefusal is a refusal as adopt.Refusal answers it.
+type testRefusal struct{ codes []string }
+
+func (r *testRefusal) Error() string { return "refused" }
+func (r *testRefusal) RefusalCodes() []string { return r.codes }
+
+var goodObservation = Observation{AppVersion: "v1.4.0", ArtifactDigest: artifactDigest("v1.4.0"), EnvironmentBinding: artifactDigest("binding")}
+
+func newObserver() *fakeObserver { return &fakeObserver{obs: goodObservation} }
+
+// offline is a transport that counts every request and answers none: the
+// console and the instances' own origins as an adoption must never meet
+// them.
+type offline struct {
+ mu sync.Mutex
+ n int
+}
+
+func (o *offline) RoundTrip(*http.Request) (*http.Response, error) {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ o.n++
+ return nil, errors.New("offline: an adoption made a network call")
+}
+
+func (o *offline) count() int {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ return o.n
+}
+
+type adoptHarness struct {
+ *harness
+ net *offline
+}
+
+// newAdoption is an initialized Home whose env manifest holds the six
+// canonical consumers, as production's HOME_CONSUMERS does.
+func newAdoption(t *testing.T, apps ...string) *adoptHarness {
+ t.Helper()
+ h := newHarness(t)
+ h.initialized()
+ if len(apps) == 0 {
+ apps = Slugs()
+ }
+ for _, a := range apps {
+ h.home.AddEnvConsumer(a, homeop.CanonicalOrigin(a))
+ }
+ return &adoptHarness{harness: h, net: &offline{}}
+}
+
+// engine is Alta's engine as alta-adopt builds it: no console or public
+// network at all, and the given Observer (nil for none).
+func (a *adoptHarness) adopter(hook func(string) error, obs Observer) *Engine {
+ e := a.engine(hook)
+ e.cfg.Observer = obs
+ e.cfg.Console = &console.Client{HTTP: &http.Client{Transport: a.net}, Base: "https://console.invalid", Account: account, Tokens: a.tokens}
+ e.cfg.Public = &http.Client{Transport: a.net}
+ return e
+}
+
+func (a *adoptHarness) proposed() string {
+ a.t.Helper()
+ ins, o, _ := a.engine(nil).cfg.Home.Inspect(a.ctx(), homeop.Directory)
+ if o != homeop.OK || ins.TeamSQID == "" {
+ a.t.Fatalf("inspect %v", o)
+ }
+ return ins.TeamSQID
+}
+
+// planA runs Plan A to its end.
+func (a *adoptHarness) planA(e *Engine) int64 {
+ a.t.Helper()
+ run, err := e.StartAdoption(a.ctx(), "Oficina", ownerCanary)
+ if err != nil {
+ a.t.Fatal(err)
+ }
+ a.confirm(homeop.KindCreateTeam)
+ if r := a.drive(e, run, 20); r.State != "done" || r.Code != "awaiting-configuration" {
+ a.t.Fatalf("plan A %s %s", r.State, r.Code)
+ }
+ return run
+}
+
+// activate starts and confirms a Plan B/C run once Plan A's windows have
+// closed.
+func (a *adoptHarness) activate(e *Engine, apps ...string) int64 {
+ a.t.Helper()
+ a.tick(homeop.WindowLifetime * time.Second)
+ run, err := e.ActivateAdopted(a.ctx(), apps)
+ if err != nil {
+ a.t.Fatal(err)
+ }
+ a.confirm(homeop.KindAddApps)
+ return run
+}
+
+func (a *adoptHarness) plans(run int64) map[string]homeop.Plan {
+ a.t.Helper()
+ r, err := a.store.Run(a.ctx(), run)
+ if err != nil {
+ a.t.Fatal(err)
+ }
+ subs, err := a.store.Plans(a.ctx(), r.PlanID)
+ if err != nil {
+ a.t.Fatal(err)
+ }
+ out := map[string]homeop.Plan{}
+ for role, s := range subs {
+ raw, err := homeop.EnvelopePayload(s.Signed)
+ if err != nil {
+ a.t.Fatalf("%s plan: %v", role, err)
+ }
+ var p homeop.Plan
+ if err := homeop.Decode(raw, &p); err != nil {
+ a.t.Fatalf("%s plan: %v", role, err)
+ }
+ out[role] = p
+ }
+ return out
+}
+
+// signed decodes the operation input of the last request Alta holds for
+// app's purpose.
+func (a *adoptHarness) signed(app, purpose string, v any) homeop.Authorization {
+ a.t.Helper()
+ req, ok, err := a.store.LastRequest(a.ctx(), AdoptionLabel, app, purpose)
+ if err != nil || !ok {
+ a.t.Fatalf("no %s request for %s: %v", purpose, app, err)
+ }
+ var w struct {
+ Version int `json:"version"`
+ Authorization jsontext.Value `json:"signed_authorization"`
+ Input jsontext.Value `json:"operation_input"`
+ }
+ if err := homeop.Decode(req.Bytes, &w); err != nil {
+ a.t.Fatal(err)
+ }
+ if err := homeop.Decode(w.Input, v); err != nil {
+ a.t.Fatal(err)
+ }
+ r, err := homeop.ReadRequest(req.Bytes)
+ if err != nil {
+ a.t.Fatal(err)
+ }
+ return r.Authorization
+}
+
+func (a *adoptHarness) evidence(app string) homeop.ActivationEvidence {
+ a.t.Helper()
+ var in homeop.ActivationInput
+ a.signed(app, "activate", &in)
+ return in.Evidence
+}
+
+func (a *adoptHarness) step(app, name string) Step {
+ a.t.Helper()
+ s, ok, err := a.store.Step(a.ctx(), AdoptionLabel, app, name)
+ if err != nil || !ok {
+ a.t.Fatalf("no %s step for %s: %v", name, app, err)
+ }
+ return s
+}
+
+// onceEach: no committed operation repeats beyond its exact replays,
+// which Requests never lists.
+func onceEach(t *testing.T, reqs []string) {
+ t.Helper()
+ seen := map[string]int{}
+ for _, r := range reqs {
+ if seen[r]++; seen[r] > 1 {
+ t.Fatalf("%s committed twice: %v", r, reqs)
+ }
+ }
+}
+
+func countOf(reqs []string, entry string) int {
+ n := 0
+ for _, r := range reqs {
+ if r == entry {
+ n++
+ }
+ }
+ return n
+}
+
+func failCode(t *testing.T, err error, code string) {
+ t.Helper()
+ var fl *Fail
+ if !errors.As(err, &fl) || fl.Code != code {
+ t.Fatalf("got %v, want failed: %s", err, code)
+ }
+}
+
+func TestAdoptionPlanACarriesExistingTeamOnBothRoles(t *testing.T) {
+ a := newAdoption(t)
+ e := a.adopter(nil, nil)
+ _, err := e.StartAdoption(a.ctx(), "Oficina team", ownerCanary)
+ failCode(t, err, "name-not-oficina")
+ _, err = e.StartAdoption(a.ctx(), "Oficina", "Paul <"+ownerCanary+">")
+ failCode(t, err, "owner-shape")
+ if used, _ := a.store.LabelUsed(a.ctx(), AdoptionLabel); used {
+ t.Fatal("a refused start recorded the team")
+ }
+ proposed := a.proposed()
+ run, err := e.StartAdoption(a.ctx(), "Oficina", ownerCanary)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if r, _ := a.store.Run(a.ctx(), run); !r.Adoption || r.Kind != homeop.KindCreateTeam || r.Label != AdoptionLabel || strings.Join(r.Apps, ",") != strings.Join(Slugs(), ",") {
+ t.Fatalf("run %+v", r)
+ }
+ checkA := func(plans map[string]homeop.Plan) {
+ t.Helper()
+ if len(plans) != 2 {
+ t.Fatalf("roles %d", len(plans))
+ }
+ for role, p := range plans {
+ if p.ExistingTeam != proposed || p.Kind != homeop.KindCreateTeam || strings.Join(p.Apps, ",") != strings.Join(Slugs(), ",") {
+ t.Fatalf("%s plan existing %q kind %s apps %v", role, p.ExistingTeam, p.Kind, p.Apps)
+ }
+ }
+ if d := plans[homeop.Directory]; d.Label != AdoptionLabel || d.DisplayName != "Oficina" || d.Owner != "" {
+ t.Fatal("directory plan fields")
+ }
+ if c := plans[homeop.Credential]; c.Owner != ownerCanary || c.Label != "" || c.DisplayName != "" {
+ t.Fatal("credential plan fields")
+ }
+ }
+ first := a.plans(run)
+ checkA(first)
+ _, err = e.StartAdoption(a.ctx(), "Oficina", ownerCanary)
+ failCode(t, err, "label-used")
+ // Unconfirmed until it expired: a fresh plan binds the same team.
+ a.tick((homeop.PlanLifetime + 1) * time.Second)
+ if err := e.Resubmit(a.ctx(), run); err != nil {
+ t.Fatal(err)
+ }
+ again := a.plans(run)
+ if again[homeop.Directory].PlanID == first[homeop.Directory].PlanID {
+ t.Fatal("resubmit reused the expired plan")
+ }
+ checkA(again)
+ a.confirm(homeop.KindCreateTeam)
+ if r := a.drive(e, run, 20); r.State != "done" || r.Code != "awaiting-configuration" {
+ t.Fatalf("plan A %s %s", r.State, r.Code)
+ }
+ // The address went with the seed: no input, no owner-seed request, no
+ // credential plan bytes, nowhere in the files.
+ var n int
+ _ = a.store.DB().QueryRow("SELECT (SELECT count(*) FROM owner_inputs)+(SELECT count(*) FROM operator_requests WHERE action='credential.owner-seed')+(SELECT count(*) FROM plan_submissions WHERE role='credential' AND sealed_plan IS NOT NULL)").Scan(&n)
+ if n != 0 {
+ t.Fatalf("%d rows still carry the owner", n)
+ }
+ _, _ = a.store.DB().Exec("PRAGMA wal_checkpoint(TRUNCATE)")
+ if a.scan(ownerCanary) || strings.Contains(a.logs.String(), ownerCanary) {
+ t.Fatal("the owner's address survives the seed")
+ }
+ // Plan B: add-apps on both roles, the seeded team, no owner.
+ team, _ := a.store.Team(a.ctx(), AdoptionLabel)
+ b := a.activate(a.adopter(nil, newObserver()), "calendar")
+ plans := a.plans(b)
+ if len(plans) != 2 {
+ t.Fatalf("plan B roles %d", len(plans))
+ }
+ for role, p := range plans {
+ if p.ExistingTeam != team.TeamSQID || p.Kind != homeop.KindAddApps || strings.Join(p.Apps, ",") != "calendar" || p.Owner != "" || p.DisplayName != "" {
+ t.Fatalf("plan B %s: existing %q kind %s apps %v", role, p.ExistingTeam, p.Kind, p.Apps)
+ }
+ }
+ if plans[homeop.Directory].Label != AdoptionLabel || plans[homeop.Credential].Label != "" {
+ t.Fatal("plan B labels")
+ }
+ // Plan B unconfirmed until it expired: re-signed for the same team.
+ a.tick((homeop.PlanLifetime + 1) * time.Second)
+ if err := e.Resubmit(a.ctx(), b); err != nil {
+ t.Fatal(err)
+ }
+ for role, p := range a.plans(b) {
+ if p.ExistingTeam != team.TeamSQID || p.Kind != homeop.KindAddApps || p.PlanID == plans[role].PlanID {
+ t.Fatalf("resubmitted plan B %s: existing %q", role, p.ExistingTeam)
+ }
+ }
+}
+
+func TestAdoptionSeedsAtProposedSQIDOnly(t *testing.T) {
+ t.Run("at the proposal", func(t *testing.T) {
+ a := newAdoption(t)
+ proposed := a.proposed()
+ a.planA(a.adopter(nil, nil))
+ _, sqid, ok := a.home.Team(AdoptionLabel)
+ team, _ := a.store.Team(a.ctx(), AdoptionLabel)
+ if !ok || sqid != proposed || team.TeamSQID != proposed || a.home.TeamCount() != 1 {
+ t.Fatalf("seeded at %q, Alta holds %q, proposed %q", sqid, team.TeamSQID, proposed)
+ }
+ var seed homeop.SeedInput
+ a.signed("", "seed-team", &seed)
+ if seed.TeamSQID != proposed || seed.Label != AdoptionLabel || seed.Name != "Oficina" {
+ t.Fatal("seed-team input")
+ }
+ if a.home.Calls[homeop.CredentialOwnerSeed] != 1 || a.home.Calls[homeop.DirectorySeedTeam] != 1 {
+ t.Fatalf("owner-seed %d, seed-team %d", a.home.Calls[homeop.CredentialOwnerSeed], a.home.Calls[homeop.DirectorySeedTeam])
+ }
+ })
+ t.Run("proposal moved", func(t *testing.T) {
+ // Alta's copy of the plan binds another SQID than the directory
+ // now proposes: nothing is signed against the proposal.
+ a := newAdoption(t)
+ e := a.adopter(nil, nil)
+ run, err := e.StartAdoption(a.ctx(), "Oficina", ownerCanary)
+ if err != nil {
+ t.Fatal(err)
+ }
+ r, _ := a.store.Run(a.ctx(), run)
+ p := a.plans(run)[homeop.Directory]
+ p.ExistingTeam = "txxz"
+ raw, err := homeop.SignPlan(a.key, p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ sealed, err := a.store.seal(planPurpose(r.PlanID, homeop.Directory), raw)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := a.store.DB().Exec("UPDATE plan_submissions SET sealed_plan=? WHERE plan_id=? AND role='directory'", sealed, r.PlanID); err != nil {
+ t.Fatal(err)
+ }
+ a.confirm(homeop.KindCreateTeam)
+ if r := a.drive(e, run, 5); r.State != "failed" || r.Code != "proposal-moved" {
+ t.Fatalf("run %s %s", r.State, r.Code)
+ }
+ if a.home.Calls[homeop.CredentialOwnerSeed] != 0 || a.home.TeamCount() != 0 {
+ t.Fatal("an owner-seed was sent for a moved proposal")
+ }
+ })
+ t.Run("plan unreadable", func(t *testing.T) {
+ a := newAdoption(t)
+ e := a.adopter(nil, nil)
+ run, err := e.StartAdoption(a.ctx(), "Oficina", ownerCanary)
+ if err != nil {
+ t.Fatal(err)
+ }
+ a.confirm(homeop.KindCreateTeam)
+ if _, err := a.store.DB().Exec("UPDATE plan_submissions SET sealed_plan=NULL WHERE role='directory'"); err != nil {
+ t.Fatal(err)
+ }
+ if r := a.drive(e, run, 5); r.State != "failed" || r.Code != "plan-unreadable" {
+ t.Fatalf("run %s %s", r.State, r.Code)
+ }
+ if a.home.Calls[homeop.CredentialOwnerSeed] != 0 {
+ t.Fatal("an owner-seed was sent without the confirmed plan")
+ }
+ })
+}
+
+// Each entry point refuses what comes before its phase, before anything
+// is recorded or planned.
+func TestAdoptionRefusesOutOfOrder(t *testing.T) {
+ fresh := &adoptHarness{harness: newHarness(t), net: &offline{}}
+ _, err := fresh.adopter(nil, nil).StartAdoption(fresh.ctx(), "Oficina", ownerCanary)
+ failCode(t, err, "home-not-initialized")
+ for _, role := range []string{homeop.Credential, homeop.Directory} {
+ a := newAdoption(t)
+ if role == homeop.Credential {
+ a.cred.Close()
+ } else {
+ a.dir.Close()
+ }
+ _, err := a.adopter(nil, nil).StartAdoption(a.ctx(), "Oficina", ownerCanary)
+ var fl *Fail
+ if !errors.As(err, &fl) || !strings.HasPrefix(fl.Code, "home-"+role+"-") {
+ t.Fatalf("%s unreachable: %v", role, err)
+ }
+ if used, _ := a.store.LabelUsed(a.ctx(), AdoptionLabel); used {
+ t.Fatal("recorded with Home unreachable")
+ }
+ }
+
+ // A fresh Plan A binds the proposal Home answers now, or none.
+ r := newAdoption(t)
+ planned, err := r.adopter(nil, nil).StartAdoption(r.ctx(), "Oficina", ownerCanary)
+ if err != nil {
+ t.Fatal(err)
+ }
+ r.dir.Close()
+ failCode(t, r.adopter(nil, nil).Resubmit(r.ctx(), planned), "no-proposed-team")
+
+ // docs is missing from the env manifest: Plan A seeds, provisions docs
+ // and stops at its register.
+ a := newAdoption(t, "sheets", "slides", "calendar", "calls", "memoria")
+ e := a.adopter(nil, newObserver())
+ _, err = e.ActivateAdopted(a.ctx(), []string{"calendar"})
+ failCode(t, err, "no-team")
+ _, err = e.DisableAdopted(a.ctx(), "calendar", AdoptionLabel)
+ failCode(t, err, "no-team")
+ run, err := e.StartAdoption(a.ctx(), "Oficina", ownerCanary)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, err = e.ActivateAdopted(a.ctx(), []string{"calendar"})
+ failCode(t, err, "team-not-seeded")
+ _, err = e.DisableAdopted(a.ctx(), "calendar", AdoptionLabel)
+ failCode(t, err, "team-not-seeded")
+ a.confirm(homeop.KindCreateTeam)
+ if r := a.drive(e, run, 10); r.State != "failed" || r.Code != "register-refused" {
+ t.Fatalf("plan A %s %s", r.State, r.Code)
+ }
+ a.tick(homeop.WindowLifetime * time.Second)
+ for code, apps := range map[string][]string{
+ "no-apps": nil,
+ "unknown-app": {"calendar", "mail"},
+ "not-registered": {"docs"},
+ } {
+ _, err := e.ActivateAdopted(a.ctx(), apps)
+ failCode(t, err, code)
+ }
+ _, err = e.ActivateAdopted(a.ctx(), []string{"calendar", "calendar"})
+ failCode(t, err, "unknown-app")
+ _, err = e.DisableAdopted(a.ctx(), "sheets", AdoptionLabel)
+ failCode(t, err, "not-provisioned")
+ var n int
+ _ = a.store.DB().QueryRow("SELECT count(*) FROM runs WHERE kind<>'create-team' AND label=?", AdoptionLabel).Scan(&n)
+ if n != 0 {
+ t.Fatal("a refused call recorded a run")
+ }
+}
+
+func TestAdoptionRegisterInsertsNothing(t *testing.T) {
+ a := newAdoption(t)
+ a.planA(a.adopter(nil, nil))
+ if n := a.home.ConsumerCount(); n != 0 {
+ t.Fatalf("register inserted %d credential consumers", n)
+ }
+ env := map[string]string{"directory": dirOrigin, "alta": "https://alta.example.test"}
+ for _, s := range Slugs() {
+ env[s] = homeop.CanonicalOrigin(s)
+ }
+ want := homeop.ManifestDigest(env)
+ reqs := a.home.Requests()
+ for _, s := range Slugs() {
+ if got := str(a.step(s, StepRegister).Data, "manifest_digest"); got != want {
+ t.Fatalf("%s manifest digest is not the env manifest's", s)
+ }
+ if countOf(reqs, homeop.CredentialRegister+":"+s) != 1 || countOf(reqs, homeop.DirectoryProvision+":"+s) != 1 {
+ t.Fatalf("%s: %v", s, reqs)
+ }
+ if got := a.home.InstanceState(s); got != "pending" {
+ t.Fatalf("%s directory row %q", s, got)
+ }
+ }
+ // Without the exact env entry Home refuses, and Alta stops there.
+ b := newAdoption(t, "docs", "sheets", "slides", "calendar", "calls")
+ e := b.adopter(nil, nil)
+ run, err := e.StartAdoption(b.ctx(), "Oficina", ownerCanary)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b.confirm(homeop.KindCreateTeam)
+ if r := b.drive(e, run, 20); r.State != "failed" || r.Code != "register-refused" {
+ t.Fatalf("run %s %s", r.State, r.Code)
+ }
+ if b.home.ConsumerCount() != 0 {
+ t.Fatal("a refused register inserted a consumer")
+ }
+}
+
+func TestAdoptionMakesNoConsoleCalls(t *testing.T) {
+ a := newAdoption(t)
+ obs := newObserver()
+ e := a.adopter(nil, obs)
+ a.planA(e)
+ run := a.activate(e, "calendar")
+ if r := a.drive(e, run, 10); r.State != "done" || r.Code != "" {
+ t.Fatalf("plan B %s %s", r.State, r.Code)
+ }
+ a.tick(homeop.WindowLifetime * time.Second)
+ off, err := e.DisableAdopted(a.ctx(), "calendar", AdoptionLabel)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := a.home.Confirm(homeop.Directory, ""); err != nil {
+ t.Fatal(err)
+ }
+ if r := a.drive(e, off, 5); r.State != "done" {
+ t.Fatalf("disable %s %s", r.State, r.Code)
+ }
+ if n := a.net.count(); n != 0 {
+ t.Fatalf("%d console or instance requests", n)
+ }
+}
+
+func TestActivateAdoptedUsesExistingPolicy(t *testing.T) {
+ a := newAdoption(t)
+ obs := newObserver()
+ e := a.adopter(nil, obs)
+ a.planA(e)
+ run := a.activate(e, "calendar")
+ if r := a.drive(e, run, 10); r.State != "done" {
+ t.Fatalf("plan B %s %s", r.State, r.Code)
+ }
+ team, _ := a.store.Team(a.ctx(), AdoptionLabel)
+ ev := a.evidence("calendar")
+ if ev.Policy != homeop.ExistingActivationPolicy || ev.Consumer != "calendar" || ev.App != "calendar" || ev.Audience != "https://calendar.oficina.works" || ev.AliasHost != "calendar.oficina.works" || ev.TeamSQID != team.TeamSQID || ev.Owner != team.OwnerRef {
+ t.Fatalf("evidence %+v", ev)
+ }
+ if ev.AppVersion != goodObservation.AppVersion || ev.ArtifactDigest != goodObservation.ArtifactDigest || ev.EnvironmentBinding != goodObservation.EnvironmentBinding {
+ t.Fatal("evidence does not carry the observation")
+ }
+ if ev.ManifestDigest != str(a.step("calendar", StepRegister).Data, "manifest_digest") {
+ t.Fatal("evidence does not carry the register result's manifest")
+ }
+ if strings.Join(obs.calls, ",") != "calendar/"+team.TeamSQID {
+ t.Fatalf("observed %v", obs.calls)
+ }
+ reqs := a.home.Requests()
+ onceEach(t, reqs)
+ if countOf(reqs, homeop.DirectoryActivate+":calendar") != 1 || a.home.InstanceState("calendar") != "live" {
+ t.Fatalf("requests %v", reqs)
+ }
+ for _, s := range Slugs() {
+ if s != "calendar" && a.home.InstanceState(s) != "pending" {
+ t.Fatalf("%s activated by a calendar plan", s)
+ }
+ }
+ a.tick(homeop.WindowLifetime * time.Second)
+ _, err := e.ActivateAdopted(a.ctx(), []string{"calendar"})
+ failCode(t, err, "app-active")
+}
+
+func TestActivateAdoptedWithoutObserverFails(t *testing.T) {
+ a := newAdoption(t)
+ a.planA(a.adopter(nil, nil))
+ a.tick(homeop.WindowLifetime * time.Second)
+ bare := a.adopter(nil, nil)
+ _, err := bare.ActivateAdopted(a.ctx(), []string{"calendar"})
+ failCode(t, err, "no-observer")
+ var n int
+ _ = a.store.DB().QueryRow("SELECT count(*) FROM runs WHERE kind='add-apps'").Scan(&n)
+ if n != 0 {
+ t.Fatal("a run was recorded without an observer")
+ }
+ if err := a.home.Confirm(homeop.Directory, ""); err == nil {
+ t.Fatal("a plan was submitted without an observer")
+ }
+ // An engine without one that advances the run never activates.
+ run, err := a.adopter(nil, newObserver()).ActivateAdopted(a.ctx(), []string{"calendar"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ a.confirm(homeop.KindAddApps)
+ if r := a.drive(bare, run, 5); r.State != "failed" || r.Code != "no-observer" {
+ t.Fatalf("run %s %s", r.State, r.Code)
+ }
+ if countOf(a.home.Requests(), homeop.DirectoryActivate+":calendar") != 0 {
+ t.Fatal("activated without an observer")
+ }
+}
+
+func TestActivateAdoptedParksOnObserverRefusal(t *testing.T) {
+ a := newAdoption(t)
+ obs := newObserver()
+ obs.set(&testRefusal{codes: []string{"missing-witness", "witness-superseded"}})
+ e := a.adopter(nil, obs)
+ a.planA(e)
+ run := a.activate(e, "calendar")
+ if r := a.drive(e, run, 3); r.State != "parked" || r.Code != "observe-missing-witness,witness-superseded" {
+ t.Fatalf("run %s %s", r.State, r.Code)
+ }
+ if s := a.step("calendar", StepActivate); s.State != "parked" || s.Code != "observe-missing-witness,witness-superseded" {
+ t.Fatalf("step %s %s", s.State, s.Code)
+ }
+ obs.set(errors.New("carlos unreachable"))
+ if r := a.drive(e, run, 2); r.State != "parked" || r.Code != "observer-unavailable" {
+ t.Fatalf("run %s %s", r.State, r.Code)
+ }
+ if countOf(a.home.Requests(), homeop.DirectoryActivate+":calendar") != 0 || a.home.Calls[homeop.DirectoryActivate] != 0 {
+ t.Fatal("activation sent on a refused observation")
+ }
+ // The refusal clears: the same run activates.
+ obs.set(nil)
+ if r := a.drive(e, run, 3); r.State != "done" {
+ t.Fatalf("run %s %s", r.State, r.Code)
+ }
+
+ // An observation Home would refuse is never signed.
+ for name, bad := range map[string]Observation{
+ "version": {AppVersion: "v1 4", ArtifactDigest: goodObservation.ArtifactDigest, EnvironmentBinding: goodObservation.EnvironmentBinding},
+ "artifact": {AppVersion: "v1", ArtifactDigest: "c2hh", EnvironmentBinding: goodObservation.EnvironmentBinding},
+ "binding": {AppVersion: "v1", ArtifactDigest: goodObservation.ArtifactDigest, EnvironmentBinding: ""},
+ } {
+ t.Run(name, func(t *testing.T) {
+ b := newAdoption(t)
+ e := b.adopter(nil, &fakeObserver{obs: bad})
+ b.planA(e)
+ run := b.activate(e, "calendar")
+ if r := b.drive(e, run, 3); r.State != "failed" || r.Code != "observation-shape" {
+ t.Fatalf("run %s %s", r.State, r.Code)
+ }
+ if b.home.Calls[homeop.DirectoryActivate] != 0 {
+ t.Fatal("a malformed observation was sent")
+ }
+ })
+ }
+}
+
+func TestActivateAdoptedStartedNotBeforeRecordedIssued(t *testing.T) {
+ for _, lose := range []bool{false, true} {
+ t.Run(fmt.Sprintf("verify answer lost %v", lose), func(t *testing.T) {
+ a := newAdoption(t)
+ e := a.adopter(nil, newObserver())
+ a.planA(e)
+ if lose {
+ lost := false
+ a.home.LoseAnswer = func(action string) bool {
+ if action == homeop.DirectoryVerify && !lost {
+ lost = true
+ return true
+ }
+ return false
+ }
+ }
+ run := a.activate(e, "calendar")
+ if r := a.drive(e, run, 10); r.State != "done" {
+ t.Fatalf("run %s %s", r.State, r.Code)
+ }
+ var vin homeop.VerificationInput
+ a.signed("calendar", "verify", &vin)
+ recorded := num(a.step("calendar", StepVerify).Data, "issued_at")
+ ev := a.evidence("calendar")
+ if ev.Started != recorded || recorded < vin.Issued {
+ t.Fatalf("started %d, recorded %d, Home's issued %d", ev.Started, recorded, vin.Issued)
+ }
+ if lose && recorded <= vin.Issued {
+ t.Fatal("a replayed attempt recorded Home's issued_at, which its result does not carry")
+ }
+ if !lose && recorded != vin.Issued {
+ t.Fatal("a fresh attempt did not record the issued_at it signed")
+ }
+ if ev.Completed < ev.Started {
+ t.Fatal("completed before started")
+ }
+ if countOf(a.home.Requests(), homeop.DirectoryVerify+":calendar") != 1 {
+ t.Fatal("verify committed twice")
+ }
+ })
+ }
+}
+
+func TestActivateAdoptedReverifiesLapsedAttempt(t *testing.T) {
+ a := newAdoption(t)
+ obs := newObserver()
+ obs.set(&testRefusal{codes: []string{"missing-witness"}})
+ e := a.adopter(nil, obs)
+ a.planA(e)
+ run := a.activate(e, "calendar")
+ a.drive(e, run, 2)
+ first := a.signed("calendar", "verify", &homeop.VerificationInput{})
+ // The attempt lapses while the observation is refused.
+ a.tick(600 * time.Second)
+ obs.set(nil)
+ if r := a.drive(e, run, 5); r.State != "done" {
+ t.Fatalf("run %s %s", r.State, r.Code)
+ }
+ var vin homeop.VerificationInput
+ second := a.signed("calendar", "verify", &vin)
+ if second.OperationID == first.OperationID {
+ t.Fatal("the lapsed attempt was not replaced")
+ }
+ ev := a.evidence("calendar")
+ if ev.Attempt != second.OperationID || ev.Started != num(a.step("calendar", StepVerify).Data, "issued_at") || ev.Started < vin.Issued {
+ t.Fatal("activation does not carry the new attempt")
+ }
+ reqs := a.home.Requests()
+ if countOf(reqs, homeop.DirectoryVerify+":calendar") != 2 || countOf(reqs, homeop.DirectoryActivate+":calendar") != 1 {
+ t.Fatalf("requests %v", reqs)
+ }
+}
+
+func TestOrdinaryRunsStillRefuseOficina(t *testing.T) {
+ a := newAdoption(t)
+ e := a.adopter(nil, nil)
+ _, err := a.engine(nil).CreateTeam(a.ctx(), NewTeam{Label: AdoptionLabel, Name: "Oficina", Owner: ownerCanary, Apps: []string{"docs"}})
+ failCode(t, err, "label-reserved")
+ a.planA(e)
+ a.tick(homeop.WindowLifetime * time.Second)
+ _, err = a.engine(nil).AddApps(a.ctx(), AdoptionLabel, []string{"calendar"}, RunOptions{})
+ failCode(t, err, "label-reserved")
+ _, err = a.engine(nil).RetireApps(a.ctx(), AdoptionLabel, []string{"calendar"}, AdoptionLabel)
+ failCode(t, err, "label-reserved")
+ // A run under the label that is not an adoption never advances.
+ before := len(a.home.Requests())
+ id, err := a.store.NewRun(a.ctx(), homeop.KindAddApps, AdoptionLabel, []string{"calendar"}, RunOptions{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ failCode(t, e.Advance(a.ctx(), id), "label-reserved")
+ if r, _ := a.store.Run(a.ctx(), id); r.State != "failed" || r.Code != "label-reserved" {
+ t.Fatalf("run %s %s", r.State, r.Code)
+ }
+ if len(a.home.Requests()) != before {
+ t.Fatal("an ordinary run under oficina reached Home")
+ }
+}
+
+func TestDisableAdoptedRequiresTypedLabel(t *testing.T) {
+ a := newAdoption(t)
+ e := a.adopter(nil, newObserver())
+ a.planA(e)
+ run := a.activate(e, "calendar")
+ if r := a.drive(e, run, 10); r.State != "done" {
+ t.Fatalf("plan B %s %s", r.State, r.Code)
+ }
+ a.tick(homeop.WindowLifetime * time.Second)
+ for _, typed := range []string{"", "Oficina", "oficin", " oficina", "calendar"} {
+ _, err := e.DisableAdopted(a.ctx(), "calendar", typed)
+ failCode(t, err, "label-mismatch")
+ }
+ _, err := e.DisableAdopted(a.ctx(), "mail", AdoptionLabel)
+ failCode(t, err, "unknown-app")
+ var n int
+ _ = a.store.DB().QueryRow("SELECT count(*) FROM runs WHERE kind='retire-apps'").Scan(&n)
+ if n != 0 {
+ t.Fatal("a refused disable recorded a run")
+ }
+ before := a.home.Requests()
+ off, err := e.DisableAdopted(a.ctx(), "calendar", AdoptionLabel)
+ if err != nil {
+ t.Fatal(err)
+ }
+ plans := a.plans(off)
+ d, ok := plans[homeop.Directory]
+ if len(plans) != 1 || !ok || d.Kind != homeop.KindRetireApps || d.Label != AdoptionLabel || d.ExistingTeam != "" || strings.Join(d.Apps, ",") != "calendar" {
+ t.Fatalf("disable plans %d", len(plans))
+ }
+ if err := a.home.Confirm(homeop.Directory, ""); err != nil {
+ t.Fatal(err)
+ }
+ if r := a.drive(e, off, 5); r.State != "done" {
+ t.Fatalf("disable %s %s", r.State, r.Code)
+ }
+ after := a.home.Requests()
+ if got := after[len(before):]; strings.Join(got, ",") != homeop.DirectoryDisable+":calendar" {
+ t.Fatalf("disable sent %v", got)
+ }
+ if a.home.InstanceState("calendar") != "disabled" || a.home.Calls[homeop.CredentialRetire] != 0 {
+ t.Fatal("disable state")
+ }
+ // The app stays the suite's: its env consumer, its team row.
+ team, _ := a.store.Team(a.ctx(), AdoptionLabel)
+ if team.Apps["calendar"] != "active" {
+ t.Fatalf("calendar %q", team.Apps["calendar"])
+ }
+ a.tick(homeop.WindowLifetime * time.Second)
+ _, err = e.ActivateAdopted(a.ctx(), []string{"calendar"})
+ failCode(t, err, "app-disabled")
+}
+
+// adoptionActs runs Plan A and Plan B for calendar cleanly and returns
+// each plan's acts in order.
+func adoptionActs(t *testing.T) (planA, planB []string) {
+ a := newAdoption(t)
+ var acts *[]string
+ e := a.adopter(func(k string) error { *acts = append(*acts, k); return nil }, newObserver())
+ acts = &planA
+ a.planA(e)
+ acts = &planB
+ run := a.activate(e, "calendar")
+ if r := a.drive(e, run, 10); r.State != "done" {
+ t.Fatalf("clean plan B %s %s", r.State, r.Code)
+ }
+ return planA, planB
+}
+
+// crashAt returns a hook that fails at the i-th act, once.
+func crashAt(i int, crashed *bool) func(string) error {
+ n := 0
+ return func(string) error {
+ if n == i && !*crashed {
+ *crashed = true
+ return errors.New("kill -9")
+ }
+ n++
+ return nil
+ }
+}
+
+// TestAdoptionCrashAfterEveryAct: Alta dies after each act has taken
+// effect at Home and before it is recorded; a fresh engine resumes by
+// exact replay and nothing is committed twice.
+func TestAdoptionCrashAfterEveryAct(t *testing.T) {
+ planA, planB := adoptionActs(t)
+ if len(planA) != 2+2*len(Apps) || strings.Join(planB, ",") != "verify,activate" {
+ t.Fatalf("acts %v / %v", planA, planB)
+ }
+ for i := range planA {
+ t.Run(fmt.Sprintf("A%02d-%s", i, planA[i]), func(t *testing.T) {
+ a := newAdoption(t)
+ crashed := false
+ e := a.adopter(crashAt(i, &crashed), nil)
+ run, err := e.StartAdoption(a.ctx(), "Oficina", ownerCanary)
+ if err != nil {
+ t.Fatal(err)
+ }
+ a.confirm(homeop.KindCreateTeam)
+ for j := 0; j < 20 && !crashed; j++ {
+ _ = e.Advance(a.ctx(), run)
+ a.tick(5 * time.Second)
+ }
+ if !crashed {
+ t.Fatalf("act %d never reached", i)
+ }
+ a.tick(time.Minute)
+ if r := a.drive(a.adopter(nil, nil), run, 20); r.State != "done" || r.Code != "awaiting-configuration" {
+ t.Fatalf("after crash at %s: %s %s", planA[i], r.State, r.Code)
+ }
+ if a.home.TeamCount() != 1 {
+ t.Fatalf("teams %d", a.home.TeamCount())
+ }
+ for _, s := range Slugs() {
+ if a.home.InstanceState(s) != "pending" {
+ t.Fatalf("%s %q", s, a.home.InstanceState(s))
+ }
+ }
+ reqs := a.home.Requests()
+ onceEach(t, reqs)
+ if len(reqs) != 1+len(planA) || a.home.ConsumerCount() != 0 {
+ t.Fatalf("requests %v", reqs)
+ }
+ })
+ }
+ for i := range planB {
+ t.Run(fmt.Sprintf("B%02d-%s", i, planB[i]), func(t *testing.T) {
+ a := newAdoption(t)
+ a.planA(a.adopter(nil, nil))
+ crashed := false
+ obs := newObserver()
+ e := a.adopter(crashAt(i, &crashed), obs)
+ run := a.activate(e, "calendar")
+ for j := 0; j < 10 && !crashed; j++ {
+ _ = e.Advance(a.ctx(), run)
+ a.tick(5 * time.Second)
+ }
+ if !crashed {
+ t.Fatalf("act %d never reached", i)
+ }
+ a.tick(time.Minute)
+ if r := a.drive(a.adopter(nil, obs), run, 10); r.State != "done" {
+ t.Fatalf("after crash at %s: %s %s", planB[i], r.State, r.Code)
+ }
+ // The activation was observed once and replayed exactly.
+ if obs.count() != 1 || a.home.InstanceState("calendar") != "live" {
+ t.Fatalf("observed %d times", obs.count())
+ }
+ reqs := a.home.Requests()
+ onceEach(t, reqs)
+ if !slices.Contains(reqs, homeop.DirectoryActivate+":calendar") {
+ t.Fatalf("requests %v", reqs)
+ }
+ })
+ }
+}
diff --git a/provision/engine.go b/provision/engine.go
index 8e8f876..90dc849 100644
--- a/provision/engine.go
+++ b/provision/engine.go
@@ -36,6 +36,10 @@ type Config struct {
// 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)
+ // Observer re-observes an adopted app before its activation
+ // (existing-team-adoption.md). The served alta has none, so it never
+ // activates an adopted app.
+ Observer Observer
}
// Engine runs §6's state machine. Every step is probe → act → verify →
@@ -119,7 +123,7 @@ func (e *Engine) StartInitialize(ctx context.Context, typed string) (int64, erro
return 0, err
}
e.cfg.Store.Audit(ctx, id, "", "", "run-start", homeop.KindInitialize)
- return id, e.submitPlans(ctx, id, "", "", "", homeop.KindInitialize, nil)
+ return id, e.submitPlans(ctx, id, "", "", "", homeop.KindInitialize, nil, "")
}
// NewTeam is the New team form.
@@ -196,7 +200,7 @@ func (e *Engine) CreateTeam(ctx context.Context, in NewTeam) (int64, error) {
}
e.cfg.Store.Audit(ctx, id, in.Label, "", "run-start", homeop.KindCreateTeam)
e.auditOptions(ctx, id, in.Label, opt)
- return id, e.submitPlans(ctx, id, in.Label, in.Name, in.Owner, homeop.KindCreateTeam, in.Apps)
+ 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
@@ -266,7 +270,7 @@ func (e *Engine) AddApps(ctx context.Context, label string, apps []string, opt R
}
e.cfg.Store.Audit(ctx, id, label, "", "run-start", homeop.KindAddApps)
e.auditOptions(ctx, id, label, opt)
- return id, e.submitPlans(ctx, id, label, "", "", homeop.KindAddApps, apps)
+ return id, e.submitPlans(ctx, id, label, "", "", homeop.KindAddApps, apps, "")
}
// ContinueApps is what "Continue under a new plan" takes: the team's
@@ -352,7 +356,7 @@ func (e *Engine) resumeCreate(ctx context.Context, t Team, apps []string, opt Ru
}
e.cfg.Store.Audit(ctx, id, t.Label, "", "run-start", homeop.KindCreateTeam)
e.auditOptions(ctx, id, t.Label, opt)
- return id, e.submitPlans(ctx, id, t.Label, t.Name, owner, homeop.KindCreateTeam, apps)
+ 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.
@@ -384,7 +388,7 @@ func (e *Engine) RetireApps(ctx context.Context, label string, apps []string, ty
return 0, err
}
e.cfg.Store.Audit(ctx, id, label, "", "run-start", homeop.KindRetireApps)
- return id, e.submitPlans(ctx, id, label, "", "", homeop.KindRetireApps, apps)
+ return id, e.submitPlans(ctx, id, label, "", "", homeop.KindRetireApps, apps, "")
}
// Resubmit signs a fresh plan for a run whose plan expired unconfirmed.
@@ -414,7 +418,13 @@ func (e *Engine) Resubmit(ctx context.Context, runID int64) error {
return fail("owner-needed")
}
}
- return e.submitPlans(ctx, runID, r.Label, name, owner, r.Kind, r.Apps)
+ existing := ""
+ if r.Adoption {
+ if existing, err = e.adoptedTeam(ctx, r); err != nil {
+ return err
+ }
+ }
+ return e.submitPlans(ctx, runID, r.Label, name, owner, r.Kind, r.Apps, existing)
}
// preflight is §6 step 0's console and Home half.
@@ -472,12 +482,17 @@ func (e *Engine) preflight(ctx context.Context, label, env string, forked bool,
// 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 {
+// the owner; Home keeps its own copy and Paul confirms that copy. An
+// adoption plan carries the team's SQID, existing, on both roles.
+func (e *Engine) submitPlans(ctx context.Context, runID int64, label, name, owner, kind string, apps []string, existing string) error {
planID := homeop.Token()
issued := e.now().Add(-homeop.Skew * time.Second)
roles := []string{homeop.Directory, homeop.Credential}
- if kind == homeop.KindInitialize {
+ // Initialize is the directory's alone, and so is disabling an adopted
+ // app: an ordinary retire-apps window under oficina may disable a
+ // directory binding and never retires an env-manifest consumer, so the
+ // credential role has nothing to confirm.
+ if kind == homeop.KindInitialize || (kind == homeop.KindRetireApps && label == AdoptionLabel) {
roles = roles[:1]
}
signed := map[string][]byte{}
@@ -496,6 +511,7 @@ func (e *Engine) submitPlans(ctx context.Context, runID int64, label, name, owne
if role == homeop.Credential && kind == homeop.KindCreateTeam {
p.Owner = owner
}
+ p.ExistingTeam = existing
raw, err := homeop.SignPlan(e.cfg.Home.Key, p)
if err != nil {
return err
@@ -559,6 +575,11 @@ func (e *Engine) Advance(ctx context.Context, runID int64) error {
}
_ = st.DropExpiredPlans(ctx)
p := &pass{run: r, ins: map[string]homeop.Inspection{}, open: map[string]int64{}, closed: map[string]string{}}
+ // The adoption label is the adoption runs' alone, and an adoption run
+ // has no other: neither ever reaches the other's steps.
+ if (r.Label == AdoptionLabel) != r.Adoption {
+ return e.settle(ctx, p, fail("label-reserved"))
+ }
if r.Label != "" {
if p.team, err = st.Team(ctx, r.Label); err != nil {
return err
@@ -567,10 +588,12 @@ func (e *Engine) Advance(ctx context.Context, runID int64) error {
if err := e.windows(ctx, p); err != nil {
return e.settle(ctx, p, err)
}
- switch r.Kind {
- case homeop.KindInitialize:
+ switch {
+ case r.Adoption:
+ return e.settle(ctx, p, e.adoption(ctx, p))
+ case r.Kind == homeop.KindInitialize:
return e.settle(ctx, p, e.initialize(ctx, p))
- case homeop.KindRetireApps:
+ case r.Kind == homeop.KindRetireApps:
return e.settle(ctx, p, e.retire(ctx, p))
default:
return e.settle(ctx, p, e.provision(ctx, p))
@@ -584,7 +607,12 @@ func (e *Engine) settle(ctx context.Context, p *pass, err error) error {
var fl *Fail
switch {
case err == nil:
- _ = st.SetRunState(ctx, p.run.ID, "done", "")
+ code := ""
+ if p.run.Adoption && p.run.Kind == homeop.KindCreateTeam {
+ // Plan A ends here: configure (CARLOS) comes next, then Plan B.
+ code = "awaiting-configuration"
+ }
+ _ = st.SetRunState(ctx, p.run.ID, "done", code)
st.Audit(ctx, p.run.ID, p.run.Label, "", "run-done", p.run.Kind)
return nil
case errors.Is(err, errCrash):
diff --git a/provision/steps.go b/provision/steps.go
index 43e17e1..8e61a48 100644
--- a/provision/steps.go
+++ b/provision/steps.go
@@ -133,7 +133,12 @@ func (e *Engine) provision(ctx context.Context, p *pass) error {
}
func (e *Engine) appPipeline(ctx context.Context, p *pass, app App) error {
- for _, step := range AppSteps(app) {
+ return e.pipeline(ctx, p, app, AppSteps(app))
+}
+
+// pipeline runs app's steps in order, skipping those already done.
+func (e *Engine) pipeline(ctx context.Context, p *pass, app App, steps []string) error {
+ for _, step := range steps {
if _, ok, err := e.cfg.Store.Done(ctx, p.run.Label, app.Slug, step); err != nil {
return err
} else if ok {
@@ -170,6 +175,10 @@ func (e *Engine) runStep(ctx context.Context, p *pass, app App, step string) err
return e.stepActivate(ctx, p, app)
case StepAudit:
return e.stepAudit(ctx, p, app)
+ case StepDisable:
+ // An adopted app's disable (DisableAdopted); §9's runs use
+ // retireApp's own order.
+ return e.stepDisable(ctx, p, app)
}
return fail("unknown-step")
}
@@ -258,6 +267,17 @@ func (e *Engine) ownerReceipt(ctx context.Context, p *pass) ([]byte, homeop.Owne
label := p.run.Label
proposed := p.ins[homeop.Directory]
now := e.now().Unix()
+ if p.run.Adoption {
+ // Adoption seeds at the SQID Paul confirmed on both roles and no
+ // other: if the directory now proposes another, nothing is signed.
+ existing, err := e.planExisting(ctx, p)
+ if err != nil {
+ return nil, homeop.OwnerReceipt{}, err
+ }
+ if existing != proposed.TeamSQID {
+ return nil, homeop.OwnerReceipt{}, fail("proposal-moved")
+ }
+ }
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 {
@@ -757,6 +777,12 @@ func (e *Engine) stepVerify(ctx context.Context, p *pass, app App) error {
_ = 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}
}
+ if p.run.Adoption {
+ // An adopted instance keeps its own access: adoption enables no team
+ // mode, so there is no /api/team readiness to wait for. The
+ // Observer's re-observation at activation stands in for it.
+ return e.record(ctx, p, app.Slug, StepVerify, prev.Data)
+ }
status, body, err := e.get(ctx, PublicOrigin(p.run.Label, app.Slug)+"/api/team")
if err != nil {
return park("roster-unreachable")
@@ -789,6 +815,9 @@ func artifactDigest(serving string) string {
var activationVersion = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$`)
func (e *Engine) stepActivate(ctx context.Context, p *pass, app App) error {
+ if p.run.Adoption {
+ return e.stepActivateAdopted(ctx, p, app)
+ }
st := e.cfg.Store
label := p.run.Label
if prev, ok, _ := st.LastRequest(ctx, label, app.Slug, "activate"); !ok || prev.State != "committed" {