carlos / platform Public

subdomains: rollback restarts the cooldown; each write has a revision

Astra's final re-review, two Important findings, each fixed in one place.

1. Rollback never shortens a cooldown. Undoing an unretire or a replace
   restored the old retirement verbatim, already past its hour, so
   another account could take the name at once while a create admitted
   under the briefly active name was still to land. subdomainRollBack
   now retires the claim again, as the account it activated, at the
   door's clock (RetireAccountNamespace at the undone write's ETag): the
   hour restarts from the moment the name was last exposed. A fresh
   create is still deleted at its own ETag. RestoreRetiredAccountNamespace
   is gone.
2. Same-second ETag ABA. Claim.Revision (revision, omitempty): 128 random
   bits in hex, fresh on every namespace write (AttachAccountNamespace
   and putNamespace, the only two Puts). Create, retire and unretire in
   one second by one operator no longer write the same bytes, so an
   older rollback cannot land on the successor. Additive; older binaries
   drop it.

Also (Fable minor): the untrusted own-claim refusal logged %!v(<nil>).

Tests: TestSubdomainRollbackRestartsCooldown (Astra's interleaving:
replace, a placements create admitted and paused, re-read fails,
rollback; bcd and bdq refused with retired_cooldown until now+1h, then
bcd refused as occupied by bab's late write), TestSubdomainRetiredRollbacks
updated, TestSubdomainRollbackSparesASuccessor/same_second and
TestNamespaceWritesNeverRepeatAnETag. The group-name class census pins
Claim.Revision.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev b47061fd1865504585fb059ce20ceaeb81b27f2c parent d6bf9e3
6 files changed, +351 −150
  • internal/console/apisubdomain.go +23 −18
  • internal/console/subdomain_retire_test.go +248 −43
  • internal/domains/claims.go +10 −0
  • internal/domains/namespace.go +30 −32
  • internal/domains/namespace_retire_test.go +39 −56
  • internal/host/group_names_test.go +1 −1

Intent

Human

A

diff --git a/internal/console/apisubdomain.go b/internal/console/apisubdomain.go
index 25bae9831..07b4b4cb9 100644
--- a/internal/console/apisubdomain.go
+++ b/internal/console/apisubdomain.go
@@ -433,11 +433,11 @@ func (s *Server) handleAPISubdomainSet(w http.ResponseWriter, r *http.Request) {
}
// subdomainUndo is set's own write, as its rollback undoes it: the ETag the
-// write answered, and the retired claim it wrote over (an unretire or a
-// replace), nil for a fresh create.
+// write answered, and whether it activated a retired claim (an unretire or
+// a replace) rather than creating a fresh one.
type subdomainUndo struct {
- etag string
- prev *domains.Claim
+ etag string
+ activation bool
}
// subdomainWrite is set's write, judged on a fresh read of the name's key
@@ -502,7 +502,7 @@ func (s *Server) subdomainWrite(w http.ResponseWriter, ctx context.Context, acct
unreadable("write over the retired claim", err)
return subdomainUndo{}, false
}
- return subdomainUndo{etag: newETag, prev: cur}, true
+ return subdomainUndo{etag: newETag, activation: true}, true
}
switch byName, _ := domains.AccountNamespaces([]domains.Claim{*cur}, domain); {
case byName[name] == acct.Sqid:
@@ -514,7 +514,7 @@ func (s *Server) subdomainWrite(w http.ResponseWriter, ctx context.Context, acct
// account's name; one they do not (pending, carrying more, a
// retired_at that does not parse) is not, and reads as unread
// until an operator fixes it.
- unreadable("its own claim at "+host+" is not one the console trusts", nil)
+ unreadable("read "+host, errors.New("the account's own claim there is not one the console trusts"))
default:
s.refuseSubdomain(w, domains.SubdomainOccupied, acct, raw, name, "",
[]occupant{{Host: cur.Host, Account: cur.Account, App: cur.App, Source: occupantClaim}})
@@ -560,24 +560,29 @@ func (s *Server) subdomainReread(ctx context.Context, account, name string) (fou
}
// subdomainRollBack undoes set's own write and refuses with what the
-// re-read found: a fresh create is deleted (DetachAccountNamespaceAt), an
-// unretire or a replace has the retired claim it wrote over put back
-// (RestoreRetiredAccountNamespace). Either is conditional on the ETag the
-// write answered, never a fresh read, so a later write at the key (another
-// console's remove and set between the re-read and here) is never undone.
-// An undo that does not land leaves the name held: the answer is a 500
-// saying so and how to remove it, and show reports the name; a key found
-// empty instead is rolled back all the same. Either way the claim was
-// written, so the readers are told.
+// re-read found. A fresh create is deleted (DetachAccountNamespaceAt). An
+// unretire or a replace is retired again, as the account it activated, at
+// the door's clock (RetireAccountNamespace): never put back as it was, so
+// a rollback never shortens a cooldown. The name was exposed as that
+// account's while the write stood, and a create admitted under it then may
+// still land, so the hour restarts from now (Astra final re-review,
+// Important 1). Either is conditional on the ETag the write answered,
+// never a fresh read, and every namespace write carries a fresh revision,
+// so a later write at the key (another console's remove and set between
+// the re-read and here, in the same second included) is never undone. An
+// undo that does not land leaves the name held: the answer is a 500 saying
+// so and how to remove it, and show reports the name; a key found empty
+// instead is rolled back all the same. Either way the claim was written,
+// so the readers are told.
func (s *Server) subdomainRollBack(w http.ResponseWriter, ctx context.Context, acct *Account, raw, name string, found []occupant, undo subdomainUndo) {
defer s.subdomainWritten(ctx)
domain := s.appsDomain()
var undone bool
var err error
- if undo.prev == nil {
- undone, err = domains.DetachAccountNamespaceAt(ctx, s.cfg.Releases, name, domain, acct.Sqid, undo.etag)
+ if undo.activation {
+ _, undone, err = domains.RetireAccountNamespace(ctx, s.cfg.Releases, name, domain, acct.Sqid, undo.etag, s.subdomainClock())
} else {
- undone, err = domains.RestoreRetiredAccountNamespace(ctx, s.cfg.Releases, name, domain, acct.Sqid, undo.etag, *undo.prev)
+ undone, err = domains.DetachAccountNamespaceAt(ctx, s.cfg.Releases, name, domain, acct.Sqid, undo.etag)
}
if err == nil && !undone {
if _, _, rerr := domains.GetClaimETag(ctx, s.cfg.Releases, domains.NamespaceHost(name, domain)); !errors.Is(rerr, os.ErrNotExist) {
diff --git a/internal/console/subdomain_retire_test.go b/internal/console/subdomain_retire_test.go
index 466f254dc..86c47f1c5 100644
--- a/internal/console/subdomain_retire_test.go
+++ b/internal/console/subdomain_retire_test.go
@@ -229,17 +229,20 @@ func TestSubdomainRetiredOldHolderOccupantRefuses(t *testing.T) {
}
// TestSubdomainRetiredRollbacks: when set's re-read finds a conflict, an
-// unretire is undone by putting the retirement back (retired_at as it was)
-// and a replace by putting the old holder's retired claim back.
+// unretire or a replace is undone by retiring the claim again, as the
+// account it activated, at the door's clock: never by putting the old
+// retirement back, so the cooldown restarts from the moment the name was
+// last exposed (Astra final re-review, Important 1). Another account is
+// refused until an hour after the rollback.
func TestSubdomainRetiredRollbacks(t *testing.T) {
for _, c := range []struct {
- name, account string
- at time.Duration
- }{{"unretire", "bdq", time.Minute}, {"replace", "bcd", domains.NamespaceCooldown}} {
+ name, account, other string
+ at time.Duration
+ }{{"unretire", "bdq", "bcd", time.Minute}, {"replace", "bcd", "bdq", domains.NamespaceCooldown + 5*time.Minute}} {
t.Run(c.name, func(t *testing.T) {
fx, operator, clock := sdRetireFixture(t, "code-sd-rb-"+c.name)
- retired := nsClaimAt(t, fx, nsHarbourHost)
- clock.Set(sdT0.Add(c.at))
+ now := sdT0.Add(c.at)
+ clock.Set(now)
foreign := domains.Claim{Schema: 1, Host: "x.harbour." + nsApps, Account: fx.sqid, App: "web", CreatedAt: sdT0.Format(time.RFC3339)}
fx.srv.cfg.Releases = &nsRaceStore{Store: fx.rel, key: domains.ClaimKey(nsHarbourHost), after: func() { nsPutClaim(t, fx, foreign) }}
fx.srv.claims.Reset()
@@ -247,8 +250,15 @@ func TestSubdomainRetiredRollbacks(t *testing.T) {
if code != http.StatusConflict || a.Code != string(domains.SubdomainRolledBack) {
t.Fatalf("%s under a race = %d %s, want 409 rolled_back", c.name, code, out)
}
- if got := nsClaimAt(t, fx, nsHarbourHost); !reflect.DeepEqual(got, retired) {
- t.Errorf("claim after the rollback = %+v, want the retired claim back %+v", got, retired)
+ got := nsClaimAt(t, fx, nsHarbourHost)
+ if got == nil || got.Account != c.account || got.RetiredAt != now.Format(time.RFC3339) {
+ t.Fatalf("claim after the rollback = %+v, want %s's, retired at %s", got, c.account, now.Format(time.RFC3339))
+ }
+ fx.srv.cfg.Releases = fx.rel
+ fx.srv.claims.Reset()
+ want := fmt.Sprintf(subdomainRefuseRetiredCooldownCopy, "harbour", retiredCooldownShown(now.Add(domains.NamespaceCooldown)))
+ if code, a, out := sdReq(t, fx, http.MethodPost, c.other, operator, `{"name":"harbour"}`); code != http.StatusConflict || a.Error != want {
+ t.Errorf("%s right after the rollback = %d %s, want 409 %q", c.other, code, out, want)
}
})
}
@@ -312,41 +322,63 @@ func (s *nsSuccessorStore) DeleteIfMatch(ctx context.Context, key, etag string)
// TestSubdomainRollbackSparesASuccessor: set's rollback is conditioned on
// the ETag its own create answered, so it never deletes the successor
// another console wrote after the failed re-read. The successor stands and
-// the door says the name is still held.
+// the door says the name is still held. "same second" is Astra's final
+// re-review Important 2: the successor is a retire and unretire by the same
+// operator in the same second as the create (a fixed clock), which writes
+// the create's fields again; only the namespace revision tells the two
+// writes apart.
func TestSubdomainRollbackSparesASuccessor(t *testing.T) {
- fx, operator, _ := sdFixture(t, "code-sd-successor")
- ctx := context.Background()
- var successorETag string
- store := &nsSuccessorStore{Store: fx.rel, key: domains.ClaimKey(nsHarbourHost), successor: func() {
- // Another console: remove (retire), then set again (unretire).
- _, etag, err := domains.GetClaimETag(ctx, fx.rel, nsHarbourHost)
- if err != nil {
- t.Error(err)
- return
- }
- retired, ok, err := domains.RetireAccountNamespace(ctx, fx.rel, "harbour", nsApps, "bdq", etag, time.Now().Add(-time.Minute))
- if err != nil || !ok {
- t.Errorf("successor retire = %v, %v", ok, err)
- return
- }
- successorETag, ok, err = domains.UnretireAccountNamespace(ctx, fx.rel, "harbour", nsApps, "bdq", retired, time.Now().Add(time.Hour), "other@example.com")
- if err != nil || !ok {
- t.Errorf("successor unretire = %v, %v", ok, err)
- }
- }}
- fx.srv.cfg.Releases = store
- fx.srv.claims.Reset()
- code, a, out := sdReq(t, fx, http.MethodPost, "bdq", operator, `{"name":"harbour"}`)
- if !store.fired {
- t.Fatalf("the successor never landed (set = %d %s); the test did not reach the rollback", code, out)
- }
- want := fmt.Sprintf(subdomainRefuseRollbackFailedCopy, "harbour", "bdq", "bdq")
- if code != http.StatusInternalServerError || a.Code != string(subdomainCodeRollbackFailed) || a.Error != want {
- t.Errorf("set whose rollback meets a successor = %d %s, want 500 %q", code, out, want)
- }
- c, etag, err := domains.GetClaimETag(ctx, fx.rel, nsHarbourHost)
- if err != nil || etag != successorETag || c.Account != "bdq" || c.RetiredAt != "" || c.CreatedBy != "other@example.com" {
- t.Errorf("after the rollback: %+v at %q (%v), want the successor at %q", c, etag, err, successorETag)
+ for _, c := range []struct {
+ name string
+ retireAt time.Time
+ setAt time.Time
+ by string
+ }{
+ {"later", sdT0.Add(time.Minute), sdT0.Add(time.Hour), "other@example.com"},
+ {"same second", sdT0, sdT0, "ops@example.com"},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ fx, operator, _ := sdFixture(t, "code-sd-successor-"+strings.ReplaceAll(c.name, " ", "-"))
+ fx.srv.subdomainNow = func() time.Time { return sdT0 }
+ ctx := context.Background()
+ var successorETag string
+ var created *domains.Claim
+ store := &nsSuccessorStore{Store: fx.rel, key: domains.ClaimKey(nsHarbourHost), successor: func() {
+ // Another console: remove (retire), then set again (unretire).
+ cur, etag, err := domains.GetClaimETag(ctx, fx.rel, nsHarbourHost)
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ created = cur
+ retired, ok, err := domains.RetireAccountNamespace(ctx, fx.rel, "harbour", nsApps, "bdq", etag, c.retireAt)
+ if err != nil || !ok {
+ t.Errorf("successor retire = %v, %v", ok, err)
+ return
+ }
+ successorETag, ok, err = domains.UnretireAccountNamespace(ctx, fx.rel, "harbour", nsApps, "bdq", retired, c.setAt, c.by)
+ if err != nil || !ok {
+ t.Errorf("successor unretire = %v, %v", ok, err)
+ }
+ }}
+ fx.srv.cfg.Releases = store
+ fx.srv.claims.Reset()
+ code, a, out := sdReq(t, fx, http.MethodPost, "bdq", operator, `{"name":"harbour"}`)
+ if !store.fired {
+ t.Fatalf("the successor never landed (set = %d %s); the test did not reach the rollback", code, out)
+ }
+ want := fmt.Sprintf(subdomainRefuseRollbackFailedCopy, "harbour", "bdq", "bdq")
+ if code != http.StatusInternalServerError || a.Code != string(subdomainCodeRollbackFailed) || a.Error != want {
+ t.Errorf("set whose rollback meets a successor = %d %s, want 500 %q", code, out, want)
+ }
+ got, etag, err := domains.GetClaimETag(ctx, fx.rel, nsHarbourHost)
+ if err != nil || etag != successorETag || got.Account != "bdq" || got.RetiredAt != "" || got.CreatedBy != c.by {
+ t.Fatalf("after the rollback: %+v at %q (%v), want the successor at %q", got, etag, err, successorETag)
+ }
+ if c.name == "same second" && (created == nil || got.CreatedAt != created.CreatedAt || got.CreatedBy != created.CreatedBy) {
+ t.Errorf("the successor %+v does not repeat the create %+v but for its revision", got, created)
+ }
+ })
}
}
@@ -467,3 +499,176 @@ func TestSubdomainRetiredInterleaving(t *testing.T) {
t.Errorf("bcd was answered the name: %s", out)
}
}
+
+// nsRollbackRaceStore drives Astra's final re-review interleaving
+// (Important 1) inside one set: right after set's Put of key it runs
+// admit (another request is admitted under the name the Put exposed), and
+// then fails the next record walk once, so set's re-read fails and it
+// rolls back. claimsListed closes on the first claims listing after
+// armClaims, the admitted request's namespace view.
+type nsRollbackRaceStore struct {
+ release.Store
+ key string
+ admit func()
+ mu sync.Mutex
+ admitted bool
+ failWalk bool
+ armClaims bool
+ claimsListed chan struct{}
+}
+
+func (s *nsRollbackRaceStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ etag, err := s.Store.Put(ctx, key, body, ifMatch)
+ s.mu.Lock()
+ run := err == nil && key == s.key && !s.admitted
+ if run {
+ s.admitted = true
+ }
+ s.mu.Unlock()
+ if run {
+ s.admit()
+ s.mu.Lock()
+ s.failWalk = true
+ s.mu.Unlock()
+ }
+ return etag, err
+}
+
+func (s *nsRollbackRaceStore) List(ctx context.Context, prefix string) ([]string, error) {
+ s.mu.Lock()
+ fail := s.failWalk && prefix == "accounts/"
+ if fail {
+ s.failWalk = false
+ }
+ s.mu.Unlock()
+ if fail {
+ return nil, errors.New("nsRollbackRaceStore: record walk refused")
+ }
+ keys, err := s.Store.List(ctx, prefix)
+ s.mu.Lock()
+ if s.armClaims && prefix == domains.ClaimsPrefix {
+ s.armClaims = false
+ close(s.claimsListed)
+ }
+ s.mu.Unlock()
+ return keys, err
+}
+
+func (s *nsRollbackRaceStore) DeleteIfMatch(ctx context.Context, key, etag string) error {
+ return release.DeleteIfMatch(ctx, s.Store, key, etag)
+}
+
+// TestSubdomainRollbackRestartsCooldown is Astra's final re-review
+// interleaving (Important 1). bdq's harbour retired more than an hour ago.
+// bab sets it (a replace); while bab holds it, bab's placements PUT for
+// x.api.harbour.<apps> is admitted and waits on its body; set's re-read
+// then fails and it rolls back. The rollback retires harbour as bab's at
+// now, so bcd (and bdq) are refused until an hour after the rollback; bab's
+// late write lands under the retired name; and from that hour on bcd is
+// refused as occupied while it sits there. With the old retirement put
+// back as it was, already past its hour, bcd would get the name at once
+// and bab's write would land under bcd's name.
+func TestSubdomainRollbackRestartsCooldown(t *testing.T) {
+ w := newRegionalWorld(t, "code-sd-rb-cooldown")
+ fx := w.fx
+ fx.srv.cfg.AppsDomain = nsApps
+ nsAccount(t, fx, 82, "bdq")
+ nsAccount(t, fx, 49, "bcd")
+ clock := &sdClock{now: sdT0}
+ fx.srv.subdomainNow = clock.Now
+ if code, _, out := sdReq(t, fx, http.MethodPost, "bdq", w.token, `{"name":"harbour"}`); code != http.StatusOK {
+ t.Fatalf("set harbour for bdq = %d %s", code, out)
+ }
+ if code, _, out := sdReq(t, fx, http.MethodDelete, "bdq", w.token, ""); code != http.StatusOK {
+ t.Fatalf("remove harbour from bdq = %d %s", code, out)
+ }
+ rollbackAt := sdT0.Add(domains.NamespaceCooldown + 5*time.Minute)
+ clock.Set(rollbackAt)
+
+ host := "x.api.harbour." + nsApps
+ body, err := json.Marshal(rdBoth())
+ if err != nil {
+ t.Fatal(err)
+ }
+ pr, pw := io.Pipe()
+ t.Cleanup(func() { pw.CloseWithError(errors.New("test over")) })
+ type answer struct {
+ code int
+ out string
+ err error
+ }
+ done := make(chan answer, 1)
+ store := &nsRollbackRaceStore{Store: fx.rel, key: domains.ClaimKey(nsHarbourHost), claimsListed: make(chan struct{})}
+ store.admit = func() {
+ req, err := http.NewRequest(http.MethodPut, placementsURL(fx, "shop", host), pr)
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Authorization", "Bearer "+w.token)
+ store.mu.Lock()
+ store.armClaims = true
+ store.mu.Unlock()
+ go func() {
+ res, err := http.DefaultClient.Do(req)
+ if err != nil {
+ done <- answer{err: err}
+ return
+ }
+ defer res.Body.Close()
+ out, err := io.ReadAll(res.Body)
+ done <- answer{code: res.StatusCode, out: string(out), err: err}
+ }()
+ select {
+ case <-store.claimsListed:
+ case <-time.After(10 * time.Second):
+ t.Error("the PUT never loaded its namespace view")
+ }
+ }
+ fx.srv.cfg.Releases = store
+ fx.srv.claims.Reset()
+
+ code, a, out := sdReq(t, fx, http.MethodPost, fx.sqid, w.token, `{"name":"harbour"}`)
+ if code != http.StatusConflict || a.Code != string(domains.SubdomainRolledBack) {
+ t.Fatalf("bab's set with the re-read failing = %d %s, want 409 rolled_back", code, out)
+ }
+ c := nsClaimAt(t, fx, nsHarbourHost)
+ if c == nil || c.Account != fx.sqid || c.RetiredAt != rollbackAt.Format(time.RFC3339) {
+ t.Errorf("claim after the rollback = %+v, want bab's, retired at %s", c, rollbackAt.Format(time.RFC3339))
+ }
+ want := fmt.Sprintf(subdomainRefuseRetiredCooldownCopy, "harbour", retiredCooldownShown(rollbackAt.Add(domains.NamespaceCooldown)))
+ for _, other := range []string{"bcd", "bdq"} {
+ if code, a, out := sdReq(t, fx, http.MethodPost, other, w.token, `{"name":"harbour"}`); code != http.StatusConflict || a.Error != want {
+ t.Errorf("%s right after the rollback = %d %s, want 409 %q", other, code, out, want)
+ }
+ }
+
+ // bab's admitted create lands, late, under the retired name.
+ if _, err := pw.Write(body); err != nil {
+ t.Fatal(err)
+ }
+ pw.Close()
+ var res answer
+ select {
+ case res = <-done:
+ case <-time.After(30 * time.Second):
+ t.Fatal("bab's admitted PUT never answered")
+ }
+ if res.err != nil || res.code != http.StatusOK {
+ t.Fatalf("bab's admitted PUT = %d %s %v, want 200 (the late write)", res.code, res.out, res.err)
+ }
+
+ clock.Set(rollbackAt.Add(domains.NamespaceCooldown - time.Second))
+ if code, a, out := sdReq(t, fx, http.MethodPost, "bcd", w.token, `{"name":"harbour"}`); code != http.StatusConflict || a.Error != want {
+ t.Errorf("bcd a second before the hour = %d %s, want 409 %q", code, out, want)
+ }
+ clock.Set(rollbackAt.Add(domains.NamespaceCooldown))
+ code, a, out = sdReq(t, fx, http.MethodPost, "bcd", w.token, `{"name":"harbour"}`)
+ if code != http.StatusConflict || a.Code != string(domains.SubdomainOccupied) || len(a.Hosts) != 1 || a.Hosts[0].Host != host {
+ t.Errorf("bcd after the hour, bab's host under harbour = %d %s, want 409 occupied listing %s", code, out, host)
+ }
+ if c := nsClaimAt(t, fx, nsHarbourHost); c == nil || c.Account != fx.sqid || c.RetiredAt == "" {
+ t.Errorf("claim = %+v, want bab's, retired", c)
+ }
+}
diff --git a/internal/domains/claims.go b/internal/domains/claims.go
index df7d9fb7d..89c48c1d1 100644
--- a/internal/domains/claims.go
+++ b/internal/domains/claims.go
@@ -115,6 +115,16 @@ type Claim struct {
// namespace.go set or clear it, and only on an AccountNamespace claim.
// Declared here for the round-trip reason above.
RetiredAt string `json:"retired_at,omitempty"`
+ // Revision is a namespace write's own identity: 128 random bits, hex,
+ // fresh on every write of an AccountNamespace claim (namespace.go:
+ // AttachAccountNamespace and putNamespace, the only two). A store's
+ // ETag is a hash of the body, so without it two writes of the same
+ // account, operator and second would have the same bytes and the same
+ // ETag, and an undo conditioned on the earlier write's ETag would land
+ // on the later one. Nothing reads it. Additive: an older binary drops
+ // it on decode and never writes a namespace claim. Declared here for
+ // the round-trip reason above.
+ Revision string `json:"revision,omitempty"`
// Placements makes this a regional claim (#447): the hostname is served
// in each listed region by that region's bound host, never backhauled.
// Only SetClaimPlacements writes it, and only on a schema-2 claim, which
diff --git a/internal/domains/namespace.go b/internal/domains/namespace.go
index 163c9956f..9fece0b5a 100644
--- a/internal/domains/namespace.go
+++ b/internal/domains/namespace.go
@@ -10,6 +10,8 @@ package domains
import (
"context"
+ "crypto/rand"
+ "encoding/hex"
"encoding/json"
"errors"
"fmt"
@@ -144,9 +146,13 @@ func AttachAccountNamespace(ctx context.Context, s release.Store, name, appsDoma
if err != nil {
return "", false, err
}
+ rev, err := newNamespaceRevision()
+ if err != nil {
+ return "", false, err
+ }
body, err := json.Marshal(Claim{
Schema: 1, Host: host, Account: account,
- CreatedAt: createdAt, CreatedBy: createdBy, AccountNamespace: true,
+ CreatedAt: createdAt, CreatedBy: createdBy, AccountNamespace: true, Revision: rev,
})
if err != nil {
return "", false, err
@@ -244,7 +250,9 @@ func (r RetiredNamespace) AvailableAt() time.Time { return r.RetiredAt.Add(Names
// the revision the caller read and judged; the write is conditional on that
// revision too. Anything else at the key, a changed or an absent claim
// answers retired=false. The claim stays at its key: nothing deletes a
-// retired claim but an operator's direct bucket write.
+// retired claim but an operator's direct bucket write. The set door's
+// rollback of an unretire or a replace retires through this too, at its
+// own write's ETag and the door's now, so the cooldown restarts.
func RetireAccountNamespace(ctx context.Context, s release.Store, name, appsDomain, account, etag string, retiredAt time.Time) (newETag string, retired bool, err error) {
host, err := namespaceHostChecked(name, appsDomain, account)
if err != nil {
@@ -266,11 +274,10 @@ func RetireAccountNamespace(ctx context.Context, s release.Store, name, appsDoma
// (RetiredAccountNamespaces trusts it), conditional on that revision;
// anything else answers unretired=false.
//
-// The claim is stamped with now and createdBy as a fresh set is. Besides
-// saying who set the name last, that keeps a retire-then-unretire from
-// writing the bytes of an earlier revision back: a store's ETag is a hash
-// of the body, so identical bytes would let an undo conditioned on the
-// earlier write's ETag land on the later one.
+// The claim is stamped with now and createdBy as a fresh set is, saying who
+// set the name last. Its Revision is fresh (putNamespace), so even an
+// unretire in the same second by the same operator never writes the bytes,
+// and so the ETag, of an earlier revision back.
func UnretireAccountNamespace(ctx context.Context, s release.Store, name, appsDomain, account, etag string, now time.Time, createdBy string) (newETag string, unretired bool, err error) {
host, err := namespaceHostChecked(name, appsDomain, account)
if err != nil {
@@ -319,29 +326,6 @@ func ReplaceRetiredAccountNamespace(ctx context.Context, s release.Store, name,
}, etag)
}
-// RestoreRetiredAccountNamespace undoes an unretire or a replace: it writes
-// prev, the retired claim the undone write replaced, back at its key, only
-// when the claim there is still account's active namespace claim at etag,
-// the ETag the undone write answered, and conditional on that revision. So
-// it never overwrites a later write. prev must be a retired namespace claim
-// for name (RetiredAccountNamespaces trusts it). Anything else answers
-// restored=false.
-func RestoreRetiredAccountNamespace(ctx context.Context, s release.Store, name, appsDomain, account, etag string, prev Claim) (restored bool, err error) {
- host, err := namespaceHostChecked(name, appsDomain, account)
- if err != nil {
- return false, err
- }
- if _, ok := retiredNamespace(prev, name, appsDomain); !ok || prev.Host != host {
- return false, fmt.Errorf("domains: account namespace %q: the claim to restore is not a retired namespace claim", name)
- }
- cur, ok, err := namespaceAt(ctx, s, host, etag)
- if err != nil || !ok || cur.Account != account || cur.RetiredAt != "" {
- return false, err
- }
- _, restored, err = putNamespace(ctx, s, host, prev, etag)
- return restored, err
-}
-
// namespaceAt reads the namespace claim at host when its ETag is etag: ok is
// false with a nil error when the key is empty, holds another revision or a
// claim that is not an AccountNamespace one.
@@ -359,9 +343,14 @@ func namespaceAt(ctx context.Context, s release.Store, host, etag string) (*Clai
return cur, true, nil
}
-// putNamespace writes c at host conditional on etag: a lost CAS answers
-// written=false with a nil error.
+// putNamespace writes c at host conditional on etag, with a fresh
+// Revision: a lost CAS answers written=false with a nil error.
func putNamespace(ctx context.Context, s release.Store, host string, c Claim, etag string) (string, bool, error) {
+ rev, err := newNamespaceRevision()
+ if err != nil {
+ return "", false, err
+ }
+ c.Revision = rev
body, err := json.Marshal(c)
if err != nil {
return "", false, err
@@ -376,6 +365,15 @@ func putNamespace(ctx context.Context, s release.Store, host string, c Claim, et
return newETag, true, nil
}
+// newNamespaceRevision is a fresh Claim.Revision: 128 random bits, hex.
+func newNamespaceRevision() (string, error) {
+ var b [16]byte
+ if _, err := rand.Read(b[:]); err != nil {
+ return "", fmt.Errorf("domains: account namespace revision: %w", err)
+ }
+ return hex.EncodeToString(b[:]), nil
+}
+
// AccountNamespaces folds claims into the namespaces in force under
// appsDomain: byName maps a name to its account's sqid, byAccount a sqid to
// its name. Only claims trustedNamespace accepts count, and of those only
diff --git a/internal/domains/namespace_retire_test.go b/internal/domains/namespace_retire_test.go
index 1cf01d53c..acac3bfec 100644
--- a/internal/domains/namespace_retire_test.go
+++ b/internal/domains/namespace_retire_test.go
@@ -128,64 +128,47 @@ func TestReplaceRetiredAccountNamespaceWaitsTheHour(t *testing.T) {
}
}
-// TestRestoreRetiredAccountNamespaceOnlyOverItsOwnWrite: the undo of an
-// unretire or a replace writes the retired claim back, conditional on the
-// undone write's ETag; a later write at the key is never overwritten.
-func TestRestoreRetiredAccountNamespaceOnlyOverItsOwnWrite(t *testing.T) {
+// TestNamespaceWritesNeverRepeatAnETag (Astra final re-review, Important
+// 2): create, retire and unretire within one second by one operator would
+// write the create's bytes again but for Revision. Each write carries a
+// fresh one, so the ETag is new, and an undo of the create conditioned on
+// its ETag leaves the successor untouched.
+func TestNamespaceWritesNeverRepeatAnETag(t *testing.T) {
ctx := context.Background()
+ s := release.NewDirStore(t.TempDir())
host := NamespaceHost("harbour", nsApps)
- setup := func(t *testing.T) (release.Store, Claim, string) {
- s := release.NewDirStore(t.TempDir())
- etag := heldETag(t, s, "bdq")
- retired, _, err := RetireAccountNamespace(ctx, s, "harbour", nsApps, "bdq", etag, retireT0)
- if err != nil {
- t.Fatal(err)
- }
- prev, _, _ := GetClaimETag(ctx, s, host)
- return s, *prev, retired
- }
- t.Run("unretire", func(t *testing.T) {
- s, prev, retired := setup(t)
- back, _, _ := UnretireAccountNamespace(ctx, s, "harbour", nsApps, "bdq", retired, retireT0.Add(time.Minute), "")
- if ok, err := RestoreRetiredAccountNamespace(ctx, s, "harbour", nsApps, "bdq", back, prev); err != nil || !ok {
- t.Fatalf("restore = (%v, %v)", ok, err)
- }
- if c, _ := GetClaim(ctx, s, host); c.RetiredAt != prev.RetiredAt || c.Account != "bdq" {
- t.Errorf("after restore: %+v", c)
- }
- })
- t.Run("replace", func(t *testing.T) {
- s, prev, retired := setup(t)
- newETag, _, _ := ReplaceRetiredAccountNamespace(ctx, s, "harbour", nsApps, "bcd", retired, retireT0.Add(time.Hour), "")
- if ok, err := RestoreRetiredAccountNamespace(ctx, s, "harbour", nsApps, "bcd", newETag, prev); err != nil || !ok {
- t.Fatalf("restore = (%v, %v)", ok, err)
- }
- if c, _ := GetClaim(ctx, s, host); c.RetiredAt != prev.RetiredAt || c.Account != "bdq" {
- t.Errorf("after restore: %+v", c)
- }
- })
- t.Run("successor", func(t *testing.T) {
- s, prev, retired := setup(t)
- back, _, _ := UnretireAccountNamespace(ctx, s, "harbour", nsApps, "bdq", retired, retireT0.Add(time.Minute), "")
- // Another console retires and takes it back: a later revision.
- again, _, _ := RetireAccountNamespace(ctx, s, "harbour", nsApps, "bdq", back, retireT0.Add(time.Minute))
- later, _, _ := UnretireAccountNamespace(ctx, s, "harbour", nsApps, "bdq", again, retireT0.Add(2*time.Minute), "")
- if ok, err := RestoreRetiredAccountNamespace(ctx, s, "harbour", nsApps, "bdq", back, prev); err != nil || ok {
- t.Fatalf("restore over a successor = (%v, %v), want refused", ok, err)
- }
- if c, got, _ := GetClaimETag(ctx, s, host); got != later || c.RetiredAt != "" {
- t.Errorf("the successor changed: %+v at %q", c, got)
- }
- })
- t.Run("not retired", func(t *testing.T) {
- s, prev, retired := setup(t)
- back, _, _ := UnretireAccountNamespace(ctx, s, "harbour", nsApps, "bdq", retired, retireT0.Add(time.Minute), "")
- active := prev
- active.RetiredAt = ""
- if ok, err := RestoreRetiredAccountNamespace(ctx, s, "harbour", nsApps, "bdq", back, active); err == nil || ok {
- t.Fatalf("restore of an active claim = (%v, %v), want an error", ok, err)
- }
- })
+ at := retireT0.Format(time.RFC3339)
+ created, ok, err := AttachAccountNamespace(ctx, s, "harbour", nsApps, "bdq", at, "ops@example.com")
+ if err != nil || !ok {
+ t.Fatalf("attach = %v, %v", ok, err)
+ }
+ first, _ := GetClaim(ctx, s, host)
+ retired, _, err := RetireAccountNamespace(ctx, s, "harbour", nsApps, "bdq", created, retireT0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ successor, ok, err := UnretireAccountNamespace(ctx, s, "harbour", nsApps, "bdq", retired, retireT0, "ops@example.com")
+ if err != nil || !ok {
+ t.Fatalf("unretire = %v, %v", ok, err)
+ }
+ c, _ := GetClaim(ctx, s, host)
+ if c.Revision == "" || len(c.Revision) != 32 || c.Revision == first.Revision {
+ t.Errorf("revisions: create %q, successor %q; want two different 128-bit hex values", first.Revision, c.Revision)
+ }
+ same := *c
+ same.Revision = first.Revision
+ if same.CreatedAt != first.CreatedAt || same.CreatedBy != first.CreatedBy || same.RetiredAt != "" {
+ t.Fatalf("the sequence did not reproduce the create's fields: %+v vs %+v", same, first)
+ }
+ if successor == created {
+ t.Fatalf("the successor's ETag %q repeats the create's", successor)
+ }
+ if removed, err := DetachAccountNamespaceAt(ctx, s, "harbour", nsApps, "bdq", created); err != nil || removed {
+ t.Fatalf("the create's undo over the successor = %v, %v; want refused", removed, err)
+ }
+ if _, got, err := GetClaimETag(ctx, s, host); err != nil || got != successor {
+ t.Errorf("after the undo: ETag %q (%v), want the successor's %q", got, err, successor)
+ }
}
// TestRetiredAccountNamespacesNeedsATime: a retired_at that does not parse
diff --git a/internal/host/group_names_test.go b/internal/host/group_names_test.go
index 771c22605..8a4a41b23 100644
--- a/internal/host/group_names_test.go
+++ b/internal/host/group_names_test.go
@@ -261,7 +261,7 @@ func TestGroupNameClassCensus(t *testing.T) {
{registry.Route{}, "DemoID DemoHost DemoLifetime DemoExpiresAt ClaimOwnership WakeIncarnation Host Slug Kind Socket Addr Addrs Health Status HoldOp Incarnation ServingSeq SeedSource ImportGate AssetsOff AssetGen PagesOff LastError Stateless FleetBoxes Copies ReplicaRevision ReplicaIncarnation DBPath Version PrevVersion GoodVersion GoodDigest GoodDemand ServingVersion App Pool Region Channel Environment Tunnel FleetBox FleetLabel Assigned Moved Caps Hibernate HA Runtime Gate RateLimit Canary Replication NextDue StatusNamed Backing Unit Platform Provisioned Seed Args IdleSeconds MaxRunSeconds DNSStatus DNSCheckedAt CertExpiresAt Account Steering UpdateSettings EgressAllow Size PolicyExpiresAt BuildState Replicas Replica CreatedAt"},
{provision.Record{}, "DemoClaim Demo ReplicaAssignment Coordinator ReplicaDeploy RecordSeq Acquisition Maintenance Schema Host Slug App Account Pool Region Channel CreatedAt CreatedBy FleetBox FleetBoxAt FleetBoxMoved HA Move LastMove ActiveRun Interactive RunKeys Seed Kind Addr Unit Hibernate Runtime Environment StatusNamed Addrs Health Steering Assets AssetGen Pages Gate Incarnation IncarnationMigrating MoveSeq Retired RateLimit Role Replicas Updates Major Pin InstallRequest"},
{edgeHost{}, "Role Platform Alias Replica Wildcard Account App Stamp Incarnation ServingSeq TargetHost Assets DNSPointing"},
- {domains.Claim{}, "Acquisition RecordIncarnation OwnershipState Schema Host Account App Route CreatedAt CreatedBy Wildcard Catchall Paths Instances AccountNamespace RetiredAt Placements Pending PendingUntil"},
+ {domains.Claim{}, "Acquisition RecordIncarnation OwnershipState Schema Host Account App Route CreatedAt CreatedBy Wildcard Catchall Paths Instances AccountNamespace RetiredAt Revision Placements Pending PendingUntil"},
{registry.RouteAlias{}, "Alias Host Account App DNSStatus DNSCheckedAt CertExpiresAt CreatedAt"},
{registry.RoutePath{}, "Host Prefix Target Account App"},
{registry.WildcardDomain{}, "Host Account App CreatedAt"},