carlos / platform Public

Regional domains (#447) Tasks 2+3 fix round 1: team scope covers the claim revision served

Astra T2+T3 R1 P1: a team request authorized on one claim revision could
act on its successor (a pending claim replaced by a regional one between
the scope step and the handler).

- domains: DetachClaimAt deletes a claim only at the revision the caller
  authorized (ETag match, then release.DeleteIfMatch; a changed or absent
  claim answers removed=false; no unconditional fallback).
- teamdoors.go: inScopeClaimAt (the judged revision's ETag) and
  claimInScope (the rule on a claim already read); teamScopedHook test
  seam after the scope step.
- detach door: a team request takes the app then hostname locks in both
  lifetime modes, judges the scope again under them, answers the scope
  step's not-found bytes when out of scope, skips the first-route
  branches, and deletes through DetachClaimAt at the judged ETag.
- per-host GET and placements GET: a team is answered only about a claim
  snapshot in its scope (teamClaimSnapshotInScope), else the not-found
  bytes.

Tests: TestTeamScopeHoldsForTheClaimRevisionServed (DELETE lifetimes off
and on, GET, placements GET), TestDetachClaimAtDeletesOnlyTheAuthorizedRevision.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev aeb938395161b7db52658215b1318a0923b8641c parent 422a90b
6 files changed, +278 −11
  • internal/console/apidomains.go +69 −4
  • internal/console/apiplacements.go +5 −0
  • internal/console/regional_writers_test.go +87 −0
  • internal/console/teamdoors.go +40 −7
  • internal/domains/claims.go +36 −0
  • internal/domains/regional_claims_test.go +41 −0

Intent

Human

<task-notification> <task-id>af17d5e1dbe1fd0b0</task-id> <tool-use-id>toolu_01MSc8q2yeg1Po4qemSPh7RK</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/c2acaf22-306d-491b-b2b6-addbf33b8e87/tasks/af17d5e1dbe1fd0b0.output</output-file> <status>completed</status> <summary>Agent "Controller: build regional domains #447" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>The Task 3 implementer is working on fix round 1. I'll wait for it before committing anything else in the worktree.</result> <usage><subagent_tokens>257677</subagent_tokens><tool_uses>29</tool_uses><duration_ms>8102492</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>af17d5e1dbe1fd0b0</task-id> <tool-use-id>toolu_01AGcjxsA3ktNZ7RznmwE3pw</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/c2acaf22-306d-491b-b2b6-addbf33b8e87/tasks/af17d5e1dbe1fd0b0.output</output-file> <status>completed</status> <summary>Agent "Controller: build regional domains #447" is waiting on its own background work</summary> <note>This agent stopped with background work of its own still running. It may resume on its own when that work completes or reports, and the same task-id notifies again if it does; the result below may be interim.</note> <result>The fix is in progress in the worktree. I'm watching for its commit and will take the result when it lands.</result> <usage><subagent_tokens>261573</subagent_tokens><tool_uses>33</tool_uses><duration_ms>8356110</duration_ms></usage> </task-notification>

diff --git a/internal/console/apidomains.go b/internal/console/apidomains.go
index cc6d21059..180c63cfd 100644
--- a/internal/console/apidomains.go
+++ b/internal/console/apidomains.go
@@ -1042,10 +1042,33 @@ func (s *Server) handleAPIDomainDetach(w http.ResponseWriter, r *http.Request) {
defer cancel()
// Admitted on, the claim read, the record and the claim release run
// inside the app lock and the hostname exclusion that every attach of
- // the hostname holds from its claim to its record (lifetimes.go).
- if lifetimesUnit(ctx) {
+ // the hostname holds from its claim to its record (lifetimes.go). A team
+ // credential's detach takes them too, admitted on or off.
+ tv, team := teamFrom(r.Context())
+ if lifetimesUnit(ctx) || team {
defer s.lockAppHost(acct.Sqid, app, host)()
}
+ // A team's scope step judged the claim before this handler ran, and the
+ // claim may have changed since (#447: a pending claim the team could
+ // detach can be replaced by a regional one it cannot). So the scope is
+ // judged again here, under the locks, and only the revision judged is
+ // deleted (DetachClaimAt, a conditional delete). Out of scope now is the
+ // scope step's own not-found answer. A team never takes the first-route
+ // branches below: a claim in its scope has a Route.
+ teamETag := ""
+ if team {
+ _, etag, ok, err := tv.inScopeClaimAt(ctx, s, host)
+ if err != nil {
+ log.Printf("console: api domains detach %s/%s %s (team %s): %v", acct.Sqid, app, host, tv.scope, err)
+ jsonError(w, http.StatusBadGateway, "could not read the hostname — try again")
+ return
+ }
+ if !ok {
+ jsonError(w, http.StatusNotFound, "no such hostname")
+ return
+ }
+ teamETag = etag
+ }
// The first-route half (#82): a claim with an empty Route minted the
// app's own primary route via a declared provision record, and that
// record must go BEFORE the claim — the mirror of attach's claim-then-
@@ -1054,7 +1077,9 @@ func (s *Server) handleAPIDomainDetach(w http.ResponseWriter, r *http.Request) {
// first-route claim takes this branch; every other shape (absent,
// another owner's, an alias) skips it silently and DetachClaim's own
// neutrality answers as before.
- if cur, err := domains.GetClaim(ctx, s.cfg.Releases, host); err == nil &&
+ if team {
+ // No first-route branch for a team (above).
+ } else if cur, err := domains.GetClaim(ctx, s.cfg.Releases, host); err == nil &&
cur.Account == acct.Sqid && cur.App == app && cur.Route == "" && lifetimesUnit(ctx) {
// Admitted on: the record retires through its tombstone inside the
// two locks held above (domainattach.go detachRetireLocked).
@@ -1082,7 +1107,17 @@ func (s *Server) handleAPIDomainDetach(w http.ResponseWriter, r *http.Request) {
return
}
}
- removed, err := s.detachDomainClaim(ctx, host, acct.Sqid, app)
+ var (
+ removed bool
+ err error
+ )
+ if team && !s.cfg.HostClaim {
+ removed, err = domains.DetachClaimAt(ctx, s.cfg.Releases, host, acct.Sqid, app, teamETag)
+ } else {
+ // A host-claim console's detachDomainClaim never deletes an alias
+ // marker (errClaimAliasDetachUnsupported), team or not.
+ removed, err = s.detachDomainClaim(ctx, host, acct.Sqid, app)
+ }
if msg, ok := claimAliasRefusal(err); ok {
jsonError(w, http.StatusConflict, msg)
return
@@ -1411,6 +1446,12 @@ func (s *Server) handleAPIDomainGet(w http.ResponseWriter, r *http.Request) {
jsonError(w, http.StatusNotFound, "no such hostname")
return
}
+ // A team answers with the claim it was authorized for only: the scope
+ // step read the claim before this read, and it may have turned regional
+ // (or moved out of scope) in between (#447).
+ if !s.teamClaimSnapshotInScope(w, r, ctx, c, "api domain get") {
+ return
+ }
now := time.Now()
writeJSON(w, http.StatusOK, map[string]any{
"domain": s.domainItem(ctx, *c, aliasReadings(ctx, s.cfg.Releases, now),
@@ -1437,6 +1478,30 @@ func (s *Server) handleAPIDomainGet(w http.ResponseWriter, r *http.Request) {
})
}
+// teamClaimSnapshotInScope judges, for a team request, the claim snapshot a
+// per-host door is about to answer with: the scope step's rule
+// (claimInScope) on what the handler itself read. Out of scope answers the
+// scope step's not-found bytes; a read the judgement needs and cannot make
+// answers 502. ok is false when it has answered. Every other caller is
+// in scope.
+func (s *Server) teamClaimSnapshotInScope(w http.ResponseWriter, r *http.Request, ctx context.Context, c *domains.Claim, door string) bool {
+ tv, team := teamFrom(r.Context())
+ if !team {
+ return true
+ }
+ ok, err := tv.claimInScope(ctx, s, c)
+ if err != nil {
+ log.Printf("console: %s %s/%s %s (team %s): %v", door, tv.acct.Sqid, tv.app, c.Host, tv.scope, err)
+ jsonError(w, http.StatusBadGateway, "could not read the hostname — try again")
+ return false
+ }
+ if !ok {
+ jsonError(w, http.StatusNotFound, "no such hostname")
+ return false
+ }
+ return true
+}
+
// domainListCNAMELookupCap bounds how many live CNAME lookups one
// `carlos domains list` call may perform (IMPORTANT-2, Task 5 review): the
// stamp is a real DNS round trip per wildcard-enabled hostname, sequential
diff --git a/internal/console/apiplacements.go b/internal/console/apiplacements.go
index 17b414cbe..a3b02c8e7 100644
--- a/internal/console/apiplacements.go
+++ b/internal/console/apiplacements.go
@@ -93,6 +93,11 @@ func (s *Server) handleAPIDomainPlacementsGet(w http.ResponseWriter, r *http.Req
jsonError(w, http.StatusNotFound, "no such hostname")
return
}
+ // A team is answered about the claim snapshot read here only if that
+ // snapshot is in its scope (#447): never a regional one.
+ if !s.teamClaimSnapshotInScope(w, r, ctx, c, "api domain placements") {
+ return
+ }
now := time.Now()
var (
snap edgesfile.Snapshot
diff --git a/internal/console/regional_writers_test.go b/internal/console/regional_writers_test.go
index 0684df5f0..496aecea3 100644
--- a/internal/console/regional_writers_test.go
+++ b/internal/console/regional_writers_test.go
@@ -438,3 +438,90 @@ func TestRegionalRecheckLeavesNoPendingAllocation(t *testing.T) {
})
}
}
+
+// TestTeamScopeHoldsForTheClaimRevisionServed (Astra T2+T3 R1 P1): a team
+// request passes its scope step on a pending ordinary claim bound to its
+// own instance, and the member replaces that claim with a regional one
+// (SetClaimPlacements over a pending claim, spec §6.2) before the handler
+// runs. DELETE, the per-host GET and the placements GET each judge the
+// revision they act on: the unknown hostname's not-found bytes, and the
+// regional claim's bytes untouched. DELETE is checked with lifetimes off
+// and on.
+func TestTeamScopeHoldsForTheClaimRevisionServed(t *testing.T) {
+ cases := []struct {
+ name, method, suffix string
+ lifetimesOn bool
+ }{
+ {"DELETE, lifetimes off", http.MethodDelete, "", false},
+ {"DELETE, lifetimes on", http.MethodDelete, "", true},
+ {"GET", http.MethodGet, "", false},
+ {"GET placements", http.MethodGet, "/placements", false},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ var clock *lifetimesClock
+ if c.lifetimesOn {
+ clock = useLifetimesClock(t)
+ }
+ w := newTeamWorld(t, "code-team-race")
+ if c.lifetimesOn {
+ turnLifetimesOn(t, w.fx.srv, clock)
+ }
+ ctx := context.Background()
+ const host = "race.example.com"
+ _, _, pending, err := domains.AttachClaimProven(ctx, w.fx.rel,
+ domains.Claim{Host: host, Account: "bab", App: "titogo", Route: "mine.go.tito.io"},
+ time.Now(), func() bool { return false })
+ if err != nil || !pending {
+ t.Fatalf("pending claim: pending=%v err=%v", pending, err)
+ }
+ unknownStatus, _, unknown := rawReq(t, http.MethodGet, w.url("/domains/nope.example.com"), w.team, "")
+ if unknownStatus != http.StatusNotFound {
+ t.Fatalf("GET an unknown hostname = %d %s", unknownStatus, unknown)
+ }
+ var (
+ fired atomic.Bool
+ mu sync.Mutex
+ writeErr error
+ )
+ h := func(r *http.Request) {
+ if !fired.CompareAndSwap(false, true) {
+ return
+ }
+ cur, etag, err := domains.GetClaimETag(ctx, w.fx.rel, host)
+ if err == nil {
+ next := domains.Claim{Host: host, Account: "bab", App: "titogo", Route: "mine.go.tito.io",
+ CreatedAt: cur.CreatedAt, CreatedBy: cur.CreatedBy,
+ Placements: []domains.Placement{{Region: "", Host: "mine.go.tito.io"}, {Region: "uk", Host: rdUKHost}}}
+ var changed bool
+ if changed, err = domains.SetClaimPlacements(ctx, w.fx.rel, next, cur, etag); err == nil && !changed {
+ err = errors.New("SetClaimPlacements wrote nothing")
+ }
+ }
+ mu.Lock()
+ writeErr = err
+ mu.Unlock()
+ }
+ teamScopedHook.Store(&h)
+ t.Cleanup(func() { teamScopedHook.Store(nil) })
+ status, _, out := rawReq(t, c.method, w.url("/domains/"+host+c.suffix), w.team, "")
+ teamScopedHook.Store(nil)
+ mu.Lock()
+ err = writeErr
+ mu.Unlock()
+ if !fired.Load() || err != nil {
+ t.Fatalf("the claim was not replaced after the scope step (fired %v): %v", fired.Load(), err)
+ }
+ if status != unknownStatus || out != unknown {
+ t.Errorf("%s %s = %d %s, want the unknown hostname's %d %s", c.method, c.suffix, status, out, unknownStatus, unknown)
+ }
+ got, err := domains.GetClaim(ctx, w.fx.rel, host)
+ if err != nil || !got.Regional() {
+ t.Fatalf("claim after the race = %+v, %v; want the regional claim standing", got, err)
+ }
+ if n := eventsOf(t, w.fx.st, "titogo", "domain-detach"); n != 0 {
+ t.Fatalf("%d domain-detach rows, want none", n)
+ }
+ })
+ }
+}
diff --git a/internal/console/teamdoors.go b/internal/console/teamdoors.go
index 24bb122a1..22031d2bf 100644
--- a/internal/console/teamdoors.go
+++ b/internal/console/teamdoors.go
@@ -26,6 +26,7 @@ import (
"sort"
"strings"
"sync"
+ "sync/atomic"
"github.com/carlosframework/platform/internal/appconfig"
"github.com/carlosframework/platform/internal/domains"
@@ -88,12 +89,20 @@ func (s *Server) cliScopedRoute(pattern string, allow svcrole.Set, target scopeT
if !ok {
return
}
+ if h := teamScopedHook.Load(); h != nil {
+ (*h)(r)
+ }
r = r.WithContext(context.WithValue(r.Context(), teamKey{}, tv))
}
h(w, r)
}))
}
+// teamScopedHook, when set, runs after a team request passes its scope
+// step and before the handler. A TEST SEAM: the stale-authorization races
+// (#447), where the target changes between the two.
+var teamScopedHook atomic.Pointer[func(r *http.Request)]
+
// teamKey is the context key the scoped registration stashes the team's
// view under. Unexported, so nothing outside this package can forge one.
type teamKey struct{}
@@ -229,18 +238,42 @@ func (tv *teamView) inScopeHost(ctx context.Context, s *Server, host string) (*p
// A regional claim (#447, spec §6.4) is out of scope too, whichever of its
// bound hosts is in scope: it serves the app in every region at once.
func (tv *teamView) inScopeClaim(ctx context.Context, s *Server, host string) (*domains.Claim, bool, error) {
- c, err := domains.GetClaim(ctx, s.cfg.Releases, host)
- if err != nil && !errors.Is(err, os.ErrNotExist) {
- return nil, false, err
+ c, _, ok, err := tv.inScopeClaimAt(ctx, s, host)
+ return c, ok, err
+}
+
+// inScopeClaimAt is inScopeClaim with the ETag of the revision it judged,
+// so a writer can act on exactly that revision (the team detach deletes
+// only it, #447).
+func (tv *teamView) inScopeClaimAt(ctx context.Context, s *Server, host string) (*domains.Claim, string, bool, error) {
+ c, etag, err := domains.GetClaimETag(ctx, s.cfg.Releases, host)
+ if errors.Is(err, os.ErrNotExist) {
+ return nil, "", false, nil
}
- if err != nil || c == nil || c.Account != tv.acct.Sqid || c.App != tv.app || c.Route == "" || c.Instances || c.Regional() {
- return nil, false, nil
+ if err != nil {
+ return nil, "", false, err
+ }
+ ok, err := tv.claimInScope(ctx, s, c)
+ if err != nil || !ok {
+ return nil, "", false, err
+ }
+ return c, etag, true, nil
+}
+
+// claimInScope is inScopeClaim's rule applied to a claim already read. The
+// scope step judges the claim it reads before the handler runs; a handler
+// that reads the claim again judges what it read here before answering
+// with it, so the revision a team sees is the revision that was authorized
+// (#447: a claim can turn regional in between).
+func (tv *teamView) claimInScope(ctx context.Context, s *Server, c *domains.Claim) (bool, error) {
+ if c == nil || c.Account != tv.acct.Sqid || c.App != tv.app || c.Route == "" || c.Instances || c.Regional() {
+ return false, nil
}
_, ok, err := tv.inScopeHost(ctx, s, c.Route)
if err != nil || !ok {
- return nil, false, err
+ return false, err
}
- return c, true, nil
+ return true, nil
}
// teamInScope is THE deciding function (§4): for a team principal at a
diff --git a/internal/domains/claims.go b/internal/domains/claims.go
index dfe213e9b..656688bc2 100644
--- a/internal/domains/claims.go
+++ b/internal/domains/claims.go
@@ -829,6 +829,35 @@ func claimRawDetachClaim(ctx context.Context, s release.Store, host, account, ap
return true, nil
}
+// claimRawDetachClaimAt is DetachClaim held to one revision of the claim:
+// it deletes host's claim only when it is still account/app's and its ETag
+// is etag, the revision the caller authorized (a team credential's detach,
+// #447). The delete is release.DeleteIfMatch, so a claim replaced between
+// the read here and the delete is not removed either. A changed or absent
+// claim answers removed=false, like any claim that is not the caller's. A
+// store that cannot delete conditionally refuses
+// (release.ErrConditionalDeleteUnsupported): never an unconditional delete.
+func claimRawDetachClaimAt(ctx context.Context, s release.Store, host, account, app, etag string) (bool, error) {
+ cur, curETag, err := getClaimETag(ctx, s, host)
+ if errors.Is(err, os.ErrNotExist) {
+ return false, nil
+ }
+ if err != nil {
+ return false, err
+ }
+ if curETag != etag || cur.Account != account || cur.App != app {
+ return false, nil
+ }
+ err = release.DeleteIfMatch(ctx, s, ClaimKey(host), etag)
+ if errors.Is(err, release.ErrCASConflict) {
+ return false, nil
+ }
+ if err != nil {
+ return false, err
+ }
+ return true, nil
+}
+
// ListClaims returns every valid claim in the bucket. An unparseable or
// newer-schema object is logged and skipped — one bad claim must never take
// the whole listing down.
@@ -1151,6 +1180,13 @@ func DetachClaim(ctx context.Context, s release.Store, host, account, app string
})
return
}
+func DetachClaimAt(ctx context.Context, s release.Store, host, account, app, etag string) (claimResult0 bool, claimResult1 error) {
+ claimResult1 = release.WithAppMutation(ctx, s, account, app, "domains.DetachClaimAt", func(claimContext context.Context) error {
+ claimResult0, claimResult1 = claimRawDetachClaimAt(claimContext, s, host, account, app, etag)
+ return claimResult1
+ })
+ return
+}
func SetClaimCapabilities(ctx context.Context, s release.Store, host, account, app string, wildcard, catchall bool) (claimResult0 bool, claimResult1 error) {
claimResult1 = release.WithAppMutation(ctx, s, account, app, "domains.SetClaimCapabilities", func(claimContext context.Context) error {
claimResult0, claimResult1 = claimRawSetClaimCapabilities(claimContext, s, host, account, app, wildcard, catchall)
diff --git a/internal/domains/regional_claims_test.go b/internal/domains/regional_claims_test.go
index 536712924..b011da7a3 100644
--- a/internal/domains/regional_claims_test.go
+++ b/internal/domains/regional_claims_test.go
@@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"fmt"
+ "os"
"reflect"
"strings"
"testing"
@@ -424,3 +425,43 @@ func TestRegionalRoute(t *testing.T) {
t.Fatalf("no home: got %q, want the first region in code order (de)", got)
}
}
+
+// TestDetachClaimAtDeletesOnlyTheAuthorizedRevision (Astra T2+T3 R1 P1): a
+// team detach authorizes one revision of the claim and deletes only that
+// one. A claim replaced since (here by a regional claim) answers
+// removed=false and keeps its bytes; another owner's claim is not removed;
+// the authorized revision is.
+func TestDetachClaimAtDeletesOnlyTheAuthorizedRevision(t *testing.T) {
+ ctx := context.Background()
+ s := release.NewDirStore(t.TempDir())
+ pending := Claim{Host: "shop.example.com", Account: "bab", App: "shop", Route: "shop-ie.example.net"}
+ if _, _, _, err := AttachClaimProven(ctx, s, pending, time.Now(), func() bool { return false }); err != nil {
+ t.Fatal(err)
+ }
+ cur, authorized, err := GetClaimETag(ctx, s, "shop.example.com")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := SetClaimPlacements(ctx, s, regionalClaim(), cur, authorized); err != nil {
+ t.Fatal(err)
+ }
+ before, beforeETag := rawClaim(t, s, "shop.example.com")
+ if removed, err := DetachClaimAt(ctx, s, "shop.example.com", "bab", "shop", authorized); err != nil || removed {
+ t.Fatalf("detach at the replaced revision: removed=%v err=%v, want false, nil", removed, err)
+ }
+ if after, afterETag := rawClaim(t, s, "shop.example.com"); string(after) != string(before) || afterETag != beforeETag {
+ t.Fatalf("the regional claim changed:\n%s\n%s", before, after)
+ }
+ if removed, err := DetachClaimAt(ctx, s, "shop.example.com", "acme", "shop", beforeETag); err != nil || removed {
+ t.Fatalf("another owner's detach: removed=%v err=%v, want false, nil", removed, err)
+ }
+ if removed, err := DetachClaimAt(ctx, s, "shop.example.com", "bab", "shop", beforeETag); err != nil || !removed {
+ t.Fatalf("detach at the current revision: removed=%v err=%v, want true", removed, err)
+ }
+ if _, err := GetClaim(ctx, s, "shop.example.com"); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("claim after the detach: %v, want none", err)
+ }
+ if removed, err := DetachClaimAt(ctx, s, "shop.example.com", "bab", "shop", beforeETag); err != nil || removed {
+ t.Fatalf("detach of an absent claim: removed=%v err=%v, want false, nil", removed, err)
+ }
+}