adopt: environment binding with witness; activation gate
EnvironmentBinding commits to both identities, both var lists, both layer sets, team, issuer, artifact SHA-256, version, the three delivery observations, the witness and the pre-plan-a preflight time. Observer.Observe refuses with fixed codes unless the journal's evidence is complete and a fresh read still matches it: identity, preservation, config, agent keys, a current witness (no clock limit), delivery, Home's version shape, the reviewed artifact and the live checks. The artifact is Alta's scheme: SHA-256 of the served release name (X-Carlos-Version).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
5 files changed,
+903
−0
adopt/binding.go+96 −0adopt/binding_test.go+159 −0adopt/observer.go+248 −0adopt/observer_test.go+383 −0provision/adopt.go+17 −0
diff --git a/adopt/binding.go b/adopt/binding.go| new file mode 100644 |
| index 0000000..ffd7c89 |
| --- /dev/null |
| +++ b/adopt/binding.go |
| @@ -0,0 +1,96 @@ |
| +// This file computes an adopted app's environment_binding: the digest |
| +// Home's signed activation carries of everything the runner observed. |
| +package adopt |
| + |
| +import ( |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "encoding/json" |
| + "sort" |
| + "time" |
| + |
| + "amadan.net/oficina/alta/carlosop" |
| +) |
| + |
| +// bindingContext names the scheme, so a binding of these parts is never |
| +// mistaken for one of any other. |
| +const bindingContext = "oficina/existing-app-observation/v1" |
| + |
| +// BindingInput is everything one adopted app's binding commits to. |
| +// ArtifactSHA256 is the reviewed artifact's SHA-256 as 64 lowercase hex; |
| +// Version is the delivered version; HomePreflightAt is when the |
| +// pre-plan-a Home preflight was attested. |
| +type BindingInput struct { |
| + Before, After Identity |
| + BeforeVars, AfterVars []carlosop.EffectiveVar |
| + BeforeLayers, AfterLayers map[string]string |
| + TeamSQID, Issuer, ArtifactSHA256, Version string |
| + BeforeDelivery, AfterDelivery, NowDelivery Delivery |
| + Witness Witness |
| + HomePreflightAt time.Time |
| +} |
| + |
| +// EnvironmentBinding is base64url(SHA-256) of the JSON array, in order: |
| +// |
| +// 1. "oficina/existing-app-observation/v1"; |
| +// 2. the before and after identities; |
| +// 3. the before and after effective vars, each list as [key, kind, |
| +// digest, from] entries sorted (Shadows is not part of an entry); |
| +// 4. the before and after layer versions (JSON objects, keys sorted); |
| +// 5. the team SQID, the issuer, the artifact SHA-256 and the version; |
| +// 6. the before, after and now delivery observations; |
| +// 7. the witness: [app, sentence, identity, delivery, after version, |
| +// time]; |
| +// 8. the pre-plan-a Home preflight's attestation time. |
| +// |
| +// Paul's witness and the delivery observations are inside the binding, |
| +// so Home's signed activation commits to them. The result is as |
| +// sensitive as the digests it covers: it is never printed or logged. |
| +func EnvironmentBinding(in BindingInput) string { |
| + w := in.Witness |
| + parts := []any{ |
| + bindingContext, |
| + in.Before, in.After, |
| + varEntries(in.BeforeVars), varEntries(in.AfterVars), |
| + layers(in.BeforeLayers), layers(in.AfterLayers), |
| + in.TeamSQID, in.Issuer, in.ArtifactSHA256, in.Version, |
| + in.BeforeDelivery, in.AfterDelivery, in.NowDelivery, |
| + []any{w.App, w.Typed, w.Identity, w.Delivery, w.AfterVersion, w.At}, |
| + in.HomePreflightAt, |
| + } |
| + // Every part is a string, a time, a map of strings or a struct of |
| + // those: Marshal cannot fail on them. |
| + raw, err := json.Marshal(parts) |
| + if err != nil { |
| + panic("adopt: the binding's parts did not encode") |
| + } |
| + sum := sha256.Sum256(raw) |
| + return base64.RawURLEncoding.EncodeToString(sum[:]) |
| +} |
| + |
| +// varEntries is vars as sorted [key, kind, digest, from] entries, never |
| +// nil, leaving the caller's slice as it was. |
| +func varEntries(vars []carlosop.EffectiveVar) [][4]string { |
| + out := make([][4]string, 0, len(vars)) |
| + for _, v := range vars { |
| + out = append(out, [4]string{v.Key, v.Kind, v.Digest, v.From}) |
| + } |
| + sort.Slice(out, func(i, j int) bool { |
| + for k := range out[i] { |
| + if out[i][k] != out[j][k] { |
| + return out[i][k] < out[j][k] |
| + } |
| + } |
| + return false |
| + }) |
| + return out |
| +} |
| + |
| +// layers is m, or an empty object for none, so an absent map and an |
| +// empty one bind alike. |
| +func layers(m map[string]string) map[string]string { |
| + if m == nil { |
| + return map[string]string{} |
| + } |
| + return m |
| +} |
diff --git a/adopt/binding_test.go b/adopt/binding_test.go| new file mode 100644 |
| index 0000000..a17d27b |
| --- /dev/null |
| +++ b/adopt/binding_test.go |
| @@ -0,0 +1,159 @@ |
| +package adopt |
| + |
| +import ( |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "encoding/json" |
| + "reflect" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/alta/carlosop" |
| +) |
| + |
| +// bindingInput is a complete binding input with every field set. |
| +func bindingInput() BindingInput { |
| + at := time.Date(2026, 11, 16, 10, 0, 0, 0, time.UTC) |
| + id := Identity{Account: "bds", App: "docs", RecordHost: "docs.oficina.works", Slug: "s-docs", |
| + Channel: "stable", Region: "eu", CreatedAt: at.Add(-1000 * time.Hour), RecordSeq: 4, ReplicaAssignment: `{"boxes":["b1"]}`} |
| + d := func(ops OpsShape, min int) Delivery { |
| + return Delivery{Version: "v1.4.0", Header: "v1.4.0", Health: 200, Ops: ops, At: at.Add(time.Duration(min) * time.Minute)} |
| + } |
| + before := []carlosop.EffectiveVar{ |
| + {Key: "DOCS_HOME_ISSUER", Kind: "env", Digest: "vd1:" + hex64("a"), From: "default"}, |
| + {Key: "DOCS_INSTANCE_KEY", Kind: "secret", Digest: "vd1:" + hex64("b"), From: "default"}, |
| + } |
| + after := append(append([]carlosop.EffectiveVar(nil), before...), |
| + carlosop.EffectiveVar{Key: "DOCS_AGENT_ISSUER", Kind: "env", Digest: "vd1:" + hex64("c"), From: "default"}, |
| + carlosop.EffectiveVar{Key: "DOCS_AGENT_TEAM", Kind: "env", Digest: "vd1:" + hex64("d"), From: "default"}) |
| + return BindingInput{ |
| + Before: id, After: id, |
| + BeforeVars: before, AfterVars: after, |
| + BeforeLayers: map[string]string{"default": "cv1:" + hex64("1"), "overlay": "none"}, |
| + AfterLayers: map[string]string{"default": "cv1:" + hex64("2"), "overlay": "none"}, |
| + TeamSQID: fixtureSQID, Issuer: Issuer, ArtifactSHA256: hex64("e"), Version: "v1.4.0", |
| + BeforeDelivery: d(OpsAbsent, 0), AfterDelivery: d(OpsAgent401, 5), NowDelivery: d(OpsAgent401, 60), |
| + Witness: Witness{App: "docs", Typed: "I signed in to docs.oficina.works and it works as before", |
| + Identity: id, Delivery: d(OpsAgent401, 10), AfterVersion: "cv1:" + hex64("2"), At: at.Add(10 * time.Minute)}, |
| + HomePreflightAt: at.Add(-24 * time.Hour), |
| + } |
| +} |
| + |
| +func hex64(c string) string { |
| + out := "" |
| + for len(out) < 64 { |
| + out += c |
| + } |
| + return out |
| +} |
| + |
| +func TestBindingIncludesWitnessAndDelivery(t *testing.T) { |
| + in := bindingInput() |
| + b := EnvironmentBinding(in) |
| + raw, err := base64.RawURLEncoding.DecodeString(b) |
| + if err != nil || len(raw) != sha256.Size { |
| + t.Fatalf("binding is not base64url of 32 bytes: %d bytes, %v", len(raw), err) |
| + } |
| + if EnvironmentBinding(in) != b { |
| + t.Fatal("the binding is not deterministic") |
| + } |
| + |
| + // The first part names the scheme: the binding is the documented |
| + // array, not some other encoding of the same values. |
| + parts := []any{"oficina/existing-app-observation/v1", |
| + in.Before, in.After, |
| + [][4]string{{"DOCS_HOME_ISSUER", "env", "vd1:" + hex64("a"), "default"}, {"DOCS_INSTANCE_KEY", "secret", "vd1:" + hex64("b"), "default"}}, |
| + [][4]string{{"DOCS_AGENT_ISSUER", "env", "vd1:" + hex64("c"), "default"}, {"DOCS_AGENT_TEAM", "env", "vd1:" + hex64("d"), "default"}, |
| + {"DOCS_HOME_ISSUER", "env", "vd1:" + hex64("a"), "default"}, {"DOCS_INSTANCE_KEY", "secret", "vd1:" + hex64("b"), "default"}}, |
| + in.BeforeLayers, in.AfterLayers, |
| + in.TeamSQID, in.Issuer, in.ArtifactSHA256, in.Version, |
| + in.BeforeDelivery, in.AfterDelivery, in.NowDelivery, |
| + []any{in.Witness.App, in.Witness.Typed, in.Witness.Identity, in.Witness.Delivery, in.Witness.AfterVersion, in.Witness.At}, |
| + in.HomePreflightAt, |
| + } |
| + js, err := json.Marshal(parts) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + sum := sha256.Sum256(js) |
| + if want := base64.RawURLEncoding.EncodeToString(sum[:]); b != want { |
| + t.Fatalf("the binding is not base64url(sha256) of the documented array") |
| + } |
| + |
| + // Every part moves it, the witness and the three deliveries above all. |
| + edits := map[string]func(*BindingInput){ |
| + "witness app": func(in *BindingInput) { in.Witness.App = "sheets" }, |
| + "witness sentence": func(in *BindingInput) { in.Witness.Typed += "." }, |
| + "witness identity": func(in *BindingInput) { in.Witness.Identity.RecordSeq++ }, |
| + "witness delivery": func(in *BindingInput) { in.Witness.Delivery.Header = "v1.4.1" }, |
| + "witness delivery ops": func(in *BindingInput) { in.Witness.Delivery.Ops = OpsAgent200 }, |
| + "witness after version": func(in *BindingInput) { in.Witness.AfterVersion = "cv1:" + hex64("3") }, |
| + "witness time": func(in *BindingInput) { in.Witness.At = in.Witness.At.Add(time.Second) }, |
| + "before delivery": func(in *BindingInput) { in.BeforeDelivery.Ops = OpsApp401 }, |
| + "after delivery": func(in *BindingInput) { in.AfterDelivery.Version = "v1.4.1" }, |
| + "after delivery health": func(in *BindingInput) { in.AfterDelivery.Health = 503 }, |
| + "now delivery": func(in *BindingInput) { in.NowDelivery.Redirected = true }, |
| + "now delivery time": func(in *BindingInput) { in.NowDelivery.At = in.NowDelivery.At.Add(time.Hour) }, |
| + "before identity": func(in *BindingInput) { in.Before.Region = "us" }, |
| + "after identity": func(in *BindingInput) { in.After.Seed = `{"s":1}` }, |
| + "before var gone": func(in *BindingInput) { in.BeforeVars = []carlosop.EffectiveVar{in.BeforeVars[0]} }, |
| + "before var digest": func(in *BindingInput) { in.BeforeVars = withDigest(in.BeforeVars, 1, "vd1:"+hex64("9")) }, |
| + "after var source": func(in *BindingInput) { in.AfterVars = withFrom(in.AfterVars, 0, "environment") }, |
| + "before layers": func(in *BindingInput) { in.BeforeLayers = map[string]string{"default": "none"} }, |
| + "after layers": func(in *BindingInput) { in.AfterLayers = map[string]string{"default": "none"} }, |
| + "team": func(in *BindingInput) { in.TeamSQID = "other" }, |
| + "issuer": func(in *BindingInput) { in.Issuer = "https://elsewhere.example" }, |
| + "artifact": func(in *BindingInput) { in.ArtifactSHA256 = hex64("f") }, |
| + "version": func(in *BindingInput) { in.Version = "v1.4.1" }, |
| + "home preflight attested": func(in *BindingInput) { in.HomePreflightAt = in.HomePreflightAt.Add(time.Second) }, |
| + } |
| + for name, edit := range edits { |
| + t.Run(name, func(t *testing.T) { |
| + e := bindingInput() |
| + edit(&e) |
| + if EnvironmentBinding(e) == b { |
| + t.Fatalf("changing the %s left the binding unchanged", name) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func withDigest(vars []carlosop.EffectiveVar, i int, d string) []carlosop.EffectiveVar { |
| + out := append([]carlosop.EffectiveVar(nil), vars...) |
| + out[i].Digest = d |
| + return out |
| +} |
| + |
| +func withFrom(vars []carlosop.EffectiveVar, i int, from string) []carlosop.EffectiveVar { |
| + out := append([]carlosop.EffectiveVar(nil), vars...) |
| + out[i].From = from |
| + return out |
| +} |
| + |
| +func TestBindingIsOrderIndependent(t *testing.T) { |
| + in := bindingInput() |
| + want := EnvironmentBinding(in) |
| + |
| + shuffled := bindingInput() |
| + reverse := func(v []carlosop.EffectiveVar) []carlosop.EffectiveVar { |
| + out := make([]carlosop.EffectiveVar, len(v)) |
| + for i := range v { |
| + out[len(v)-1-i] = v[i] |
| + } |
| + return out |
| + } |
| + shuffled.BeforeVars = reverse(shuffled.BeforeVars) |
| + shuffled.AfterVars = reverse(shuffled.AfterVars) |
| + // Maps built in another order, and shadows (not part of a var's |
| + // entry) differing, change nothing. |
| + shuffled.BeforeLayers = map[string]string{"overlay": "none"} |
| + shuffled.BeforeLayers["default"] = "cv1:" + hex64("1") |
| + shuffled.AfterVars[0].Shadows = []string{"default"} |
| + keep := append([]carlosop.EffectiveVar(nil), shuffled.AfterVars...) |
| + if got := EnvironmentBinding(shuffled); got != want { |
| + t.Fatal("the binding depends on the order of vars or layers") |
| + } |
| + if !reflect.DeepEqual(keep, shuffled.AfterVars) { |
| + t.Fatal("EnvironmentBinding reordered its caller's vars") |
| + } |
| +} |
diff --git a/adopt/observer.go b/adopt/observer.go| new file mode 100644 |
| index 0000000..c3c6a9e |
| --- /dev/null |
| +++ b/adopt/observer.go |
| @@ -0,0 +1,248 @@ |
| +// This file is the activation gate: an adopted app's re-observation |
| +// immediately before Home activates it. Nothing activates without the |
| +// journal's complete evidence and a fresh read that still matches it. |
| +package adopt |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "errors" |
| + "net/http" |
| + "regexp" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/alta/carlosop" |
| + "amadan.net/oficina/alta/provision" |
| +) |
| + |
| +// Refusal is the gate's refusal: fixed codes, sorted, carrying key names, |
| +// layer names and identity fields only. |
| +type Refusal struct{ Codes []string } |
| + |
| +func (r *Refusal) Error() string { |
| + return "adopt: observation refused: " + strings.Join(r.Codes, ", ") |
| +} |
| + |
| +func refuse(codes ...string) error { return &Refusal{Codes: sortedSet(codes)} } |
| + |
| +// appVersion is the app_version Home's directory.activate-consumer |
| +// admits, as provision's step 10 mirrors it (Home 0cee9ba, |
| +// internal/operator/verification.go observedVersion). |
| +var appVersion = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$`) |
| + |
| +// artifactShape is a reviewed artifact SHA-256: 64 lowercase hex. |
| +var artifactShape = regexp.MustCompile(`^[0-9a-f]{64}$`) |
| + |
| +// Observer is the CARLOS half's provision.Observer. Artifacts holds each |
| +// app's reviewed artifact SHA-256 as 64 lowercase hex: the SHA-256 of the |
| +// release name Paul reviewed, Alta's artifact scheme (provision |
| +// artifactDigest). Now stamps the fresh delivery; it is no age limit. |
| +type Observer struct { |
| + C *carlosop.Client |
| + H *http.Client |
| + S *Store |
| + Artifacts map[string]string |
| + Now func() time.Time |
| +} |
| + |
| +var _ provision.Observer = (*Observer)(nil) |
| + |
| +func (o *Observer) now() time.Time { |
| + if o.Now == nil { |
| + return time.Now().UTC() |
| + } |
| + return o.Now().UTC() |
| +} |
| + |
| +// Observe re-observes app and answers its activation evidence. It reads |
| +// and probes; it writes nothing, to CARLOS or the journal. It refuses |
| +// (a *Refusal) unless every one of these holds: |
| +// |
| +// - evidence: the pre-plan-a Home preflight, the baseline, a landed |
| +// write, the after snapshot and the witness (missing-<x>); no |
| +// rollback (rollback-recorded); |
| +// - the write sent Issuer and teamSQID (issuer-mismatch, |
| +// team-mismatch); |
| +// - live checks: S.LiveGate passes (live-checks-missing); |
| +// - the app's reviewed artifact SHA-256 is configured |
| +// (artifact-unreviewed); |
| +// - identity: a fresh read's equals the baseline's, the after |
| +// snapshot's and the witness's (identity-<code>); |
| +// - preservation: Preserved(baseline, after) is empty |
| +// (after-not-preserved), and so is Preserved(baseline, fresh) |
| +// (drift-<code>); |
| +// - config: the fresh read equals the after snapshot, every key's |
| +// digest, kind and source and every layer's version |
| +// (config-<code>); no team-mode key (team-mode-<KEY>); both agent |
| +// keys are plain vars from the write layer carrying the sent |
| +// digests (agent-key-<KEY>); |
| +// - the witness is current: its after version is the fresh write |
| +// layer's, and its delivered version and header are the fresh ones |
| +// (witness-superseded). There is no wall-clock limit; |
| +// - delivery: the fresh probe passes Delivered against the baseline |
| +// (not-delivered), the version body equals X-Carlos-Version |
| +// (version-header-mismatch) and Home admits it |
| +// (version-unacceptable); |
| +// - artifact: the SHA-256 of the served release name (X-Carlos-Version) |
| +// is the reviewed one (artifact-mismatch). |
| +// |
| +// Stored evidence is checked before anything is read. A read that fails |
| +// is an error, not a refusal. |
| +func (o *Observer) Observe(ctx context.Context, app, teamSQID string) (provision.Observation, error) { |
| + if o == nil || o.C == nil || o.H == nil || o.S == nil { |
| + return provision.Observation{}, errors.New("adopt: the observer needs a console, a client and the journal") |
| + } |
| + a, ok := provision.AppBySlug(app) |
| + if !ok { |
| + return provision.Observation{}, refuse("unknown-app") |
| + } |
| + if !sqidShape.MatchString(teamSQID) { |
| + return provision.Observation{}, refuse("team-not-sqid") |
| + } |
| + ev, err := o.evidence(ctx, a, teamSQID) |
| + if err != nil { |
| + return provision.Observation{}, err |
| + } |
| + |
| + fresh, err := Observe(ctx, o.C, o.H, a) |
| + if err != nil { |
| + return provision.Observation{}, err |
| + } |
| + fresh.Delivery.At = o.now() |
| + |
| + var codes []string |
| + addAll := func(prefix string, cs ...string) { |
| + for _, c := range cs { |
| + codes = append(codes, prefix+c) |
| + } |
| + } |
| + add := func(code string) { codes = append(codes, code) } |
| + keys := AgentKeys(a) |
| + addAll("identity-", SameIdentity(ev.base.Identity, fresh.Identity)...) |
| + addAll("identity-", SameIdentity(ev.after.Identity, fresh.Identity)...) |
| + addAll("identity-", SameIdentity(ev.witness.Identity, fresh.Identity)...) |
| + if len(Preserved(ev.base, ev.after, keys)) > 0 { |
| + add("after-not-preserved") |
| + } |
| + addAll("drift-", Preserved(ev.base, fresh, keys)...) |
| + addAll("config-", sameConfig(ev.after, fresh)...) |
| + addAll("team-mode-", TeamModeKeys(a, fresh.Vars)...) |
| + for _, k := range keys { |
| + v := findVar(fresh.Vars, k) |
| + if v == nil || v.Kind != "env" || v.From != layerName(ev.base.WriteLayer) || v.Digest != carlosop.EnvDigest(ev.write.Sent[k]) { |
| + add("agent-key-" + k) |
| + } |
| + } |
| + w := ev.witness |
| + if w.AfterVersion != fresh.Layer.Version || w.Delivery.Version != fresh.Delivery.Version || w.Delivery.Header != fresh.Delivery.Header { |
| + add("witness-superseded") |
| + } |
| + d := fresh.Delivery |
| + if Delivered(ev.base.Delivery, d) != nil { |
| + add("not-delivered") |
| + } |
| + if d.Version != d.Header { |
| + add("version-header-mismatch") |
| + } |
| + if !appVersion.MatchString(d.Version) { |
| + add("version-unacceptable") |
| + } |
| + // The served release name is X-Carlos-Version, the release the edge |
| + // served from: Alta's artifact scheme hashes that name. |
| + sum := sha256.Sum256([]byte(d.Header)) |
| + artifact := hex.EncodeToString(sum[:]) |
| + if artifact != ev.artifact { |
| + add("artifact-mismatch") |
| + } |
| + if len(codes) > 0 { |
| + return provision.Observation{}, refuse(codes...) |
| + } |
| + |
| + return provision.Observation{ |
| + AppVersion: d.Version, |
| + ArtifactDigest: base64.RawURLEncoding.EncodeToString(sum[:]), |
| + EnvironmentBinding: EnvironmentBinding(BindingInput{ |
| + Before: ev.base.Identity, After: ev.after.Identity, |
| + BeforeVars: ev.base.Vars, AfterVars: ev.after.Vars, |
| + BeforeLayers: ev.base.Layers, AfterLayers: ev.after.Layers, |
| + TeamSQID: teamSQID, Issuer: Issuer, ArtifactSHA256: artifact, Version: d.Version, |
| + BeforeDelivery: ev.base.Delivery, AfterDelivery: ev.after.Delivery, NowDelivery: d, |
| + Witness: w, HomePreflightAt: ev.home.AttestedAt, |
| + }), |
| + }, nil |
| +} |
| + |
| +// gateEvidence is the journal's records for one app's activation. |
| +type gateEvidence struct { |
| + home HomePreflight |
| + base, after Snapshot |
| + write WriteRecord |
| + witness Witness |
| + artifact string |
| +} |
| + |
| +// evidence reads and checks the stored evidence, before anything is |
| +// read from CARLOS or the app. |
| +func (o *Observer) evidence(ctx context.Context, a provision.App, teamSQID string) (gateEvidence, error) { |
| + var ev gateEvidence |
| + var missing []string |
| + have := func(ok bool, err error, what string) error { |
| + if err == nil && !ok { |
| + missing = append(missing, "missing-"+what) |
| + } |
| + return err |
| + } |
| + home, ok, err := o.S.HomePreflight(ctx, PhasePrePlanA) |
| + if err := have(ok, err, "home-preflight"); err != nil { |
| + return ev, err |
| + } |
| + base, ok, err := o.S.Baseline(ctx, a.Slug) |
| + if err := have(ok, err, "baseline"); err != nil { |
| + return ev, err |
| + } |
| + write, ok, err := o.S.Write(ctx, a.Slug) |
| + if err := have(ok && write.State == "landed", err, "write"); err != nil { |
| + return ev, err |
| + } |
| + after, ok, err := o.S.After(ctx, a.Slug) |
| + if err := have(ok, err, "after"); err != nil { |
| + return ev, err |
| + } |
| + witness, ok, err := o.S.Witness(ctx, a.Slug) |
| + if err := have(ok, err, "witness"); err != nil { |
| + return ev, err |
| + } |
| + if len(missing) > 0 { |
| + return ev, refuse(missing...) |
| + } |
| + if _, ok, err := o.S.Rollback(ctx, a.Slug); err != nil { |
| + return ev, err |
| + } else if ok { |
| + return ev, refuse("rollback-recorded") |
| + } |
| + keys := AgentKeys(a) |
| + var codes []string |
| + if write.Sent[keys[0]] != Issuer { |
| + codes = append(codes, "issuer-mismatch") |
| + } |
| + if write.Sent[keys[1]] != teamSQID { |
| + codes = append(codes, "team-mismatch") |
| + } |
| + if len(codes) > 0 { |
| + return ev, refuse(codes...) |
| + } |
| + if err := o.S.LiveGate(ctx, a.Slug); err != nil { |
| + if errors.Is(err, ErrLiveChecksMissing) { |
| + return ev, refuse("live-checks-missing") |
| + } |
| + return ev, err |
| + } |
| + artifact := o.Artifacts[a.Slug] |
| + if !artifactShape.MatchString(artifact) { |
| + return ev, refuse("artifact-unreviewed") |
| + } |
| + return gateEvidence{home: home, base: base, after: after, write: write, witness: witness, artifact: artifact}, nil |
| +} |
diff --git a/adopt/observer_test.go b/adopt/observer_test.go| new file mode 100644 |
| index 0000000..9edab56 |
| --- /dev/null |
| +++ b/adopt/observer_test.go |
| @@ -0,0 +1,383 @@ |
| +package adopt |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "slices" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/alta/carlosop" |
| + "amadan.net/oficina/alta/provision" |
| +) |
| + |
| +// observerFixture is an app through configure: written, restarted until |
| +// delivered, its after snapshot captured and witnessed, with the |
| +// pre-plan-a Home preflight recorded and its served release reviewed. |
| +type observerFixture struct { |
| + *writeFixture |
| + o *Observer |
| + now time.Time |
| +} |
| + |
| +func sha256Hex(s string) string { |
| + sum := sha256.Sum256([]byte(s)) |
| + return hex.EncodeToString(sum[:]) |
| +} |
| + |
| +func newObserverFixture(t *testing.T, slug string, before ...func(*writeFixture)) *observerFixture { |
| + t.Helper() |
| + w := newWriteFixture(t, slug) |
| + for _, f := range before { |
| + f(w) |
| + } |
| + w.configured(t) |
| + ctx := context.Background() |
| + if err := RecordWitness(ctx, w.s, w.c, w.h, w.app, WitnessSentence(w.app), true); err != nil { |
| + t.Fatalf("RecordWitness: %v", err) |
| + } |
| + if err := w.s.SaveHomePreflight(ctx, HomePreflight{Phase: PhasePrePlanA, ProposedID: 1, ProposedSQID: fixtureSQID, AttestedAt: at.Add(-time.Hour)}); err != nil { |
| + t.Fatal(err) |
| + } |
| + x := &observerFixture{writeFixture: w, now: at} |
| + x.o = &Observer{C: w.c, H: w.h, S: w.s, Artifacts: map[string]string{slug: sha256Hex(w.site.header)}, Now: func() time.Time { return x.now }} |
| + return x |
| +} |
| + |
| +func (x *observerFixture) observe() (provision.Observation, error) { |
| + return x.o.Observe(context.Background(), x.app.Slug, fixtureSQID) |
| +} |
| + |
| +// refused observes and returns the refusal's codes, failing unless the |
| +// observation was refused with every code in want. |
| +func (x *observerFixture) refused(t *testing.T, want ...string) []string { |
| + t.Helper() |
| + obs, err := x.observe() |
| + if err == nil { |
| + // The observation is not printed: the binding never is. |
| + t.Fatal("observed, want a refusal") |
| + } |
| + noValues(t, err) |
| + var r *Refusal |
| + if !errors.As(err, &r) { |
| + t.Fatalf("err = %v, want a refusal", err) |
| + } |
| + if obs != (provision.Observation{}) { |
| + t.Fatal("a refusal carried an observation") |
| + } |
| + for _, c := range want { |
| + if !slices.Contains(r.Codes, c) { |
| + t.Fatalf("codes = %q, want %q among them", r.Codes, c) |
| + } |
| + } |
| + return r.Codes |
| +} |
| + |
| +// evidence is the journal's records the gate reads; nil is absent. |
| +type evidence struct { |
| + home *HomePreflight |
| + base *Snapshot |
| + write *WriteRecord |
| + after *Snapshot |
| + witness *Witness |
| +} |
| + |
| +// rejournal moves the observer onto a new journal holding the current |
| +// records as edit leaves them: how an absent or hand-written record is |
| +// staged, since the journal itself refuses to drop or retake one. |
| +func (x *observerFixture) rejournal(t *testing.T, edit func(e *evidence)) { |
| + t.Helper() |
| + ctx := context.Background() |
| + var e evidence |
| + if r, ok, _ := x.s.HomePreflight(ctx, PhasePrePlanA); ok { |
| + e.home = &r |
| + } |
| + if r, ok, _ := x.s.Baseline(ctx, x.app.Slug); ok { |
| + e.base = &r |
| + } |
| + if r, ok, _ := x.s.Write(ctx, x.app.Slug); ok { |
| + e.write = &r |
| + } |
| + if r, ok, _ := x.s.After(ctx, x.app.Slug); ok { |
| + e.after = &r |
| + } |
| + if r, ok, _ := x.s.Witness(ctx, x.app.Slug); ok { |
| + e.witness = &r |
| + } |
| + edit(&e) |
| + s := newJournal(t) |
| + must := func(err error) { |
| + t.Helper() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if e.home != nil { |
| + must(s.SaveHomePreflight(ctx, *e.home)) |
| + } |
| + if e.base != nil { |
| + must(s.SaveBaseline(ctx, x.app.Slug, *e.base)) |
| + } |
| + if e.write != nil { |
| + must(s.SaveWrite(ctx, *e.write)) |
| + } |
| + if e.after != nil { |
| + must(s.SaveAfter(ctx, x.app.Slug, *e.after)) |
| + } |
| + if e.witness != nil { |
| + must(s.SaveWitness(ctx, *e.witness)) |
| + } |
| + x.s, x.o.S = s, s |
| +} |
| + |
| +func TestObserverHappyPathEvidenceTokens(t *testing.T) { |
| + x := newObserverFixture(t, "calendar") |
| + ctx := context.Background() |
| + host := CanonicalHost(x.app) |
| + puts, restarts := x.puts(), x.f.RestartCount(host) |
| + |
| + obs, err := x.observe() |
| + if err != nil { |
| + t.Fatalf("Observe: %v", err) |
| + } |
| + if obs.AppVersion != valueVersion { |
| + t.Fatal("app_version is not the delivered version") |
| + } |
| + sum := sha256.Sum256([]byte(valueVersion)) |
| + if obs.ArtifactDigest != base64.RawURLEncoding.EncodeToString(sum[:]) { |
| + t.Fatal("artifact_digest is not base64url of the reviewed SHA-256") |
| + } |
| + |
| + // The binding is over the journal's evidence and this observation. |
| + base, _, _ := x.s.Baseline(ctx, "calendar") |
| + after, _, _ := x.s.After(ctx, "calendar") |
| + wit, _, _ := x.s.Witness(ctx, "calendar") |
| + home, _, _ := x.s.HomePreflight(ctx, PhasePrePlanA) |
| + now := x.site.delivery(t, x.carlosFixture) |
| + now.At = x.now |
| + want := EnvironmentBinding(BindingInput{ |
| + Before: base.Identity, After: after.Identity, |
| + BeforeVars: base.Vars, AfterVars: after.Vars, |
| + BeforeLayers: base.Layers, AfterLayers: after.Layers, |
| + TeamSQID: fixtureSQID, Issuer: Issuer, ArtifactSHA256: hex.EncodeToString(sum[:]), Version: valueVersion, |
| + BeforeDelivery: base.Delivery, AfterDelivery: after.Delivery, NowDelivery: now, |
| + Witness: wit, HomePreflightAt: home.AttestedAt, |
| + }) |
| + if obs.EnvironmentBinding != want { |
| + t.Fatal("environment_binding is not the binding of the journal's evidence and the fresh delivery") |
| + } |
| + |
| + // Observing reads; it writes and restarts nothing. |
| + if x.puts() != puts || x.f.RestartCount(host) != restarts || x.f.AppWideRestarts() != 0 { |
| + t.Fatal("Observe wrote or restarted") |
| + } |
| +} |
| + |
| +// The witness has no age limit: a later session, days on, with nothing |
| +// else changed, still passes. |
| +func TestObserverAcceptsWitnessFromEarlierSession(t *testing.T) { |
| + x := newObserverFixture(t, "calendar") |
| + first, err := x.observe() |
| + if err != nil { |
| + t.Fatalf("Observe: %v", err) |
| + } |
| + later := time.Now().Add(72 * time.Hour) |
| + o := &Observer{C: x.c, H: x.h, S: x.s, Artifacts: x.o.Artifacts, Now: func() time.Time { return later }} |
| + obs, err := o.Observe(context.Background(), "calendar", fixtureSQID) |
| + if err != nil { |
| + t.Fatalf("Observe three days on: %v", err) |
| + } |
| + if obs.AppVersion != first.AppVersion || obs.ArtifactDigest != first.ArtifactDigest { |
| + t.Fatal("the observation's tokens moved with the clock") |
| + } |
| +} |
| + |
| +func TestObserverRefusesSupersededWitness(t *testing.T) { |
| + t.Run("after snapshot retaken", func(t *testing.T) { |
| + x := newObserverFixture(t, "calendar") |
| + // A platform writer adds a key (reported, not fatal) and the after |
| + // snapshot is taken again: the witness saw the earlier version. |
| + x.f.PlatformWrite("calendar", "", x.app.Prefix+"_PLATFORM_NOTE", "n") |
| + if _, err := CaptureAfter(context.Background(), x.c, x.h, x.s, x.app); err != nil { |
| + t.Fatalf("CaptureAfter: %v", err) |
| + } |
| + wantCodes(t, x.refused(t), "witness-superseded") |
| + }) |
| + edits := map[string]func(w *Witness){ |
| + "after version": func(w *Witness) { w.AfterVersion = "cv1:" + hex64("9") }, |
| + "delivered version": func(w *Witness) { w.Delivery.Version = "v1.3.9" }, |
| + "delivered header": func(w *Witness) { w.Delivery.Header = "v1.3.9" }, |
| + } |
| + for name, edit := range edits { |
| + t.Run(name, func(t *testing.T) { |
| + x := newObserverFixture(t, "calendar") |
| + x.rejournal(t, func(e *evidence) { edit(e.witness) }) |
| + wantCodes(t, x.refused(t), "witness-superseded") |
| + }) |
| + } |
| + t.Run("redeployed", func(t *testing.T) { |
| + x := newObserverFixture(t, "calendar") |
| + x.site.version, x.site.header = "v1.5.0", "v1.5.0" |
| + x.refused(t, "witness-superseded") |
| + }) |
| +} |
| + |
| +// Each guard refuses with its own code. |
| +func TestObserverRefusals(t *testing.T) { |
| + ctx := context.Background() |
| + cases := []struct { |
| + name string |
| + app string |
| + before func(*writeFixture) |
| + edit func(t *testing.T, x *observerFixture) |
| + want []string |
| + exact bool |
| + }{ |
| + {name: "no pre-plan-a preflight", edit: func(t *testing.T, x *observerFixture) { |
| + x.rejournal(t, func(e *evidence) { e.home = nil }) |
| + _ = x.s.SaveHomePreflight(ctx, HomePreflight{Phase: PhasePreInitialize}) |
| + }, want: []string{"missing-home-preflight"}, exact: true}, |
| + {name: "no baseline", edit: func(t *testing.T, x *observerFixture) { x.rejournal(t, func(e *evidence) { e.base = nil }) }, |
| + want: []string{"missing-baseline"}, exact: true}, |
| + {name: "write not landed", edit: func(t *testing.T, x *observerFixture) { x.rejournal(t, func(e *evidence) { e.write.State = "sent" }) }, |
| + want: []string{"missing-write"}, exact: true}, |
| + {name: "no after", edit: func(t *testing.T, x *observerFixture) { x.rejournal(t, func(e *evidence) { e.after = nil }) }, |
| + want: []string{"missing-after"}, exact: true}, |
| + {name: "no witness", edit: func(t *testing.T, x *observerFixture) { x.rejournal(t, func(e *evidence) { e.witness = nil }) }, |
| + want: []string{"missing-witness"}, exact: true}, |
| + {name: "rollback recorded", edit: func(t *testing.T, x *observerFixture) { |
| + _ = x.s.SaveRollback(ctx, RollbackRecord{App: x.app.Slug, State: "sent"}) |
| + }, want: []string{"rollback-recorded"}, exact: true}, |
| + {name: "live checks missing", app: "docs", want: []string{"live-checks-missing"}, exact: true}, |
| + {name: "live check failed", app: "docs", edit: func(t *testing.T, x *observerFixture) { |
| + for _, c := range RequiredLiveChecks { |
| + _ = x.s.SaveCheck(ctx, c, "passed") |
| + } |
| + _ = x.s.SaveCheck(ctx, "member-no-local-permission-refused", "failed") |
| + }, want: []string{"live-checks-missing"}, exact: true}, |
| + {name: "artifact not reviewed", edit: func(t *testing.T, x *observerFixture) { x.o.Artifacts = nil }, |
| + want: []string{"artifact-unreviewed"}, exact: true}, |
| + {name: "artifact not lowercase hex", edit: func(t *testing.T, x *observerFixture) { |
| + x.o.Artifacts = map[string]string{"calendar": "AB" + sha256Hex(valueVersion)[2:]} |
| + }, want: []string{"artifact-unreviewed"}, exact: true}, |
| + {name: "artifact differs", edit: func(t *testing.T, x *observerFixture) { |
| + x.o.Artifacts = map[string]string{"calendar": hex64("0")} |
| + }, want: []string{"artifact-mismatch"}, exact: true}, |
| + {name: "another team", edit: func(t *testing.T, x *observerFixture) { |
| + x.rejournal(t, func(e *evidence) { e.write.Sent[AgentKeys(x.app)[1]] = "otherTeam" }) |
| + }, want: []string{"team-mismatch"}, exact: true}, |
| + {name: "another issuer", edit: func(t *testing.T, x *observerFixture) { |
| + x.rejournal(t, func(e *evidence) { e.write.Sent[AgentKeys(x.app)[0]] = "https://elsewhere.example" }) |
| + }, want: []string{"issuer-mismatch"}, exact: true}, |
| + {name: "identity changed", edit: func(t *testing.T, x *observerFixture) { |
| + x.f.AddInstance(carlosop.Instance{Host: CanonicalHost(x.app), App: "calendar", Slug: "s-calendar", Channel: "stable", Region: "us", |
| + CreatedAt: time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC), RecordSeq: 4, ReplicaAssignment: json.RawMessage(`{"boxes":["b1"]}`)}) |
| + }, want: []string{"identity-region"}}, |
| + {name: "baseline identity differs", edit: func(t *testing.T, x *observerFixture) { |
| + x.rejournal(t, func(e *evidence) { e.base.Identity.Region = "us" }) |
| + }, want: []string{"after-not-preserved", "drift-region", "identity-region"}, exact: true}, |
| + {name: "after identity differs", edit: func(t *testing.T, x *observerFixture) { |
| + x.rejournal(t, func(e *evidence) { e.after.Identity.Region = "us" }) |
| + }, want: []string{"after-not-preserved", "identity-region"}, exact: true}, |
| + {name: "witness identity differs", edit: func(t *testing.T, x *observerFixture) { |
| + x.rejournal(t, func(e *evidence) { e.witness.Identity.Channel = "beta" }) |
| + }, want: []string{"identity-channel"}, exact: true}, |
| + {name: "after not preserved", edit: func(t *testing.T, x *observerFixture) { |
| + // A hand-written after row in which a preserved secret was |
| + // resealed: CaptureAfter would have refused it. |
| + x.rejournal(t, func(e *evidence) { |
| + for i, v := range e.after.Vars { |
| + if v.Key == "CALENDAR_INSTANCE_KEY" { |
| + e.after.Vars = withDigest(e.after.Vars, i, "vd1:"+hex64("7")) |
| + } |
| + } |
| + }) |
| + }, want: []string{"after-not-preserved"}}, |
| + {name: "secret resealed since", edit: func(t *testing.T, x *observerFixture) { |
| + x.f.SetSecret("calendar", "", "CALENDAR_INSTANCE_KEY") |
| + }, want: []string{"drift-changed:CALENDAR_INSTANCE_KEY"}}, |
| + {name: "plain value changed since", edit: func(t *testing.T, x *observerFixture) { |
| + x.f.SetVar("calendar", "", "CALENDAR_ORIGIN", "https://calendar.oficina.works/another-plain-value") |
| + }, want: []string{"drift-changed:CALENDAR_ORIGIN"}}, |
| + {name: "config moved since", edit: func(t *testing.T, x *observerFixture) { |
| + x.f.PlatformWrite("calendar", "", "CALENDAR_PLATFORM_NOTE", "n") |
| + }, want: []string{"config-added:CALENDAR_PLATFORM_NOTE"}}, |
| + {name: "team-mode key", edit: func(t *testing.T, x *observerFixture) { |
| + x.f.SetVar("calendar", "", "CALENDAR_TEAM_ROSTER", "x") |
| + }, want: []string{"team-mode-CALENDAR_TEAM_ROSTER"}}, |
| + {name: "agent key with another digest", edit: func(t *testing.T, x *observerFixture) { |
| + x.f.SetVar("calendar", "", "CALENDAR_AGENT_TEAM", "otherTeam") |
| + }, want: []string{"agent-key-CALENDAR_AGENT_TEAM"}}, |
| + {name: "overlay shadows an agent key", edit: func(t *testing.T, x *observerFixture) { |
| + // The same value, so the same digest: only its source differs. |
| + x.f.SetOverlay("calendar", CanonicalHost(x.app), "CALENDAR_AGENT_ISSUER", Issuer) |
| + }, want: []string{"agent-key-CALENDAR_AGENT_ISSUER"}}, |
| + {name: "unhealthy", edit: func(t *testing.T, x *observerFixture) { x.site.health = 503 }, |
| + want: []string{"not-delivered"}, exact: true}, |
| + {name: "operations reverted", edit: func(t *testing.T, x *observerFixture) { x.site.ops = nil }, |
| + want: []string{"not-delivered"}, exact: true}, |
| + {name: "version malformed", before: func(w *writeFixture) { w.site.version, w.site.header = "-v1", "-v1" }, |
| + want: []string{"version-unacceptable"}, exact: true}, |
| + {name: "version body and header differ", edit: func(t *testing.T, x *observerFixture) { |
| + x.site.header = "rel-2026" |
| + x.o.Artifacts = map[string]string{"calendar": sha256Hex("rel-2026")} |
| + x.rejournal(t, func(e *evidence) { |
| + e.base.Delivery.Header, e.after.Delivery.Header, e.witness.Delivery.Header = "rel-2026", "rel-2026", "rel-2026" |
| + }) |
| + }, want: []string{"version-header-mismatch"}, exact: true}, |
| + } |
| + for _, tc := range cases { |
| + t.Run(tc.name, func(t *testing.T) { |
| + app := tc.app |
| + if app == "" { |
| + app = "calendar" |
| + } |
| + var before []func(*writeFixture) |
| + if tc.before != nil { |
| + before = append(before, tc.before) |
| + } |
| + x := newObserverFixture(t, app, before...) |
| + if tc.edit != nil { |
| + tc.edit(t, x) |
| + } |
| + codes := x.refused(t, tc.want...) |
| + if tc.exact { |
| + wantCodes(t, codes, tc.want...) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestObserverRefusesUnknownAppAndBadTeam(t *testing.T) { |
| + x := newObserverFixture(t, "calendar") |
| + codes := func(app, team string) []string { |
| + var r *Refusal |
| + if _, err := x.o.Observe(context.Background(), app, team); !errors.As(err, &r) { |
| + t.Fatalf("%s/%s: err = %v, want a refusal", app, team, err) |
| + } |
| + return r.Codes |
| + } |
| + wantCodes(t, codes("nope", fixtureSQID), "unknown-app") |
| + wantCodes(t, codes("calendar", "not a sqid"), "team-not-sqid") |
| + for _, o := range []*Observer{nil, {}, {C: x.c, H: x.h}, {C: x.c, S: x.s}, {H: x.h, S: x.s}} { |
| + if _, err := o.Observe(context.Background(), "calendar", fixtureSQID); err == nil { |
| + t.Fatal("an Observer without a console, a client or the journal observed") |
| + } |
| + } |
| +} |
| + |
| +func TestObserverPassesNonCanaryWithLiveChecks(t *testing.T) { |
| + x := newObserverFixture(t, "docs") |
| + for _, c := range RequiredLiveChecks { |
| + if err := x.s.SaveCheck(context.Background(), c, "passed"); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if _, err := x.observe(); err != nil { |
| + t.Fatalf("Observe: %v", err) |
| + } |
| +} |
diff --git a/provision/adopt.go b/provision/adopt.go| new file mode 100644 |
| index 0000000..c2926b9 |
| --- /dev/null |
| +++ b/provision/adopt.go |
| @@ -0,0 +1,17 @@ |
| +package provision |
| + |
| +import "context" |
| + |
| +// Observation is what an adopted app's activation evidence takes from the |
| +// CARLOS half: the delivered version, the reviewed artifact's digest and |
| +// the environment binding. EnvironmentBinding is never printed or logged. |
| +type Observation struct { |
| + AppVersion, ArtifactDigest, EnvironmentBinding string |
| +} |
| + |
| +// Observer re-observes one adopted app immediately before its activation |
| +// and answers its evidence, or refuses with a fixed code. The engine |
| +// never activates an adopted app without it. The served alta has none. |
| +type Observer interface { |
| + Observe(ctx context.Context, app, teamSQID string) (Observation, error) |
| +} |