carlos / platform Public

domains: WriteImport survives failed confirms and withdraws (#1429)

Astra R3 P2-2, Fable R3 P2-1 and P3-7.

WriteImport refuses a store without conditional delete before writing
(ErrImportStoreUnsupported; the door answers 503). After its Put it
confirms on its own bounded context, detached from the request, reading
the claim up to three times with a short backoff, and withdraws only on
a confirmed mismatch or absence or when the reads run out. A withdraw
that fails is ErrImportWithdrawFailed, which never matches
ErrImportNoClaim; the door logs one line and answers 500. The gate now
refuses a claim with no created_at before validation.

The simulation adds entry-read, Put and delete failures, transient and
persistent claim-read failures, cancelled contexts and a store without
conditional delete; S2 allows a left-behind entry only after a failed
withdraw (S4 then requires the next clean reconcile to remove it); S6
checks a writer withdraws only after a confirmed mismatch or three
failed reads; S7 checks the unsupported store is never written. Ten
weakenings each fail it. WriteImport's record-write census digest is
re-pinned.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 4f4dac489ba6645b8c12877746d3057340d0e6d8 parent 6d9fe57
7 files changed, +416 −59
  • internal/console/apidomaincert.go +16 −4
  • internal/console/apidomaincert_test.go +40 −0
  • internal/console/domaincert_copy.go +8 −0
  • internal/domains/certimport_invariant.go +84 −16
  • internal/domains/certimport_invariant_test.go +45 −0
  • internal/domains/certimport_sim_test.go +222 −38
  • internal/provision/cert_import_1429_census_test.go +1 −1
diff --git a/internal/console/apidomaincert.go b/internal/console/apidomaincert.go
index a0a240ace..2b8fd400d 100644
--- a/internal/console/apidomaincert.go
+++ b/internal/console/apidomaincert.go
@@ -340,8 +340,10 @@ func (s *Server) certDoorGate(w http.ResponseWriter, r *http.Request) (p Princip
jsonError(w, http.StatusBadGateway, certReadFailed)
return
}
+ // created_at is the acquisition stamp an import is bound to: a claim
+ // without one cannot hold an import, and answers before validation.
if err != nil || c == nil || c.Account != acct.Sqid || c.App != app || c.Pending || c.Instances ||
- strings.HasPrefix(c.Host, "*.") {
+ strings.HasPrefix(c.Host, "*.") || c.CreatedAt == "" {
cancel()
jsonError(w, http.StatusNotFound, certNoSuchHost)
return
@@ -389,11 +391,21 @@ func (s *Server) handleAPIDomainCertImport(w http.ResponseWriter, r *http.Reques
Host: host, Account: acct.Sqid, App: app, ClaimCreated: c.CreatedAt,
}, v.pkcs8, v.chain)
})
- if errors.Is(err, domains.ErrImportNoClaim) {
+ switch {
+ case errors.Is(err, domains.ErrImportStoreUnsupported):
+ log.Printf("console: domain cert import %s/%s %s: %v", acct.Sqid, app, host, err)
+ jsonError(w, http.StatusServiceUnavailable, certStoreUnsupported)
+ return
+ case errors.Is(err, domains.ErrImportWithdrawFailed):
+ // One line: the host and why, never the entry. The issuer's
+ // reconcile deletes the entry once it reads the claim.
+ log.Printf("console: domain cert import %s/%s %s: %v", acct.Sqid, app, host, err)
+ jsonError(w, http.StatusInternalServerError, certWithdrawFailed)
+ return
+ case errors.Is(err, domains.ErrImportNoClaim):
jsonError(w, http.StatusNotFound, certNoSuchHost)
return
- }
- if err != nil {
+ case err != nil:
log.Printf("console: domain cert import %s/%s %s: %v", acct.Sqid, app, host, err)
jsonError(w, http.StatusBadGateway, certWriteFailed)
return
diff --git a/internal/console/apidomaincert_test.go b/internal/console/apidomaincert_test.go
index ddfacd56f..37c7468b7 100644
--- a/internal/console/apidomaincert_test.go
+++ b/internal/console/apidomaincert_test.go
@@ -27,6 +27,7 @@ import (
"time"
"github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/release"
)
// ---- a fixture CA: root, intermediate, leaves ----------------------------
@@ -770,3 +771,42 @@ func TestCertRemoveAndGet(t *testing.T) {
t.Fatalf("%d domain-cert-remove rows, want 1 (only the effective removal)", n)
}
}
+
+// certNoCondStore hides the bucket's conditional delete.
+type certNoCondStore struct{ release.Store }
+
+// TestCertImportRefusesAStoreWithoutConditionalDelete: the invariant needs
+// a withdraw by revision, so such a store is refused before any write.
+func TestCertImportRefusesAStoreWithoutConditionalDelete(t *testing.T) {
+ d := newCertDoorFixture(t, "code-cert-nocond")
+ fx := d.fx
+ fx.srv.cfg.Releases = certNoCondStore{fx.rel}
+ code, _, out := rawReq(t, http.MethodPut, certURL(fx, "bab", "titogo", "tickets.example.com"), d.paul,
+ certBody(pemCerts(d.leaf, d.ca.inter), pemPKCS8(t, d.key), false))
+ if code != http.StatusServiceUnavailable || jsonErrorText(t, out) != certStoreUnsupported {
+ t.Fatalf("import = %d %s, want 503 %q", code, out, certStoreUnsupported)
+ }
+ importAbsent(t, fx, "tickets.example.com")
+}
+
+// TestCertImportClaimWithoutCreatedAtIsNotFoundFirst: a claim with no
+// acquisition stamp cannot hold an import, and says so before the body is
+// even validated.
+func TestCertImportClaimWithoutCreatedAtIsNotFoundFirst(t *testing.T) {
+ d := newCertDoorFixture(t, "code-cert-nocreated")
+ fx := d.fx
+ putClaim(t, fx, domains.Claim{Host: "first.example.com", Account: "bab", App: "titogo", Route: "go.tito.io", CreatedAt: "-"})
+ raw, etag, err := fx.rel.Get(context.Background(), domains.ClaimKey("first.example.com"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ raw = []byte(strings.Replace(string(raw), `"created_at":"-"`, `"created_at":""`, 1))
+ if _, err := fx.rel.Put(context.Background(), domains.ClaimKey("first.example.com"), raw, etag); err != nil {
+ t.Fatal(err)
+ }
+ code, _, out := rawReq(t, http.MethodPut, certURL(fx, "bab", "titogo", "first.example.com"), d.paul,
+ certBody([]byte("not a certificate"), []byte("not a key"), false))
+ if code != http.StatusNotFound || jsonErrorText(t, out) != certNoSuchHost {
+ t.Fatalf("import = %d %s, want 404 %q before validation", code, out, certNoSuchHost)
+ }
+}
diff --git a/internal/console/domaincert_copy.go b/internal/console/domaincert_copy.go
index f339728e5..648736b45 100644
--- a/internal/console/domaincert_copy.go
+++ b/internal/console/domaincert_copy.go
@@ -42,6 +42,14 @@ const (
certWriteFailed = "could not save the certificate. Try again"
certRemoveFailed = "could not remove the certificate. Try again"
+ // certStoreUnsupported: the deployment's store cannot delete
+ // conditionally, so the import invariant cannot be kept.
+ certStoreUnsupported = "this deployment's storage cannot hold imported certificates"
+ // certWithdrawFailed: the entry was written, could not be confirmed
+ // against the claim, and could not be withdrawn. (Not yet reviewed by
+ // Luna.)
+ certWithdrawFailed = "the certificate was saved but could not be confirmed; the issuer removes it within minutes. Try again"
+
// The Activity rows. %s are the host, the leaf's SHA-256 (hex), the
// issuer's common name and the expiry (RFC 3339).
certAuditImport = "imported a certificate for %s: SHA-256 %s, issued by %s, expires %s"
diff --git a/internal/domains/certimport_invariant.go b/internal/domains/certimport_invariant.go
index 715c97285..3020c05e0 100644
--- a/internal/domains/certimport_invariant.go
+++ b/internal/domains/certimport_invariant.go
@@ -59,6 +59,30 @@ 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")
+// ErrImportStoreUnsupported is a store that cannot delete conditionally.
+// WriteImport refuses it before writing anything: a write it could not
+// withdraw would break the invariant.
+var ErrImportStoreUnsupported = errors.New("domains: this store cannot delete conditionally, so it cannot hold imports")
+
+// ErrImportWithdrawFailed is a write that could not be confirmed and then
+// could not be withdrawn. The entry stays until the reconcile, which
+// deletes it once it reads the claim that does not match. It never
+// matches ErrImportNoClaim.
+var ErrImportWithdrawFailed = errors.New("domains: import written but neither confirmed nor withdrawn")
+
+// importConfirmReads is how many times the confirm step tries to read the
+// claim before it gives up and withdraws; importConfirmBackoff is the wait
+// before each retry (a test seam). importFinishTimeout bounds the confirm
+// and the withdraw together, which run detached from the caller's context:
+// once the Put has landed, a cancelled request must neither leave the write
+// unconfirmed nor withdraw a good one.
+const importConfirmReads = 3
+
+var (
+ importConfirmBackoff = 100 * time.Millisecond
+ importFinishTimeout = 10 * time.Second
+)
+
// 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
@@ -103,16 +127,22 @@ func readImportEntry(ctx context.Context, s release.Store, host string) (raw []b
// 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.
+// A store that cannot delete conditionally is refused before anything is
+// written (ErrImportStoreUnsupported). 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, up to three times on a
+// read failure; the write is withdrawn, by the revision it created and
+// nothing else, only on a confirmed mismatch or absence or when the reads
+// run out. A withdraw that fails is ErrImportWithdrawFailed.
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
}
+ if _, ok := s.(release.ConditionalDeleter); !ok {
+ return Claim{}, ErrImportStoreUnsupported
+ }
key := ImportKey(host)
for attempt := 0; attempt < importAttempts; attempt++ {
_, etag, err := readImportEntry(ctx, s, host)
@@ -134,20 +164,58 @@ func WriteImport(ctx context.Context, s release.Store, host, account, app string
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)
+ return finishImport(ctx, s, host, key, written, binding, *c)
+ }
+ return Claim{}, ErrImportRace
+}
+
+// finishImport is WriteImport after its Put: confirm the claim still
+// matches the binding, else withdraw the revision written. It runs on its
+// own bounded context, detached from the caller's.
+func finishImport(ctx context.Context, s release.Store, host, key, written string, binding ImportBinding, held Claim) (Claim, error) {
+ fctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), importFinishTimeout)
+ defer cancel()
+ var readErr error
+ reason := "the claim changed"
+ for read := 0; read < importConfirmReads; read++ {
+ if read > 0 && !waitImportBackoff(fctx) {
+ break
}
+ now, absent, err := readImportClaim(fctx, s, host)
if err != nil {
- return Claim{}, err
+ readErr, reason = err, "the claim could not be read"
+ continue
}
- return Claim{}, ErrImportNoClaim
+ if !absent && binding.Matches(*now) {
+ return held, nil
+ }
+ readErr = nil
+ if absent {
+ reason = "the claim is gone"
+ }
+ break
+ }
+ if werr := withdrawImport(fctx, s, key, written); werr != nil {
+ return Claim{}, fmt.Errorf("%w: %s, and the withdraw failed: %v", ErrImportWithdrawFailed, reason, werr)
+ }
+ if readErr != nil {
+ return Claim{}, readErr
+ }
+ return Claim{}, ErrImportNoClaim
+}
+
+func waitImportBackoff(ctx context.Context) bool {
+ if importConfirmBackoff <= 0 {
+ return ctx.Err() == nil
+ }
+ t := time.NewTimer(importConfirmBackoff)
+ defer t.Stop()
+ select {
+ case <-t.C:
+ return true
+ case <-ctx.Done():
+ return false
}
- return Claim{}, ErrImportRace
}
// withdrawImport deletes the revision this process wrote. A conflict means
diff --git a/internal/domains/certimport_invariant_test.go b/internal/domains/certimport_invariant_test.go
index bd6e47dc1..714d212a7 100644
--- a/internal/domains/certimport_invariant_test.go
+++ b/internal/domains/certimport_invariant_test.go
@@ -174,3 +174,48 @@ func mustETag(t *testing.T, s release.Store, key string) string {
}
return etag
}
+
+// flipStore answers the confirm read with another owner's claim and fails
+// every conditional delete, so a write can be neither confirmed nor
+// withdrawn.
+type flipStore struct {
+ *release.DirStore
+ puts int
+}
+
+func (f *flipStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ etag, err := f.DirStore.Put(ctx, key, body, ifMatch)
+ if err == nil && key == ImportKey(simHost) {
+ f.puts++
+ }
+ return etag, err
+}
+
+func (f *flipStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ raw, etag, err := f.DirStore.Get(ctx, key)
+ if err == nil && key == ClaimKey(simHost) && f.puts > 0 {
+ var c Claim
+ if json.Unmarshal(raw, &c) == nil {
+ c.Account = "accb"
+ raw, _ = json.Marshal(c)
+ }
+ }
+ return raw, etag, err
+}
+
+func (f *flipStore) DeleteIfMatch(ctx context.Context, key, etag string) error {
+ return errors.New("delete failed")
+}
+
+func TestWriteImportWithdrawFailedIsItsOwnError(t *testing.T) {
+ ctx := context.Background()
+ s := &flipStore{DirStore: release.NewDirStore(t.TempDir())}
+ putTestClaim(t, s.DirStore, Claim{Host: simHost, Account: "acca", App: "web", Route: "r.example.net", CreatedAt: "2026-11-20T10:00:00Z"})
+ _, err := WriteImport(ctx, s, simHost, "acca", "web", testEntry(t, "acca", "web"))
+ if !errors.Is(err, ErrImportWithdrawFailed) || errors.Is(err, ErrImportNoClaim) {
+ t.Fatalf("err = %v, want ErrImportWithdrawFailed and not ErrImportNoClaim", err)
+ }
+ if _, err := WriteImport(ctx, noCondStore{s.DirStore}, simHost, "acca", "web", testEntry(t, "acca", "web")); !errors.Is(err, ErrImportStoreUnsupported) {
+ t.Fatalf("no conditional delete: %v, want ErrImportStoreUnsupported", err)
+ }
+}
diff --git a/internal/domains/certimport_sim_test.go b/internal/domains/certimport_sim_test.go
index 1bef213aa..c21b8bdb4 100644
--- a/internal/domains/certimport_sim_test.go
+++ b/internal/domains/certimport_sim_test.go
@@ -6,7 +6,11 @@ package domains
// 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:
+// returns (S1, S2, S4, S7); S6 is checked when a writer withdraws. Claim
+// reads (persistent and transient), entry reads, Puts, deletes and listings
+// can fail, any operation's context can be cancelled mid-flight, and one
+// seed in ten runs on a store without conditional delete. A failure prints
+// its seed:
// go test ./internal/domains/ -run TestImportInvariantSim -sim.seed=<n>
import (
@@ -57,32 +61,85 @@ var errSimInjected = errors.New("sim: injected read failure")
// 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
+ w *simWorld
+ objs map[string]simObj
+ n int
+ failGet bool // every claim Get fails
+ failNext int // the next n claim Gets fail (a transient failure)
+ failEntryGet bool // import entry Gets fail
+ failPut bool // Puts fail without writing
+ failDelete bool // deletes fail without deleting
+ failList bool
}
+func (s *simStore) anyFailure() bool {
+ return s.failGet || s.failNext > 0 || s.failEntryGet || s.failPut || s.failDelete || s.failList
+}
+
+// enter is every call's prologue: the interleaving hook, then the
+// caller's context.
+func (s *simStore) enter(ctx context.Context) error {
+ s.w.beforeCall()
+ if err := ctx.Err(); err != nil {
+ s.w.sawFailure = true
+ return err
+ }
+ return nil
+}
+
+// simNoCond is the same bucket without conditional delete.
+type simNoCond struct{ s *simStore }
+
+func (n simNoCond) Get(ctx context.Context, key string) ([]byte, string, error) {
+ return n.s.Get(ctx, key)
+}
+func (n simNoCond) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ return n.s.Put(ctx, key, body, ifMatch)
+}
+func (n simNoCond) Delete(ctx context.Context, key string) error { return n.s.Delete(ctx, key) }
+func (n simNoCond) List(ctx context.Context, prefix string) ([]string, error) {
+ return n.s.List(ctx, prefix)
+}
+func (n simNoCond) ListDirs(ctx context.Context, prefix string) ([]string, error) { return nil, nil }
+
var _ release.ConditionalDeleter = (*simStore)(nil)
func (s *simStore) Get(ctx context.Context, key string) ([]byte, string, error) {
- s.w.beforeCall()
+ if err := s.enter(ctx); err != nil {
+ s.w.noteClaimRead(key, nil, false, err)
+ return nil, "", err
+ }
s.w.tracef("%*s get %s", 2*len(s.w.stack), "", key)
- if s.failGet && strings.HasPrefix(key, ClaimsPrefix) {
+ if strings.HasPrefix(key, ClaimsPrefix) && (s.failGet || s.failNext > 0) {
+ if s.failNext > 0 {
+ s.failNext--
+ }
+ s.w.sawFailure = true
+ s.w.noteClaimRead(key, nil, false, errSimInjected)
+ return nil, "", errSimInjected
+ }
+ if key == ImportKey(simHost) && s.failEntryGet {
s.w.sawFailure = true
return nil, "", errSimInjected
}
o, ok := s.objs[key]
if !ok {
+ s.w.noteClaimRead(key, nil, true, nil)
return nil, "", fmt.Errorf("sim: %s: %w", key, os.ErrNotExist)
}
+ s.w.noteClaimRead(key, o.body, false, nil)
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()
+ if err := s.enter(ctx); err != nil {
+ return "", err
+ }
s.w.tracef("%*s put %s if-match %q", 2*len(s.w.stack), "", key, ifMatch)
+ if s.failPut {
+ s.w.sawFailure = true
+ return "", errSimInjected
+ }
o, ok := s.objs[key]
if (ifMatch == "" && ok) || (ifMatch != "" && (!ok || o.etag != ifMatch)) {
return "", fmt.Errorf("sim: %s: %w", key, release.ErrCASConflict)
@@ -98,7 +155,13 @@ func (s *simStore) Put(ctx context.Context, key string, body []byte, ifMatch str
}
func (s *simStore) Delete(ctx context.Context, key string) error {
- s.w.beforeCall()
+ if err := s.enter(ctx); err != nil {
+ return err
+ }
+ if s.failDelete {
+ s.w.sawFailure = true
+ return errSimInjected
+ }
if o, ok := s.objs[key]; ok {
s.w.onImportMutation(key, o, true, nil)
delete(s.objs, key)
@@ -107,8 +170,15 @@ func (s *simStore) Delete(ctx context.Context, key string) error {
}
func (s *simStore) DeleteIfMatch(ctx context.Context, key, etag string) error {
- s.w.beforeCall()
+ if err := s.enter(ctx); err != nil {
+ return err
+ }
s.w.tracef("%*s delete-if-match %s %s", 2*len(s.w.stack), "", key, etag)
+ s.w.onWithdraw(key)
+ if s.failDelete {
+ s.w.sawFailure = true
+ return errSimInjected
+ }
o, ok := s.objs[key]
if !ok {
return nil
@@ -122,7 +192,9 @@ func (s *simStore) DeleteIfMatch(ctx context.Context, key, etag string) error {
}
func (s *simStore) List(ctx context.Context, prefix string) ([]string, error) {
- s.w.beforeCall()
+ if err := s.enter(ctx); err != nil {
+ return nil, err
+ }
if s.failList {
s.w.sawFailure = true
return nil, errSimInjected
@@ -178,6 +250,81 @@ type simWorld struct {
// definition, served while it matches, but not protected from a
// deleter that saw the claim gone in between.
claimBorn int
+ // noCond: this seed's store cannot delete conditionally.
+ noCond bool
+ // cancels are the running ops' context cancels, innermost last;
+ // cancelled marks the ops whose context was cancelled.
+ cancels []context.CancelFunc
+ cancelled map[int]bool
+ // opBinding is each write op's binding (captured when it builds its
+ // entry); confirm is its claim reads since: consecutive failures, and
+ // whether the last good read matched the binding.
+ opBinding map[int]ImportBinding
+ confirm map[int]*simConfirm
+}
+
+type simConfirm struct {
+ fails int
+ read bool
+ matched bool
+}
+
+// noteClaimRead records a write op's claim reads for S6.
+func (w *simWorld) noteClaimRead(key string, body []byte, absent bool, err error) {
+ if key != ClaimKey(simHost) || len(w.stack) == 0 {
+ return
+ }
+ op := w.stack[len(w.stack)-1]
+ if op.kind != "write" {
+ return
+ }
+ cf := w.confirm[op.id]
+ if cf == nil {
+ cf = &simConfirm{}
+ w.confirm[op.id] = cf
+ }
+ if err != nil {
+ cf.fails++
+ cf.read = false
+ return
+ }
+ cf.fails, cf.read, cf.matched = 0, true, false
+ b, ok := w.opBinding[op.id]
+ if !ok || absent {
+ return
+ }
+ var c Claim
+ if json.Unmarshal(body, &c) == nil && b.Matches(c) {
+ cf.matched = true
+ }
+}
+
+// onWithdraw is S6: a writer withdraws its entry only after a confirmed
+// mismatch or absence, or once three confirm reads have failed.
+func (w *simWorld) onWithdraw(key string) {
+ if key != ImportKey(simHost) || len(w.stack) == 0 {
+ return
+ }
+ op := w.stack[len(w.stack)-1]
+ if op.kind != "write" {
+ return
+ }
+ cf := w.confirm[op.id]
+ switch {
+ case cf == nil:
+ w.fail("S6: op %d withdrew without reading the claim", op.id)
+ case cf.read && cf.matched:
+ w.fail("S6: op %d withdrew though its confirm read matched", op.id)
+ case !cf.read && cf.fails < 3:
+ w.fail("S6: op %d withdrew after %d failed confirm read(s), fewer than three", op.id, cf.fails)
+ }
+}
+
+func (w *simWorld) store() release.Store {
+ if w.noCond {
+ return simNoCond{w.st}
+ }
+ return w.st
}
func (w *simWorld) tracef(format string, a ...any) {
@@ -209,7 +356,14 @@ func (w *simWorld) fail(format string, a ...any) {
}
func (w *simWorld) beforeCall() {
- if w.failed != "" || w.depth >= simDepth || w.rng.Intn(3) != 0 {
+ if w.failed != "" {
+ return
+ }
+ if len(w.cancels) > 0 && w.rng.Intn(40) == 0 {
+ w.cancels[len(w.cancels)-1]()
+ w.cancelled[w.stack[len(w.stack)-1].id] = true
+ }
+ if w.depth >= simDepth || w.rng.Intn(3) != 0 {
return
}
w.depth++
@@ -261,6 +415,9 @@ func (w *simWorld) onImportMutation(key string, before simObj, existed bool, aft
return
}
op := w.stack[len(w.stack)-1]
+ if w.noCond {
+ w.fail("S7: op %d (%s) changed an import on a store without conditional delete", op.id, op.kind)
+ }
w.importMuts++
w.lastBy = op.id
if after != nil {
@@ -288,10 +445,11 @@ func (w *simWorld) onImportMutation(key string, before simObj, existed bool, aft
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 {
+func (w *simWorld) entryFor(opID int, 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})
+ b := ImportBinding{Host: simHost, Account: actor.account, App: actor.app, ClaimCreated: c.CreatedAt}
+ w.opBinding[opID] = b
+ return EncodeImport(b, w.pkcs8, [][]byte{w.leaf})
}
}
@@ -333,9 +491,15 @@ func (w *simWorld) runKind(kind string, actor simActor) {
w.nextID++
w.nested++
op := simOp{id: w.nextID, kind: kind, actor: actor}
- ctx := context.Background()
+ ctx, cancel := context.WithCancel(context.Background())
w.stack = append(w.stack, op)
- defer func() { w.stack = w.stack[:len(w.stack)-1] }()
+ w.cancels = append(w.cancels, cancel)
+ defer func() {
+ cancel()
+ w.stack = w.stack[:len(w.stack)-1]
+ w.cancels = w.cancels[:len(w.cancels)-1]
+ }()
+ st := w.store()
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())
@@ -343,11 +507,10 @@ func (w *simWorld) runKind(kind string, actor simActor) {
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))
+ got, err := WriteImport(ctx, st, simHost, op.actor.account, op.actor.app, w.entryFor(op.id, op.actor))
w.checkWrite(op, got, err)
case "detach":
- w.st.Delete(ctx, ClaimKey(simHost))
+ st.Delete(ctx, ClaimKey(simHost))
case "attach":
if w.rng.Intn(3) != 0 {
w.clock++ // else deliberately the same second
@@ -355,9 +518,9 @@ func (w *simWorld) runKind(kind string, actor simActor) {
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, "")
+ st.Put(ctx, ClaimKey(simHost), raw, "")
case "verify":
- raw, etag, err := w.st.Get(ctx, ClaimKey(simHost))
+ raw, etag, err := st.Get(ctx, ClaimKey(simHost))
if err != nil {
return
}
@@ -367,19 +530,28 @@ func (w *simWorld) runKind(kind string, actor simActor) {
}
c.Pending = false
raw, _ = json.Marshal(c)
- w.st.Put(ctx, ClaimKey(simHost), raw, etag)
+ st.Put(ctx, ClaimKey(simHost), raw, etag)
case "remove":
- RemoveImport(ctx, w.st, simHost, op.actor.account, op.actor.app)
+ RemoveImport(ctx, st, simHost, op.actor.account, op.actor.app)
case "reconcile":
- w.reconcile(ctx, op)
+ w.reconcile(ctx, st, op)
case "toggle":
- switch w.rng.Intn(3) {
+ switch w.rng.Intn(8) {
case 0:
w.st.failGet = !w.st.failGet
case 1:
+ w.st.failNext = 1 + w.rng.Intn(2)
+ case 2:
+ w.st.failEntryGet = !w.st.failEntryGet
+ case 3:
+ w.st.failPut = !w.st.failPut
+ case 4:
+ w.st.failDelete = !w.st.failDelete
+ case 5:
w.st.failList = !w.st.failList
default:
- w.st.failGet, w.st.failList = false, false
+ w.st.failGet, w.st.failNext, w.st.failEntryGet = false, 0, false
+ w.st.failPut, w.st.failDelete, w.st.failList = false, false, false
}
}
}
@@ -405,32 +577,40 @@ func (w *simWorld) checkWrite(op simOp, got Claim, err error) {
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.)
+ // S2: no write leaves a non-matching entry of its own behind unless
+ // its withdraw failed (and then S4: the next clean reconcile removes
+ // it). 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)) {
+ (c == nil || !ob.Matches(*c)) && !errors.Is(err, ErrImportWithdrawFailed) {
w.fail("S2: op %d WriteImport returned (%v) leaving its entry %+v beside claim %+v", op.id, err, ob, c)
}
+ if errors.Is(err, ErrImportWithdrawFailed) && errors.Is(err, ErrImportNoClaim) {
+ w.fail("S2: op %d a failed withdraw reads as ErrImportNoClaim", op.id)
+ }
+ // S7: a store without conditional delete is refused before any write.
+ if w.noCond && !errors.Is(err, ErrImportStoreUnsupported) {
+ w.fail("S7: op %d WriteImport on a store without conditional delete returned %v", op.id, err)
+ }
}
// 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
+func (w *simWorld) reconcile(ctx context.Context, st release.Store, op simOp) {
+ startNested, hadFailure := w.nested, w.st.anyFailure()
w.sawFailure = false
- keys, err := w.st.List(ctx, "control/certs/")
+ keys, err := 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)
+ ReconcileImport(ctx, 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 err == nil && !hadFailure && !w.sawFailure && w.nested == startNested && !w.noCond && !w.cancelled[op.id] {
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)
@@ -460,7 +640,8 @@ func simMaterial(t *testing.T) (pkcs8, leaf []byte) {
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}
+ lastPut: map[int][2]int{}, trace: trace, noCond: seed%10 == 9, cancelled: map[int]bool{},
+ opBinding: map[int]ImportBinding{}, confirm: map[int]*simConfirm{}}
w.st = &simStore{w: w, objs: map[string]simObj{}}
for i := 0; i < simOps && w.failed == ""; i++ {
w.runOp()
@@ -472,6 +653,9 @@ func runImportSim(t *testing.T, seed int64, pkcs8, leaf []byte, trace bool) (fai
}
func TestImportInvariantSim(t *testing.T) {
+ prev := importConfirmBackoff
+ importConfirmBackoff = 0
+ t.Cleanup(func() { importConfirmBackoff = prev })
pkcs8, leaf := simMaterial(t)
if *simSeed >= 0 {
if f, _ := runImportSim(t, *simSeed, pkcs8, leaf, true); f != "" {
diff --git a/internal/provision/cert_import_1429_census_test.go b/internal/provision/cert_import_1429_census_test.go
index d6bbe337a..0f6aeb00f 100644
--- a/internal/provision/cert_import_1429_census_test.go
+++ b/internal/provision/cert_import_1429_census_test.go
@@ -39,7 +39,7 @@ func certImport1429WriteCensusInventory() []censusEntry {
}
}
return append(entries,
- censusEntry{"internal/domains/certimport_invariant.go", "WriteImport", "nonrecord", "sel:Put", "7504f93cc5c8c1c265cf268a384509edd8e1abe6d9b3b370131a914b0b754648"},
+ censusEntry{"internal/domains/certimport_invariant.go", "WriteImport", "nonrecord", "sel:Put", "c9eddf29ba4b5949eed2b1de6dfedfdee7b0d4124fbb7c0100c3d39a601966e8"},
censusEntry{"internal/edge/certimport.go", "certMirror.reconcileLocalImport", "nonrecord", "sel:Put", "75389fc8111a3d299a0b87861136af4f0284fb5b43edcdaf05548f1a768e9f3e"},
)
}