Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): bind Secret mutations to the object we proved we own
Jose Ramireza1f9e1ed89cb
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 1460a7f48..a8d653d2c 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.410",+ "version": "0.1.411","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.410",+ "version": "0.1.411","dependencies": {"@clerum/image-policy": "file:../packages/image-policy","@clerum/llm-providers": "file:../packages/llm-providers",diff --git a/control-api/package.json b/control-api/package.jsonindex 571d4ba58..b614221db 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.410",+ "version": "0.1.411","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/k8s.ts b/control-api/src/k8s.tsindex 53f7c00f4..c50ab23da 100644--- a/control-api/src/k8s.ts+++ b/control-api/src/k8s.ts@@ -8,7 +8,12 @@ import {} from './services/llmAllowedModelsConfigMap.js'import { ResourceService, mergeAnnotationsForReplace } from './services/resourceService.js'import { SecretService } from './services/secretService.js'-import { ClerumResourceType, HostOverview, SecretUpsertRequest } from './types.js'+import {+ ClerumResourceType,+ HostOverview,+ SecretPreconditions,+ SecretUpsertRequest,+} from './types.js'/*** Namespaces where exec operations are permitted.@@ -394,8 +399,12 @@ export class K8sGateway {return this.secrets.createSecret(req)}- async updateSecret(req: SecretUpsertRequest): Promise<unknown> {- return this.secrets.updateSecret(req)+ /** `precondition` makes the replace ownership-bound; see `SecretPreconditions`. */+ async updateSecret(+ req: SecretUpsertRequest,+ precondition?: SecretPreconditions+ ): Promise<unknown> {+ return this.secrets.updateSecret(req, precondition)}async mergeSecret(req: SecretUpsertRequest): Promise<unknown> {@@ -406,8 +415,13 @@ export class K8sGateway {return this.secrets.removeSecretKey(req)}- async deleteSecret(name: string, namespace?: string): Promise<unknown> {- return this.secrets.deleteSecret(name, namespace)+ /** `precondition` binds the delete to a specific object; see `SecretPreconditions`. */+ async deleteSecret(+ name: string,+ namespace?: string,+ precondition?: SecretPreconditions+ ): Promise<unknown> {+ return this.secrets.deleteSecret(name, namespace, precondition)}async getHostOverview(hostName: string, namespace?: string): Promise<HostOverview> {diff --git a/control-api/src/services/registryPullSecretService.ts b/control-api/src/services/registryPullSecretService.tsindex a11f389c2..8a9b35e35 100644--- a/control-api/src/services/registryPullSecretService.ts+++ b/control-api/src/services/registryPullSecretService.ts@@ -72,11 +72,11 @@* against each other, not against an operator, another controller or a `kubectl` replacing* the same NAME — and the reconcile cron reopens that window on every tick rather than once* per install. So every mutation re-proves ownership immediately before it acts, comparing- * `metadata.uid` and the ownership marker against what was classified (`recheckOwnership`).+ * `metadata.uid` and the ownership marker against what was classified (`recheckOwnership`),+ * and then CARRIES that identity into the write itself as a precondition, so the apiserver+ * refuses a replace or delete against an object that moved in the gap (`mutateOwned`).* A namespace that changed hands is recorded (`ownership_changed`) and left alone; one that- * merely vanished is created, since the mint has already revoked whatever key it held. This- * is a narrow compare-and-swap, not an atomic one — the proof read is a separate request —- * and the residual is spelled out on `recheckOwnership`.+ * merely vanished is created, since the mint has already revoked whatever key it held.*/import { createHash } from 'node:crypto'import { config } from '../config.js'@@ -87,7 +87,7 @@ import {EVENFIRE_REGISTRY_PULL_SECRET_NAME,registryHostFromUrl,} from '../routes/admin/registryImagePullSecret.js'-import type { SecretUpsertRequest } from '../types.js'+import type { SecretPreconditions, SecretUpsertRequest } from '../types.js'import { mintOrgPullCredential, resolvePublishScope } from './registryClient.js'import { isRegistryAuthActive } from './registryConnectionDb.js'@@ -493,9 +493,16 @@ function classify(current: SecretView | null, host: string): TargetState {return { kind: 'valid', fingerprint, observed }}-/** What a pre-mutation re-read concluded about the object still sitting under that name. */+/**+ * What a pre-mutation re-read concluded about the object still sitting under that name.+ *+ * `same` carries the identity THAT READ saw, not the one `classify` saw: it is what the+ * following mutation binds itself to, so the API server can reject the write if anything+ * moves in between (see `mutateOwned`). Passing the older identity would pin the write to a+ * version the object may legitimately have left behind.+ */type OwnershipRecheck =- | { verdict: 'same' }+ | { verdict: 'same'; current: SecretIdentity }| { verdict: 'gone' }| { verdict: 'taken'; why: string }@@ -513,25 +520,29 @@ type OwnershipRecheck =* only holds for as long as nobody else moves — and the reconcile cron reopens the window* every tick rather than once per install.*- * WHAT IT IS. A narrow compare-and-swap, NOT an atomic one: the proof read is a separate- * API request from the mutation, so a takeover landing between the two still slips through.- * What it buys is the size of the window — one round trip instead of the whole pass (read- * all → mint → write all, with a registry call in the middle). Closing it completely means- * an `If-Match`-style precondition on the write itself: `metadata.resourceVersion` on the- * replace, and `preconditions.uid` on the delete. Both live in `SecretService`, which is- * shared with the admin /secrets routes and inter-service token rotation, so changing their- * semantics is out of scope here.+ * WHAT IT IS — AND IS NOT. On its own this is only half a compare-and-swap: the proof read+ * is a separate API request from the mutation, so a takeover landing between the two would+ * still slip through. It is never called on its own for that reason. `mutateOwned` pairs it+ * with an `If-Match`-style precondition on the write itself — the identity returned here is+ * carried into `metadata.resourceVersion` on the replace and `preconditions.uid` on the+ * delete — so the API server, not this function, is what finally refuses a write to an+ * object that moved. This read still earns its place: it produces the fresh identity the+ * write binds to, and it distinguishes `gone` (create instead) from `taken` (surrender),+ * neither of which a bare 409 can tell apart.** WHAT IT COMPARES. `uid` and the ownership label, per the two ways a name changes hands:* - `uid` differs ⇒ deleted and recreated. Data, labels and annotations can all be* reproduced by the new owner; the uid cannot.* - the marker is gone ⇒ adopted in place by an external owner, and `classify` would now* call it `foreign`.- * `resourceVersion` is deliberately NOT a gate. It changes on any edit, including benign- * ones by something that left our marker in place — and refusing there would be worse than- * writing: the mint has already revoked the key that copy holds, so declining to overwrite- * leaves the namespace on a dead credential. It is carried for the log line, which is where- * "still ours, but someone edited it" is worth seeing.+ * `resourceVersion` is deliberately NOT a gate HERE, though it is a precondition on the+ * write. It changes on any edit, including benign ones by something that left our marker in+ * place, and refusing on that basis would be worse than writing: the mint has already+ * revoked the key that copy holds, so declining to overwrite leaves the namespace on a dead+ * credential. That is why `mutateOwned` treats the resulting 409 as "re-read and try again",+ * not as "surrender" — only this function's ownership verdict may end the attempt. Here the+ * version difference is logged, which is where "still ours, but someone edited it" is worth+ * seeing.** `uid` is compared only when both reads surfaced one. The API server always sets it; a* caller that cannot see it (an older gateway, a fake) falls back to the ownership label,@@ -567,7 +578,79 @@ async function recheckOwnership('evenfire-registry-pull Secret was modified between classification and write; still ours, proceeding')}- return { verdict: 'same' }+ return { verdict: 'same', current: { uid: now.uid, resourceVersion: now.resourceVersion } }+}++/**+ * How many times an ownership-bound mutation may lose a benign race before we stop.+ *+ * Each attempt is one read plus one write, and the only thing that makes an attempt fail+ * without ending the loop is a 409 from something else writing the same Secret in that gap.+ * Three is chosen to absorb a genuine race, not to wait out a controller that is fighting us+ * for the name: with a persistent writer no number of retries converges, and the honest+ * answer is to stop and report, which is what exhausting these does.+ */+const OWNERSHIP_CAS_ATTEMPTS = 3++/** The outcome of an ownership-bound mutation. `done` means it landed. */+type MutateOutcome = { verdict: 'done' } | { verdict: 'gone' } | { verdict: 'taken'; why: string }++/**+ * Mutate the Secret in `ns` ONLY IF it is still the object this pass classified and still+ * ours — a real compare-and-swap, decided by the API server rather than by a read we hope+ * nothing raced.+ *+ * `recheckOwnership` alone cannot do this: it proves ownership in one request and the+ * mutation happens in the next, so a takeover in that gap is invisible to it. Here the+ * identity it observed is carried INTO the mutation as a precondition (`resourceVersion` on+ * a replace, `preconditions.uid` on a delete), so a write to an object that moved is+ * refused with 409 by the apiserver — the check and the use become one operation.+ *+ * WHY 409 IS NOT AN ANSWER BY ITSELF. It says "this object is not what you thought", which+ * conflates two very different situations: someone took the name over, and someone edited a+ * Secret that is still ours. Surrendering on both would be wrong — the mint upstream has+ * already revoked the key the existing copy holds, so refusing to write over a benign edit+ * strands that namespace on a dead credential, an ImagePullBackOff we caused ourselves. So a+ * 409 sends us back through `recheckOwnership`, which CAN tell the two apart, and only its+ * `taken` verdict ends the loop. That is also why the retry drops the stale+ * `resourceVersion` but keeps the `uid`: the version is expected to have moved, the identity+ * is not.+ *+ * `gone` is returned rather than retried — the object is absent, and what to do about that+ * differs per call site (create the credential, or accept that the delete is already done).+ */+async function mutateOwned(+ gateway: K8sGateway,+ ns: string,+ observed: SecretIdentity,+ mutate: (precondition: SecretPreconditions) => Promise<unknown>+): Promise<MutateOutcome> {+ let expected = observed+ for (let attempt = 1; attempt <= OWNERSHIP_CAS_ATTEMPTS; attempt++) {+ const recheck = await recheckOwnership(gateway, ns, expected)+ if (recheck.verdict !== 'same') return recheck+ try {+ await mutate({+ uid: recheck.current.uid,+ resourceVersion: recheck.current.resourceVersion,+ })+ return { verdict: 'done' }+ } catch (err) {+ if (k8sStatus(err) !== 409) throw err+ logger.info(+ { namespace: ns, attempt },+ 'evenfire-registry-pull Secret changed under an ownership-bound write; re-proving ownership before retrying'+ )+ // Keep the identity, drop the version: the next `recheckOwnership` must still catch a+ // delete-and-recreate, but the version it compares against is known to be stale and+ // would only log noise.+ expected = { uid: recheck.current.uid, resourceVersion: undefined }+ }+ }+ return {+ verdict: 'taken',+ why: `something else rewrote it during each of ${OWNERSHIP_CAS_ATTEMPTS} ownership-bound write attempts, so this pass never managed to write it without risking somebody else's object`,+ }}/**@@ -847,18 +930,17 @@ async function ensureLocked(for (const ns of ours) {const state = states.get(ns)!if (state.kind !== 'broken' || !state.wrongType) continue- const recheck = await recheckOwnership(gateway, ns, state.observed)- if (recheck.verdict === 'taken') {- recordTakeover(pass, ns, recheck.why)+ const outcome = await mutateOwned(gateway, ns, state.observed, precondition =>+ gateway.deleteSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, ns, precondition)+ )+ if (outcome.verdict === 'taken') {+ recordTakeover(pass, ns, outcome.why)surrendered.add(ns)continue}// 'gone': already deleted by someone else, so there is nothing to delete — but the// namespace still needs the credential, and `recreate` is exactly "create, do not// update" downstream. Falling through to the update path would 404.- if (recheck.verdict === 'same') {- await gateway.deleteSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, ns)- }recreate.add(ns)}// Namespaces that changed hands are no longer ours to write. Every caller that references@@ -971,10 +1053,24 @@ async function writeCredential(}return 'exists-foreign'}- // Read-then-write with no gap: `winner` was read immediately above, and the ownership- // check on it is this path's compare-and-swap. Nothing more can be proved here — the- // object had no prior classification to compare against, it did not exist yet.- await gateway.updateSecret(buildSecretReq(ns, cred))+ // The winner is ours, so adopt it — but bind the write to the object we just read.+ // "Read `winner`, then update by name" is the same TOCTOU as everywhere else on this+ // path: the ownership check and the replace are two requests, and `updateSecret`+ // without a precondition re-reads and wins regardless of what landed in between. A+ // create race is precisely when a third writer is known to be active on this name, so+ // this is the LAST place to assume the gap is safe.+ const adopted = await mutateOwned(gateway, ns, winner, precondition =>+ gateway.updateSecret(buildSecretReq(ns, cred), precondition)+ )+ if (adopted.verdict === 'taken') {+ recordTakeover(ctx.pass, ns, adopted.why)+ return 'exists-foreign'+ }+ if (adopted.verdict === 'gone') {+ // Deleted again in the gap. Nobody holds the name and the namespace still needs a+ // credential, so create rather than leaving it empty.+ await gateway.createSecret(buildSecretReq(ns, cred))+ }return 'created'}}@@ -984,16 +1080,18 @@ async function writeCredential(// turn invariant 1 into a runtime accident.return 'exists-foreign'}- // The update path. `SecretService.updateSecret` re-reads to pick up the latest- // `resourceVersion` and therefore ALWAYS wins the write — it proves the object is current,- // never that it is still ours — so ownership has to be re-proved here, against the object- // `classify` decided about. See `recheckOwnership` for what this does and does not buy.- const recheck = await recheckOwnership(gateway, ns, state.observed)- if (recheck.verdict === 'taken') {- recordTakeover(ctx.pass, ns, recheck.why)+ // The update path. Left to itself `SecretService.updateSecret` re-reads to pick up the+ // latest `resourceVersion` and therefore ALWAYS wins the write — it proves the object is+ // current, never that it is still ours. `mutateOwned` binds the replace to the identity we+ // classified instead, so the apiserver refuses it if the object moved.+ const outcome = await mutateOwned(gateway, ns, state.observed, precondition =>+ gateway.updateSecret(buildSecretReq(ns, cred), precondition)+ )+ if (outcome.verdict === 'taken') {+ recordTakeover(ctx.pass, ns, outcome.why)return 'exists-foreign'}- if (recheck.verdict === 'gone') {+ if (outcome.verdict === 'gone') {// Deleted under us. NOT a takeover — nobody else holds the name — and the mint above has// already revoked whatever key that copy carried, so leaving the namespace empty is the// one outcome guaranteed to ImagePullBackOff. Create, because an update against an@@ -1001,7 +1099,6 @@ async function writeCredential(await gateway.createSecret(buildSecretReq(ns, cred))return 'created'}- await gateway.updateSecret(buildSecretReq(ns, cred))return state.kind === 'valid' ? 'exists-ours' : 'repaired'}diff --git a/control-api/src/services/secretService.ts b/control-api/src/services/secretService.tsindex 914f949ad..6ff92ef00 100644--- a/control-api/src/services/secretService.ts+++ b/control-api/src/services/secretService.ts@@ -1,5 +1,5 @@import * as k8s from '@kubernetes/client-node'-import { SecretUpsertRequest } from '../types.js'+import { SecretPreconditions, SecretUpsertRequest } from '../types.js'import { assertValidSecretDataKey, assertValidSecretWriteKeys } from './secretKeys.js'export class SecretService {@@ -62,11 +62,27 @@ export class SecretService {* truth for the whole Secret body — admin /secrets, registry credentials,* inter-service token rotation. For multi-owner Secrets where individual* keys must survive a partial update, use `mergeSecret` instead.+ *+ * Pass `precondition` to make the replace ownership-bound rather than+ * last-writer-wins (see `SecretPreconditions`). When it carries a+ * `resourceVersion` the pre-read is SKIPPED and that version is sent as-is,+ * so the API server rejects the write with 409 if anything touched the+ * object since the caller read it. Re-reading here would defeat the entire+ * point, by refreshing away the staleness we are trying to detect.+ *+ * Because that read is skipped, a precondition caller must supply everything+ * it wants persisted: the `labels`/`annotations`/`type` fallbacks to the+ * existing object are not available on this path.*/- async updateSecret(req: SecretUpsertRequest): Promise<unknown> {+ async updateSecret(+ req: SecretUpsertRequest,+ precondition?: SecretPreconditions+ ): Promise<unknown> {assertValidSecretWriteKeys(req)const ns = req.namespace || this.defaultNamespace- const existing = await this.coreApi.readNamespacedSecret({ namespace: ns, name: req.name })+ const existing = precondition?.resourceVersion+ ? undefined+ : await this.coreApi.readNamespacedSecret({ namespace: ns, name: req.name })const body: k8s.V1Secret = {apiVersion: 'v1',@@ -74,11 +90,14 @@ export class SecretService {metadata: {name: req.name,namespace: ns,- resourceVersion: existing.metadata?.resourceVersion,- labels: req.labels || existing.metadata?.labels,- annotations: req.annotations || existing.metadata?.annotations,+ resourceVersion: precondition?.resourceVersion ?? existing?.metadata?.resourceVersion,+ // Enforced by the API server when set: a replace naming a different uid than the+ // stored object is refused. Free when the caller does not set it.+ ...(precondition?.uid ? { uid: precondition.uid } : {}),+ labels: req.labels || existing?.metadata?.labels,+ annotations: req.annotations || existing?.metadata?.annotations,},- type: req.type || existing.type || 'Opaque',+ type: req.type || existing?.type || 'Opaque',data: req.data,stringData: req.stringData,}@@ -148,10 +167,36 @@ export class SecretService {)}- async deleteSecret(name: string, namespace?: string): Promise<unknown> {+ /**+ * Delete a Secret by name.+ *+ * Pass `precondition` to bind the delete to a specific object rather than to+ * whatever currently answers to that name (see `SecretPreconditions`). A+ * name-addressed delete is the more dangerous of the two mutations: an+ * ownership check followed by a bare delete will remove a REPLACEMENT object+ * — including one an external owner created in the gap — on the strength of+ * a decision made about something that no longer exists. With `uid` set the+ * API server refuses that with 409 instead.+ */+ async deleteSecret(+ name: string,+ namespace?: string,+ precondition?: SecretPreconditions+ ): Promise<unknown> {+ const hasPrecondition = Boolean(precondition?.uid || precondition?.resourceVersion)return this.coreApi.deleteNamespacedSecret({namespace: namespace || this.defaultNamespace,name,+ ...(hasPrecondition && {+ body: {+ preconditions: {+ ...(precondition?.uid && { uid: precondition.uid }),+ ...(precondition?.resourceVersion && {+ resourceVersion: precondition.resourceVersion,+ }),+ },+ },+ }),})}}diff --git a/control-api/src/types.ts b/control-api/src/types.tsindex 8cfa8081f..cc33eed1f 100644--- a/control-api/src/types.ts+++ b/control-api/src/types.ts@@ -49,3 +49,33 @@ export interface SecretUpsertRequest {data?: Record<string, string>stringData?: Record<string, string>}++/**+ * Optimistic-concurrency preconditions for a Secret mutation: "act on THIS object, or+ * fail". Both fields come from a read the caller has already performed.+ *+ * WHY THIS EXISTS. `updateSecret` and `deleteSecret` are name-addressed by default — the+ * update re-reads to pick up the current `resourceVersion` (so it always wins the write)+ * and the delete carries no preconditions at all. That is the right default for a+ * single-owner Secret, where the caller IS the source of truth. It is wrong for one whose+ * ownership can change hands, because a caller that checked ownership and then mutated by+ * name will happily overwrite or delete whatever answers to that name now.+ *+ * Supplying these turns the mutation itself into the compare-and-swap: the API server+ * rejects it with 409 rather than the caller trying to prove freshness with a second+ * request it can never fuse to the write. Callers are expected to handle 409 — re-read,+ * decide whether the object is still theirs, and retry or surrender.+ *+ * `uid` is the identity check that survives a delete-and-recreate of the same name: data,+ * labels and annotations can all be reproduced by a new owner, the uid cannot.+ * `resourceVersion` is the change check — it says "something edited this", not "this is a+ * different object".+ *+ * OPTIONAL BY DESIGN. Omit them and both methods behave exactly as they always have; the+ * admin `/secrets` routes and inter-service token rotation are single-owner writers and+ * want the last-writer-wins default.+ */+export interface SecretPreconditions {+ uid?: string+ resourceVersion?: string+}diff --git a/control-api/test/mockGateway.ts b/control-api/test/mockGateway.tsindex 24675c367..fd7d2aa81 100644--- a/control-api/test/mockGateway.ts+++ b/control-api/test/mockGateway.ts@@ -1,4 +1,5 @@import { K8sNotFoundError } from '../src/services/resourceService.js'+import type { SecretPreconditions } from '../src/types.js'type ResourceType =| 'hosts'@@ -304,7 +305,17 @@ export class MockGateway {return req}- async updateSecret(req: unknown): Promise<unknown> {+ /**+ * Mock Secret replace. Honours `precondition` the way the API server does: a `uid` or+ * `resourceVersion` that disagrees with the stored object is a 409, not a silent+ * overwrite. Without this a test could not tell an ownership-bound write from a+ * name-addressed one — both would "pass" — which is the exact defect the preconditions+ * exist to prevent.+ *+ * A successful write bumps `resourceVersion`, so a caller replaying a stale version is+ * rejected on the second attempt just as it would be against a real cluster.+ */+ async updateSecret(req: unknown, precondition?: SecretPreconditions): Promise<unknown> {const body = req as {name: stringnamespace?: string@@ -314,18 +325,54 @@ export class MockGateway {data?: Record<string, string>stringData?: Record<string, string>}- this.secretStore.set(this.key(body.name, body.namespace), {+ const key = this.key(body.name, body.namespace)+ const existing = this.secretStore.get(key)+ this.assertPrecondition(body.name, existing, precondition)+ this.secretStore.set(key, {name: body.name,namespace: body.namespace || this.ns,type: body.type,labels: body.labels,annotations: body.annotations,+ uid: existing?.uid,+ resourceVersion: MockGateway.nextResourceVersion(existing?.resourceVersion),data: body.data,stringData: body.stringData,})return req}+ /**+ * Reject a mutation whose preconditions do not match the stored object, with the same+ * 409 the API server returns. `undefined` fields are not constraints — a caller that+ * supplies neither gets the historical last-writer-wins behaviour.+ */+ private assertPrecondition(+ name: string,+ existing: { uid?: string; resourceVersion?: string } | undefined,+ precondition?: SecretPreconditions+ ): void {+ if (!precondition) return+ const mismatch =+ (precondition.uid !== undefined && existing?.uid !== precondition.uid) ||+ (precondition.resourceVersion !== undefined &&+ existing?.resourceVersion !== precondition.resourceVersion)+ if (!mismatch) return+ const err = new Error(+ `Operation cannot be fulfilled on secrets "${name}": the object has been modified; please apply your changes to the latest version and try again`+ ) as Error & { statusCode: number; code: number }+ err.statusCode = 409+ err.code = 409+ throw err+ }++ /** Monotonic, and only meaningful relative to itself — exactly like the real one. */+ private static nextResourceVersion(current?: string): string | undefined {+ if (current === undefined) return undefined+ const n = Number(current)+ return Number.isFinite(n) ? String(n + 1) : `${current}-1`+ }+async removeSecretKey(req: { name: string; namespace?: string; key: string }): Promise<unknown> {const ns = req.namespace || this.nsconst key = this.key(req.name, ns)@@ -339,9 +386,16 @@ export class MockGateway {return { name: req.name, namespace: ns, deletedKey: req.key }}- async deleteSecret(name: string, namespace?: string): Promise<unknown> {+ /** Mock Secret delete. Honours `precondition` exactly as `updateSecret` does. */+ async deleteSecret(+ name: string,+ namespace?: string,+ precondition?: SecretPreconditions+ ): Promise<unknown> {const ns = namespace || this.ns- const deleted = this.secretStore.delete(this.key(name, ns))+ const key = this.key(name, ns)+ this.assertPrecondition(name, this.secretStore.get(key), precondition)+ const deleted = this.secretStore.delete(key)return { deleted, name, namespace: ns }}diff --git a/control-api/test/registryPullSecretService.test.ts b/control-api/test/registryPullSecretService.test.tsindex a80c4a35e..1f234af8b 100644--- a/control-api/test/registryPullSecretService.test.ts+++ b/control-api/test/registryPullSecretService.test.ts@@ -382,6 +382,8 @@ describe('ensureRegistryPullSecret — provisioning', () => {mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS, {type: 'Opaque',labels: OURS,+ uid: 'uid-wrong-type',+ resourceVersion: '100',data: {},})const deleteSpy = vi.spyOn(mock, 'deleteSecret')@@ -389,7 +391,14 @@ describe('ensureRegistryPullSecret — provisioning', () => {// An in-place update of `type` would 422, so it must delete first — and the delete// must still precede the (now single, up-front) mint, so a failed delete cannot// strand a freshly-rotated key that has already revoked the cluster's credential.- expect(deleteSpy).toHaveBeenCalledWith(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS)+ //+ // The delete must also be OWNERSHIP-BOUND. A bare name-addressed delete removes+ // whatever answers to that name at the moment it lands — including a replacement an+ // external owner created after we classified this one.+ expect(deleteSpy).toHaveBeenCalledWith(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS, {+ uid: 'uid-wrong-type',+ resourceVersion: '100',+ })expect(deleteSpy.mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(mintOrgPullCredential).mock.invocationCallOrder[0])@@ -857,11 +866,10 @@ describe('ensureRegistryPullSecrets — ownership taken over between classify an)})- // This is a narrow compare-and-swap, not an atomic one — the proof read is a separate- // request from the mutation. What keeps it worth having is that NOTHING happens between- // them, so the window is one round trip rather than the whole pass (read all, mint, write- // all). Pin both halves: one extra read per mutating namespace, and it is the last thing- // before the mutation.+ // The re-proof read is what produces the identity the write then binds itself to, so it+ // has to be the LAST thing before the mutation — a read with anything in between would+ // pin the write to an identity that is already one step stale. Pin both halves: one extra+ // read per mutating namespace, and it is the last thing before the mutation.it('re-reads immediately before each mutation, and only then', async () => {const { gateway, mock } = gw()// One of each mutating shape: wrong-typed (delete + create), valid (update), absent@@ -890,6 +898,169 @@ describe('ensureRegistryPullSecrets — ownership taken over between classify an})})+/**+ * The half of the TOCTOU that a re-read CANNOT close: a takeover landing AFTER the ownership+ * re-proof and BEFORE the mutation it authorises. No amount of checking beforehand helps —+ * the check and the write are two requests, and the gap between them is exactly where this+ * lands.+ *+ * What closes it is carrying the identity the re-proof observed INTO the write, as a+ * precondition the apiserver enforces: `metadata.resourceVersion` on a replace,+ * `preconditions.uid` on a delete. The write to a moved object is then refused with 409+ * rather than silently winning.+ *+ * Every test here arms the takeover on the RE-PROOF read specifically (the classify read is+ * #1, the re-proof is #2), so the re-proof itself succeeds. That is what makes them+ * regression tests rather than restatements of the block above: against a name-addressed+ * mutation they fail, because the check passes and the write lands anyway.+ */+describe('ensureRegistryPullSecrets — ownership taken over between the re-proof and the write', () => {+ /**+ * Fire `mutate` immediately after the `nth` read of `ns`, placing a takeover in a chosen+ * gap. Counted in `finally` so a 404 advances the clock too — an absent Secret is still a+ * read, and without this "the Nth read" would quietly mean "the Nth read that found+ * something", which is a different position in the sequence on the create path.+ */+ function takeoverAfterRead(+ mock: MockGateway,+ ns: string,+ nth: number,+ mutate: (mock: MockGateway) => void+ ): void {+ const real = mock.getSecret.bind(mock)+ let seen = 0+ vi.spyOn(mock, 'getSecret').mockImplementation(async (name: string, namespace?: string) => {+ try {+ return await real(name, namespace)+ } finally {+ if (namespace === ns && ++seen === nth) mutate(mock)+ }+ })+ }++ /** A stranger's Secret: usable, and NOT carrying our ownership marker. */+ function seedStranger(mock: MockGateway, ns: string, uid: string): void {+ mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, ns, {+ type: 'kubernetes.io/dockerconfigjson',+ uid,+ data: { [DOCKERCONFIG_KEY]: encodeDockercfg(HOST, 'stranger-key') },+ })+ }++ it('refuses the replace when a stranger takes the name after the re-proof', async () => {+ const { gateway, mock } = gw()+ seedValid(mock, [NS], 'efrk_live', 'uid-ns')+ mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, SANDBOX, {+ type: 'kubernetes.io/dockerconfigjson',+ labels: OURS,+ uid: 'uid-sandbox',+ resourceVersion: '42',+ annotations: { [FINGERPRINT_ANNOTATION]: fingerprintOf('efrk_live') },+ data: { [DOCKERCONFIG_KEY]: encodeDockercfg(HOST, 'efrk_live') },+ })+ // sandbox-ui is absent, so the pass mints and rewrites every namespace it owns.+ takeoverAfterRead(mock, SANDBOX, 2, m => seedStranger(m, SANDBOX, 'uid-stranger'))++ await expect(ensureRegistryPullSecrets(gateway, ALL)).rejects.toMatchObject({+ reason: 'ownership_changed',+ status: 409,+ })+ const squatter = await readStored(mock, SANDBOX)+ expect(squatter.labels['clerum.io/managed-by']).toBeUndefined()+ expect(squatter.blob).toBe(encodeDockercfg(HOST, 'stranger-key'))+ })++ // The destructive half. A name-addressed delete does not just lose a race, it REMOVES the+ // object that won it — here an external owner's credential, which no later pass restores.+ it('refuses the delete when a stranger takes the name after the re-proof', async () => {+ const { gateway, mock } = gw()+ seedValid(mock, [SANDBOX, UI], 'efrk_live')+ mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS, {+ // Wrong type ⇒ the immutable-field path, which deletes and recreates.+ type: 'Opaque',+ labels: OURS,+ uid: 'uid-ours',+ resourceVersion: '7',+ data: {},+ })+ takeoverAfterRead(mock, NS, 2, m => seedStranger(m, NS, 'uid-theirs'))++ await expect(ensureRegistryPullSecrets(gateway, ALL)).rejects.toMatchObject({+ reason: 'ownership_changed',+ status: 409,+ })+ // Still there, and still theirs.+ const squatter = await readStored(mock, NS)+ expect(squatter.type).toBe('kubernetes.io/dockerconfigjson')+ expect(squatter.labels['clerum.io/managed-by']).toBeUndefined()+ expect(squatter.blob).toBe(encodeDockercfg(HOST, 'stranger-key'))+ })++ // The other direction, and the reason a 409 cannot simply mean "give up": a benign edit+ // that leaves the object ours produces the SAME 409 as a takeover. Surrendering there would+ // strand this namespace on the key the mint has already revoked — an ImagePullBackOff we+ // caused ourselves, in the name of safety.+ it('retries the write when the 409 came from a benign edit, not a takeover', async () => {+ const { gateway, mock } = gw()+ seedValid(mock, [NS], 'efrk_live', 'uid-ns')+ mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, SANDBOX, {+ type: 'kubernetes.io/dockerconfigjson',+ labels: OURS,+ uid: 'uid-sandbox',+ resourceVersion: '42',+ annotations: { [FINGERPRINT_ANNOTATION]: fingerprintOf('efrk_live') },+ data: { [DOCKERCONFIG_KEY]: encodeDockercfg(HOST, 'efrk_live') },+ })+ // Same object (same uid), still marked ours — somebody just edited it. Only the version+ // moved, which is enough to make our precondition fail.+ takeoverAfterRead(mock, SANDBOX, 2, m =>+ m.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, SANDBOX, {+ type: 'kubernetes.io/dockerconfigjson',+ labels: { ...OURS, 'example.com/touched-by': 'something-else' },+ uid: 'uid-sandbox',+ resourceVersion: '43',+ annotations: { [FINGERPRINT_ANNOTATION]: fingerprintOf('efrk_live') },+ data: { [DOCKERCONFIG_KEY]: encodeDockercfg(HOST, 'efrk_live') },+ })+ )++ const res = await ensureRegistryPullSecrets(gateway, ALL)++ expect(res.get(SANDBOX)).toBe('exists-ours')+ // The retry wrote OUR freshly minted key, not the one the mint just revoked.+ const stored = await readStored(mock, SANDBOX)+ expect(stored.annotations[FINGERPRINT_ANNOTATION]).toBe(fingerprintOf('efrk_test_key'))+ })++ // The create-race path adopts a winner it read a moment earlier. A create race is the one+ // situation where a third writer is KNOWN to be active on this name, so it is the last+ // place to assume the gap between that read and the write is safe.+ it('binds the adopt-the-winner write to the winner it just read', async () => {+ const { gateway, mock } = gw()+ const create = mock.createSecret.bind(mock)+ vi.spyOn(mock, 'createSecret').mockImplementation(async req => {+ if ((req as { namespace?: string }).namespace !== NS) return create(req)+ mock.seedSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, NS, {+ type: 'kubernetes.io/dockerconfigjson',+ labels: OURS,+ uid: 'uid-winner',+ resourceVersion: '5',+ data: { [DOCKERCONFIG_KEY]: encodeDockercfg(HOST, 'efrk_winner') },+ })+ throw Object.assign(new Error('already exists'), { statusCode: 409, code: 409 })+ })+ // Reads of mcp-server: #1 classify (404), #2 read the race winner, #3 re-prove it. The+ // takeover lands after #3, so only the precondition on the write can still catch it.+ takeoverAfterRead(mock, NS, 3, m => seedStranger(m, NS, 'uid-stranger'))++ await expect(ensureRegistryPullSecrets(gateway, ALL)).rejects.toMatchObject({+ reason: 'ownership_changed',+ status: 409,+ })+ expect((await readStored(mock, NS)).blob).toBe(encodeDockercfg(HOST, 'stranger-key'))+ })+})+describe('ensureRegistryPullSecrets — fan-out across platform namespaces', () => {async function blobIn(mock: MockGateway, ns: string) {const raw = (await mock.getSecret(EVENFIRE_REGISTRY_PULL_SECRET_NAME, ns)) as {diff --git a/control-api/test/services.secretService.test.ts b/control-api/test/services.secretService.test.tsindex 117181a14..49f57a830 100644--- a/control-api/test/services.secretService.test.ts+++ b/control-api/test/services.secretService.test.ts@@ -161,6 +161,75 @@ describe('SecretService — invalid Secret keys never reach the apiserver', () =})})+/**+ * The preconditions are only worth anything if they reach the apiserver in the shape it+ * enforces. Every other test of this feature asserts that the CALLER passes a precondition;+ * these assert that passing one changes the actual request. Get the translation wrong —+ * resourceVersion on the wrong field, delete preconditions omitted — and the whole+ * ownership-bound write silently degrades to last-writer-wins with every test still green.+ */+describe('SecretService — ownership-bound mutations', () => {+ let coreApi: CoreApiMock+ let svc: SecretService++ beforeEach(() => {+ coreApi = createCoreApiMock()+ svc = new SecretService(coreApi as unknown as k8s.CoreV1Api, 'test-ns')+ })++ it('sends the CALLER’s resourceVersion on a replace, without re-reading', async () => {+ coreApi.readNamespacedSecret.mockResolvedValue({+ metadata: { resourceVersion: '999' },+ type: 'Opaque',+ data: {},+ })++ await svc.updateSecret(+ { name: 's', namespace: 'ns', type: 'Opaque', data: { k: 'dg==' } },+ { resourceVersion: '42', uid: 'uid-1' }+ )++ // The re-read is the bug, not an optimization: it would replace the stale version we+ // are trying to detect with the current one, and the write would win regardless.+ expect(coreApi.readNamespacedSecret).not.toHaveBeenCalled()+ const body = coreApi.replaceNamespacedSecret.mock.calls[0][0].body+ expect(body.metadata.resourceVersion).toBe('42')+ expect(body.metadata.uid).toBe('uid-1')+ })++ it('keeps last-writer-wins when no precondition is given', async () => {+ coreApi.readNamespacedSecret.mockResolvedValue({+ metadata: { resourceVersion: '999' },+ type: 'Opaque',+ data: {},+ })++ await svc.updateSecret({ name: 's', namespace: 'ns', data: { k: 'dg==' } })++ // Unchanged for the admin /secrets routes and token rotation, which are single-owner+ // writers and want the current version.+ expect(coreApi.readNamespacedSecret).toHaveBeenCalled()+ const body = coreApi.replaceNamespacedSecret.mock.calls[0][0].body+ expect(body.metadata.resourceVersion).toBe('999')+ expect(body.metadata.uid).toBeUndefined()+ })++ it('sends delete preconditions so the apiserver refuses to delete a replacement', async () => {+ await svc.deleteSecret('s', 'ns', { uid: 'uid-1', resourceVersion: '42' })++ const req = coreApi.deleteNamespacedSecret.mock.calls[0][0]+ expect(req.body.preconditions).toEqual({ uid: 'uid-1', resourceVersion: '42' })+ })++ it('sends no delete body at all when no precondition is given', async () => {+ await svc.deleteSecret('s', 'ns')++ // An empty `preconditions: {}` is not the same as none — keep the historical request+ // shape for callers that never opted in.+ expect(coreApi.deleteNamespacedSecret.mock.calls[0][0].body).toBeUndefined()+ })+})+describe('invalidSecretDataKeyReason — the shared rule', () => {it('accepts every legitimate key', () => {for (const key of VALID_KEYS) {