adopt: rollback checks preserved keys first; retries re-run preflight
ClassifyRollback now takes 522 §4.7's preserved-first order: a changed preserved key stops the rollback before any unset. A write's retry after a 412 or lost answer re-runs every preflight refusal on a fresh read and classifies that read again before it sends, so a team-mode key or an inheriting neighbour that appeared in between never gets the keys.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2 files changed,
+210
−33
adopt/write.go+70 −32adopt/write_test.go+140 −1
diff --git a/adopt/write.go b/adopt/write.go| index a497122..d6153c5 100644 |
| --- a/adopt/write.go |
| +++ b/adopt/write.go |
| @@ -36,21 +36,23 @@ const ( |
| StopConflict |
| ) |
| -// RollbackBranch is what a reread says of a rollback. The first that |
| -// matches wins, in this order. The zero value is none of them. |
| +// RollbackBranch is what a reread says of a rollback. As for the write, |
| +// the first that matches wins, preserved keys first. The zero value is |
| +// none of them. |
| type RollbackBranch int |
| const ( |
| - // RetryUnset: both agent keys hold exactly what the write sent. |
| + // RetryUnset: every preserved key equals the baseline and both agent |
| + // keys hold exactly what the write sent. |
| RetryUnset RollbackBranch = iota + 1 |
| - // RolledBack: both agent keys are absent and every preserved key |
| - // equals the baseline. |
| + // RolledBack: every preserved key equals the baseline and both agent |
| + // keys are absent. |
| RolledBack |
| // StopForeign: one key alone is present, or either holds another |
| // digest or kind. The runner never unsets a value it did not write. |
| StopForeign |
| - // StopPreservedChanged: both keys are absent but a preserved key |
| - // changed, so the layer is not back at the baseline. |
| + // RollbackStopPreservedChanged: a preserved key changed or went. |
| + // Nothing is unset; a person looks first. |
| RollbackStopPreservedChanged |
| ) |
| @@ -130,23 +132,24 @@ func Classify(baseline, read carlosop.Layer, sent map[string]string) Branch { |
| return StopConflict |
| } |
| -// ClassifyRollback takes the first matching rollback branch. Our keys |
| -// are unset whatever else moved: a rollback stops delegated access, and |
| -// refusing it because a platform writer resealed some other key would |
| -// leave that access live. |
| +// ClassifyRollback takes the first matching rollback branch, preserved |
| +// keys first (522 §4.7's rule, which binds the rollback too): a |
| +// preserved key that changed stops the rollback, even with our keys |
| +// still in place, for a person to investigate. |
| func ClassifyRollback(baseline, read carlosop.Layer, sent map[string]string) RollbackBranch { |
| + if !preservedEqual(baseline, read, sent) { |
| + return RollbackStopPreservedChanged |
| + } |
| mine, absent := agentState(read, sent) |
| switch { |
| case len(sent) != 2: |
| return StopForeign |
| case mine == 2: |
| return RetryUnset |
| - case absent == 2 && preservedEqual(baseline, read, sent): |
| + case absent == 2: |
| return RolledBack |
| - case absent != 2: |
| - return StopForeign |
| } |
| - return RollbackStopPreservedChanged |
| + return StopForeign |
| } |
| // The journal's states move one way only. A write is sent, then landed |
| @@ -339,29 +342,22 @@ func WriteAgentKeys(ctx context.Context, c *carlosop.Client, h *http.Client, s * |
| if have { |
| mine = rec.Sent |
| } |
| - fresh, codes, err := Preflight(ctx, c, h, app, mine) |
| + base, ok, err := s.Baseline(ctx, app.Slug) |
| if err != nil { |
| return "", err |
| } |
| - if len(codes) > 0 { |
| - return "", errors.New("adopt: configure refused: " + strings.Join(codes, ", ")) |
| + var against *Snapshot |
| + if ok { |
| + against = &base |
| } |
| - base, ok, err := s.Baseline(ctx, app.Slug) |
| + fresh, codes, err := admit(ctx, c, h, app, mine, against) |
| if err != nil { |
| return "", err |
| } |
| - if ok { |
| - var moved []string |
| - if base.WriteLayer != fresh.WriteLayer || base.Layer.Bundle != fresh.Layer.Bundle { |
| - moved = append(moved, "write-layer-moved") |
| - } |
| - for _, code := range SameIdentity(base.Identity, fresh.Identity) { |
| - moved = append(moved, "identity-"+code) |
| - } |
| - if len(moved) > 0 { |
| - return "", errors.New("adopt: configure refused: " + strings.Join(moved, ", ")) |
| - } |
| - } else { |
| + if len(codes) > 0 { |
| + return "", errors.New("adopt: configure refused: " + strings.Join(codes, ", ")) |
| + } |
| + if !ok { |
| base = fresh |
| } |
| summary := WriteSummary(keys, base.Layer.Bundle) |
| @@ -432,8 +428,50 @@ func WriteAgentKeys(ctx context.Context, c *carlosop.Client, h *http.Client, s * |
| } |
| return "", errors.New("adopt: retry-exhausted: the layer kept moving") |
| } |
| - ifVersion = read.Version |
| + // Whatever moved the layer may be a refusal of its own (a |
| + // team-mode key, a neighbour that would inherit): every preflight |
| + // refusal is enforced again, on a fresh read, before the retry. |
| + fresh, codes, err := admit(ctx, c, h, app, nil, &base) |
| + if err != nil { |
| + return "", err |
| + } |
| + if len(codes) > 0 { |
| + w.Code = "preflight-refused" |
| + if serr := advanceWrite(ctx, s, w); serr != nil { |
| + return "", serr |
| + } |
| + return "", errors.New("adopt: configure refused: " + strings.Join(codes, ", ")) |
| + } |
| + // The retry is conditional on the layer that read saw, so it is |
| + // classified again: anything else in between is a 412. |
| + switch Classify(base.Layer, fresh.Layer, sent) { |
| + case Retry: |
| + case StopPreservedChanged: |
| + return stop("preserved-changed", ErrStopPreserved) |
| + default: |
| + return stop("agent-keys-conflict", ErrStopConflict) |
| + } |
| + ifVersion = fresh.Layer.Version |
| + } |
| +} |
| + |
| +// admit runs Preflight on a fresh read and, given the journalled |
| +// baseline, adds write-layer-moved when the write layer is no longer the |
| +// baseline's and identity-<code> for each way the instance differs from |
| +// it. Any code refuses a write. Before a retry, mine is nil: the agent |
| +// keys were just read absent, so a present one is another writer's. |
| +func admit(ctx context.Context, c *carlosop.Client, h *http.Client, app provision.App, mine map[string]string, base *Snapshot) (Snapshot, []string, error) { |
| + fresh, codes, err := Preflight(ctx, c, h, app, mine) |
| + if err != nil || len(codes) > 0 || base == nil { |
| + return fresh, codes, err |
| + } |
| + if base.WriteLayer != fresh.WriteLayer || base.Layer.Bundle != fresh.Layer.Bundle { |
| + codes = append(codes, "write-layer-moved") |
| + } |
| + for _, code := range SameIdentity(base.Identity, fresh.Identity) { |
| + codes = append(codes, "identity-"+code) |
| } |
| + return fresh, codes, nil |
| } |
| // CaptureAfter takes and stores app's after snapshot, once the restart |
diff --git a/adopt/write_test.go b/adopt/write_test.go| index 015ed9e..793364a 100644 |
| --- a/adopt/write_test.go |
| +++ b/adopt/write_test.go |
| @@ -442,6 +442,100 @@ func TestWriteRetriesAfterUnrelatedKeyAdded(t *testing.T) { |
| } |
| } |
| +// Every preflight refusal a reread can see is enforced again before a |
| +// retry: a 412 caused by another writer's team-mode key, or by a new |
| +// neighbour that would inherit the keys, never ends in a write. |
| +func TestWriteRetryRevalidatesPreflight(t *testing.T) { |
| + cases := map[string]struct { |
| + edit func(w *writeFixture) |
| + code string |
| + }{ |
| + "team mode": {func(w *writeFixture) { w.f.SetVar("docs", "", "DOCS_TEAM_ID", "team-id-value") }, "team-mode-DOCS_TEAM_ID"}, |
| + "other team key": {func(w *writeFixture) { w.f.SetVar("docs", "", "DOCS_TEAM_NEW_THING", "1") }, |
| + "team-mode-DOCS_TEAM_NEW_THING"}, |
| + "inheriting neighbour": {func(w *writeFixture) { |
| + w.neighbour("bare.docs.example", "") |
| + w.f.PlatformWrite("docs", "", "DOCS_MAIL_EVENTS_URL", "https://mail.example/hook") |
| + }, "inherits-bare.docs.example"}, |
| + } |
| + for name, tc := range cases { |
| + t.Run(name, func(t *testing.T) { |
| + w := newWriteFixture(t, "docs") |
| + w.f.BeforePut = once(func() { tc.edit(w) }) |
| + _, err := w.configure(true) |
| + if err == nil || !strings.Contains(err.Error(), "configure refused") || !strings.Contains(err.Error(), tc.code) { |
| + t.Fatalf("err = %v, want a refusal naming %s", err, tc.code) |
| + } |
| + noValues(t, err) |
| + if n := w.puts(); n != 1 { |
| + t.Fatalf("PUTs = %d: retried past a preflight refusal", n) |
| + } |
| + if present, _ := w.stored(t); present != [2]bool{} { |
| + t.Fatalf("agent keys written: %v", present) |
| + } |
| + rec, _ := w.writeRecord(t) |
| + if rec.State != "sent" || rec.Code != "preflight-refused" { |
| + t.Fatalf("state %q code %q", rec.State, rec.Code) |
| + } |
| + // A resume meets the same refusal and sends nothing. |
| + if _, err := w.configure(true); err == nil || !strings.Contains(err.Error(), tc.code) { |
| + t.Fatalf("resume err = %v", err) |
| + } |
| + if n := w.puts(); n != 1 { |
| + t.Fatalf("PUTs = %d after resume", n) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// A preserved key resealed after the reread that said Retry, but before |
| +// the retry, is caught by classifying the admission's own read: the |
| +// retry never writes past it. |
| +func TestWriteRetryReclassifiesAfterAdmission(t *testing.T) { |
| + w := newWriteFixture(t, "docs") |
| + w.f.BeforePut = once(func() { w.f.PlatformWrite("docs", "", "DOCS_MAIL_EVENTS_URL", "https://mail.example/hook") }) |
| + target, err := url.Parse(w.f.URL()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rp := httputil.NewSingleHostReverseProxy(target) |
| + var mu sync.Mutex |
| + refused, resealed := false, false |
| + rp.ModifyResponse = func(resp *http.Response) error { |
| + mu.Lock() |
| + defer mu.Unlock() |
| + switch { |
| + case resp.Request.Method == http.MethodPut && resp.StatusCode == http.StatusPreconditionFailed: |
| + refused = true |
| + case refused && !resealed && resp.Request.Method == http.MethodGet && strings.HasSuffix(resp.Request.URL.Path, "/config"): |
| + // The reread has been answered; the reseal lands after it. |
| + resealed = true |
| + w.f.SetSecret("docs", "", "DOCS_INSTANCE_KEY") |
| + } |
| + return nil |
| + } |
| + srv := httptest.NewServer(rp) |
| + t.Cleanup(srv.Close) |
| + w.c = carlosop.New(srv.URL, fixtureAccount, w.f.Token()) |
| + t.Cleanup(w.c.Close) |
| + _, err = w.configure(true) |
| + mu.Lock() |
| + fired := resealed |
| + mu.Unlock() |
| + if !fired { |
| + t.Fatal("the reseal never landed between the reread and the retry") |
| + } |
| + if !errors.Is(err, ErrStopPreserved) { |
| + t.Fatalf("err = %v, want ErrStopPreserved", err) |
| + } |
| + if n := w.puts(); n != 1 { |
| + t.Fatalf("PUTs = %d: retried past a resealed key", n) |
| + } |
| + if present, _ := w.stored(t); present != [2]bool{} { |
| + t.Fatal("agent keys written") |
| + } |
| +} |
| + |
| func TestWriteStopsWhenPreservedKeyResealed(t *testing.T) { |
| w := newWriteFixture(t, "docs") |
| w.f.BeforePut = once(func() { w.f.SetSecret("docs", "", "DOCS_INSTANCE_KEY") }) |
| @@ -712,7 +806,8 @@ func TestRollbackClassifyBranchesInOrder(t *testing.T) { |
| want RollbackBranch |
| }{ |
| "ours": {layerOf(sec, iss, team), RetryUnset}, |
| - "ours, another key resealed": {layerOf(resealed, iss, team), RetryUnset}, |
| + "ours, another key resealed": {layerOf(resealed, iss, team), RollbackStopPreservedChanged}, |
| + "one, another key resealed": {layerOf(resealed, iss), RollbackStopPreservedChanged}, |
| "absent": {layerOf(sec), RolledBack}, |
| "one": {layerOf(sec, iss), StopForeign}, |
| "foreign": {layerOf(sec, iss, foreignTeam), StopForeign}, |
| @@ -996,6 +1091,50 @@ func TestRollbackRefusesForeignValue(t *testing.T) { |
| } |
| } |
| +// Preserved keys first: a baseline secret resealed since the write stops |
| +// the rollback with our keys still in place, for a person to look at. |
| +func TestRollbackStopsWhenPreservedKeyResealed(t *testing.T) { |
| + w := newWriteFixture(t, "docs") |
| + w.configured(t) |
| + w.f.SetSecret("docs", "", "DOCS_INSTANCE_KEY") |
| + p, r := w.puts(), w.f.RestartCount("docs.oficina.works") |
| + for _, apply := range []bool{false, true} { |
| + err := w.rollback(apply) |
| + if !errors.Is(err, ErrStopPreserved) { |
| + t.Fatalf("apply %v: err = %v, want ErrStopPreserved", apply, err) |
| + } |
| + noValues(t, err) |
| + } |
| + if w.rollbackPuts(p) != 0 || w.f.RestartCount("docs.oficina.works") != r { |
| + t.Fatal("the rollback unset or restarted past a changed preserved key") |
| + } |
| + if _, ours := w.stored(t); ours != [2]bool{true, true} { |
| + t.Fatal("the keys were removed") |
| + } |
| + rec, _ := w.rollbackRecord(t) |
| + if rec.State != "stopped" || rec.Code != "preserved-changed" { |
| + t.Fatalf("state %q code %q", rec.State, rec.Code) |
| + } |
| +} |
| + |
| +// A 412 whose reread shows a preserved key resealed stops the rollback |
| +// rather than retrying the unset. |
| +func TestRollbackConflict412StopsOnResealedKey(t *testing.T) { |
| + w := newWriteFixture(t, "docs") |
| + w.configured(t) |
| + p := w.puts() |
| + w.f.BeforePut = once(func() { w.f.SetSecret("docs", "", "DOCS_INSTANCE_KEY") }) |
| + if err := w.rollback(true); !errors.Is(err, ErrStopPreserved) { |
| + t.Fatalf("err = %v, want ErrStopPreserved", err) |
| + } |
| + if n := w.rollbackPuts(p); n != 1 { |
| + t.Fatalf("rollback PUTs = %d", n) |
| + } |
| + if _, ours := w.stored(t); ours != [2]bool{true, true} { |
| + t.Fatal("the keys were removed") |
| + } |
| +} |
| + |
| func TestRollbackConflict412Rereads(t *testing.T) { |
| w := newWriteFixture(t, "docs") |
| w.configured(t) |