oficina / alta Public

adopt: snapshots, preservation, prospective-inheritance preflight

Observe reads the canonical host's record, effective view, write layer
and delivery; Preflight refuses with fixed codes, including any other
instance that would inherit the agent keys. Preserved and NewKeys compare
snapshots by digest. record_seq stays in SameIdentity (step 0).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev d954494a566fb1641698b2ef56f27e6e26c7f6e6 parent ecbc5bb
3 files changed, +925 −0
  • adopt/snapshot.go +371 −0
  • adopt/snapshot_test.go +545 −0
  • adopt/types.go +9 −0
diff --git a/adopt/snapshot.go b/adopt/snapshot.go
new file mode 100644
index 0000000..e8f2f74
--- /dev/null
+++ b/adopt/snapshot.go
@@ -0,0 +1,371 @@
+// This file holds the 522 Plan 1 snapshots, the preservation check and
+// the CARLOS preflight that runs before any configuration write.
+package adopt
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "sort"
+ "strings"
+ "time"
+
+ "amadan.net/oficina/alta/carlosop"
+ "amadan.net/oficina/alta/provision"
+)
+
+// HomeIssuerOrigin is the Home issuer the canonical apps trust: Home's
+// credential role. An app trusting another issuer is not one this
+// adoption's directory team can speak for.
+const HomeIssuerOrigin = "https://id.oficina.works"
+
+// The effective view's layer names, lowest first. A higher layer covers a
+// lower one for the keys it sets.
+var layerRank = map[string]int{"default": 0, "environment": 1, "overlay": 2}
+
+// layerName is the effective view's name for a write layer: "default"
+// for "", else "environment".
+func layerName(writeLayer string) string {
+ if writeLayer == "" {
+ return "default"
+ }
+ return "environment"
+}
+
+func findVar(vars []carlosop.EffectiveVar, key string) *carlosop.EffectiveVar {
+ for i := range vars {
+ if vars[i].Key == key {
+ return &vars[i]
+ }
+ }
+ return nil
+}
+
+// plainValue is key's value in a stored layer, if the layer holds it as a
+// plain var with exactly the digest the effective view reports. "" for a
+// secret, an absent key or a digest that disagrees.
+func plainValue(l carlosop.Layer, ev *carlosop.EffectiveVar) string {
+ if ev == nil || ev.Kind != "env" {
+ return ""
+ }
+ for _, v := range l.Vars {
+ if v.Key == ev.Key && v.Kind == "env" && v.Digest == ev.Digest {
+ return v.Value
+ }
+ }
+ return ""
+}
+
+// observe reads one snapshot of app's canonical host, and the app's
+// instance list it found that host in. The codes are the refusals that
+// leave no snapshot to check: instance-missing, layer-overlay, and
+// home-issuer-mismatch when the host has no Home issuer to locate the
+// write layer by.
+func observe(ctx context.Context, c *carlosop.Client, h *http.Client, app provision.App) (Snapshot, []carlosop.Instance, []string, error) {
+ host := CanonicalHost(app)
+ all, err := c.Instances(ctx, app.Slug)
+ if err != nil {
+ return Snapshot{}, nil, nil, err
+ }
+ // The canonical host is the record's own host or its public alias.
+ var rec *carlosop.Instance
+ for i := range all {
+ if all[i].Host == host || all[i].PublicHost == host {
+ if rec != nil {
+ return Snapshot{}, nil, nil, errors.New("adopt: more than one instance record answers for the canonical host")
+ }
+ rec = &all[i]
+ }
+ }
+ if rec == nil {
+ return Snapshot{}, all, []string{"instance-missing"}, nil
+ }
+ eff, err := c.Effective(ctx, app.Slug, rec.Host)
+ if err != nil {
+ return Snapshot{}, nil, nil, err
+ }
+ snap := Snapshot{Identity: IdentityOf(*rec, eff), Layers: map[string]string{}, Vars: eff.Vars, At: time.Now().UTC()}
+ for k, v := range eff.Layers {
+ snap.Layers[k] = v
+ }
+ iss := findVar(eff.Vars, app.Prefix+"_HOME_ISSUER")
+ switch {
+ case iss == nil:
+ return snap, all, []string{"home-issuer-mismatch"}, nil
+ case iss.From == "overlay":
+ return snap, all, []string{"layer-overlay"}, nil
+ case iss.From == "environment":
+ snap.WriteLayer = eff.Environment
+ }
+ read := func(name string) (carlosop.Layer, error) {
+ env := ""
+ if name == "environment" {
+ env = eff.Environment
+ }
+ l, err := c.Config(ctx, app.Slug, env)
+ if err != nil {
+ return carlosop.Layer{}, err
+ }
+ // Two reads of one layer: if it moved between them, the
+ // snapshot would describe no single moment.
+ if l.Version != eff.Layers[name] {
+ return carlosop.Layer{}, errors.New("adopt: the config changed while it was being read; read it again")
+ }
+ return l, nil
+ }
+ if snap.Layer, err = read(layerName(snap.WriteLayer)); err != nil {
+ return Snapshot{}, nil, nil, err
+ }
+ snap.HomeIssuer = plainValue(snap.Layer, iss)
+ // The overlay's plain values are not readable, so a consumer ID that
+ // comes from it stays "" and is refused.
+ if cons := findVar(eff.Vars, app.Prefix+"_HOME_CONSUMER_ID"); cons != nil && cons.From != "overlay" {
+ src := snap.Layer
+ if cons.From != layerName(snap.WriteLayer) {
+ if src, err = read(cons.From); err != nil {
+ return Snapshot{}, nil, nil, err
+ }
+ }
+ snap.HomeConsumer = plainValue(src, cons)
+ }
+ if snap.Delivery, err = Probe(ctx, h, provision.PublicOrigin(provision.AdoptionLabel, app.Slug)); err != nil {
+ return Snapshot{}, nil, nil, err
+ }
+ return snap, all, nil, nil
+}
+
+// Observe reads one snapshot of app's canonical host: its instance
+// identity, the write layer and its stored vars, every layer's version,
+// the complete effective config by digest, the Home issuer and consumer
+// ID, and a delivery probe. A host whose write layer cannot be located is
+// an error naming the code.
+func Observe(ctx context.Context, c *carlosop.Client, h *http.Client, app provision.App) (Snapshot, error) {
+ snap, _, codes, err := observe(ctx, c, h, app)
+ if err != nil {
+ return Snapshot{}, err
+ }
+ if len(codes) > 0 {
+ return Snapshot{}, fmt.Errorf("adopt: cannot observe %s: %s", app.Slug, strings.Join(codes, ", "))
+ }
+ return snap, nil
+}
+
+// TeamModeKeys names the team-mode keys among vars, sorted: those
+// provision.TeamKeyNames lists and any other <P>_TEAM_ key. <P>_TEAM
+// itself (Memoria's) is not one.
+func TeamModeKeys(app provision.App, vars []carlosop.EffectiveVar) []string {
+ named := map[string]bool{}
+ for _, k := range provision.TeamKeyNames(app) {
+ named[k] = true
+ }
+ var out []string
+ for _, v := range vars {
+ if named[v.Key] || strings.HasPrefix(v.Key, app.Prefix+"_TEAM_") {
+ out = append(out, v.Key)
+ }
+ }
+ return sortedSet(out)
+}
+
+// inherits reports whether host eff would receive any of keys from a
+// write to writeLayer: the layer is in its chain, and nothing above it
+// in that chain already sets the key. What else the host overrides is
+// irrelevant.
+func inherits(eff carlosop.Effective, writeLayer string, keys [2]string) bool {
+ switch {
+ case writeLayer == "" && eff.Owned:
+ return false // an owned environment never folds the default in
+ case writeLayer != "" && eff.Environment != writeLayer:
+ return false
+ }
+ at := layerRank[layerName(writeLayer)]
+ for _, k := range keys {
+ if v := findVar(eff.Vars, k); v == nil || layerRank[v.From] <= at {
+ return true
+ }
+ }
+ return false
+}
+
+// Preflight observes app and lists every reason its configuration may
+// not be written, as fixed codes carrying key names and hosts only:
+//
+// - instance-missing, instance-moving, owned-environment, layer-overlay;
+// - home-issuer-mismatch, home-consumer-mismatch;
+// - team-mode-<KEY>;
+// - agent-keys-present, unless each present key is a plain var in the
+// write layer whose digest is EnvDigest(mine[key]) (the journal's own
+// sent values, on a resume);
+// - inherits-<host>, for every other instance a write would reach;
+// - version-header-mismatch, healthz.
+//
+// An error is a read that failed; it is not a refusal to guess past.
+func Preflight(ctx context.Context, c *carlosop.Client, h *http.Client, app provision.App, mine map[string]string) (Snapshot, []string, error) {
+ snap, all, codes, err := observe(ctx, c, h, app)
+ if err != nil || len(codes) > 0 {
+ return snap, codes, err
+ }
+ add := func(code string) { codes = append(codes, code) }
+ if snap.Identity.Moving {
+ add("instance-moving")
+ }
+ if snap.Identity.Owned {
+ add("owned-environment")
+ }
+ if snap.HomeIssuer != HomeIssuerOrigin {
+ add("home-issuer-mismatch")
+ }
+ if snap.HomeConsumer != provision.ConsumerID(provision.AdoptionLabel, app.Slug) {
+ add("home-consumer-mismatch")
+ }
+ for _, k := range TeamModeKeys(app, snap.Vars) {
+ add("team-mode-" + k)
+ }
+ keys := AgentKeys(app)
+ for _, k := range keys {
+ v := findVar(snap.Vars, k)
+ if v == nil {
+ continue
+ }
+ ours := mine[k] != "" && v.Kind == "env" && v.From == layerName(snap.WriteLayer) && v.Digest == carlosop.EnvDigest(mine[k])
+ if !ours {
+ add("agent-keys-present")
+ break
+ }
+ }
+ for _, in := range all {
+ if in.Host == snap.Identity.RecordHost {
+ continue
+ }
+ eff, err := c.Effective(ctx, app.Slug, in.Host)
+ if err != nil {
+ return snap, nil, err
+ }
+ if inherits(eff, snap.WriteLayer, keys) {
+ add("inherits-" + in.Host)
+ }
+ }
+ d := snap.Delivery
+ if d.Redirected || d.Version == "" || d.Version != d.Header {
+ add("version-header-mismatch")
+ }
+ if d.Health != http.StatusOK {
+ add("healthz")
+ }
+ return snap, sortedSet(codes), nil
+}
+
+// Preserved lists how after fails to preserve before, every key but the
+// two added: changed:<KEY> (digest), gone:<KEY>, kind:<KEY> and
+// from:<KEY> (the layer it comes from) in the effective config, the same
+// for the write layer's stored vars (which covers a stored key a higher
+// layer shadows), layer:<name> when a layer the write does not touch
+// moved, and SameIdentity's codes. Empty means preserved. A new key is
+// not a violation; NewKeys reports it.
+func Preserved(before, after Snapshot, added [2]string) []string {
+ skip := map[string]bool{added[0]: true, added[1]: true}
+ var out []string
+ effAfter := map[string]carlosop.EffectiveVar{}
+ for _, v := range after.Vars {
+ effAfter[v.Key] = v
+ }
+ for _, b := range before.Vars {
+ if skip[b.Key] {
+ continue
+ }
+ a, ok := effAfter[b.Key]
+ if !ok {
+ out = append(out, "gone:"+b.Key)
+ continue
+ }
+ if a.Kind != b.Kind {
+ out = append(out, "kind:"+b.Key)
+ }
+ if a.Digest != b.Digest {
+ out = append(out, "changed:"+b.Key)
+ }
+ if a.From != b.From {
+ out = append(out, "from:"+b.Key)
+ }
+ }
+ touched := layerName(before.WriteLayer)
+ if before.WriteLayer != after.WriteLayer || before.Layer.Bundle != after.Layer.Bundle {
+ out = append(out, "layer:"+touched)
+ } else {
+ stored := map[string]carlosop.Var{}
+ for _, v := range after.Layer.Vars {
+ stored[v.Key] = v
+ }
+ for _, b := range before.Layer.Vars {
+ if skip[b.Key] {
+ continue
+ }
+ a, ok := stored[b.Key]
+ switch {
+ case !ok:
+ out = append(out, "gone:"+b.Key)
+ continue
+ case a.Kind != b.Kind:
+ out = append(out, "kind:"+b.Key)
+ }
+ if a.Digest != b.Digest {
+ out = append(out, "changed:"+b.Key)
+ }
+ }
+ }
+ for _, m := range []map[string]string{before.Layers, after.Layers} {
+ for name := range m {
+ if name == touched {
+ continue
+ }
+ bv, bok := before.Layers[name]
+ av, aok := after.Layers[name]
+ if bok != aok || bv != av {
+ out = append(out, "layer:"+name)
+ }
+ }
+ }
+ out = append(out, SameIdentity(before.Identity, after.Identity)...)
+ return sortedSet(out)
+}
+
+// NewKeys lists the keys after holds that before did not, other than the
+// two added, as added:<KEY>, sorted. A platform writer's new key is
+// reported, never fatal.
+func NewKeys(before, after Snapshot, added [2]string) []string {
+ had := map[string]bool{added[0]: true, added[1]: true}
+ for _, v := range before.Vars {
+ had[v.Key] = true
+ }
+ for _, v := range before.Layer.Vars {
+ had[v.Key] = true
+ }
+ var out []string
+ for _, v := range after.Vars {
+ if !had[v.Key] {
+ out = append(out, "added:"+v.Key)
+ }
+ }
+ for _, v := range after.Layer.Vars {
+ if !had[v.Key] {
+ out = append(out, "added:"+v.Key)
+ }
+ }
+ return sortedSet(out)
+}
+
+// sortedSet sorts s and drops repeats; nil for none.
+func sortedSet(s []string) []string {
+ if len(s) == 0 {
+ return nil
+ }
+ sort.Strings(s)
+ out := s[:1]
+ for _, v := range s[1:] {
+ if v != out[len(out)-1] {
+ out = append(out, v)
+ }
+ }
+ return out
+}
diff --git a/adopt/snapshot_test.go b/adopt/snapshot_test.go
new file mode 100644
index 0000000..a337442
--- /dev/null
+++ b/adopt/snapshot_test.go
@@ -0,0 +1,545 @@
+package adopt
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/alta/carlosop"
+ "amadan.net/oficina/alta/carlosop/fakecarlos"
+ "amadan.net/oficina/alta/provision"
+)
+
+// carlosFixture is one app on a fake console, with its canonical instance
+// on the default bundle and a fake origin answering every probe.
+type carlosFixture struct {
+ f *fakecarlos.Fake
+ c *carlosop.Client
+ h *http.Client
+ site *site
+ app provision.App
+}
+
+const (
+ fixtureAccount = "bds"
+ // Plain values seeded into the fake: none may appear in any output.
+ valueOrigin = "https://docs.oficina.works/plain-origin-value"
+ valueVersion = "v1.4.0"
+)
+
+func appNamed(t *testing.T, slug string) provision.App {
+ t.Helper()
+ a, ok := provision.AppBySlug(slug)
+ if !ok {
+ t.Fatalf("no app %q", slug)
+ }
+ return a
+}
+
+func newCarlosFixture(t *testing.T, slug string) *carlosFixture {
+ t.Helper()
+ app := appNamed(t, slug)
+ f := fakecarlos.New(fixtureAccount)
+ t.Cleanup(f.Close)
+ p := app.Prefix
+ f.SetVar(app.Slug, "", p+"_HOME_ISSUER", HomeIssuerOrigin)
+ f.SetVar(app.Slug, "", p+"_HOME_CONSUMER_ID", provision.ConsumerID(provision.AdoptionLabel, app.Slug))
+ f.SetVar(app.Slug, "", p+"_ORIGIN", valueOrigin)
+ f.SetSecret(app.Slug, "", p+"_INSTANCE_KEY")
+ f.AddInstance(carlosop.Instance{
+ Host: CanonicalHost(app), App: app.Slug, Slug: "s-" + app.Slug, Channel: "stable", Region: "eu",
+ CreatedAt: time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC), RecordSeq: 4,
+ ReplicaAssignment: json.RawMessage(`{"boxes":["b1"]}`),
+ })
+ c := carlosop.New(f.URL(), fixtureAccount, f.Token())
+ t.Cleanup(c.Close)
+
+ s := &site{version: valueVersion, header: valueVersion, health: 200}
+ srv := httptest.NewTLSServer(s.handler())
+ t.Cleanup(srv.Close)
+ tr := srv.Client().Transport.(*http.Transport).Clone()
+ addr := srv.Listener.Addr().String()
+ // Every https origin the probe names lands on the fake site.
+ tr.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) {
+ var d net.Dialer
+ return d.DialContext(ctx, network, addr)
+ }
+ tr.TLSClientConfig.ServerName = "example.com"
+ return &carlosFixture{f: f, c: c, h: &http.Client{Transport: tr, Timeout: 10 * time.Second}, site: s, app: app}
+}
+
+// neighbour adds another instance of the fixture's app on env (""= none).
+func (x *carlosFixture) neighbour(host, env string) {
+ x.f.AddInstance(carlosop.Instance{Host: host, App: x.app.Slug, Slug: "s-" + host, Environment: env,
+ Channel: "stable", Region: "eu", CreatedAt: time.Date(2026, 4, 1, 0, 0, 0, 0, time.UTC)})
+}
+
+func (x *carlosFixture) preflight(t *testing.T, mine map[string]string) (Snapshot, []string) {
+ t.Helper()
+ snap, codes, err := Preflight(context.Background(), x.c, x.h, x.app, mine)
+ if err != nil {
+ t.Fatalf("Preflight: %v", err)
+ }
+ return snap, codes
+}
+
+func TestPreflightPassesCleanApp(t *testing.T) {
+ x := newCarlosFixture(t, "docs")
+ snap, codes := x.preflight(t, nil)
+ wantCodes(t, codes)
+ if snap.WriteLayer != "" || snap.Layer.Bundle != "default" || snap.HomeIssuer != HomeIssuerOrigin || snap.HomeConsumer != "docs" {
+ t.Fatalf("snapshot write layer %q bundle %q", snap.WriteLayer, snap.Layer.Bundle)
+ }
+ if snap.Identity.RecordHost != "docs.oficina.works" || snap.Delivery.Version != valueVersion || snap.At.IsZero() {
+ t.Fatalf("snapshot identity/delivery not recorded")
+ }
+ if len(snap.Vars) != 4 || len(snap.Layers) != 2 {
+ t.Fatalf("vars %d layers %d", len(snap.Vars), len(snap.Layers))
+ }
+}
+
+func TestPreflightFindsCanonicalAlias(t *testing.T) {
+ x := newCarlosFixture(t, "docs")
+ x.f = fakecarlos.New(fixtureAccount)
+ t.Cleanup(x.f.Close)
+ x.f.SetVar("docs", "", "DOCS_HOME_ISSUER", HomeIssuerOrigin)
+ x.f.SetVar("docs", "", "DOCS_HOME_CONSUMER_ID", "docs")
+ x.f.AddInstance(carlosop.Instance{Host: "docs-1.carlos.run", PublicHost: "docs.oficina.works", App: "docs", Slug: "s", Channel: "stable"})
+ x.f.AddInstance(carlosop.Instance{Host: "other.carlos.run", App: "docs", Slug: "o", Environment: "o", Channel: "stable"})
+ x.f.Own("docs", "o", "alta")
+ x.c = carlosop.New(x.f.URL(), fixtureAccount, x.f.Token())
+ t.Cleanup(x.c.Close)
+ snap, codes := x.preflight(t, nil)
+ wantCodes(t, codes)
+ if snap.Identity.RecordHost != "docs-1.carlos.run" || snap.Identity.PublicHost != "docs.oficina.works" {
+ t.Fatalf("record %q alias %q", snap.Identity.RecordHost, snap.Identity.PublicHost)
+ }
+}
+
+// Review focus 1: a neighbour overriding another key still inherits both
+// agent keys from the shared default.
+func TestPreflightRefusesInheritanceDespiteOtherOverride(t *testing.T) {
+ x := newCarlosFixture(t, "docs")
+ x.neighbour("staging.docs.example", "staging")
+ x.f.SetVar("docs", "staging", "DOCS_HOME_ISSUER", "https://id.staging.example")
+ _, codes := x.preflight(t, nil)
+ wantCodes(t, codes, "inherits-staging.docs.example")
+}
+
+func TestPreflightRefusesUnboundNeighbour(t *testing.T) {
+ x := newCarlosFixture(t, "docs")
+ x.neighbour("bare.docs.example", "")
+ _, codes := x.preflight(t, nil)
+ wantCodes(t, codes, "inherits-bare.docs.example")
+}
+
+func TestPreflightRefusesNeighbourShadowingOneKey(t *testing.T) {
+ x := newCarlosFixture(t, "docs")
+ x.neighbour("staging.docs.example", "staging")
+ x.f.SetVar("docs", "staging", "DOCS_AGENT_ISSUER", "https://connect.staging.example")
+ _, codes := x.preflight(t, nil)
+ wantCodes(t, codes, "inherits-staging.docs.example")
+}
+
+func TestPreflightAllowsOwnedEnvironmentNeighbour(t *testing.T) {
+ x := newCarlosFixture(t, "docs")
+ x.neighbour("acme.docs.oficina.works", "acme-docs")
+ x.f.SetVar("docs", "acme-docs", "DOCS_HOME_ISSUER", HomeIssuerOrigin)
+ x.f.Own("docs", "acme-docs", "alta")
+ _, codes := x.preflight(t, nil)
+ wantCodes(t, codes)
+}
+
+func TestPreflightAllowsNeighbourThatAlreadyShadowsBothKeys(t *testing.T) {
+ x := newCarlosFixture(t, "docs")
+ x.neighbour("staging.docs.example", "staging")
+ x.f.SetVar("docs", "staging", "DOCS_AGENT_ISSUER", "https://connect.staging.example")
+ x.f.SetVar("docs", "staging", "DOCS_AGENT_TEAM", "stg")
+ _, codes := x.preflight(t, nil)
+ wantCodes(t, codes)
+}
+
+// A write to a named environment reaches only that environment's routes.
+func TestPreflightNamedWriteLayerInheritance(t *testing.T) {
+ x := newCarlosFixture(t, "docs")
+ x.f = fakecarlos.New(fixtureAccount)
+ t.Cleanup(x.f.Close)
+ x.f.SetVar("docs", "prod", "DOCS_HOME_ISSUER", HomeIssuerOrigin)
+ x.f.SetVar("docs", "prod", "DOCS_HOME_CONSUMER_ID", "docs")
+ x.f.SetVar("docs", "other", "DOCS_ORIGIN", "x")
+ x.f.AddInstance(carlosop.Instance{Host: "docs.oficina.works", App: "docs", Slug: "s", Environment: "prod", Channel: "stable"})
+ x.f.AddInstance(carlosop.Instance{Host: "other.docs.example", App: "docs", Slug: "o", Environment: "other", Channel: "stable"})
+ x.f.AddInstance(carlosop.Instance{Host: "bare.docs.example", App: "docs", Slug: "b", Channel: "stable"})
+ x.c = carlosop.New(x.f.URL(), fixtureAccount, x.f.Token())
+ t.Cleanup(x.c.Close)
+ snap, codes := x.preflight(t, nil)
+ wantCodes(t, codes)
+ if snap.WriteLayer != "prod" || snap.Layer.Bundle != "prod" {
+ t.Fatalf("write layer %q", snap.WriteLayer)
+ }
+ x.f.AddInstance(carlosop.Instance{Host: "twin.docs.example", App: "docs", Slug: "t", Environment: "prod", Channel: "stable"})
+ _, codes = x.preflight(t, nil)
+ wantCodes(t, codes, "inherits-twin.docs.example")
+}
+
+func TestPreflightRefusesTeamMode(t *testing.T) {
+ x := newCarlosFixture(t, "docs")
+ x.f.SetVar("docs", "", "DOCS_TEAM_ID", "abc")
+ x.f.SetVar("docs", "", "DOCS_TEAM_SOMETHING_NEW", "1")
+ _, codes := x.preflight(t, nil)
+ wantCodes(t, codes, "team-mode-DOCS_TEAM_ID", "team-mode-DOCS_TEAM_SOMETHING_NEW")
+
+ m := newCarlosFixture(t, "memoria")
+ m.f.SetVar("memoria", "", "MEMORIA_TEAM", "on")
+ _, codes = m.preflight(t, nil)
+ wantCodes(t, codes)
+ m.f.SetSecret("memoria", "", "MEMORIA_TEAM_ROSTER_TOKEN")
+ _, codes = m.preflight(t, nil)
+ wantCodes(t, codes, "team-mode-MEMORIA_TEAM_ROSTER_TOKEN")
+}
+
+func TestTeamModeKeys(t *testing.T) {
+ app := appNamed(t, "calls")
+ got := TeamModeKeys(app, []carlosop.EffectiveVar{
+ {Key: "CALLS_TEAM"}, {Key: "CALLS_TEAM_ZZ"}, {Key: "CALLS_TEAM_ID"}, {Key: "DOCS_TEAM_ID"}, {Key: "CALLS_ORIGIN"},
+ })
+ if !reflect.DeepEqual(got, []string{"CALLS_TEAM_ID", "CALLS_TEAM_ZZ"}) {
+ t.Fatalf("team keys = %q", got)
+ }
+}
+
+func TestPreflightRefusesForeignAgentKeys(t *testing.T) {
+ mine := map[string]string{"DOCS_AGENT_ISSUER": Issuer, "DOCS_AGENT_TEAM": "tQ3"}
+
+ x := newCarlosFixture(t, "docs")
+ x.f.SetVar("docs", "", "DOCS_AGENT_ISSUER", Issuer)
+ x.f.SetVar("docs", "", "DOCS_AGENT_TEAM", "someone-else")
+ _, codes := x.preflight(t, mine)
+ wantCodes(t, codes, "agent-keys-present")
+ _, codes = x.preflight(t, nil)
+ wantCodes(t, codes, "agent-keys-present")
+
+ // The journal's own sent values, on a resume, pass.
+ x.f.SetVar("docs", "", "DOCS_AGENT_TEAM", "tQ3")
+ _, codes = x.preflight(t, mine)
+ wantCodes(t, codes)
+
+ // The same value as a secret is not ours.
+ x.f.SetSecret("docs", "", "DOCS_AGENT_TEAM")
+ _, codes = x.preflight(t, mine)
+ wantCodes(t, codes, "agent-keys-present")
+
+ // Our value, but from a layer above the write layer: not ours either.
+ y := newCarlosFixture(t, "docs")
+ y.f.SetOverlay("docs", "docs.oficina.works", "DOCS_AGENT_ISSUER", Issuer)
+ _, codes = y.preflight(t, mine)
+ wantCodes(t, codes, "agent-keys-present")
+}
+
+func TestPreflightRefusesMovingInstance(t *testing.T) {
+ x := newCarlosFixture(t, "docs")
+ x.f.AddInstance(carlosop.Instance{Host: "docs.oficina.works", App: "docs", Slug: "s-docs", Channel: "stable", Region: "eu",
+ Move: json.RawMessage(`{"to":"us"}`)})
+ _, codes := x.preflight(t, nil)
+ wantCodes(t, codes, "instance-moving")
+}
+
+func TestPreflightRefusesEachConfigCode(t *testing.T) {
+ cases := map[string]struct {
+ edit func(x *carlosFixture)
+ want []string
+ }{
+ "instance-missing": {func(x *carlosFixture) {
+ x.f = fakecarlos.New(fixtureAccount)
+ x.f.SetVar("docs", "", "DOCS_HOME_ISSUER", HomeIssuerOrigin)
+ x.f.AddInstance(carlosop.Instance{Host: "elsewhere.docs.example", App: "docs", Slug: "e", Channel: "stable"})
+ x.c = carlosop.New(x.f.URL(), fixtureAccount, x.f.Token())
+ }, []string{"instance-missing"}},
+ "layer-overlay": {func(x *carlosFixture) {
+ x.f.SetOverlay("docs", "docs.oficina.works", "DOCS_HOME_ISSUER", HomeIssuerOrigin)
+ }, []string{"layer-overlay"}},
+ "home-issuer-absent": {func(x *carlosFixture) {
+ x.f.Unset("docs", "", "DOCS_HOME_ISSUER")
+ }, []string{"home-issuer-mismatch"}},
+ "home-issuer-other": {func(x *carlosFixture) {
+ x.f.SetVar("docs", "", "DOCS_HOME_ISSUER", "https://id.example")
+ }, []string{"home-issuer-mismatch"}},
+ "home-issuer-secret": {func(x *carlosFixture) {
+ x.f.SetSecret("docs", "", "DOCS_HOME_ISSUER")
+ }, []string{"home-issuer-mismatch"}},
+ "home-consumer-other": {func(x *carlosFixture) {
+ x.f.SetVar("docs", "", "DOCS_HOME_CONSUMER_ID", "oficina-docs")
+ }, []string{"home-consumer-mismatch"}},
+ "home-consumer-absent": {func(x *carlosFixture) {
+ x.f.Unset("docs", "", "DOCS_HOME_CONSUMER_ID")
+ }, []string{"home-consumer-mismatch"}},
+ "home-consumer-overlay": {func(x *carlosFixture) {
+ x.f.SetOverlay("docs", "docs.oficina.works", "DOCS_HOME_CONSUMER_ID", "docs")
+ }, []string{"home-consumer-mismatch"}},
+ "owned-environment": {func(x *carlosFixture) {
+ x.f.AddInstance(carlosop.Instance{Host: "docs.oficina.works", App: "docs", Slug: "s-docs", Environment: "mine", Channel: "stable"})
+ x.f.SetVar("docs", "mine", "DOCS_HOME_ISSUER", HomeIssuerOrigin)
+ x.f.SetVar("docs", "mine", "DOCS_HOME_CONSUMER_ID", "docs")
+ x.f.Own("docs", "mine", "alta")
+ }, []string{"owned-environment"}},
+ "version-header-mismatch": {func(x *carlosFixture) { x.site.header = "v1.3.9" }, []string{"version-header-mismatch"}},
+ "version-empty": {func(x *carlosFixture) { x.site.version, x.site.header = "", "" }, []string{"version-header-mismatch"}},
+ "version-redirect": {func(x *carlosFixture) { x.site.redirectVersion = true }, []string{"version-header-mismatch"}},
+ "ops-redirect": {func(x *carlosFixture) {
+ x.site.ops = func(w http.ResponseWriter) { w.Header().Set("Location", "/elsewhere"); w.WriteHeader(http.StatusFound) }
+ }, []string{"version-header-mismatch"}},
+ "healthz": {func(x *carlosFixture) { x.site.health = 503 }, []string{"healthz"}},
+ }
+ for name, c := range cases {
+ t.Run(name, func(t *testing.T) {
+ x := newCarlosFixture(t, "docs")
+ c.edit(x)
+ t.Cleanup(x.f.Close)
+ t.Cleanup(x.c.Close)
+ _, codes := x.preflight(t, nil)
+ wantCodes(t, codes, c.want...)
+ })
+ }
+}
+
+func TestPreflightErrorsOnUnreadableNeighbour(t *testing.T) {
+ x := newCarlosFixture(t, "docs")
+ // Bound to an environment that was never created: the console answers
+ // 502 for its view, and the run stops rather than guess.
+ x.neighbour("ghost.docs.example", "ghost")
+ _, _, err := Preflight(context.Background(), x.c, x.h, x.app, nil)
+ if err == nil {
+ t.Fatal("an unreadable neighbour passed")
+ }
+}
+
+func TestObserveRefusesWithoutWriteLayer(t *testing.T) {
+ x := newCarlosFixture(t, "docs")
+ x.f.SetOverlay("docs", "docs.oficina.works", "DOCS_HOME_ISSUER", HomeIssuerOrigin)
+ if _, err := Observe(context.Background(), x.c, x.h, x.app); err == nil || !strings.Contains(err.Error(), "layer-overlay") {
+ t.Fatalf("Observe = %v", err)
+ }
+ y := newCarlosFixture(t, "docs")
+ snap, err := Observe(context.Background(), y.c, y.h, y.app)
+ if err != nil || snap.Layer.Version == "" || snap.Identity.Slug != "s-docs" {
+ t.Fatalf("Observe = %v", err)
+ }
+}
+
+func TestPreflightOutputHasNoValuesOrDigests(t *testing.T) {
+ x := newCarlosFixture(t, "docs")
+ x.f.SetVar("docs", "", "DOCS_AGENT_TEAM", "foreign-team-value")
+ x.f.SetVar("docs", "", "DOCS_TEAM_ID", "team-id-value")
+ x.f.SetVar("docs", "", "DOCS_HOME_CONSUMER_ID", "consumer-value")
+ x.neighbour("staging.docs.example", "staging")
+ x.f.SetVar("docs", "staging", "DOCS_HOME_ISSUER", "https://issuer-value.example")
+ x.site.header = "header-value"
+ x.site.health = 500
+ _, codes, err := Preflight(context.Background(), x.c, x.h, x.app, map[string]string{"DOCS_AGENT_TEAM": "mine-value"})
+ if err != nil {
+ t.Fatalf("Preflight: %v", err)
+ }
+ if len(codes) < 5 {
+ t.Fatalf("codes = %q", codes)
+ }
+ out := strings.Join(codes, " ")
+ for _, bad := range []string{"vd1:", "cv1:", "-value", valueOrigin, valueVersion, HomeIssuerOrigin, x.f.URL(), string(x.f.Token())} {
+ if strings.Contains(out, bad) {
+ t.Fatalf("codes carry %q: %q", bad, out)
+ }
+ }
+ // And the errors: an Observe that refuses names codes only.
+ x.f.SetOverlay("docs", "docs.oficina.works", "DOCS_HOME_ISSUER", "https://overlay-value.example")
+ _, err = Observe(context.Background(), x.c, x.h, x.app)
+ if err == nil {
+ t.Fatal("Observe passed an overlay issuer")
+ }
+ for _, bad := range []string{"vd1:", "cv1:", "-value", x.f.URL()} {
+ if strings.Contains(err.Error(), bad) {
+ t.Fatalf("error carries %q: %v", bad, err)
+ }
+ }
+}
+
+// ---- Preserved and NewKeys ----
+
+const (
+ dA = "vd1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+ dB = "vd1:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
+ dC = "vd1:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
+ vA = "cv1:1111111111111111111111111111111111111111111111111111111111111111"
+ vB = "cv1:2222222222222222222222222222222222222222222222222222222222222222"
+ vC = "cv1:3333333333333333333333333333333333333333333333333333333333333333"
+)
+
+var added = [2]string{"DOCS_AGENT_ISSUER", "DOCS_AGENT_TEAM"}
+
+// beforeSnap is a canonical host on default, with an environment layer
+// it does not write and an overlay.
+func beforeSnap() Snapshot {
+ id, eff := inst()
+ return Snapshot{
+ Identity: IdentityOf(id, eff),
+ WriteLayer: "",
+ Layer: carlosop.Layer{Bundle: "default", Version: vA, Vars: []carlosop.Var{
+ {Key: "DOCS_HOME_ISSUER", Kind: "env", Digest: dA},
+ {Key: "DOCS_KEY", Kind: "secret", Digest: dB},
+ {Key: "DOCS_SHADOWED", Kind: "env", Digest: dA},
+ }},
+ Layers: map[string]string{"default": vA, "environment": vB, "overlay": "none"},
+ Vars: []carlosop.EffectiveVar{
+ {Key: "DOCS_HOME_ISSUER", Kind: "env", Digest: dA, From: "default"},
+ {Key: "DOCS_KEY", Kind: "secret", Digest: dB, From: "default"},
+ {Key: "DOCS_SHADOWED", Kind: "env", Digest: dC, From: "environment", Shadows: []string{"default"}},
+ {Key: "DOCS_ZONE", Kind: "env", Digest: dC, From: "environment"},
+ },
+ }
+}
+
+// afterSnap is beforeSnap with the two agent keys written to default.
+func afterSnap() Snapshot {
+ s := beforeSnap()
+ s.Layer.Version = vC
+ s.Layer.Vars = append(append([]carlosop.Var{}, s.Layer.Vars...),
+ carlosop.Var{Key: "DOCS_AGENT_ISSUER", Kind: "env", Digest: dA}, carlosop.Var{Key: "DOCS_AGENT_TEAM", Kind: "env", Digest: dB})
+ s.Layers = map[string]string{"default": vC, "environment": vB, "overlay": "none"}
+ s.Vars = append(append([]carlosop.EffectiveVar{}, s.Vars...),
+ carlosop.EffectiveVar{Key: "DOCS_AGENT_ISSUER", Kind: "env", Digest: dA, From: "default"},
+ carlosop.EffectiveVar{Key: "DOCS_AGENT_TEAM", Kind: "env", Digest: dB, From: "default"})
+ return s
+}
+
+func effVar(s *Snapshot, key string) *carlosop.EffectiveVar {
+ for i := range s.Vars {
+ if s.Vars[i].Key == key {
+ return &s.Vars[i]
+ }
+ }
+ return nil
+}
+
+func TestPreservedAcceptsTheWrite(t *testing.T) {
+ if v := Preserved(beforeSnap(), afterSnap(), added); len(v) != 0 {
+ t.Fatalf("violations = %q", v)
+ }
+ if v := Preserved(beforeSnap(), beforeSnap(), added); len(v) != 0 {
+ t.Fatalf("violations = %q", v)
+ }
+}
+
+func TestPreservedReportsEachViolation(t *testing.T) {
+ cases := map[string]struct {
+ edit func(a *Snapshot)
+ want []string
+ }{
+ "changed": {func(a *Snapshot) { effVar(a, "DOCS_KEY").Digest = dC }, []string{"changed:DOCS_KEY"}},
+ "gone": {func(a *Snapshot) {
+ kept := a.Vars[:0]
+ for _, v := range a.Vars {
+ if v.Key != "DOCS_ZONE" {
+ kept = append(kept, v)
+ }
+ }
+ a.Vars = kept
+ }, []string{"gone:DOCS_ZONE"}},
+ "kind": {func(a *Snapshot) { effVar(a, "DOCS_HOME_ISSUER").Kind = "secret" }, []string{"kind:DOCS_HOME_ISSUER"}},
+ "from": {func(a *Snapshot) { effVar(a, "DOCS_ZONE").From = "overlay" }, []string{"from:DOCS_ZONE"}},
+ "shadowed-in-write-layer": {func(a *Snapshot) {
+ for i := range a.Layer.Vars {
+ if a.Layer.Vars[i].Key == "DOCS_SHADOWED" {
+ a.Layer.Vars[i].Digest = dB
+ }
+ }
+ }, []string{"changed:DOCS_SHADOWED"}},
+ "gone-from-write-layer": {func(a *Snapshot) { a.Layer.Vars = a.Layer.Vars[1:] }, []string{"gone:DOCS_HOME_ISSUER"}},
+ "layer-environment": {func(a *Snapshot) { a.Layers["environment"] = vA }, []string{"layer:environment"}},
+ "layer-overlay": {func(a *Snapshot) { a.Layers["overlay"] = vA }, []string{"layer:overlay"}},
+ "layer-dropped": {func(a *Snapshot) { delete(a.Layers, "environment") }, []string{"layer:environment"}},
+ "identity": {func(a *Snapshot) {
+ a.Identity.Slug = "other"
+ a.Identity.RecordSeq++
+ }, []string{"record", "storage"}},
+ "several": {func(a *Snapshot) {
+ effVar(a, "DOCS_KEY").Digest = dC
+ effVar(a, "DOCS_ZONE").Kind = "secret"
+ a.Identity.Moving = true
+ }, []string{"changed:DOCS_KEY", "kind:DOCS_ZONE", "moving"}},
+ }
+ for name, c := range cases {
+ t.Run(name, func(t *testing.T) {
+ a := afterSnap()
+ c.edit(&a)
+ wantCodes(t, Preserved(beforeSnap(), a, added), c.want...)
+ })
+ }
+}
+
+func TestPreservedIgnoresNewUnrelatedKey(t *testing.T) {
+ a := afterSnap()
+ a.Vars = append(a.Vars, carlosop.EffectiveVar{Key: "DOCS_SMTP_HOST", Kind: "env", Digest: dA, From: "default"})
+ a.Layer.Vars = append(a.Layer.Vars, carlosop.Var{Key: "DOCS_SMTP_HOST", Kind: "env", Digest: dA})
+ if v := Preserved(beforeSnap(), a, added); len(v) != 0 {
+ t.Fatalf("violations = %q", v)
+ }
+ if got := NewKeys(beforeSnap(), a, added); !reflect.DeepEqual(got, []string{"added:DOCS_SMTP_HOST"}) {
+ t.Fatalf("new keys = %q", got)
+ }
+ if got := NewKeys(beforeSnap(), afterSnap(), added); len(got) != 0 {
+ t.Fatalf("new keys = %q", got)
+ }
+}
+
+// The two added keys are exempt only as additions: present before the
+// write and changed after, they are violations like any other key.
+func TestPreservedExemptsOnlyTheTwoAdded(t *testing.T) {
+ b := afterSnap()
+ a := afterSnap()
+ effVar(&a, "DOCS_AGENT_TEAM").Digest = dC
+ if v := Preserved(b, a, added); len(v) != 0 {
+ t.Fatalf("an added key is preserved-checked: %q", v)
+ }
+ wantCodes(t, Preserved(b, a, [2]string{"DOCS_AGENT_ISSUER", "DOCS_OTHER"}), "changed:DOCS_AGENT_TEAM")
+}
+
+// A platform writer landing between the effective read and the layer's
+// read leaves no single moment to describe: Observe errors, never mixes.
+func TestPreflightErrorsWhenLayerMovesBetweenReads(t *testing.T) {
+ x := newCarlosFixture(t, "docs")
+ moved := false
+ proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/config") && !moved {
+ moved = true
+ x.f.PlatformWrite("docs", "", "DOCS_SMTP_HOST", "smtp.example")
+ }
+ req, _ := http.NewRequestWithContext(r.Context(), r.Method, x.f.URL()+r.URL.RequestURI(), r.Body)
+ req.Header = r.Header.Clone()
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ w.WriteHeader(502)
+ return
+ }
+ defer resp.Body.Close()
+ w.WriteHeader(resp.StatusCode)
+ _, _ = io.Copy(w, resp.Body)
+ }))
+ t.Cleanup(proxy.Close)
+ c := carlosop.New(proxy.URL, fixtureAccount, x.f.Token())
+ t.Cleanup(c.Close)
+ if _, _, err := Preflight(context.Background(), c, x.h, x.app, nil); err == nil {
+ t.Fatal("a layer that moved between reads passed")
+ }
+ if !moved {
+ t.Fatal("the proxy never saw the layer read")
+ }
+ // The next read is coherent again.
+ if _, codes, err := Preflight(context.Background(), c, x.h, x.app, nil); err != nil || len(codes) != 0 {
+ t.Fatalf("Preflight = %q, %v", codes, err)
+ }
+}
diff --git a/adopt/types.go b/adopt/types.go
index 3413262..f5e5ee4 100644
--- a/adopt/types.go
+++ b/adopt/types.go
@@ -79,6 +79,15 @@ func canonical(raw json.RawMessage) string {
// storage (slug, created_at, replica, seed), instance (record host, and
// account or app), alias (public host), environment, owned, channel,
// region, moving and record (the record's sequence).
+//
+// record stays in (Task 7 step 0, read at carlos/platform config-receipts-1
+// 8e229fdb): record_seq advances only through provision.WriteRecord, and
+// neither of the runner's own writes calls it. PUT /config
+// (console/apiconfig.go handleAPIConfigPut) writes the config bundle and
+// bumps the serial; POST /restart/scope (console/apirestartscope.go)
+// appends to the app's restart-scope.json log and bumps the serial, and
+// the boxes cycle units without writing the record (internal/host). So a
+// moved record_seq means some other writer touched the record.
func SameIdentity(a, b Identity) []string {
set := map[string]bool{}
flag := func(differs bool, code string) {