carlos / platform Public

moves: place's rootfs refusal holds through its writes; alias-protect every guarded field; C23 for fleet rows

Task 13 round 1 (Astra):
- carlos apps place holds the app lock from its record and route checks
  through its last write, and the lifetimes-off create takes the same lock
  (the lifetime create already did), so no console create lands between
  the check and the writes. A route with a runtime refuses the place too.
- protectedKeys is derived from runtimeFields' json tags, so every field
  the runtime guard reads (runtime, hibernate, host, region, move) is
  alias-protected before the create, write-back and tombstone exemptions.
- moveGate's binary class rails (fleet, hibernation) no longer answer for
  a record with a runtime: every start door answers it with C23.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 01f06913f9e6a16fc9de935cb1ef42e67f0ecfcf parent 8c14abe
7 files changed, +398 −45
  • internal/console/apiinstancemove.go +8 −4
  • internal/console/fleets.go +16 −6
  • internal/console/hostsused.go +4 −1
  • internal/console/rootfs_move_test.go +259 −24
  • internal/console/seedmove.go +13 −0
  • internal/provision/rootfs_move_test.go +78 −6
  • internal/provision/runtime.go +20 −4
diff --git a/internal/console/apiinstancemove.go b/internal/console/apiinstancemove.go
index f729a6bd4..1eafb2e57 100644
--- a/internal/console/apiinstancemove.go
+++ b/internal/console/apiinstancemove.go
@@ -73,6 +73,13 @@ func (s *Server) moveGate(w http.ResponseWriter, r *http.Request) (acct *Account
jsonError(w, http.StatusBadGateway, "could not read the instance")
return nil, "", "", nil, false
}
+ // The class rails below speak for binary records. A record with a
+ // runtime goes on to the door: every start answers it with C23
+ // (refuseRootfsMove), and the status, cut and abort doors find it with
+ // no move, which no runtime record can carry.
+ if rec.Runtime != "" {
+ return acct, app, host, rec, true
+ }
if k := rec.Kind; k != "" && k != "instance" {
jsonError(w, http.StatusBadRequest, c.kind(k))
return nil, "", "", nil, false
@@ -89,10 +96,7 @@ func (s *Server) moveGate(w http.ResponseWriter, r *http.Request) (acct *Account
jsonError(w, http.StatusBadRequest, c.pool)
return nil, "", "", nil, false
}
- // A record with a runtime runs under the activator whatever its
- // hibernation. It never moves, and the move doors say so
- // (refuseRootfsMove), so this rail does not answer for it.
- if !rec.HibernateOrDefault() && rec.Runtime == "" {
+ if !rec.HibernateOrDefault() {
jsonError(w, http.StatusBadRequest, c.hibernate)
return nil, "", "", nil, false
}
diff --git a/internal/console/fleets.go b/internal/console/fleets.go
index b295642d1..7dd5cbc6e 100644
--- a/internal/console/fleets.go
+++ b/internal/console/fleets.go
@@ -607,17 +607,27 @@ func (s *Server) placeAppTarget(ctx context.Context, acct *Account, app, target
}
}
- // A place re-homes every record of the app, so a record with a runtime
- // (which never moves) and a seed that may not move yet (spec §5.8)
- // refuse it, before any write. A record that cannot be read refuses it
- // too. SetRecordRegion refuses both again under its CAS, for a record
- // created after this read.
+ // A place re-homes every record of the app, so a record or route with a
+ // runtime (which never moves) and a seed that may not move yet (spec
+ // §5.8) refuse it, before any write. A record that cannot be read
+ // refuses it too. The app lock holds from these reads through the last
+ // write: every console create of an instance record takes it
+ // (createRecordWithLifetime, createRecordMarked), so no record can
+ // appear between the check and the writes it vouches for.
+ // SetRecordRegion refuses both again under its CAS, for a writer outside
+ // the console.
+ defer s.lockApp(acct.Sqid, app)()
recs, err := placeRecords(ctx, s.cfg.Releases, provision.JudgeFrom(ctx), acct.Sqid, app)
if err != nil {
log.Printf("console: place %s/%s: read instances: %v", acct.Sqid, app, err)
return http.StatusBadGateway, placeSeedReadFailed
}
- if placeRootfsBlock(recs) {
+ before, err := reg.List()
+ if err != nil {
+ log.Printf("console: place %s/%s: list routes: %v", acct.Sqid, app, err)
+ return http.StatusBadGateway, "could not read the app's routes — try again"
+ }
+ if placeRootfsBlock(recs) || placeRootfsRoutes(before, acct.Sqid, app) {
return http.StatusConflict, rootfsPlaceWords
}
if block := placeSeedBlock(recs); block != "" {
diff --git a/internal/console/hostsused.go b/internal/console/hostsused.go
index b3fd81990..e52bb2185 100644
--- a/internal/console/hostsused.go
+++ b/internal/console/hostsused.go
@@ -163,8 +163,11 @@ func recordUse(rec provision.Record) provision.HostUse {
// createRecordMarked is the lifetimes-off create of an instance record
// (the instance, seed and import doors): the mark for a data kind, then
-// provision.CreateRecord. Exempt kinds write as before.
+// provision.CreateRecord. Exempt kinds write as before. It holds the app
+// lock, as the lifetime create does, so carlos apps place's check of the
+// app's records holds through its writes (placeAppTarget).
func (s *Server) createRecordMarked(ctx context.Context, rec provision.Record) error {
+ defer s.lockApp(rec.Account, rec.App)()
if rec.DataKind() {
if err := s.markBeforeCreate(ctx, recordUse(rec), provision.RecordKey(rec.Account, rec.App, rec.Host)); err != nil {
return err
diff --git a/internal/console/rootfs_move_test.go b/internal/console/rootfs_move_test.go
index 839fee007..171c008e1 100644
--- a/internal/console/rootfs_move_test.go
+++ b/internal/console/rootfs_move_test.go
@@ -7,14 +7,17 @@ import (
"go/ast"
"go/parser"
"go/token"
+ "maps"
"net/http"
"path/filepath"
"slices"
"strings"
+ "sync"
"testing"
"time"
"github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
)
@@ -47,15 +50,27 @@ func wantRootfsMoveWords(host string) string {
// POST .../move (the legacy door and the Phase 1 door) and the offline
// door (start and stage) answer 409 with C23 for a rootfs instance,
-// hibernating or always awake, and write nothing.
+// hibernating or always awake, in a region or placed on a fleet, and write
+// nothing.
func TestMoveDoorsRefuseRootfs(t *testing.T) {
- for _, door := range []struct {
+ type door struct {
name string
phase1 bool
hibernate bool
- }{{"legacy", false, false}, {"legacy", false, true}, {"phase 1", true, false}, {"phase 1", true, true}} {
+ region string
+ }
+ var doors []door
+ for _, d := range []door{{name: "legacy"}, {name: "phase 1", phase1: true}} {
+ for _, h := range []bool{false, true} {
+ for _, region := range []string{"ie", "fleet/pi"} {
+ d.hibernate, d.region = h, region
+ doors = append(doors, d)
+ }
+ }
+ }
+ for _, door := range doors {
fx, token := seedMoveFixture(t, "code-rootfs-move", door.phase1)
- putRuntimeRecordHibernating(t, fx.rel, release.OpsAccount, rootfsMoveHost, "ie", provision.RuntimeRootfsV1, door.hibernate)
+ putRuntimeRecordHibernating(t, fx.rel, release.OpsAccount, rootfsMoveHost, door.region, provision.RuntimeRootfsV1, door.hibernate)
key := provision.RecordKey(release.OpsAccount, "shop", rootfsMoveHost)
stored, _, err := fx.rel.Get(context.Background(), key)
if err != nil {
@@ -63,7 +78,7 @@ func TestMoveDoorsRefuseRootfs(t *testing.T) {
}
code, _, raw := rawReq(t, http.MethodPost, instancesURL(fx, release.OpsAccount, "shop")+"/"+rootfsMoveHost+"/move", token, `{"region":"uk"}`)
if code != http.StatusConflict || errorText(raw) != wantRootfsMoveWords(rootfsMoveHost) {
- t.Fatalf("%s door = %d %s", door.name, code, raw)
+ t.Fatalf("%s door (hibernate %v, %s) = %d %s", door.name, door.hibernate, door.region, code, raw)
}
if got, _, err := fx.rel.Get(context.Background(), key); err != nil || string(got) != string(stored) {
t.Fatalf("%s door: a refused move wrote the record: %s, %v", door.name, got, err)
@@ -73,10 +88,15 @@ func TestMoveDoorsRefuseRootfs(t *testing.T) {
}
}
- for _, h := range []bool{false, true} {
+ for _, c := range []struct {
+ hibernate bool
+ region string
+ }{{false, "ie"}, {true, "ie"}, {false, "fleet/pi"}, {true, "fleet/pi"}} {
+ h := c.hibernate
w := newOfflineWorld(t, ieOff("box-ie"), ukOff("box-uk"))
rec := w.record()
rec.Runtime, rec.Hibernate, rec.Seed, rec.Pool, rec.Addr, rec.Addrs = provision.RuntimeRootfsV1, &h, nil, "", "", nil
+ rec.Region = c.region
body, err := json.Marshal(rec)
if err != nil {
t.Fatal(err)
@@ -88,34 +108,249 @@ func TestMoveDoorsRefuseRootfs(t *testing.T) {
}
}
-// carlos apps place refuses an app with any rootfs instance with C24
-// before it writes the app's placement or any record.
-func TestPlaceRefusesAnAppWithRootfsInstances(t *testing.T) {
- const want = "this app's instances are rootfs instances, which do not move. create new instances where you want them"
- fx, token := placeSeedFixture(t, "code-place-rootfs")
+const rootfsPlaceWant = "this app's instances are rootfs instances, which do not move. create new instances where you want them"
+
+// placeRootfsWorld is the shop app with the given routes seeded (before
+// the console opens its registry, see openTestReg), a binary record
+// plain.example.com in ie with its route, and an owned fleet "pi".
+func placeRootfsWorld(t *testing.T, code string, routes ...registry.Route) (*consoleFixture, string, *registry.Registry) {
+ t.Helper()
+ fx, token := fleetFixture(t, code)
+ if _, err := fx.st.CreateAppIn(OpsAccountID, "shop", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ reg := openTestReg(t, fx)
+ routes = append(routes, registry.Route{Host: "plain.example.com", Kind: "instance", App: "shop", Account: fx.sqid})
+ for _, rt := range routes {
+ if rt.Account == "" {
+ rt.Account = fx.sqid
+ }
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if status, body := postJSON(t, fleetsURL(fx, fx.sqid)+"/new",
+ map[string]string{"name": "pi", "bucket": "pi-fleet-data"}, token); status != http.StatusOK {
+ t.Fatalf("create fleet = %d %v", status, body)
+ }
putRuntimeRecord(t, fx.rel, fx.sqid, "plain.example.com", "ie", "")
+ return fx, token, reg
+}
+
+// placeState is everything a place writes: the app's placement, the region
+// of each of its routes, and the bytes of each of its records.
+type placeState struct {
+ placement string
+ routes map[string]string
+ records map[string]string
+}
+
+func readPlaceState(t *testing.T, fx *consoleFixture, reg *registry.Registry) placeState {
+ t.Helper()
+ p, err := fx.st.AppPlacement(OpsAccountID, "shop")
+ if err != nil {
+ t.Fatal(err)
+ }
+ st := placeState{placement: p, routes: map[string]string{}, records: map[string]string{}}
+ rts, err := reg.List()
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, rt := range rts {
+ if rt.App == "shop" {
+ st.routes[rt.Host] = rt.Region
+ }
+ }
+ keys, err := fx.rel.List(context.Background(), provision.RecordsPrefix(fx.sqid, "shop"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, k := range keys {
+ b, _, err := fx.rel.Get(context.Background(), k)
+ if err != nil {
+ t.Fatal(err)
+ }
+ st.records[k] = string(b)
+ }
+ return st
+}
+
+func (a placeState) equal(b placeState) bool {
+ return a.placement == b.placement && maps.Equal(a.routes, b.routes) && maps.Equal(a.records, b.records)
+}
+
+// carlos apps place refuses an app with any rootfs record, or any route
+// with a runtime, with C24 before it writes anything: the app placement,
+// every route and every record are as they were.
+func TestPlaceRefusesAnAppWithRootfsInstances(t *testing.T) {
+ fx, token, reg := placeRootfsWorld(t, "code-place-rootfs")
putRuntimeRecord(t, fx.rel, fx.sqid, rootfsMoveHost, "ie", provision.RuntimeRootfsV1)
+ before := readPlaceState(t, fx, reg)
code, _, raw := rawReq(t, http.MethodPost, placeURL(fx, "shop"), token, `{"target":"fleet/pi"}`)
- if code != http.StatusConflict || errorText(raw) != want {
+ if code != http.StatusConflict || errorText(raw) != rootfsPlaceWant {
t.Fatalf("place = %d %s", code, raw)
}
- assertNotPlaced(t, fx, "plain.example.com", rootfsMoveHost)
+ if after := readPlaceState(t, fx, reg); !after.equal(before) {
+ t.Fatalf("a refused place wrote:\nbefore %+v\nafter %+v", before, after)
+ }
- // The backstop: a rootfs record created after the place's read is
- // refused under SetRecordRegion's CAS, and the place answers C24.
- fx, token = placeSeedFixture(t, "code-place-rootfs-backstop")
- putRuntimeRecord(t, fx.rel, fx.sqid, "plain.example.com", "ie", "")
- fx.srv.cfg.Releases = &createOnSecondListStore{Store: fx.rel, prefix: provision.RecordsPrefix(fx.sqid, "shop"), create: func(st release.Store) {
- putRuntimeRecord(t, st, fx.sqid, rootfsMoveHost, "ie", provision.RuntimeRootfsV1)
- }}
+ // A route with a runtime whose record is gone (or not yet listed).
+ fx, token, reg = placeRootfsWorld(t, "code-place-rootfs-route",
+ registry.Route{Host: rootfsMoveHost, Kind: "instance", App: "shop", Runtime: registry.RuntimeRootfsV1})
+ before = readPlaceState(t, fx, reg)
code, _, raw = rawReq(t, http.MethodPost, placeURL(fx, "shop"), token, `{"target":"fleet/pi"}`)
- if code != http.StatusConflict || errorText(raw) != want {
+ if code != http.StatusConflict || errorText(raw) != rootfsPlaceWant {
+ t.Fatalf("route only: place = %d %s", code, raw)
+ }
+ if after := readPlaceState(t, fx, reg); !after.equal(before) {
+ t.Fatalf("route only: a refused place wrote:\nbefore %+v\nafter %+v", before, after)
+ }
+}
+
+// appLockWaits calls signal once when anyone starts waiting for the shop
+// app's lock from now on.
+func appLockWaits(t *testing.T, sqid string, signal chan struct{}) {
+ t.Helper()
+ var once sync.Once
+ h := func(kind, key, event string) {
+ if kind == "app" && key == sqid+"/shop" && event == lockWaiting {
+ once.Do(func() { close(signal) })
+ }
+ }
+ lifetimeLockHook.Store(&h)
+ t.Cleanup(func() { lifetimeLockHook.Store(nil) })
+}
+
+func rootfsCreateRecord(sqid string) provision.Record {
+ h := false
+ return provision.Record{Schema: 1, Host: rootfsMoveHost, Slug: "bab", App: "shop", Account: sqid,
+ Region: "ie", Channel: "stable", CreatedAt: time.Now().UTC(), Runtime: provision.RuntimeRootfsV1, Hibernate: &h}
+}
+
+// Round 1 finding 1, a create first: a console create of a rootfs record is
+// writing it (holding the app lock) when the place arrives. The place waits
+// for the lock, then reads the record and refuses with C24, and writes
+// nothing: the app placement, the routes and the binary record are as they
+// were.
+func TestPlaceWaitsForACreateInFlight(t *testing.T) {
+ fx, token, reg := placeRootfsWorld(t, "code-place-rootfs-create-first")
+ before := readPlaceState(t, fx, reg)
+ gate := &putGateStore{Store: fx.rel, key: provision.RecordKey(fx.sqid, "shop", rootfsMoveHost),
+ entered: make(chan struct{}), release: make(chan struct{})}
+ fx.srv.cfg.Releases = gate
+ created := make(chan error, 1)
+ go func() { created <- fx.srv.createRecordMarked(context.Background(), rootfsCreateRecord(fx.sqid)) }()
+ waitForSignal(t, gate.entered, "the rootfs record's create")
+ placeWaiting := make(chan struct{})
+ appLockWaits(t, fx.sqid, placeWaiting)
+ placed := make(chan string, 1)
+ go func() {
+ code, _, raw := rawReq(t, http.MethodPost, placeURL(fx, "shop"), token, `{"target":"fleet/pi"}`)
+ placed <- fmt.Sprintf("%d %s", code, errorText(raw))
+ }()
+ select {
+ case <-placeWaiting:
+ case <-time.After(2 * time.Second):
+ // The place never waited for the app lock: let the create finish,
+ // and the checks below say what the place did without it.
+ }
+ close(gate.release)
+ if err := <-created; err != nil {
+ t.Fatal(err)
+ }
+ if got, want := <-placed, fmt.Sprintf("%d %s", http.StatusConflict, rootfsPlaceWant); got != want {
+ t.Fatalf("place = %s, want %s", got, want)
+ }
+ after := readPlaceState(t, fx, reg)
+ rootfsKey := provision.RecordKey(fx.sqid, "shop", rootfsMoveHost)
+ if _, ok := after.records[rootfsKey]; !ok {
+ t.Fatal("the create did not land")
+ }
+ delete(after.records, rootfsKey)
+ if !after.equal(before) {
+ t.Fatalf("a refused place wrote:\nbefore %+v\nafter %+v", before, after)
+ }
+}
+
+// Round 1 finding 1, the place first: a console create of a rootfs record
+// that starts after the place's check waits for the app lock, so the place
+// lands whole (placement, route, binary record) and the new record is
+// created afterwards where it asked to be, not re-homed.
+func TestACreateWaitsForAPlaceInFlight(t *testing.T) {
+ fx, token, reg := placeRootfsWorld(t, "code-place-rootfs-place-first")
+ created := make(chan error, 1)
+ createWaiting := make(chan struct{})
+ lists := &listHookStore{Store: fx.rel, prefix: provision.RecordsPrefix(fx.sqid, "shop")}
+ lists.onList = func(n int) {
+ switch n {
+ case 1: // the place's check, under its lock
+ appLockWaits(t, fx.sqid, createWaiting)
+ go func() { created <- fx.srv.createRecordMarked(context.Background(), rootfsCreateRecord(fx.sqid)) }()
+ case 2: // the place's walk: the create is waiting, or (without the lock) done
+ select {
+ case <-createWaiting:
+ case err := <-created:
+ created <- err
+ case <-time.After(5 * time.Second):
+ t.Error("the create neither waited nor finished")
+ }
+ }
+ }
+ fx.srv.cfg.Releases = lists
+ code, _, raw := rawReq(t, http.MethodPost, placeURL(fx, "shop"), token, `{"target":"fleet/pi"}`)
+ if code != http.StatusOK {
t.Fatalf("place = %d %s", code, raw)
}
- got, err := provision.GetRecord(context.Background(), fx.rel, fx.sqid, "shop", rootfsMoveHost)
- if err != nil || got.Region != "ie" {
- t.Fatalf("the late rootfs record was re-homed: %+v, %v", got, err)
+ if err := <-created; err != nil {
+ t.Fatal(err)
+ }
+ after := readPlaceState(t, fx, reg)
+ if after.placement != "fleet/pi" || after.routes["plain.example.com"] != "fleet/pi" {
+ t.Fatalf("the place did not land: %+v", after)
+ }
+ for host, want := range map[string]string{"plain.example.com": "fleet/pi", rootfsMoveHost: "ie"} {
+ got, err := provision.GetRecord(context.Background(), fx.rel, fx.sqid, "shop", host)
+ if err != nil || got.Region != want {
+ t.Fatalf("%s: %+v, %v, want region %s", host, got, err, want)
+ }
+ }
+}
+
+// putGateStore holds the Put of one key until release, after closing
+// entered.
+type putGateStore struct {
+ release.Store
+ key string
+ entered, release chan struct{}
+}
+
+func (g *putGateStore) Put(ctx context.Context, key string, body []byte, etag string) (string, error) {
+ if key == g.key {
+ close(g.entered)
+ <-g.release
+ }
+ return g.Store.Put(ctx, key, body, etag)
+}
+
+// listHookStore calls onList with the count of Lists of prefix so far,
+// before each one.
+type listHookStore struct {
+ release.Store
+ prefix string
+ onList func(n int)
+ mu sync.Mutex
+ n int
+}
+
+func (l *listHookStore) List(ctx context.Context, prefix string) ([]string, error) {
+ if prefix == l.prefix {
+ l.mu.Lock()
+ l.n++
+ n := l.n
+ l.mu.Unlock()
+ l.onList(n)
}
+ return l.Store.List(ctx, prefix)
}
// rootfsMoveDoors is every function of the package that answers a move
diff --git a/internal/console/seedmove.go b/internal/console/seedmove.go
index 69b4877a0..684645232 100644
--- a/internal/console/seedmove.go
+++ b/internal/console/seedmove.go
@@ -10,6 +10,7 @@ import (
"slices"
"github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
)
@@ -88,6 +89,18 @@ func placeRootfsBlock(recs []provision.Record) bool {
return false
}
+// placeRootfsRoutes is the same rule over the registry: true when any route
+// of the app has a runtime, so a route whose record is gone or not yet
+// listed refuses the place too, before any write.
+func placeRootfsRoutes(routes []registry.Route, acct, app string) bool {
+ for _, rt := range routes {
+ if rt.Account == acct && rt.App == app && rt.Runtime != "" {
+ return true
+ }
+ }
+ return false
+}
+
// rootfsMoveWords is RFS-3-C23, the move doors' sentence for an instance
// with a runtime, filled with its host.
const rootfsMoveWords = "%s is a rootfs instance, and a rootfs instance does not move. create a new instance where you want it"
diff --git a/internal/provision/rootfs_move_test.go b/internal/provision/rootfs_move_test.go
index 6d6d17ccb..86ae17be3 100644
--- a/internal/provision/rootfs_move_test.go
+++ b/internal/provision/rootfs_move_test.go
@@ -320,10 +320,10 @@ func sortedClone(s []string) []string {
return c
}
-// The record body WriteRecord's guard reads is the one every reader
-// decodes: a region or move under another key spelling is the same field
-// to encoding/json, so the guard and the readers agree on it.
-func TestRootfsMoveGuardReadsTheDecodedFields(t *testing.T) {
+// A region under another key spelling is the same field to encoding/json,
+// so a body that carries one is refused outright (ErrRecordSequence):
+// the guard never has to guess which spelling readers will see.
+func TestRootfsMoveGuardRefusesAnAliasedRegion(t *testing.T) {
s, sqid := rootfsSetup(t)
if err := CreateRecord(ctx, s, rootfsRecord(sqid, rootfsHost, false)); err != nil {
t.Fatal(err)
@@ -343,6 +343,78 @@ func TestRootfsMoveGuardReadsTheDecodedFields(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- _, _, err = WriteRecord(ctx, s, key, raw, body, etag)
- wantRootfsMoveError(t, "REGION", err, rootfsHost)
+ if _, _, err = WriteRecord(ctx, s, key, raw, body, etag); !errors.Is(err, ErrRecordSequence) {
+ t.Fatalf("REGION: err = %v, want ErrRecordSequence", err)
+ }
+}
+
+// Round 1 finding 2: a stored body that spells region or move twice
+// ("region" and "REGION") reads as the last one, and a sequenced
+// write-back re-sorts the keys, which would change what readers see
+// while the field maps compare equal. Every field the runtime guard reads
+// is alias-protected (protectedKeys is derived from runtimeFields), and the
+// refusal runs before the write-back and tombstone exemptions.
+func TestRootfsMoveAliasesRefusedOnSequencedWriteBack(t *testing.T) {
+ for name, alias := range map[string]string{
+ "region": `"region":"uk","REGION":"ie"`,
+ "move": `"region":"ie","move":{"to":"uk","state":"preparing"},"MOVE":null`,
+ "host": `"region":"ie","HOST":"` + rootfsHost + `"`,
+ } {
+ s, sqid := rootfsSetup(t)
+ if err := CreateRecord(ctx, s, rootfsRecord(sqid, rootfsHost, false)); err != nil {
+ t.Fatal(err)
+ }
+ key := RecordKey(sqid, "shop", rootfsHost)
+ raw, _, err := s.Get(ctx, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Contains(raw, []byte(`"region":"ie"`)) {
+ t.Fatalf("stored body has no region: %s", raw)
+ }
+ putReplace(t, s, key, bytes.Replace(raw, []byte(`"region":"ie"`), []byte(alias), 1))
+ stored, etag, err := s.Get(ctx, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := WriteRecord(WithRecordSequence(ctx), s, key, stored, stored, etag); !errors.Is(err, ErrRecordSequence) {
+ t.Fatalf("%s alias: sequenced write-back = %v, want ErrRecordSequence", name, err)
+ }
+ tomb, err := TombstoneBody(stored)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := WriteRecord(WithRecordSequence(ctx), s, key, stored, tomb, etag); !errors.Is(err, ErrRecordSequence) {
+ t.Fatalf("%s alias: tombstone over an aliased body = %v, want ErrRecordSequence", name, err)
+ }
+ if got, _, err := s.Get(ctx, key); err != nil || !bytes.Equal(got, stored) {
+ t.Fatalf("%s alias: the stored record changed: %s, %v", name, got, err)
+ }
+ }
+
+ // The legitimate forms still pass: a sequenced write-back of a plain
+ // rootfs record (the lifetime fence), then its tombstone.
+ s, sqid := rootfsSetup(t)
+ if err := CreateRecord(ctx, s, rootfsRecord(sqid, rootfsHost, false)); err != nil {
+ t.Fatal(err)
+ }
+ key := RecordKey(sqid, "shop", rootfsHost)
+ raw, etag, err := s.Get(ctx, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := WriteRecord(WithRecordSequence(ctx), s, key, raw, raw, etag); err != nil {
+ t.Fatalf("plain sequenced write-back: %v", err)
+ }
+ raw, etag, err = s.Get(ctx, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ tomb, err := TombstoneBody(raw)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := WriteRecord(WithRecordSequence(ctx), s, key, raw, tomb, etag); err != nil {
+ t.Fatalf("plain tombstone: %v", err)
+ }
}
diff --git a/internal/provision/runtime.go b/internal/provision/runtime.go
index 07cd40fc0..7e12e2dc1 100644
--- a/internal/provision/runtime.go
+++ b/internal/provision/runtime.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
+ "reflect"
"strings"
"github.com/carlosframework/platform/internal/registry"
@@ -69,7 +70,8 @@ var ErrRuntimeProtected = errors.New("provision: an instance's runtime, and a ro
// runtimeFields is all runtimeFixed reads of a record body. Decoding with
// encoding/json, as DecodeRecord does, gives the same answer every reader of
// the record gets; protectedSpellings first makes sure there is only one
-// key it could have matched.
+// key it could have matched, for every field here (protectedKeys is derived
+// from these tags, so the two cannot diverge).
type runtimeFields struct {
Runtime string `json:"runtime"`
Hibernate *bool `json:"hibernate"`
@@ -78,11 +80,25 @@ type runtimeFields struct {
Move json.RawMessage `json:"move"`
}
-// protectedKeys are the fields runtimeFixed protects.
-var protectedKeys = []string{"runtime", "hibernate"}
+// protectedKeys are the fields runtimeFixed protects: the json key of every
+// field of runtimeFields, read from its tags.
+var protectedKeys = func() []string {
+ t := reflect.TypeOf(runtimeFields{})
+ keys := make([]string, 0, t.NumField())
+ for i := range t.NumField() {
+ name, _, _ := strings.Cut(t.Field(i).Tag.Get("json"), ",")
+ if name == "" || name == "-" {
+ panic("provision: runtimeFields." + t.Field(i).Name + " needs a json key")
+ }
+ keys = append(keys, name)
+ }
+ return keys
+}()
// protectedSpellings refuses a body that carries a protected field under a
-// spelling other than its own ("RUNTIME", "Hibernate"). encoding/json
+// spelling other than its own ("RUNTIME", "Hibernate", "REGION"). It runs
+// on both bodies before every exemption runtimeFixed makes (create,
+// write-back, tombstone). encoding/json
// matches keys case-insensitively and the last one wins, and
// AdvanceRecordSequence re-marshals the fields sorted, so two spellings
// could pass the guard in one order and be stored in the other.