carlos / platform Public

domains: one import invariant, its writer, remover and reconcile (#1429)

certimport_invariant.go states the invariant and is the only
implementation of each decision: WriteImport (the writer), RemoveImport
(the operator delete), StaleImport and ReconcileImport (the cleanup
decision and delete). Each reads the entry's revision first, then the
claim, then acts conditionally on that revision; a lost race starts
again from fresh reads; WriteImport confirms against a fresh claim read
after its Put and withdraws only its own revision. An unreadable claim
keeps the entry. Matches now shares claimHoldsImports (adds created_at
present and not quarantined).

The console's import and remove doors call WriteImport and RemoveImport;
their own CAS loop is gone. certimport_sim_test.go runs 2000 seeds x 50
ops with seeded interleaving before every store call and checks S1-S5;
seven weakenings (blind retry, claim read first, no confirm,
unconditional withdraw, unconditional reconcile or remove delete,
unread as absent) each fail it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 11589da8d97f8a08942f8324b504869fdfd87b55 parent 49ff83e
5 files changed, +982 −49
  • internal/console/apidomaincert.go +24 −46
  • internal/domains/certimport.go +4 −3
  • internal/domains/certimport_invariant.go +281 −0
  • internal/domains/certimport_invariant_test.go +176 −0
  • internal/domains/certimport_sim_test.go +497 −0
diff --git a/internal/console/apidomaincert.go b/internal/console/apidomaincert.go
index 293e7e441..a0a240ace 100644
--- a/internal/console/apidomaincert.go
+++ b/internal/console/apidomaincert.go
@@ -34,7 +34,6 @@ import (
"time"
"github.com/carlosframework/platform/internal/domains"
- "github.com/carlosframework/platform/internal/release"
"golang.org/x/crypto/x509roots/fallback/bundle"
)
@@ -313,30 +312,6 @@ func summarizeCert(host string, leaf *x509.Certificate) certSummary {
}
}
-// importKey is host's import entry in the deployment bucket.
-func importKey(host string) string { return "control/certs/" + domains.ImportName(host) }
-
-// putImportCAS is create-or-replace with compare-and-swap, the shape of the
-// edge's putCAS (internal/edge/certsync.go): read the etag, put on it,
-// and on a lost race read again, three times at most.
-func putImportCAS(ctx context.Context, s release.Store, key string, body []byte) error {
- for attempt := 0; attempt < 3; attempt++ {
- _, etag, err := s.Get(ctx, key)
- switch {
- case errors.Is(err, os.ErrNotExist):
- etag = ""
- case err != nil:
- return fmt.Errorf("get %s: %w", key, err)
- }
- if _, err := s.Put(ctx, key, body, etag); err == nil {
- return nil
- } else if !errors.Is(err, release.ErrCASConflict) {
- return fmt.Errorf("put %s: %w", key, err)
- }
- }
- return fmt.Errorf("%s: lost CAS race three times", key)
-}
-
// certDoorGate is gates 1 to 3 of both verbs: the domains family's gate,
// a platform operator, and a live exact claim this app holds. ok is false
// once it has answered.
@@ -376,7 +351,7 @@ func (s *Server) certDoorGate(w http.ResponseWriter, r *http.Request) (p Princip
// handleAPIDomainCertImport is PUT .../domains/{host}/cert.
func (s *Server) handleAPIDomainCertImport(w http.ResponseWriter, r *http.Request) {
- p, acct, app, host, claim, ctx, cancel, ok := s.certDoorGate(w, r)
+ p, acct, app, host, _, ctx, cancel, ok := s.certDoorGate(w, r)
if !ok {
return
}
@@ -406,17 +381,19 @@ func (s *Server) handleAPIDomainCertImport(w http.ResponseWriter, r *http.Reques
jsonError(w, http.StatusBadRequest, err.Error())
return
}
- entry := domains.EncodeImport(domains.ImportBinding{
- Host: host, Account: acct.Sqid, App: app, ClaimCreated: claim.CreatedAt,
- }, v.pkcs8, v.chain)
- // What the edges will parse is what was verified; a mismatch here is
- // this file's bug, never the caller's input.
- if _, _, err := domains.ParseImport(entry); err != nil {
- log.Printf("console: domain cert import %s/%s %s: entry does not parse", acct.Sqid, app, host)
- jsonError(w, http.StatusInternalServerError, certWriteFailed)
+ // The write, its claim check and its confirmation are WriteImport's
+ // (internal/domains/certimport_invariant.go), the one writer: the
+ // entry is bound to the claim it reads, not the one the gate read.
+ _, err = domains.WriteImport(ctx, s.cfg.Releases, host, acct.Sqid, app, func(c domains.Claim) []byte {
+ return domains.EncodeImport(domains.ImportBinding{
+ Host: host, Account: acct.Sqid, App: app, ClaimCreated: c.CreatedAt,
+ }, v.pkcs8, v.chain)
+ })
+ if errors.Is(err, domains.ErrImportNoClaim) {
+ jsonError(w, http.StatusNotFound, certNoSuchHost)
return
}
- if err := putImportCAS(ctx, s.cfg.Releases, importKey(host), entry); err != nil {
+ if err != nil {
log.Printf("console: domain cert import %s/%s %s: %v", acct.Sqid, app, host, err)
jsonError(w, http.StatusBadGateway, certWriteFailed)
return
@@ -438,25 +415,26 @@ func (s *Server) handleAPIDomainCertRemove(w http.ResponseWriter, r *http.Reques
return
}
defer cancel()
- key := importKey(host)
- raw, _, err := s.cfg.Releases.Get(ctx, key)
- if errors.Is(err, os.ErrNotExist) {
- writeJSON(w, http.StatusOK, map[string]any{"host": host, "removed": false})
+ // RemoveImport (certimport_invariant.go) is the one operator delete:
+ // it deletes only the revision it read, and only while account and
+ // app still hold the claim.
+ removed, _, cert, err := domains.RemoveImport(ctx, s.cfg.Releases, host, acct.Sqid, app)
+ if errors.Is(err, domains.ErrImportNoClaim) {
+ jsonError(w, http.StatusNotFound, certNoSuchHost)
return
}
if err != nil {
log.Printf("console: domain cert remove %s/%s %s: %v", acct.Sqid, app, host, err)
- jsonError(w, http.StatusBadGateway, certReadFailed)
+ jsonError(w, http.StatusBadGateway, certRemoveFailed)
return
}
- if err := s.cfg.Releases.Delete(ctx, key); err != nil {
- log.Printf("console: domain cert remove %s/%s %s: %v", acct.Sqid, app, host, err)
- jsonError(w, http.StatusBadGateway, certRemoveFailed)
+ if !removed {
+ writeJSON(w, http.StatusOK, map[string]any{"host": host, "removed": false})
return
}
detail := fmt.Sprintf(certAuditRemoveUnknown, host)
- if _, pair, err := domains.ParseImport(raw); err == nil {
- sum := summarizeCert(host, pair.Leaf)
+ if cert != nil && cert.Leaf != nil {
+ sum := summarizeCert(host, cert.Leaf)
detail = fmt.Sprintf(certAuditRemove, host, sum.SHA256, sum.Issuer, sum.NotAfter)
}
s.audit(acct, app, auditActor(p, acct), "domain-cert-remove", detail)
@@ -468,7 +446,7 @@ func (s *Server) handleAPIDomainCertRemove(w http.ResponseWriter, r *http.Reques
// acquisition; nil otherwise, a read failure included (the read answers
// without it rather than failing).
func (s *Server) importedCertSummary(ctx context.Context, c domains.Claim) *certSummary {
- raw, _, err := s.cfg.Releases.Get(ctx, importKey(c.Host))
+ raw, _, err := s.cfg.Releases.Get(ctx, domains.ImportKey(c.Host))
if err != nil {
if !errors.Is(err, os.ErrNotExist) {
log.Printf("console: api domain get %s: imported cert: %v", c.Host, err)
diff --git a/internal/domains/certimport.go b/internal/domains/certimport.go
index 3ed62f5c2..5b98e3fdd 100644
--- a/internal/domains/certimport.go
+++ b/internal/domains/certimport.go
@@ -55,11 +55,12 @@ type ImportBinding struct {
}
// Matches reports whether c is the claim acquisition b was made for, and
-// still a live exact claim: not pending, not an instance catch-all.
+// still a claim an import may be bound to (claimHoldsImports,
+// certimport_invariant.go): exact, proven, not a catch-all, not
+// quarantined.
func (b ImportBinding) Matches(c Claim) bool {
return c.Host == b.Host && c.Account == b.Account && c.App == b.App &&
- c.CreatedAt == b.ClaimCreated && b.ClaimCreated != "" &&
- !c.Pending && !c.Instances && !strings.HasPrefix(c.Host, "*.")
+ c.CreatedAt == b.ClaimCreated && b.ClaimCreated != "" && claimHoldsImports(c)
}
// EncodeImport builds an import entry from a binding, a PKCS#8 key DER and
diff --git a/internal/domains/certimport_invariant.go b/internal/domains/certimport_invariant.go
new file mode 100644
index 000000000..715c97285
--- /dev/null
+++ b/internal/domains/certimport_invariant.go
@@ -0,0 +1,281 @@
+package domains
+
+// THE INVARIANT (#1429, spec round 2, option A):
+//
+// control/certs/<host>+import holds only an entry whose binding matched the
+// host's claim at the moment it was confirmed; an entry is withdrawn only by
+// the revision that was read, so no writer or deleter acting on a stale view
+// can replace or delete an entry bound to a newer acquisition; an unreadable
+// claim is never read as a detached one.
+//
+// Authority is the binding's four fields: (Host, Account, App,
+// ClaimCreated). The claim's acq field belongs to host-claim mode, and a
+// host-claim console does not register the import door, so created_at is
+// the acquisition stamp. It is second-granular: two acquisitions of one
+// host that collide on all four fields within one second are, by
+// definition, the same authority (same account, same app), and an import
+// made for one serves the other.
+//
+// This file is the only implementation of each decision:
+//
+// - WriteImport: the only writer (the console's import door).
+// - RemoveImport: the only operator delete (the console's remove door).
+// - ReconcileImport and StaleImport: the only cleanup delete and the only
+// cleanup decision (the issuer's reconcile).
+//
+// One ordering rule makes the CAS sufficient, and every function here
+// follows it: read the entry's revision FIRST, then the claim, then act
+// conditionally on that revision. Any entry bound to an acquisition newer
+// than the claim that was read must have been written after that claim
+// read, so after the entry read, so it carries a different revision and the
+// conditional Put or delete refuses. Reading the claim first leaves a window
+// in which a successor's import can be read, judged against the old claim,
+// and replaced or deleted (certimport_sim_test.go's mutation shows it).
+
+import (
+ "context"
+ "crypto/tls"
+ "errors"
+ "fmt"
+ "os"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// ImportKey is host's import entry in the deployment bucket.
+func ImportKey(host string) string { return "control/certs/" + ImportName(host) }
+
+// importAttempts bounds each loop here: a lost race re-reads everything
+// and tries again, three times at most.
+const importAttempts = 3
+
+// ErrImportNoClaim is the refusal when host's claim is not a live exact
+// claim held by the caller's account and app, or stopped being one before
+// the write was confirmed.
+var ErrImportNoClaim = errors.New("domains: no live claim for this import")
+
+// ErrImportRace is three lost races in a row.
+var ErrImportRace = errors.New("domains: import changed under three attempts")
+
+// claimHoldsImports reports whether c is a claim an import may be bound
+// to: an exact name, proven, not a catch-all, not quarantined, with an
+// acquisition stamp. It is half of ImportBinding.Matches, and the whole of
+// the writer's and remover's claim check.
+func claimHoldsImports(c Claim) bool {
+ return c.CreatedAt != "" && !c.Pending && !c.Instances && !strings.HasPrefix(c.Host, "*.") &&
+ c.OwnershipState != "quarantined"
+}
+
+// readImportClaim reads host's claim for the functions below. absent is
+// true only for a confirmed absence; any other failure is an error, never
+// an absence.
+func readImportClaim(ctx context.Context, s release.Store, host string) (c *Claim, absent bool, err error) {
+ c, err = GetClaim(ctx, s, host)
+ if errors.Is(err, os.ErrNotExist) {
+ return nil, true, nil
+ }
+ if err != nil {
+ return nil, false, err
+ }
+ return c, false, nil
+}
+
+// readImportEntry reads host's entry and its revision; etag "" means
+// confirmed absent.
+func readImportEntry(ctx context.Context, s release.Store, host string) (raw []byte, etag string, err error) {
+ raw, etag, err = s.Get(ctx, ImportKey(host))
+ if errors.Is(err, os.ErrNotExist) {
+ return nil, "", nil
+ }
+ if err != nil {
+ return nil, "", err
+ }
+ if etag == "" {
+ return nil, "", fmt.Errorf("domains: import %s: read without a revision", host)
+ }
+ return raw, etag, nil
+}
+
+// WriteImport creates or replaces host's import for the claim account and
+// app hold, and returns that claim. entry builds the bytes from the claim
+// it is handed (EncodeImport with a binding of host, account, app and the
+// claim's CreatedAt); it may be called once per attempt.
+//
+// Each attempt reads afresh, in the file's order: the entry's revision,
+// then the claim, then a Put conditional on the revision read (create-only
+// when absent). A lost race starts a new attempt from new reads, never a
+// retry with only a new revision. After the Put the claim is read again;
+// if it no longer matches the binding, or cannot be read, the write is
+// withdrawn by the revision it created and nothing else is touched.
+func WriteImport(ctx context.Context, s release.Store, host, account, app string, entry func(Claim) []byte) (Claim, error) {
+ if !validHostShape(host) || account == "" || app == "" {
+ return Claim{}, ErrImportNoClaim
+ }
+ key := ImportKey(host)
+ for attempt := 0; attempt < importAttempts; attempt++ {
+ _, etag, err := readImportEntry(ctx, s, host)
+ if err != nil {
+ return Claim{}, err
+ }
+ c, absent, err := readImportClaim(ctx, s, host)
+ if err != nil {
+ return Claim{}, err
+ }
+ if absent || c.Host != host || c.Account != account || c.App != app || !claimHoldsImports(*c) {
+ return Claim{}, ErrImportNoClaim
+ }
+ binding := ImportBinding{Host: host, Account: account, App: app, ClaimCreated: c.CreatedAt}
+ written, err := s.Put(ctx, key, entry(*c), etag)
+ if errors.Is(err, release.ErrCASConflict) {
+ continue
+ }
+ if err != nil {
+ return Claim{}, err
+ }
+ // Confirm: the claim must still be the one the entry is bound to.
+ now, absent, err := readImportClaim(ctx, s, host)
+ if err == nil && !absent && binding.Matches(*now) {
+ return *c, nil
+ }
+ if werr := withdrawImport(ctx, s, key, written); werr != nil {
+ return Claim{}, errors.Join(ErrImportNoClaim, werr)
+ }
+ if err != nil {
+ return Claim{}, err
+ }
+ return Claim{}, ErrImportNoClaim
+ }
+ return Claim{}, ErrImportRace
+}
+
+// withdrawImport deletes the revision this process wrote. A conflict means
+// someone has replaced it since, and theirs stays.
+func withdrawImport(ctx context.Context, s release.Store, key, etag string) error {
+ err := release.DeleteIfMatch(ctx, s, key, etag)
+ if errors.Is(err, release.ErrCASConflict) {
+ return nil
+ }
+ return err
+}
+
+// RemoveImport deletes host's import for the claim account and app hold.
+// It reads the entry's revision, then the claim (which must still be a
+// live claim of account and app, else ErrImportNoClaim), then deletes
+// conditionally on that revision; a lost race starts again from new reads.
+// removed is false when there was no entry. b and cert describe what was
+// removed when it parsed (cert nil otherwise). A store that cannot delete
+// conditionally deletes nothing and is an error.
+func RemoveImport(ctx context.Context, s release.Store, host, account, app string) (removed bool, b ImportBinding, cert *tls.Certificate, err error) {
+ if !validHostShape(host) || account == "" || app == "" {
+ return false, ImportBinding{}, nil, ErrImportNoClaim
+ }
+ for attempt := 0; attempt < importAttempts; attempt++ {
+ raw, etag, err := readImportEntry(ctx, s, host)
+ if err != nil {
+ return false, ImportBinding{}, nil, err
+ }
+ if etag == "" {
+ return false, ImportBinding{}, nil, nil
+ }
+ c, absent, err := readImportClaim(ctx, s, host)
+ if err != nil {
+ return false, ImportBinding{}, nil, err
+ }
+ if absent || c.Account != account || c.App != app || !claimHoldsImports(*c) {
+ return false, ImportBinding{}, nil, ErrImportNoClaim
+ }
+ err = release.DeleteIfMatch(ctx, s, ImportKey(host), etag)
+ if errors.Is(err, release.ErrCASConflict) {
+ continue
+ }
+ if err != nil {
+ return false, ImportBinding{}, nil, err
+ }
+ if pb, pc, perr := ParseImport(raw); perr == nil {
+ return true, pb, pc, nil
+ }
+ return true, ImportBinding{}, nil, nil
+ }
+ return false, ImportBinding{}, nil, ErrImportRace
+}
+
+// The reconcile's reasons. Fixed sentences: no entry or claim bytes.
+const (
+ ImportStaleUnreadable = "entry does not parse"
+ ImportStaleOtherHost = "entry is bound to another hostname"
+ ImportStaleExpired = "certificate expired"
+ ImportStaleNoClaim = "claim is gone"
+ ImportStaleNotHeld = "claim is pending, a catch-all or quarantined"
+ ImportStaleOtherOwner = "claim is held by another account or app"
+ ImportStaleReacquired = "claim was acquired again since the import"
+)
+
+// StaleImport is the reconcile's only delete decision for host's entry
+// raw, judged against claim: nil with claimUnread false means confirmed
+// absent; claimUnread means the claim could not be read, which keeps the
+// entry (an unreadable claim is never read as a detached one). An entry
+// whose leaf expired more than grace ago is stale whatever the claim says.
+//
+// The claim must have been read AFTER raw's revision was read, and a
+// stale verdict acted on only with a delete conditional on that revision
+// (ReconcileImport does both). A claim view older than the entry can
+// misjudge a successor's import.
+func StaleImport(host string, raw []byte, claim *Claim, claimUnread bool, now time.Time, grace time.Duration) (reason string, stale bool) {
+ b, cert, err := ParseImport(raw)
+ if err != nil {
+ return ImportStaleUnreadable, true
+ }
+ if b.Host != host {
+ return ImportStaleOtherHost, true
+ }
+ if now.After(cert.Leaf.NotAfter.Add(grace)) {
+ return ImportStaleExpired, true
+ }
+ if claimUnread {
+ return "", false
+ }
+ if claim == nil {
+ return ImportStaleNoClaim, true
+ }
+ if b.Matches(*claim) {
+ return "", false
+ }
+ switch {
+ case claim.Account != b.Account || claim.App != b.App:
+ return ImportStaleOtherOwner, true
+ case !claimHoldsImports(*claim):
+ return ImportStaleNotHeld, true
+ default:
+ return ImportStaleReacquired, true
+ }
+}
+
+// ReconcileImport is one reconcile step for host: read the entry and its
+// revision, then the claim, judge with StaleImport, and delete only that
+// revision. A failed claim read keeps the entry. A lost delete race
+// deletes nothing and reports deleted false: the next pass judges the new
+// revision. reason is StaleImport's, for the one log line per delete.
+func ReconcileImport(ctx context.Context, s release.Store, host string, now time.Time, grace time.Duration) (deleted bool, reason string, err error) {
+ raw, etag, err := readImportEntry(ctx, s, host)
+ if err != nil || etag == "" {
+ return false, "", err
+ }
+ c, absent, cerr := readImportClaim(ctx, s, host)
+ if !absent && cerr == nil && c == nil {
+ cerr = fmt.Errorf("domains: claim %s: read nothing", host)
+ }
+ reason, stale := StaleImport(host, raw, c, cerr != nil, now, grace)
+ if !stale {
+ return false, "", cerr
+ }
+ err = release.DeleteIfMatch(ctx, s, ImportKey(host), etag)
+ if errors.Is(err, release.ErrCASConflict) {
+ return false, "", nil
+ }
+ if err != nil {
+ return false, "", err
+ }
+ return true, reason, nil
+}
diff --git a/internal/domains/certimport_invariant_test.go b/internal/domains/certimport_invariant_test.go
new file mode 100644
index 000000000..bd6e47dc1
--- /dev/null
+++ b/internal/domains/certimport_invariant_test.go
@@ -0,0 +1,176 @@
+package domains
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+func putTestClaim(t *testing.T, s release.Store, c Claim) {
+ t.Helper()
+ c.Schema = 1
+ raw, err := json.Marshal(c)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, etag, _ := s.Get(context.Background(), ClaimKey(c.Host))
+ if _, err := s.Put(context.Background(), ClaimKey(c.Host), raw, etag); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func testEntry(t *testing.T, account, app string) func(Claim) []byte {
+ pkcs8, leaf := simMaterial(t)
+ return func(c Claim) []byte {
+ return EncodeImport(ImportBinding{Host: simHost, Account: account, App: app, ClaimCreated: c.CreatedAt}, pkcs8, [][]byte{leaf})
+ }
+}
+
+// noCondStore is a store that cannot delete conditionally.
+type noCondStore struct{ release.Store }
+
+func TestWriteImportRefusesWhatTheClaimDoesNotHold(t *testing.T) {
+ ctx := context.Background()
+ live := Claim{Host: simHost, Account: "acca", App: "web", Route: "r.example.net", CreatedAt: "2026-11-20T10:00:00Z"}
+ for name, c := range map[string]*Claim{
+ "no claim": nil,
+ "other account": {Host: simHost, Account: "accb", App: "web", Route: "r.example.net", CreatedAt: live.CreatedAt},
+ "other app": {Host: simHost, Account: "acca", App: "api", Route: "r.example.net", CreatedAt: live.CreatedAt},
+ "pending": {Host: simHost, Account: "acca", App: "web", Route: "r.example.net", CreatedAt: live.CreatedAt, Pending: true},
+ "no created_at": {Host: simHost, Account: "acca", App: "web", Route: "r.example.net"},
+ "quarantined": {Host: simHost, Account: "acca", App: "web", Route: "r.example.net", CreatedAt: live.CreatedAt, OwnershipState: "quarantined"},
+ } {
+ s := release.NewDirStore(t.TempDir())
+ if c != nil {
+ putTestClaim(t, s, *c)
+ }
+ if _, err := WriteImport(ctx, s, simHost, "acca", "web", testEntry(t, "acca", "web")); !errors.Is(err, ErrImportNoClaim) {
+ t.Errorf("%s: %v, want ErrImportNoClaim", name, err)
+ }
+ if _, _, err := s.Get(ctx, ImportKey(simHost)); !errors.Is(err, os.ErrNotExist) {
+ t.Errorf("%s: an entry was written", name)
+ }
+ }
+
+ s := release.NewDirStore(t.TempDir())
+ putTestClaim(t, s, live)
+ got, err := WriteImport(ctx, s, simHost, "acca", "web", testEntry(t, "acca", "web"))
+ if err != nil || got.CreatedAt != live.CreatedAt {
+ t.Fatalf("live claim: %+v, %v", got, err)
+ }
+ raw, _, err := s.Get(ctx, ImportKey(simHost))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if b, _, err := ParseImport(raw); err != nil || !b.Matches(live) {
+ t.Fatalf("stored binding %+v (%v) does not match the claim", b, err)
+ }
+}
+
+func TestRemoveImport(t *testing.T) {
+ ctx := context.Background()
+ s := release.NewDirStore(t.TempDir())
+ live := Claim{Host: simHost, Account: "acca", App: "web", Route: "r.example.net", CreatedAt: "2026-11-20T10:00:00Z"}
+ putTestClaim(t, s, live)
+ if removed, _, _, err := RemoveImport(ctx, s, simHost, "acca", "web"); removed || err != nil {
+ t.Fatalf("nothing to remove: %v, %v", removed, err)
+ }
+ if _, err := WriteImport(ctx, s, simHost, "acca", "web", testEntry(t, "acca", "web")); err != nil {
+ t.Fatal(err)
+ }
+ // Another app of the account may not remove it.
+ if _, _, _, err := RemoveImport(ctx, s, simHost, "acca", "api"); !errors.Is(err, ErrImportNoClaim) {
+ t.Fatalf("other app: %v, want ErrImportNoClaim", err)
+ }
+ // A store that cannot delete conditionally deletes nothing.
+ if _, _, _, err := RemoveImport(ctx, noCondStore{s}, simHost, "acca", "web"); !errors.Is(err, release.ErrConditionalDeleteUnsupported) {
+ t.Fatalf("no conditional delete: %v", err)
+ }
+ if _, _, err := s.Get(ctx, ImportKey(simHost)); err != nil {
+ t.Fatalf("entry gone after a refused delete: %v", err)
+ }
+ removed, b, cert, err := RemoveImport(ctx, s, simHost, "acca", "web")
+ if !removed || err != nil || b.Account != "acca" || cert == nil || cert.Leaf == nil {
+ t.Fatalf("remove: %v %+v %v %v", removed, b, cert, err)
+ }
+ if _, _, err := s.Get(ctx, ImportKey(simHost)); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("entry still there: %v", err)
+ }
+}
+
+func TestStaleImport(t *testing.T) {
+ pkcs8, leaf := simMaterial(t)
+ created := "2026-11-20T10:00:00Z"
+ b := ImportBinding{Host: simHost, Account: "acca", App: "web", ClaimCreated: created}
+ raw := EncodeImport(b, pkcs8, [][]byte{leaf})
+ live := Claim{Host: simHost, Account: "acca", App: "web", CreatedAt: created}
+ now := time.Now()
+ claim := func(f func(*Claim)) *Claim { c := live; f(&c); return &c }
+ for _, c := range []struct {
+ name string
+ host string
+ raw []byte
+ claim *Claim
+ unread bool
+ now time.Time
+ want string
+ }{
+ {"matching", simHost, raw, &live, false, now, ""},
+ {"claim unread", simHost, raw, nil, true, now, ""},
+ {"claim unread, other owner", simHost, raw, claim(func(c *Claim) { c.Account = "accb" }), true, now, ""},
+ {"claim gone", simHost, raw, nil, false, now, ImportStaleNoClaim},
+ {"other account", simHost, raw, claim(func(c *Claim) { c.Account = "accb" }), false, now, ImportStaleOtherOwner},
+ {"other app", simHost, raw, claim(func(c *Claim) { c.App = "api" }), false, now, ImportStaleOtherOwner},
+ {"pending", simHost, raw, claim(func(c *Claim) { c.Pending = true }), false, now, ImportStaleNotHeld},
+ {"re-acquired", simHost, raw, claim(func(c *Claim) { c.CreatedAt = "2026-11-21T10:00:00Z" }), false, now, ImportStaleReacquired},
+ {"unparseable", simHost, []byte("not an entry"), &live, false, now, ImportStaleUnreadable},
+ {"other host", "other.example.com", raw, &live, false, now, ImportStaleOtherHost},
+ {"expired past grace, claim unread", simHost, raw, nil, true, now.Add(200 * 24 * time.Hour), ImportStaleExpired},
+ {"expired within grace", simHost, raw, &live, false, now.Add(91 * 24 * time.Hour), ""},
+ } {
+ reason, stale := StaleImport(c.host, c.raw, c.claim, c.unread, c.now, 30*24*time.Hour)
+ if reason != c.want || stale != (c.want != "") {
+ t.Errorf("%s: %q %v, want %q", c.name, reason, stale, c.want)
+ }
+ }
+}
+
+// TestReconcileImportKeepsOnUnreadClaim: a claim that cannot be read is
+// never taken for a detached one.
+func TestReconcileImportKeepsOnUnreadClaim(t *testing.T) {
+ ctx := context.Background()
+ s := release.NewDirStore(t.TempDir())
+ live := Claim{Host: simHost, Account: "acca", App: "web", Route: "r.example.net", CreatedAt: "2026-11-20T10:00:00Z"}
+ putTestClaim(t, s, live)
+ if _, err := WriteImport(ctx, s, simHost, "acca", "web", testEntry(t, "acca", "web")); err != nil {
+ t.Fatal(err)
+ }
+ // A claim that does not parse is unread, not absent.
+ if _, err := s.Put(ctx, ClaimKey(simHost), []byte("{"), mustETag(t, s, ClaimKey(simHost))); err != nil {
+ t.Fatal(err)
+ }
+ if deleted, _, err := ReconcileImport(ctx, s, simHost, time.Now(), 0); deleted || err == nil {
+ t.Fatalf("unread claim: deleted %v, err %v; want kept with the read error", deleted, err)
+ }
+ if err := s.Delete(ctx, ClaimKey(simHost)); err != nil {
+ t.Fatal(err)
+ }
+ deleted, reason, err := ReconcileImport(ctx, s, simHost, time.Now(), 0)
+ if !deleted || reason != ImportStaleNoClaim || err != nil {
+ t.Fatalf("claim gone: %v %q %v", deleted, reason, err)
+ }
+}
+
+func mustETag(t *testing.T, s release.Store, key string) string {
+ t.Helper()
+ _, etag, err := s.Get(context.Background(), key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return etag
+}
diff --git a/internal/domains/certimport_sim_test.go b/internal/domains/certimport_sim_test.go
new file mode 100644
index 000000000..1bef213aa
--- /dev/null
+++ b/internal/domains/certimport_sim_test.go
@@ -0,0 +1,497 @@
+package domains
+
+// A randomized interleaving simulation of the import invariant
+// (certimport_invariant.go). Every store call first lets a seeded RNG run
+// one other operation to completion (nesting at most two deep), so writers,
+// removers, the reconcile, attaches and detaches overlap at every point a
+// real bucket would let them. The invariant's properties are checked at the
+// instant each import mutation lands (S3, S5) and after every operation
+// returns (S1, S2, S4). A failure prints its seed:
+// go test ./internal/domains/ -run TestImportInvariantSim -sim.seed=<n>
+
+import (
+ "context"
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ "crypto/rand"
+ "crypto/x509"
+ "crypto/x509/pkix"
+ "encoding/json"
+ "encoding/pem"
+ "errors"
+ "flag"
+ "fmt"
+ "math/big"
+ mrand "math/rand"
+ "os"
+ "sort"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+var (
+ simSeed = flag.Int64("sim.seed", -1, "TestImportInvariantSim: run only this seed")
+ simSeeds = flag.Int("sim.seeds", 2000, "TestImportInvariantSim: seeds to run")
+)
+
+const (
+ simHost = "shop.example.com"
+ simOps = 50
+ simDepth = 2
+)
+
+// ---- the in-memory bucket ---------------------------------------------------
+
+type simObj struct {
+ body []byte
+ etag string
+ seq int // the Put that wrote it, in store order
+}
+
+var errSimInjected = errors.New("sim: injected read failure")
+
+// simStore is a bucket with CAS Put, conditional delete and injectable
+// claim-read and listing failures. Every call first runs w.beforeCall, and
+// every import mutation is checked by w.onImportMutation at its instant.
+type simStore struct {
+ w *simWorld
+ objs map[string]simObj
+ n int
+ failGet bool // claim Gets fail
+ failList bool
+}
+
+var _ release.ConditionalDeleter = (*simStore)(nil)
+
+func (s *simStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ s.w.beforeCall()
+ s.w.tracef("%*s get %s", 2*len(s.w.stack), "", key)
+ if s.failGet && strings.HasPrefix(key, ClaimsPrefix) {
+ s.w.sawFailure = true
+ return nil, "", errSimInjected
+ }
+ o, ok := s.objs[key]
+ if !ok {
+ return nil, "", fmt.Errorf("sim: %s: %w", key, os.ErrNotExist)
+ }
+ return append([]byte(nil), o.body...), o.etag, nil
+}
+
+func (s *simStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ s.w.beforeCall()
+ s.w.tracef("%*s put %s if-match %q", 2*len(s.w.stack), "", key, ifMatch)
+ o, ok := s.objs[key]
+ if (ifMatch == "" && ok) || (ifMatch != "" && (!ok || o.etag != ifMatch)) {
+ return "", fmt.Errorf("sim: %s: %w", key, release.ErrCASConflict)
+ }
+ s.n++
+ etag := fmt.Sprintf(`"e%d"`, s.n)
+ s.w.onImportMutation(key, o, ok, body)
+ if key == ClaimKey(simHost) && !ok {
+ s.w.claimBorn = s.n
+ }
+ s.objs[key] = simObj{body: append([]byte(nil), body...), etag: etag, seq: s.n}
+ return etag, nil
+}
+
+func (s *simStore) Delete(ctx context.Context, key string) error {
+ s.w.beforeCall()
+ if o, ok := s.objs[key]; ok {
+ s.w.onImportMutation(key, o, true, nil)
+ delete(s.objs, key)
+ }
+ return nil
+}
+
+func (s *simStore) DeleteIfMatch(ctx context.Context, key, etag string) error {
+ s.w.beforeCall()
+ s.w.tracef("%*s delete-if-match %s %s", 2*len(s.w.stack), "", key, etag)
+ o, ok := s.objs[key]
+ if !ok {
+ return nil
+ }
+ if o.etag != etag {
+ return fmt.Errorf("sim: %s: %w", key, release.ErrCASConflict)
+ }
+ s.w.onImportMutation(key, o, true, nil)
+ delete(s.objs, key)
+ return nil
+}
+
+func (s *simStore) List(ctx context.Context, prefix string) ([]string, error) {
+ s.w.beforeCall()
+ if s.failList {
+ s.w.sawFailure = true
+ return nil, errSimInjected
+ }
+ var out []string
+ for k := range s.objs {
+ if strings.HasPrefix(k, prefix) {
+ out = append(out, k)
+ }
+ }
+ sort.Strings(out)
+ return out, nil
+}
+
+func (s *simStore) ListDirs(ctx context.Context, prefix string) ([]string, error) { return nil, nil }
+
+// ---- the world ----------------------------------------------------------------
+
+type simActor struct{ account, app string }
+
+var simActors = []simActor{{"acca", "web"}, {"acca", "api"}, {"accb", "web"}}
+
+type simOp struct {
+ id int
+ kind string // write, remove, reconcile, attach, detach, verify, toggle
+ actor simActor
+}
+
+type simWorld struct {
+ t *testing.T
+ seed int64
+ rng *mrand.Rand
+ st *simStore
+ clock int
+ depth int
+ nextID int
+ stack []simOp
+ pkcs8 []byte
+ leaf []byte
+ sawFailure bool
+ nested int // ops started, for S4's "nothing ran during the pass"
+ // lastPut is, per op id, the revision and mutation number of its last
+ // import Put; importMuts numbers every import mutation and lastBy says
+ // which op made the latest one.
+ lastPut map[int][2]int
+ importMuts int
+ lastBy int
+ failed string
+ trace bool
+ // claimBorn is the Put that created the current claim. An entry
+ // written before it was confirmed against an earlier acquisition that
+ // collided on all four binding fields: the same authority by
+ // definition, served while it matches, but not protected from a
+ // deleter that saw the claim gone in between.
+ claimBorn int
+}
+
+func (w *simWorld) tracef(format string, a ...any) {
+ if w.trace {
+ w.t.Logf(format, a...)
+ }
+}
+
+func (w *simWorld) claimText() string {
+ c := w.truthClaim()
+ if c == nil {
+ return "none"
+ }
+ return fmt.Sprintf("%s/%s %s pending=%v", c.Account, c.App, c.CreatedAt, c.Pending)
+}
+
+func (w *simWorld) importText() string {
+ b, o, ok := w.truthImport()
+ if !ok {
+ return "none"
+ }
+ return fmt.Sprintf("%s/%s %s %s", b.Account, b.App, b.ClaimCreated, o.etag)
+}
+
+func (w *simWorld) fail(format string, a ...any) {
+ if w.failed == "" {
+ w.failed = fmt.Sprintf(format, a...)
+ }
+}
+
+func (w *simWorld) beforeCall() {
+ if w.failed != "" || w.depth >= simDepth || w.rng.Intn(3) != 0 {
+ return
+ }
+ w.depth++
+ w.runOp()
+ w.depth--
+}
+
+// truthClaim reads the claim straight from the map: no hook, no failure.
+func (w *simWorld) truthClaim() *Claim {
+ o, ok := w.st.objs[ClaimKey(simHost)]
+ if !ok {
+ return nil
+ }
+ var c Claim
+ if err := json.Unmarshal(o.body, &c); err != nil {
+ w.fail("claim does not parse: %v", err)
+ return nil
+ }
+ return &c
+}
+
+// bindingOf reads an entry's binding block alone.
+func bindingOf(raw []byte) (ImportBinding, bool) {
+ b, _ := pem.Decode(raw)
+ if b == nil || b.Type != importBindingType {
+ return ImportBinding{}, false
+ }
+ return ImportBinding{Host: b.Headers["Host"], Account: b.Headers["Account"], App: b.Headers["App"],
+ ClaimCreated: b.Headers["Claim-Created"]}, true
+}
+
+func (w *simWorld) truthImport() (ImportBinding, simObj, bool) {
+ o, ok := w.st.objs[ImportKey(simHost)]
+ if !ok {
+ return ImportBinding{}, simObj{}, false
+ }
+ b, ok2 := bindingOf(o.body)
+ if !ok2 {
+ w.fail("stored import has no binding")
+ }
+ return b, o, true
+}
+
+// onImportMutation is S5 (and S3 for the reconcile) at the instant a
+// mutation lands: an entry bound to the current claim is replaced or
+// deleted only by a WriteImport or RemoveImport of the current holder.
+func (w *simWorld) onImportMutation(key string, before simObj, existed bool, after []byte) {
+ if key != ImportKey(simHost) {
+ return
+ }
+ op := w.stack[len(w.stack)-1]
+ w.importMuts++
+ w.lastBy = op.id
+ if after != nil {
+ w.lastPut[op.id] = [2]int{w.st.n, w.importMuts}
+ }
+ if !existed {
+ return
+ }
+ b, _ := bindingOf(before.body)
+ c := w.truthClaim()
+ if c == nil || !b.Matches(*c) || before.seq < w.claimBorn {
+ return
+ }
+ if (op.kind == "write" || op.kind == "remove") && op.actor.account == c.Account && op.actor.app == c.App {
+ return
+ }
+ what := "replaced"
+ if after == nil {
+ what = "deleted"
+ }
+ label := "S5"
+ if op.kind == "reconcile" {
+ label = "S3"
+ }
+ w.fail("%s: op %d (%s by %v) %s an entry bound to the current claim %+v", label, op.id, op.kind, op.actor, what, b)
+}
+
+func (w *simWorld) entryFor(binding *ImportBinding, actor simActor) func(Claim) []byte {
+ return func(c Claim) []byte {
+ *binding = ImportBinding{Host: simHost, Account: actor.account, App: actor.app, ClaimCreated: c.CreatedAt}
+ return EncodeImport(*binding, w.pkcs8, [][]byte{w.leaf})
+ }
+}
+
+func (w *simWorld) runOp() {
+ if w.failed != "" {
+ return
+ }
+ actor := simActors[w.rng.Intn(len(simActors))]
+ switch r := w.rng.Intn(22); {
+ case r < 6:
+ w.runKind("write", actor)
+ case r < 8:
+ w.runKind("detach", actor)
+ case r < 11:
+ w.runKind("attach", actor)
+ case r < 12:
+ w.runKind("verify", actor)
+ case r < 14:
+ w.runKind("remove", actor)
+ case r < 18:
+ w.runKind("reconcile", actor)
+ case r < 20:
+ // A takeover: the name is detached, a new owner attaches it and
+ // imports at once. Each step is its own op with its own
+ // interleaving points, so a takeover lands inside another
+ // actor's window far more often than three independent picks.
+ w.runKind("detach", actor)
+ w.runKind("attach", actor)
+ w.runKind("write", actor)
+ default:
+ w.runKind("toggle", actor)
+ }
+}
+
+func (w *simWorld) runKind(kind string, actor simActor) {
+ if w.failed != "" {
+ return
+ }
+ w.nextID++
+ w.nested++
+ op := simOp{id: w.nextID, kind: kind, actor: actor}
+ ctx := context.Background()
+ w.stack = append(w.stack, op)
+ defer func() { w.stack = w.stack[:len(w.stack)-1] }()
+ w.tracef("%*sop %d %s %v (claim %s)", 2*len(w.stack), "", op.id, op.kind, op.actor, w.claimText())
+ defer func() {
+ w.tracef("%*send op %d (claim %s, import %s)", 2*len(w.stack), "", op.id, w.claimText(), w.importText())
+ }()
+
+ switch op.kind {
+ case "write":
+ var binding ImportBinding
+ got, err := WriteImport(ctx, w.st, simHost, op.actor.account, op.actor.app, w.entryFor(&binding, op.actor))
+ w.checkWrite(op, got, err)
+ case "detach":
+ w.st.Delete(ctx, ClaimKey(simHost))
+ case "attach":
+ if w.rng.Intn(3) != 0 {
+ w.clock++ // else deliberately the same second
+ }
+ c := Claim{Schema: 1, Host: simHost, Account: op.actor.account, App: op.actor.app, Route: "r.example.net",
+ CreatedAt: time.Unix(1_800_000_000+int64(w.clock), 0).UTC().Format(time.RFC3339), Pending: w.rng.Intn(5) == 0}
+ raw, _ := json.Marshal(c)
+ w.st.Put(ctx, ClaimKey(simHost), raw, "")
+ case "verify":
+ raw, etag, err := w.st.Get(ctx, ClaimKey(simHost))
+ if err != nil {
+ return
+ }
+ var c Claim
+ if json.Unmarshal(raw, &c) != nil || !c.Pending {
+ return
+ }
+ c.Pending = false
+ raw, _ = json.Marshal(c)
+ w.st.Put(ctx, ClaimKey(simHost), raw, etag)
+ case "remove":
+ RemoveImport(ctx, w.st, simHost, op.actor.account, op.actor.app)
+ case "reconcile":
+ w.reconcile(ctx, op)
+ case "toggle":
+ switch w.rng.Intn(3) {
+ case 0:
+ w.st.failGet = !w.st.failGet
+ case 1:
+ w.st.failList = !w.st.failList
+ default:
+ w.st.failGet, w.st.failList = false, false
+ }
+ }
+}
+
+// checkWrite is S1 and S2, the moment a WriteImport returns: nothing else
+// runs between its last store call and here.
+func (w *simWorld) checkWrite(op simOp, got Claim, err error) {
+ c := w.truthClaim()
+ ob, obj, present := w.truthImport()
+ if err == nil {
+ want := ImportBinding{Host: simHost, Account: op.actor.account, App: op.actor.app, ClaimCreated: got.CreatedAt}
+ if c == nil || !want.Matches(*c) {
+ w.fail("S1: op %d WriteImport returned nil but its binding %+v does not match the claim %+v", op.id, want, c)
+ return
+ }
+ put, ok := w.lastPut[op.id]
+ if !ok {
+ w.fail("S1: op %d WriteImport returned nil with no Put", op.id)
+ return
+ }
+ ours := present && obj.etag == fmt.Sprintf(`"e%d"`, put[0])
+ if !ours && !(w.importMuts > put[1] && w.lastBy != op.id) {
+ w.fail("S1: op %d WriteImport returned nil but its entry is gone and nobody else changed it", op.id)
+ }
+ }
+ // S2: the entry this call wrote, if it is still there, matches the
+ // claim. (An equal binding written by another op of the same actor
+ // may be stale until the reconcile; that is not this call's entry.)
+ if put, ok := w.lastPut[op.id]; ok && present && obj.etag == fmt.Sprintf(`"e%d"`, put[0]) &&
+ (c == nil || !ob.Matches(*c)) {
+ w.fail("S2: op %d WriteImport returned (%v) leaving its entry %+v beside claim %+v", op.id, err, ob, c)
+ }
+}
+
+// reconcile is one pass: list the imports, then ReconcileImport each.
+func (w *simWorld) reconcile(ctx context.Context, op simOp) {
+ startNested, hadFailure := w.nested, w.st.failGet || w.st.failList
+ w.sawFailure = false
+ keys, err := w.st.List(ctx, "control/certs/")
+ if err == nil {
+ for _, k := range keys {
+ host, ok := ImportHost(strings.TrimPrefix(k, "control/certs/"))
+ if !ok {
+ continue
+ }
+ ReconcileImport(ctx, w.st, host, time.Now(), 0)
+ }
+ }
+ // S4: a pass with no failure and nothing interleaved leaves only an
+ // entry that matches the claim.
+ if err == nil && !hadFailure && !w.sawFailure && w.nested == startNested {
+ if b, _, present := w.truthImport(); present {
+ if c := w.truthClaim(); c == nil || !b.Matches(*c) {
+ w.fail("S4: op %d reconcile left %+v beside claim %+v", op.id, b, c)
+ }
+ }
+ }
+}
+
+func simMaterial(t *testing.T) (pkcs8, leaf []byte) {
+ t.Helper()
+ k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ tmpl := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: simHost},
+ DNSNames: []string{simHost}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(90 * 24 * time.Hour)}
+ leaf, err = x509.CreateCertificate(rand.Reader, tmpl, tmpl, k.Public(), k)
+ if err != nil {
+ t.Fatal(err)
+ }
+ pkcs8, err = x509.MarshalPKCS8PrivateKey(k)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return pkcs8, leaf
+}
+
+func runImportSim(t *testing.T, seed int64, pkcs8, leaf []byte, trace bool) (failure string, stats [3]int) {
+ w := &simWorld{t: t, seed: seed, rng: mrand.New(mrand.NewSource(seed)), pkcs8: pkcs8, leaf: leaf,
+ lastPut: map[int][2]int{}, trace: trace}
+ w.st = &simStore{w: w, objs: map[string]simObj{}}
+ for i := 0; i < simOps && w.failed == ""; i++ {
+ w.runOp()
+ }
+ if _, _, ok := w.truthImport(); ok {
+ stats[0] = 1
+ }
+ return w.failed, stats
+}
+
+func TestImportInvariantSim(t *testing.T) {
+ pkcs8, leaf := simMaterial(t)
+ if *simSeed >= 0 {
+ if f, _ := runImportSim(t, *simSeed, pkcs8, leaf, true); f != "" {
+ t.Fatalf("seed %d: %s", *simSeed, f)
+ }
+ return
+ }
+ start := time.Now()
+ withImport := 0
+ for seed := int64(0); seed < int64(*simSeeds); seed++ {
+ f, st := runImportSim(t, seed, pkcs8, leaf, false)
+ if f != "" {
+ t.Fatalf("seed %d: %s (rerun: -sim.seed=%d)", seed, f, seed)
+ }
+ withImport += st[0]
+ }
+ // Non-vacuity: imports must survive to the end of a good share of runs,
+ // or the simulation is only exercising refusals.
+ if withImport < *simSeeds/20 {
+ t.Fatalf("only %d of %d runs ended with an import: the sim is not exercising writes", withImport, *simSeeds)
+ }
+ t.Logf("%d seeds x %d ops in %s; %d ended holding an import", *simSeeds, simOps, time.Since(start).Round(time.Millisecond), withImport)
+}