Skip to content

APIConsumer: one object per caller, so adding or rotating a key is not a release - #22

Merged
zhanghaohit merged 30 commits into
mainfrom
feat/apiconsumer
Nov 26, 2026
Merged

zhanghaohit merged 30 commits into
mainfrom
feat/apiconsumer

Conversation

@zhanghaohit

@zhanghaohit zhanghaohit commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

A ModelFleet's gateway.authConsumers names who may call that route, but who exists at all and with which keys is one list for the whole gateway — key-auth's defaultConfig.consumers, rendered today by the gateway chart. Adding a tenant is therefore a values file and a deploy, and rotating a key is the same again.

APIConsumer makes it an object: a name, a gateway namespace, and a Secret whose every value is an accepted credential. The reconciler collects every APIConsumer naming one gateway, sorts them, and writes that one list. One object per writer, one field per writer — the same model ModelFleet uses, and the reason this is a separate kind: a gateway-wide list on a per-route object would have N fleets writing one field, which is the matchRules problem again and worse, because defaultConfig is an opaque blob with no per-entry ownership under SSA.

Rotation is "add a second value to the Secret, let the caller move over, remove the old one", with no window where neither key works.

The two rules that decide when NOT to write

  • One object's problem costs that object, never the gateway. Dropping a consumer whose Secret cannot be read would revoke someone's key over a Secret that may be seconds from existing, so its live entry is kept verbatim and everybody else's changes still go through; the object says why. A name collision, an unprovable adoption and a key that duplicates a live entry are all handled the same way — refusing the round would mean nobody could rotate or revoke a key, including a leaked one, while the bad object exists.
  • Ownership comes from the record, not from the name. Keeping or adopting an entry requires the annotation this controller writes alongside the entry itself, so pointing consumerName at a chart-rendered consumer gets you nothing — with or without a readable Secret. Do not grant tenants apiconsumers/status: the ownership record is in the status.
  • The list may not be emptied unless this controller already owns it. "The last consumer was revoked" and "nobody has migrated this gateway yet, and the chart still renders its list" are the same desired state — zero objects — and only one of them may wipe a live list. The question asked instead is whether any APIConsumer records this gateway in status.appliedGatewayNamespace.

That second rule started as a flat "never write empty", which made two legitimate operations impossible: deleting the last consumer, and moving every consumer to another gateway. A test for the move caught it.

Also here

  • credentialsSecretRef is a bare name: the controller holds a cluster-wide secrets: get, and a ref that could name another namespace would turn "can write an APIConsumer here" into "can read every Secret in the cluster".
  • A duplicate consumer name across two objects is refused with both named, since the plugin would otherwise take one of them and nothing would say which.
  • Registered only when its CRD is served, like ModelFleet, so a ModelRoute-only cluster is unaffected.
  • A deleted object has its credentials withdrawn under its finalizer, because afterwards nothing remembers the key was ever accepted.
  • No watch on Secrets, deliberately: it would start an informer over every Secret in the cluster, which is what this controller went out of its way not to need. A key added to a Secret takes effect within one resync; editing the object is immediate.

ModelFleet gains spec.gateway.streamGuard and, by default, an ai-stream-guard rule on every fleet route that carries a copy of the plugin's defaultConfig — a behaviour change on upgrade, and one that does nothing until the gateway chart ships that plugin with a non-empty detectors. A fleet opts out with streamGuard.disabled: true. ⚠ On a cluster whose ModelFleet CRD has not been upgraded the API server prunes that field silently, so disabled: true is accepted and ignored.

The rest of ModelFleet is unchanged. Its check that authConsumers name consumers the gateway actually defines keeps validating against the live plugin rather than against APIConsumer objects: what matters is what is programmed, not what is declared, and the two differ exactly while something is wrong.

What this does not give you

Secrecy. key-auth's config is a blob pushed to the data plane over ECDS and the plugin cannot read a Secret, so the keys still land in plain text inside the WasmPlugin. One source of truth, online rotation, no release to add a tenant — not hidden keys.

Coordination

The gateway chart has to drop its consumers rendering (keeping the keys placeholder and global_auth), the same split as the matchRules change. Until it does, the second rule above keeps this controller from touching that list.

Validated on k8s-cpu-16 (rc25): the live takeover of that cluster's consumer list, with auth unchanged either side of it; a key added and revoked through the CRD; the label scope paths; stream-guard rules reaching the gateway and cutting a repeating stream; and bodylog's view of a cut. The scripts are in the vllm repo under tools/apiconsumer/ and tools/modelfleet/. The commits after rc25 are covered by unit tests only, and need an rc of their own before release.

…t a release

A ModelFleet's gateway.authConsumers names who may call THAT route, but who exists at all and
with which keys is one list for the whole gateway — key-auth's defaultConfig.consumers,
rendered today by the gateway chart. Adding a tenant is therefore a values file and a deploy,
and rotating a key is the same again.

APIConsumer makes it an object: a name, a gateway namespace, and a Secret whose every value is
an accepted credential. The reconciler collects every APIConsumer naming one gateway, sorts
them, and writes that one list. One object per writer, one field per writer — the same model
ModelFleet uses, and the reason this is a separate kind rather than a field on ModelFleet:
putting a gateway-wide list on a per-route object would have N fleets writing one field, which
is the matchRules problem again, and worse, because defaultConfig is an opaque blob with no
per-entry ownership under Server-Side Apply.

Rotation is "add a second value to the Secret, let the caller move, remove the old one", with
no window where neither key works. A key added to a Secret takes effect within one resync;
editing the object is immediate. There is deliberately NO watch on Secrets: it would start an
informer over every Secret in the cluster, which is exactly what this controller went out of
its way not to need (it holds `secrets: get` and reads uncached).

Two rules decide when NOT to write, and both are the dangerous direction:

  * One unreadable Secret stops the whole round. Dropping that consumer and writing the rest
    would revoke someone's key over a Secret that may be seconds from existing; a consumer
    missing from key-auth is a caller getting 401 on its next request. The gateway keeps its
    last good list and the object says why.
  * The list may not be emptied unless this controller already owns it. "The last consumer
    was revoked" and "nobody has migrated this gateway yet, and the chart still renders its
    list" are the same desired state — zero objects — and only one of them may wipe a live
    list. The question asked instead is whether any APIConsumer records this gateway in
    status.appliedGatewayNamespace. Writing an empty list over the chart's would turn off
    authentication for every route on the gateway.

That second rule started out as a flat "never write empty", which made two legitimate
operations impossible: deleting the last consumer, and moving every consumer to another
gateway. A test for the move caught it.

Also here: credentialsSecretRef is a bare name, because the controller holds a cluster-wide
`secrets: get` and a ref that could name another namespace would turn "can write an
APIConsumer here" into "can read every Secret in the cluster"; a duplicate consumer name
across two objects is refused with both named, since the plugin would otherwise take one of
them and nothing would say which; the reconciler is registered only when its CRD is served,
like ModelFleet, so a ModelRoute-only cluster is unaffected; and a deleted object has its
credentials withdrawn under its finalizer, because afterwards nothing remembers the key was
ever accepted.

ModelFleet is unchanged. Its check that authConsumers name consumers the gateway actually
defines keeps validating against the live plugin rather than against APIConsumer objects:
what matters is what is programmed, not what is declared, and the two differ exactly while
something is wrong.

What this does NOT give you is secrecy. key-auth's config is a blob pushed to the data plane
over ECDS and the plugin cannot read a Secret, so the keys still land in plain text inside the
WasmPlugin. One source of truth, online rotation, no release to add a tenant — not hidden
keys. That needs a plugin that can read a Secret, and is a different piece of work.

Claude-Session: https://claude.ai/code/session_01GVorddJkUMjYffPHXSDxop
@zhanghaohit
zhanghaohit requested a review from zoboth November 26, 2026 05:46

@zoboth zoboth left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I read the whole diff: the types, CRD, RBAC, cmd/main.go, the controller, sink/consumer.go and the tests. The design is sound: one writer per gateway list, refusing to write when any Secret is unreadable, and withdrawing the key under the finalizer. But three issues need fixing before merge.

Blockers

1. The first APIConsumer on a gateway replaces the whole chart-rendered list, and every chart-defined caller then gets 401.
The ownership guard in writeConsumers only applies when the new list is empty (len(consumers) == 0 && len(live) > 0 && !ownedBefore). Take a gateway whose key-auth still has the chart's [tenant-a, ops, tenant-b] and create one APIConsumer for tenant-a. programGateway renders [tenant-a]. ownedBefore is false, but the list is non-empty, so the guard doesn't fire and ops and tenant-b are removed. The PR says that until the chart drops consumers, "the second rule above keeps this controller from touching that list", but that only holds while zero APIConsumers exist. The consumerName doc ("a gateway-wide namespace shared with whatever the chart still renders") also suggests the two can coexist, and they can't.
The migration you'd expect (create APIConsumers for the existing tenants, then change the chart) also hits this. Even a single kubectl apply -f dir/ creates the objects one by one, and the first reconcile can run before the rest exist.
Suggested fix: when !ownedBefore, refuse any write that would remove a live entry whose name is not in the desired set, not only the empty write. Alternatively, keep unowned entries until an explicit adopt/annotation step. Either way, a chart name that collides with an APIConsumer name should be reported, like the duplicate check does between objects.

2. Status writes re-trigger the reconciler, so it hot-loops instead of resyncing every 60s.
SetupWithManager uses For(&routingv1.APIConsumer{}) with no predicate. Every reconcile ends in setConsumerStatus, which always sets LastSyncTime = now and does Status().Update. That Update event re-enqueues the object straight away, so each consumer reconciles about once per second rather than once per consumerResyncTime. Each round runs a List plus an uncached APIReader Secret GET for every consumer on the gateway, twice for the object itself. With N consumers that is about N² Secret GETs per second against the API server, which undoes the "no Secret informer" saving the PR is built around.
Suggested fix: either builder.WithPredicates(predicate.Or(predicate.GenerationChangedPredicate{}, …)) (deletion and finalizer changes still need to get through), or skip the status write when nothing but LastSyncTime would change.

3. The finalizer can make an APIConsumer impossible to delete, and its namespace with it.
On deletion, programGateway runs for spec.gateway.namespace and for appliedGatewayNamespace, and any error returns before the finalizer is removed. Some realistic cases that leave it stuck:

  • gateway.namespace has a typo, so there is no key-auth there. The object was never programmed (appliedGatewayNamespace == ""), but deletion still does Get key-auth, gets NotFound, and keeps failing.
  • Another consumer on the same gateway has a missing Secret or a duplicate name. Deleting an unrelated consumer is then blocked until someone fixes the other object.
  • Namespace teardown: Terminating hangs on the finalizer for either of the reasons above.

Suggested fix: withdraw only from status.appliedGatewayNamespace, the one place the key is known to be. If that is empty, drop the finalizer right away. Treat a NotFound key-auth as nothing to withdraw.

Non-blocking notes

  • The comment at the top of the controller says it shares wasmPluginGVK, gatewayNamespace and isAbsent with ModelFleet. The code uses defaultGatewayNamespace and never calls isAbsent. I can't see main from here, so I couldn't confirm that defaultGatewayNamespace, sink.ToMap, sameRules, wasmPlugin, condTrue and resourceVersionOf exist under those names. CI will settle it, and the comment should match whatever the code ends up using.
  • Revocation latency: removing a compromised key from the Secret only takes effect at the next resync, because Secrets aren't watched. The README covers this for adding a key. It's worth saying that removing one works the same way, and that editing the APIConsumer (for example, bumping an annotation) is the way to force it now.
  • readCredentials runs twice for the reconciled object, once inside programGateway and again for status. Returning the count from programGateway would remove the "cannot happen" branch.
  • The CredentialsSecretRef doc says "Only the fleet's own namespace". It should say this object's namespace.
  • consumerName has a MaxLength but no pattern. Restricting it to something like a DNS label would keep odd characters out of the access log and the allow lists.
  • Removing the old ModelFleet/ModelRoute rules from role.yaml / controller-rules.yaml and adding them back further down is only controller-gen reordering. The permissions are unchanged, and APIConsumer correctly gets no create/delete.
  • The deepcopy import alias changes are regenerated code and look consistent.
  • I'd like to see tests for: blocker 1 (one APIConsumer created while the chart still renders other consumers); deleting a consumer whose gateway has no key-auth; and moving the last consumer off a gateway (the "empty is allowed when owned" path).

…not wedge on delete

Three review findings, all in the same area: what this controller is entitled to overwrite.

It replaced the whole consumer list. The guard before it only refused a write that rendered
NOTHING, which left the likely case wide open: the gateway chart renders three tenants,
somebody creates their first APIConsumer - step one in the documentation - and the full
replacement revokes the other three. Three 401s, from following the instructions, with a
Programmed=True condition to show for it.

Live entries this controller did not write are now carried over verbatim, credentials and all.
Which ones those are cannot be derived from the objects that exist, because a deleted
APIConsumer leaves an entry that looks exactly like one of the chart's - so the names it wrote
are recorded in an annotation on key-auth, next to the data they describe. An entry in that
record and gone from the APIConsumers is a revocation; an entry that was never in it belongs
to somebody else and is kept. A list holding an entry that is not an object, or has no name,
is not rewritten at all: carrying entries over means reproducing them, and one that cannot be
read cannot be told apart from one of ours.

This also settles the migration order with the gateway chart, which still renders `consumers`
today. Taking over by refusing to write would have deadlocked it - the chart cannot drop the
field until the field is ours, and SSA hands it back on the next helm upgrade - so adoption is
the only sequence that works. Dropping the key entirely is not an option either: key_auth's
parsePluginConfig returns false when neither consumers nor credentials is present, and that
plugin is FAIL_CLOSE on these clusters.

Deletion could wedge the object. The rewrite that revokes a key refuses the whole round if ANY
consumer on that gateway has an unreadable Secret, and that error returned before the finalizer
came off - so somebody else's broken Secret held this object in Terminating for good, freeable
only by hand-editing a finalizer. It now retries for 15 minutes, with the reason on the object,
and then lets go: a stuck object is worse than a stale entry somebody can see.

Telling "nothing left to revoke from" apart from "could not revoke" needs its own signal, not
IsNotFound - a MISSING SECRET is also NotFound, and the first version of this fix released the
object while the credential was still live in key-auth. A sentinel error now marks the one case
where key-auth, or its CRD, genuinely is not there. The same confusion in the gateway-migration
path made a consumer retry withdrawal from an uninstalled gateway forever and never reach its
new one.

One review finding I did not take: that credentials need a "Bearer " prefix because checkAuth
strips one. Measured instead - the live consumers on the test cluster carry bare keys, 21
characters, no prefix. That TrimPrefix is defensive.

Each judge was checked by reverting the fix and watching it fail, including the one that caught
the too-broad absent check above.

Claude-Session: https://claude.ai/code/session_01GVorddJkUMjYffPHXSDxop
… included

A consumer rendered with a bare key refuses every standard client. key_auth's
extractCredential returns `header->toString()` - the entire header value, no prefix stripped,
nothing trimmed - and looks it up exactly in the credentials set. So with keys:
["Authorization"] and a client sending `Authorization: Bearer sk-x`, the string compared is
"Bearer sk-x", and a credential of "sk-x" matches nothing. Every OpenAI-compatible caller gets
401 while the APIConsumer reports Programmed=True. The Secret holds the key, in openresty's
key-file format, so the prefix is added here; one that already carries it is left alone.

I had dismissed this, on the grounds that the live consumers on the test cluster carry bare
keys - 21 characters, the length of the production key. They carry "Bearer " + a 14-character
test key, which is also 21 characters. Comparing lengths and assuming the rest is not a
measurement. The real evidence was there and pointed the other way: a fleet's match rule
allows two of those consumers, the B1 verification passed against them with Bearer clients
(200 / 403 / 401 / 401), and the gateway chart has always required the prefix. The
TrimPrefix in ModelFleet's own checkAuth was a hint I argued past.

Only the prefixed form is rendered, not both. Every standard client sends Bearer; accepting a
bare key as well would bless a non-standard calling convention that could not be withdrawn
later without breaking whoever had adopted it.

Also refuses a credential shared between consumers, or repeated within one. That is not "one
of them wins": key_auth logs `duplicate consumer credential`, returns false, and the whole
defaultConfig fails to parse - and the plugin is FAIL_CLOSE, so two tenants sharing a key
denies every caller on every route of that gateway. The check runs after the prefix is added,
so "sk-x" under one consumer and "Bearer sk-x" under another collide, as they will at runtime.
The error names the consumers and the position of the credential, never its value: that text
lands on a CR, in the logs, and in whatever ships them.

Claude-Session: https://claude.ai/code/session_01GVorddJkUMjYffPHXSDxop
A status write is an update event on the object, and this controller watches its own kind with
no predicate, so a write that always happens makes every round enqueue the next one.
lastSyncTime was stamped unconditionally, so the write always happened. Each round here costs
a List plus an UNCACHED Secret GET for every consumer on the gateway - the whole point of not
running a Secret informer - so N consumers cost N^2 GETs per iteration, and the iterations were
paced by how long a reconcile takes rather than by consumerResyncTime.

Now the write is skipped when nothing but lastSyncTime would move. The heartbeat survives:
once lastSyncTime is older than the resync interval it is written anyway, which is one write
and one extra reconcile per interval instead of a stream. Without that, a settled object's
lastSyncTime would freeze and anyone using it to answer "is this still being reconciled" would
read a dead controller.

The comparison is reflective, with lastSyncTime zeroed, rather than field by field: a field
added to either status would otherwise drop out of the comparison silently, and the symptom -
one particular field stops updating - looks nothing like that cause. ModelFleet has the same
unconditional stamp and the same self-trigger; that fix goes on its own branch, since the
helper is shared.

Measured first rather than taken on faith: on the test cluster the one live ModelFleet writes
its status about every 10s against a 30s resync, so there is real extra triggering, but not the
once-per-second loop the review predicted. I could not attribute the 10s - ModelRoute status
churn arriving through the fleet's watch would do it too - so that number is reported, not
explained.

The review's other points, and one I did not take:

  * `consumerName` now has to be a DNS label. It is written into the gateway's allow lists and
    shows up in the X-Mse-Consumer header and the access log, so a comma or a quote in it
    lands in all three.
  * README: revocation has the same 60s latency as adding a key, which matters much more -
    a leaked key keeps working for up to a minute after it leaves the Secret. Says how to make
    it immediate (touch the object, or delete it and let the finalizer revoke).
  * README: the Bearer prefix and the shared-key hazard, both one-line traps with
    gateway-wide consequences.
  * `credentialsSecretRef` said "the fleet's own namespace"; it is this object's namespace.
  * The stale comment about which helpers are shared with ModelFleet.

  * NOT taken: withdrawing only from status.appliedGatewayNamespace and releasing an object
    that was never programmed immediately. Two existing tests failed on it, correctly - their
    fixtures have a live credential in key-auth and no status, which is exactly what a round
    that wrote the gateway and then failed to write its own status leaves behind. The
    shortcut would strand that key for good. It also buys nothing: a misspelled gateway
    namespace has no key-auth to Get, which is the absent sentinel and releases at once, and
    everything else gives up at the deadline.

Blockers 1 and 3 were already fixed in 04dd684, which the review predates: it read 658a66c.

Claude-Session: https://claude.ai/code/session_01GVorddJkUMjYffPHXSDxop
@zhanghaohit

Copy link
Copy Markdown
Collaborator Author

Thanks — this review read 658a66c, and blockers 1 and 3 were already fixed in 04dd684. Blocker 2 was new and real, and is fixed in d961f95. Details, including the two points I did not take.

Blocker 1 (replacing the chart's list) — fixed in 04dd684, by adoption rather than refusal.
Refusing would have deadlocked the migration: the chart cannot drop consumers until the field is no longer helm's, and SSA hands it back on the next helm upgrade. So live entries this controller did not write are carried over verbatim, credentials included, and the names it did write are recorded in an annotation on key-auth — without that record, an entry whose APIConsumer has since been deleted is indistinguishable from one of the chart's, and deleting a consumer would stop revoking the key. A list holding an entry that is not an object, or has no name, is not rewritten at all.

Dropping the key entirely is not an option either, which is worth recording here: key_auth's parsePluginConfig returns false when neither consumers nor credentials is present, and the plugin is FAIL_CLOSE on these clusters. The gateway chart now yields the field whenever a non-helm manager owns it (modelsphere/modelsphere#90), and that was verified against the real API server with --dry-run=server.

Blocker 2 (status writes re-triggering the reconciler) — fixed in d961f95. lastSyncTime was stamped unconditionally, so the write always happened. It is now skipped when nothing but lastSyncTime would move, with a heartbeat: once it is older than the resync interval it is written anyway, so a settled object costs one write and one extra reconcile per interval instead of a stream.

Two corrections to the diagnosis, both measured:

  • The rate was not about once per second. On the test cluster, before the fix, the one live ModelFleet wrote its status roughly every 10s against a 30s resync — real extra triggering, 3× the intended rate, not a tight loop. I could not attribute the 10s (ModelRoute status churn arriving through the fleet's watch would do it too), so I am reporting the number rather than explaining it.
  • reflect.DeepEqual is unusable for this comparison, which cost me an hour: it calls a nil slice and an empty slice different, and a status that has been through the API server comes back with one where the renderer builds the other. The first version of the fix found no status settled while the serialised status was byte for byte identical. It uses equality.Semantic now.

ModelFleet has the same unconditional stamp and the same self-trigger. That fix is on #21, since the helper is shared.

Blocker 3 (finalizer wedging the object) — fixed in 04dd684, but not the way suggested. It now retries for 15 minutes with the reason on the object, then releases: a stuck object is worse than a stale entry somebody can see.

I did try the suggested version — withdraw only from status.appliedGatewayNamespace, and release immediately when it is empty — and two existing tests failed on it, correctly. Their fixtures have a live credential in key-auth and no status, which is exactly what a round that wrote the gateway and then failed to write its own status leaves behind; the shortcut would strand that key for good. It also buys nothing: the misspelled-namespace case has no key-auth to Get, and that is treated as nothing to withdraw already.

That distinction needed its own signal, not IsNotFound: a missing Secret is also NotFound, and the first version of this fix released the object while the credential was still live. There is a sentinel error for the one case where key-auth, or its CRD, genuinely is not there. The same confusion in the gateway-migration path made a consumer retry withdrawal from an uninstalled gateway forever and never reach its new one.

On the non-blocking notes:

  • The credential needed the Bearer prefix — fixed in 018248e. This was a finding from an earlier review that I wrongly dismissed, having measured the live consumers as 21-character bare keys; they are "Bearer " plus a 14-character test key, which is also 21 characters. extractCredential returns the whole header value and the lookup is exact, so a bare key 401s every standard client while the CR reports success. Only the prefixed form is rendered — accepting a bare key as well would bless a calling convention that could not be withdrawn later.
  • Reading the plugin source for that turned up something worse: a credential shared between two consumers makes key_auth log duplicate consumer credential, return false, and fail to parse its whole configuration — with FAIL_CLOSE, that denies every caller on every route. Rendering now refuses it, before and after the prefix is added, so sk-x under one consumer and Bearer sk-x under another collide as they would at runtime. The error names the consumers and the position, never the value: that text lands on a CR and in the logs.
  • consumerName is restricted to a DNS label now. It reaches the allow lists, the X-Mse-Consumer header and the access log.
  • README: revocation has the same 60s latency as adding a key, which matters far more — a leaked key keeps working for up to a minute after it leaves the Secret. It now says that, and how to make it immediate.
  • credentialsSecretRef said "the fleet's own namespace"; it is this object's namespace. The stale comment about shared helpers is corrected.
  • readCredentials running twice: left as is. The second call is what fills status.credentials, and threading the count out of programGateway means returning per-object data from a function whose job is the whole gateway.
  • Tests you asked for: one APIConsumer created while the chart renders others (TestConsumerDoesNotRevokeEntriesItDoesNotOwn), deleting with no key-auth (TestConsumerDeleteReleasesWhenTheGatewayIsGone), and the settled-status behaviour (TestConsumerSettledStatusIsNotRewritten). Moving the last consumer off a gateway is covered by TestConsumerMovingGatewayWithdrawsFromTheOldOne.

Every fix was checked by reverting it and watching the test fail — twice for two of them, where the first revert only broke the build, which is not a test catching anything.

The gateway chart will not stop rendering defaultConfig.consumers until some manager other
than helm owns it (modelsphere/modelsphere#90), and nothing in this controller was ever going
to take it. A non-apply Update only takes ownership of the fields whose VALUE it changes, and
the first thing this controller does on a populated gateway is adopt the live entries
unchanged - so the field stayed helm's for as long as the rendered list matched, which is
exactly the state a migration starts in. The chart would have waited forever.

So: one server-side apply of just defaultConfig.consumers, with its current value,
fieldManager=autoconfig, force. Measured on the test cluster beforehand (by the session
working on that chart, with --dry-run=server against a copy):

  * A same-value force apply makes autoconfig a CO-OWNER alongside helm rather than
    dispossessing it, which is all the chart needs - it yields to any manager that is not
    helm.
  * keys and global_auth stay helm's and keep their values: defaultConfig is tracked field by
    field, not as one atomic blob. That had been my objection to this approach, and it was
    wrong - the evidence was in a managedFields dump I had already taken and read as a
    boolean.
  * Once the chart stops rendering the field, helm's claim lapses and this controller is left
    as the only owner.

The claim names nothing but consumers, which the test asserts by parsing the patch rather than
grepping it: an apply naming keys or global_auth would take them from helm too, and one that
owned defaultConfig while dropping them would leave a key-auth that cannot parse at all - the
plugin is FAIL_CLOSE.

It also has to happen exactly once, not once per pass, because an apply that changes something
is an ECDS push of key-auth to the whole data plane. That is what ownsConsumers is for, and
getting it tested took teaching the fake client about apply patches: it refuses them outright,
and it keeps no managedFields, so the takeover - the one write that MUST be an apply - could
not be exercised at all and the ownership question answered "no" forever. The test interceptor
now translates an apply into the equivalent merge patch, records it, and writes the
managedFields entry a real API server would have recorded. TestConsumerUnchangedListIsNotRewritten
caught the repeat before the new test existed.

Not yet done, and not safe to do from here: the actual takeover on the test cluster. It
rewrites a live authentication list that a ModelFleet match rule is using, so it waits for an
rc image and a go-ahead.

Claude-Session: https://claude.ai/code/session_01GVorddJkUMjYffPHXSDxop
…ery pass

A value older than the resync interval means settled, not stalled, and reading it the other
way is the mistake the doc now heads off. Matches the wording on ModelFleet's own field; the
behaviour shipped with the settled-status fix.

Claude-Session: https://claude.ai/code/session_01GVorddJkUMjYffPHXSDxop
Found by doing the migration for real, on the test cluster: three consumers were adopted and
the annotation that records which entries are ours named exactly one of them.

Adopting an entry the chart already renders, with the same credential, produces a list
identical to what is live. The "nothing changed, do not write" check then returns before the
attribution is written - so the first adoption recorded itself and the next two were skipped
as no-ops. Deleting either of those two would have left its entry in place, read as somebody
else's and carried over, and the key would have kept working. That is the one thing deleting
an APIConsumer must never do.

The check now also compares the names it would record against the ones already recorded, so a
round that changes nothing but the attribution still writes. That is one write per membership
change, not per round.

No unit test covered it because every existing case changes the list in some way; the new one
renders exactly what is already live. Verified by reverting to the list-only check and
watching it report the live symptom - an empty annotation and an adopted entry that survives
its APIConsumer's deletion.

Claude-Session: https://claude.ai/code/session_01GVorddJkUMjYffPHXSDxop
Both suites declared condMessage. On separate branches each builds fine, and whichever merged
into main second would have failed there - a collision git never reports as a conflict,
because the two branches never touch the same file. It is consumerCondMessage here.
@zhanghaohit
zhanghaohit requested a review from zoboth November 26, 2026 08:34
status_settled.go now lives on main with the equality.Semantic comparison; this branch carried
an older copy that still used reflect.DeepEqual, which never finds a status settled (nil slice
vs empty slice) and so skipped no writes at all. Took main's.

zz_generated.deepcopy.go regenerated rather than hand-merged.
… whole gateway

**A carried-over entry was never compared against our credentials.** RenderConsumers refuses
two APIConsumers sharing a key, because key-auth logs `duplicate consumer credential`, fails
to parse the entire defaultConfig, and the plugin is FAIL_CLOSE - every route denying every
caller. But a foreign entry is copied into the list verbatim, so the one check that prevents
that outage never saw it.

It is reachable on the documented migration path rather than in theory: a chart entry whose
name is not a DNS label cannot be adopted under that name, since consumerName is pinned to
one, so it gets a new APIConsumer carrying the SAME key - the entire point being that the
caller changes nothing. Both entries then exist, and the gateway stops answering. The check
now runs over the final merged list, and names the two consumers without the credential.

**status.appliedGatewayNamespace recorded the spec, not what was programmed.** The status
write re-Gets the object and read the gateway out of the spec again. A spec edit landing
between the write and the status update therefore recorded a gateway that was never
programmed; the next round compares the two, finds them equal, and never withdraws the
credential from the gateway that really has it - the exact failure this field exists to
prevent. The round now passes in the namespace it wrote to.

**Attribution had a single source that lives on an object we do not own.** The
managed-consumers annotation is the only record for an APIConsumer that is already gone, but
recreating or replacing that WasmPlugin drops it - and then deleting an APIConsumer classifies
its own entry as somebody else's, carries it over, releases the object with no error, and the
revoked tenant's key keeps working. Statuses are now a second source: every object that still
exists reports the name it programmed, including the one being deleted.

**Deleting a never-programmed consumer sat in Terminating for 15 minutes.** On a gateway whose
list still belongs to the chart, a first APIConsumer with a typo'd secret ref never programs;
deleting it renders zero consumers over a non-empty list, which the empty-list guard refuses
on every pass, until the revoke deadline - reporting that a key could not be withdrawn when
none was ever granted. Now: no record of ever programming AND no entry under that name in the
live list is conclusive, and the object is released at once. Note the difference from the
shortcut I rejected earlier, which trusted the empty status alone and would have stranded a
live key written by a round that then failed to record itself.

Each fix was checked by reverting it. Two of those checks needed a second attempt: the first
two reverts broke the build, which is not a test catching anything, and the status one then
passed against the reverted code - two sequential reconciles cannot reproduce an interleaving
inside one round, because by the time the second writes its status the spec already says what
it is about to record either way. That test now checks the contract directly.

Claude-Session: https://claude.ai/code/session_01GVorddJkUMjYffPHXSDxop

@zoboth zoboth left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review at 4b3e537. I read the whole diff: types/CRD, cmd/main.go, RBAC, apiconsumer_controller.go, sink/consumer.go and the tests. The fixes from the last round hold up. Attribution now uses both the annotation and the status claims, errGatewayAbsent is a separate sentinel from a missing Secret, the settled-status heartbeat is in place, the Bearer prefix is added before the duplicate check, and the final list is checked for duplicates too. One blocker remains.

Blocker

1. Any APIConsumer writer can take over a consumer identity the chart still renders. (writeConsumers, the carry-over loop: if mine[name] || managed[name] || claimed[name] { continue })

Adoption works by name only. If a live entry has the same name as a rendered APIConsumer, it is dropped and replaced, whatever its credentials were. Concretely: the chart renders tenant-a with key K1, and some fleets list tenant-a in authConsumers. Someone who can create APIConsumers in any namespace, for example team-x, creates one with consumerName: tenant-a and a Secret holding their own key K2. On the next round the controller writes tenant-a: [Bearer K2]. They now have every route tenant-a was allowed on, and the real tenant-a gets 401 on its next request. Nothing refuses this or reports it: RenderConsumers only catches duplicates between APIConsumers, and refuseDuplicateCredentials sees no shared key.

The PR's own threat model counts namespace-scoped APIConsumer writers as less trusted than the controller. That is why credentialsSecretRef is pinned to the object's namespace. By the same reasoning, they should not be able to claim an identity that belongs to someone else.

Suggested fix, without breaking the documented migration: adopt a foreign live entry by name only when the APIConsumer's rendered credentials include every credential that live entry carries. That proves the caller holds the existing key, and the migration path in the docs and in TestConsumerAdoptionIsRecordedEvenWhenTheListDoesNotChange keeps the same key anyway. Otherwise, refuse the round and name the object and the entry, never the key. Rotation still works afterwards because the entry is then in managed/claimed. A test with a same-name foreign entry and a different key would pin it down.

Non-blocking notes

  • One bad object freezes revocation for the whole gateway. "One unreadable Secret stops the whole round" also covers an APIConsumer that has never been programmed, such as a fresh object with a typo'd ref or a duplicate consumerName. While it exists, no other consumer on that gateway can be added, rotated or revoked. That includes removing a leaked key from a Secret, and a deletion, which retries for 15 minutes and then releases with the key still live. Dropping a consumer whose status.appliedGatewayNamespace != gwNS (and whose name is not in managed) revokes nothing. Skipping it, with the error reported on that object, would keep the fail-closed rule where it matters and stop a single new object from blocking everyone else.
  • The empty-list guard can block a real revocation. Because unowned entries are now carried over, len(consumers) == 0 && len(live) > 0 can only happen when every live entry is already managed or claimed. So !ownedBefore only adds the case where the annotation says the entries are ours but no status does. That happens when the last consumer's status write failed after its gateway write and the object is then deleted. The guard refuses, the finalizer releases after 15 minutes, and the key stays live, with no APIConsumer left to trigger a cleanup. Consider counting managed names toward ownedBefore, or basing the guard on the final next list instead.
  • Field manager on the Update. claimConsumers applies as autoconfig, but r.Update(ctx, obj) uses the client's default manager. consumers is an atomic field under a preserve-unknown blob, so if the default manager isn't autoconfig, each changing Update moves ownership to it. Then ownsConsumers returns false next time, and every change becomes a force-apply plus an Update, which may mean two pushes. Passing client.FieldOwner(fieldManagerName) to the Update would keep one owner. I couldn't confirm the default manager name from the diff.
  • statusSettled, sink.ToMap, wasmPluginGVK, isAbsent, sameRules and defaultGatewayNamespace aren't in this diff. statusSettled is added by #21 (internal/controller/status_settled.go). I'm assuming these, and the existing wasmplugins patch/update and secrets: get rules, are already on main. Please make sure #21 is in before this merges, or it won't build.
  • hasNoLiveEntry matches by name only. A never-programmed object whose name matches a chart entry falls through to a full round, which is correct but slower. Fine as is.
  • The review-request head (c794a8c) differs from the head I fetched (4b3e537). This review covers 4b3e537.

@zhanghaohit

Copy link
Copy Markdown
Collaborator Author

All four taken, fixed in 4b3e537. Each was checked by reverting the fix and watching the test fail — two of those checks needed a second attempt, noted at the end.

1. Carried-over entries bypassing the duplicate-credential check — fixed, and this was the one that mattered.

Correct in every detail, including that it is reachable on the documented migration path rather than in theory: a chart entry whose name is not a DNS label cannot be adopted under that name, so it gets a new APIConsumer carrying the same key — the whole point being that the caller changes nothing. The check now runs over the final merged list, before the write, and the message names the two consumers without the credential (that text lands on a CR and in the logs).

Worth stating the blast radius for the record, since it is worse than "a duplicate entry": key_auth does not reject the entry, it return falses parsePluginConfig for the whole defaultConfig, and the plugin is FAIL_CLOSE — every route on that gateway denies every caller.

2. status.appliedGatewayNamespace recording the spec instead of what was programmed — fixed.

The round now passes the namespace it wrote to. The interleaving is exactly as described, and it defeats the one thing the field exists for.

3. Attribution having a single source that lives on an object we do not own — fixed.

Statuses are now a second source: every object that still exists reports the name it programmed, including the one being deleted, so a recreated key-auth no longer makes deletion silently stop revoking. The annotation stays for objects that are already gone, which is the case statuses cannot cover.

4. Deleting a never-programmed consumer waiting out the revoke deadline — fixed.

Released at once when there is provably nothing to revoke: no record of ever programming and no entry under that name in the live list. Both halves matter — I rejected a version of this shortcut in an earlier review round precisely because it trusted the empty status alone, and that would strand a live key written by a round which then failed to record itself. The live-list check is what makes it safe.

On the verification, since two of these checks were worthless the first time:

  • The reverts for findings 1 and 2 broke the build. A build failure is not a test catching something, and reading it as one is how a bad judge survives.
  • Finding 2's test then passed against the reverted code. Two sequential reconciles cannot reproduce an interleaving inside one round: by the time the second writes its status, the spec already says what it is about to record either way. The test checks the contract directly now — spec pointing at a third gateway, the programmed one passed in, and the recorded value has to be the programmed one.

Unrelated to this PR but found while reading key_auth for finding 1, and relevant to whoever operates the gateway chart: that chart decides whether to render consumers by lookuping the live managedFields. Rendered offline — helm template, which is how ArgoCD works — the lookup returns empty and the chart emits consumers: []. That parses (the key exists), and then every request on a route with a key-auth rule is refused, because rule.consumers is empty and so is rule.credentials. Sent to the session that owns that chart.

@zhanghaohit
zhanghaohit requested a review from zoboth November 26, 2026 09:08
…ccepts

The re-review's blocker, and it is an identity problem rather than a credential one.

Adoption worked by name alone: a live entry whose name matched a rendered APIConsumer was
dropped and replaced, whatever it had carried. An APIConsumer can be created in any namespace,
its consumerName is free-form, and nothing else objects - the names do not collide between
APIConsumers, and no credential is shared, so neither existing guard fires. So a writer who
put `consumerName: tenant-a` and their own key in their own Secret would inherit every route
tenant-a is allowed on, while the real tenant-a got 401 on its next request.

credentialsSecretRef is pinned to the object's own namespace precisely because a
namespace-scoped writer is not trusted with other people's credentials. An identity is worth
no less.

Adopting an unclaimed entry now requires carrying every credential it already accepts, which
proves the writer holds the key. That is what a migration does anyway - the point is that the
caller changes nothing - and dropping an old key comes afterwards as a rotation, when the
entry is ours and no proof is needed. A refusal names the object and the entry, never the key.

Three notes from the same review, two of which were doing real harm:

  * **One never-programmed object froze revocation for the whole gateway.** "One unreadable
    Secret stops the round" is right for a consumer that HAS a key in the list and would lose
    it. It is wrong for one that has nothing in there: while a fresh object with a typo'd
    secretRef existed, nobody else on that gateway could be added, rotated or revoked -
    including removing a leaked key, and including a deletion, which then retried for the
    revoke deadline and released with the key still live. Such an object is skipped now, with
    the error on itself; a consumer that is in the live list still fails the round closed.

  * **The empty-list guard could block a real revocation.** Revoking the LAST consumer when no
    status claims the gateway - its gateway write succeeded, the status write after it did not,
    and it was then deleted - was refused, the finalizer gave up at the deadline, and the key
    stayed live with no APIConsumer left to clean it up. The annotation counts toward ownership
    now: emptying a list it says is ours IS the revocation.

  * The Update now passes FieldOwner explicitly. The default manager happens to be this same
    name - measured on the test cluster, managedFields reads `autoconfig Update` - but it is
    derived from the user agent, and consumers is an atomic field: if that ever changed, every
    write would cost a force-apply plus an Update, two config pushes where one belongs.

Left alone: hasNoLiveEntry matching by name only, which the review called correct but slower,
and it is.

Each change was checked by reverting it. Two of the three reverts had to be redone: the first
broke the build, which catches nothing, and the ownedBefore change turned out to have no test
at all - the suite passed with it reverted, so the test for that specific sequence was written
afterwards.

Claude-Session: https://claude.ai/code/session_01GVorddJkUMjYffPHXSDxop
…sumer exists

The gateway chart stops rendering defaultConfig.consumers (modelsphere/helm-charts#122), which
makes this controller the only thing that can create it. key_auth's parsePluginConfig returns
false when neither consumers nor credentials is present, and the plugin is FAIL_CLOSE, so a
key-auth without that key means the gateway refuses every request on every route. Two gaps
stood between that plan and a working gateway, and I had told the other side one of them was
already handled, which was wrong.

**Nothing would have written the key.** writeConsumers read the live value and returned early
when nothing had changed - and sameRules treats an absent key and an empty list as equal, so a
round with zero consumers over a key-auth that has no consumers key concluded there was
nothing to do. The absent case is now distinguished from the empty one.

**Nothing would have triggered the round.** The controller watches APIConsumer and nothing
else, so a fresh install - helm creates key-auth, no APIConsumer exists yet - produced zero
reconciles and the key was never written. There is now a watch on the key-auth WasmPlugin
itself, which covers three things the APIConsumer watch cannot:

  - the fresh install above;
  - key-auth being deleted and recreated, which takes every consumer entry with it. The
    objects still exist so their own resync would restore the entries within the interval,
    but the watch makes it the next event;
  - which namespace. With no APIConsumer there is nothing to say which gateway to look at,
    and the answer is not a configured default that could be wrong - the event carries the
    namespace, so this fires for every key-auth in the cluster and guesses nothing.

It runs the same programGateway round as an APIConsumer event, not a smaller "just ensure the
key" write: one field, one way to write it. A key-auth that is gone again by the time the round
runs is not an error to retry.

Tests cover the zero-APIConsumer case the other side asked for, the recreation, and the
deleted-gateway event; the first was verified by reverting the absent-key distinction and
watching it report that the gateway would refuse everything.

Still unverified here, and said as much where it matters: how long the window is between
key-auth being created and the key being written. It should be one informer event, but a
number belongs in their documentation, so it gets measured on a cluster before it goes there.

Claude-Session: https://claude.ai/code/session_01GVorddJkUMjYffPHXSDxop
Two findings, both about one object's problem becoming everybody's.

**A colliding newcomer froze consumer management for the whole gateway.** The unreadable-Secret
case already had an escape hatch - a consumer that was never programmed here is left out
rather than failing the round, so one new broken object cannot hold the rest hostage - and
RenderConsumers had none: it refuses the whole view set on a duplicate name or a shared
credential, and that error came straight out of programGateway. So from the moment somebody
created an object whose consumerName collided, or pasted an existing key into their own
Secret, no key on that gateway could be added, rotated or REVOKED - including pulling a leaked
one - and a deletion in flight retried to the revoke deadline and then released with the key
still live.

The refusals stay: the duplicate-name one is what stops a namespace-scoped writer taking a
name that belongs to someone else, and the duplicate-credential one is what stops a
gateway-wide parse failure. Only who pays changes:

  * one claimant already serving the identity: it keeps it, and every newcomer is left out and
    told why, on its own object;
  * nobody serving it yet: ALL claimants are left out. Granting the first would arbitrate "who
    is tenant-a" by list order, which is a coin flip in a dispute, and refusing costs nobody
    access because nobody had the name;
  * two claimants already serving it: still an error. One newcomer cannot cause it, it means
    two live consumers genuinely share an identity, and dropping either revokes a working key.

Getting there needed a correction the tests forced. "Is this an incumbent" first asked whether
an entry existed under that consumer NAME, which an impostor satisfies by definition - so an
impostor and the consumer it was impersonating came out as two incumbents and the round was
refused for the whole gateway, with the impersonation deciding it. The question is whether the
live entry is attributable to THIS object: its own status is conclusive, and failing that, an
entry with no other claimant is plausibly its own (that is the object whose gateway write
landed and whose status write did not, and leaving it out would revoke a live key).

**A live credential stored without the `Bearer ` prefix could never be adopted.** The rendered
side is always prefixed, so comparing verbatim made the proof impossible: `sk-x` in the Secret
renders as `Bearer sk-x`, and `Bearer sk-x` renders as the same thing, so nothing satisfied it
- while the refusal told the operator to add a key they had already added, and the round failed
for every consumer on the gateway. Both sides are normalised now. Possession of the key is the
question; how the entry spells it is not.

Adoption then changes the spelling, from a bare key to `Bearer <key>`, and key_auth compares
the whole Authorization header - so a caller sending the bare form starts getting 401. That is
logged when it happens, naming the consumer, because nothing else would say it.

Claude-Session: https://claude.ai/code/session_01GVorddJkUMjYffPHXSDxop
These rules now span two repos and a cluster's auth stays up only if both sides keep them, so
they belong next to the CRD rather than in a thread: which side owns which field of
defaultConfig (field-level, measured, not atomic), that a missing consumers key is a
FAIL_CLOSE gateway and therefore why the key-auth watch exists, that the new chart must not
reach a cluster running an older autoconfig, that one key may belong to one consumer only, and
that credentials render with the Bearer prefix because key_auth compares the whole header.

Also the adoption rule and why it demands the existing key: consumerName is free-form and an
APIConsumer can be created in any namespace, so without that proof anyone could inherit the
routes a name is allowed on.

@zoboth zoboth left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed head 7b6d79b: the whole diff, plus #21 to confirm that statusSettled already comes from main.

Blocker

1. On a cluster without Higress, KeyAuthReconciler keeps autoconfig from starting, and ModelRoute goes down with it. (cmd/main.go, internal/controller/apiconsumer_controller.go KeyAuthReconciler.SetupWithManager)

The new watch is registered whenever servedKinds reports APIConsumer. It sets up an informer on extensions.higress.io/v1alpha1 WasmPlugin, but nothing checks that this kind is served. This PR also adds routing.modelsphere.dev_apiconsumers.yaml to deploy/helm/autoconfig/crds/, so a fresh install of this autoconfig release serves APIConsumer whether or not Higress is installed. In modelsphere, enabled.higress is false by default, so most clusters are in exactly that state.

How it fails: controller-runtime cannot resolve the WasmPlugin kind ("no matches for kind"), and the keyauth controller's cache never syncs. When CacheSyncTimeout runs out, the controller's Start returns an error and mgr.Start exits. The pod then crash-loops, taking openresty peers, CART workers and monitor.conf with it. main.go names this failure for ModelFleet ("watching a type that does not exist fails the manager, which would take ModelRoute down with it"). The PR description promises "a ModelRoute-only cluster is unaffected". errGatewayAbsent/isAbsent already treat a missing WasmPlugin CRD as a normal case. The unit tests call Reconcile on a fake client and never start a manager, so none of them can catch this. The test cluster had Higress installed, so it couldn't either.

Even with enabled.higress, the modelsphere helmfile doesn't order autoconfig after the higress release. On a fresh install autoconfig can start before the WasmPlugin CRD exists and crash-loop until it does.

What I would change: in main.go, also discover extensions.higress.io/v1alpha1 and register KeyAuthReconciler only when WasmPlugin is served. Log the skip the same way the ModelFleet and APIConsumer skips are logged. Then decide how a later Higress install gets picked up: a restart, documented next to the existing "apply crds/ and restart" message, or ordering autoconfig after higress in the modelsphere helmfile when enabled.higress. Without that, the "autoconfig adds the empty list" contract that helm-charts#122 and modelsphere#90 depend on silently doesn't happen. Add a test that runs the setup against a scheme or REST mapper without WasmPlugin.

(I couldn't see main's ModelFleet SetupWithManager. If it already watches WasmPlugin, main has the same problem, but this PR still extends it to every fresh install via the new CRD.)

Non-blocking notes

  • One Secret holding the same value under two keys freezes the gateway. readCredentials doesn't dedupe. For an incumbent, dropCollidingNewcomers sees two "incumbents" from the same source sharing a credential and refuses the round with a message about two consumers. This can happen in the middle of a rotation, e.g. copying current into next before editing it. Deduping in readCredentials (after TrimSpace, and comparing with the Bearer prefix normalised) would fix the freeze and the misleading error.
  • Collision detection compares raw values, rendering compares prefixed ones. sk-x in one consumer and Bearer sk-x in another get past dropCollidingNewcomers but fail RenderConsumers, which refuses the whole round instead of dropping the newcomer. Normalise before add("credential", …).
  • Adoption failures still freeze the whole gateway. An APIConsumer whose consumerName matches an unmanaged live entry counts as an incumbent (live entry, no other claimant). If it lacks the live credentials, writeConsumers returns an error for the whole round. Until it is fixed, no other consumer can be added, rotated or revoked. That is the "impersonation decides the freeze" case the comments set out to avoid. Now that the chart never renders consumers this only applies to hand-written or orphaned entries, so it's low priority. The fix would be to skip that object like other newcomers instead of failing the round.
  • KeyAuthReconciler writes to every WasmPlugin named key-auth, in any namespace. If one has no consumers key, autoconfig adds consumers: [] and takes ownership of that field. That's probably harmless, but it acts on plugins nobody pointed it at. Consider limiting it to namespaces that an APIConsumer or ModelFleet names, or to a label.
  • Stale comments. fieldManagerName ("what the gateway chart looks for before it yields") and the claimConsumers/ownership comment ("the gateway chart holds its upgrade back until a non-helm manager owns the field") describe the old lookup design. modelsphere#90 and helm-charts#122 now never render consumers and read nothing from the cluster.
  • Cost. Every APIConsumer reconcile runs a full gateway round and reads every consumer's Secret uncached, so N consumers cost about N² GETs per resync. That's fine at today's scale, but worth a comment or a per-gateway rate limit later.
  • The settled-status heartbeat and equality.Semantic fix look right. The delete path (fast release only when there's no status and no live entry, otherwise withdraw with a deadline) and recording the programmed namespace in status rather than the spec's both read correctly.

…Higress

The blocker, and the worst failure in this PR so far: the watch was registered whenever the
APIConsumer CRD was served, which this release installs everywhere, while
`extensions.higress.io/v1alpha1 WasmPlugin` exists only where Higress does -
`enabled.higress` is false by default. A For() watch builds its informer at startup and waits
for the cache to sync, so on those clusters the manager would exit when CacheSyncTimeout ran
out and the pod would crash-loop, taking ModelRoute down with it: openresty peers, CART
workers, monitor.conf. main.go names that exact risk for ModelFleet, and the PR description
promised a ModelRoute-only cluster was unaffected.

It is gated on discovery now, and the skip is logged like the others, saying what does not
happen until Higress is installed and the pod restarted - because the contract helm-charts#122
depends on ("autoconfig adds the empty list") then silently does not hold.

I did not reproduce the crash-loop. The reading of controller-runtime's startup is the
reviewer's and it is credible, the test cluster has Higress so it could not show it either
way, and the tests cover what I can state: discovery answers "not served" for a missing group
instead of erroring, and the gate refuses to register without the kind. Said plainly rather
than implied, since "verified" and "argued convincingly" are different.

Three freezes, all the same shape as the two fixed in the previous commit - one object's
problem becoming the whole gateway's:

  * **One Secret holding a value twice.** Ordinary mid-rotation (copy `current` into `next`,
    then edit), and it arrived as one consumer carrying a credential twice: the collision
    check read that as two claimants on one credential, both from the same object, and
    refused the round with a message about two consumers that named one object twice.
    readCredentials deduplicates now, with the prefix normalised.
  * **`sk-x` in one consumer and `Bearer sk-x` in another.** The same credential once
    rendered, and key-auth refuses a duplicate by failing to parse the whole config - but the
    collision check compared raw values, so the pair sailed past it into RenderConsumers,
    which refuses the round instead of leaving the newcomer out. Normalised before comparing.
  * **An adoption that cannot be proven.** Still returned an error for the round, so an object
    wanting an identity it does not hold stopped every other consumer on the gateway from
    being added, rotated or revoked. It moved out of writeConsumers into programGateway -
    where the objects are, which is why it could not report per-object before - and the object
    is left out with the reason on itself.

That last move exposed something worth keeping: a skipped object's own reason is now reported
BEFORE the round's error. Leaving an object out can be what makes the rendered list empty, and
the empty-list guard then refuses to write it over live entries - correct, and says nothing
about the object that caused it.

Each fix verified by reverting it; all three reverts had to be redone, because the first
attempt at each broke the build, which catches nothing.

Claude-Session: https://claude.ai/code/session_01GVorddJkUMjYffPHXSDxop
…way closed

Gating the key-auth watch on discovery stops the crash-loop, and on its own it replaces that
failure with a quieter one. Higress's CRDs come from the higress CORE release, while the
helmfile deploys autoconfig BEFORE higress-llm, which needs it - so autoconfig routinely
starts in a cluster that has no WasmPlugin kind, skips the watch correctly, and then nothing
ever writes key-auth's consumers key. The gateway is FAIL_CLOSE and stays that way until
somebody restarts autoconfig. Worse than the crash-loop, because nothing announces it: the
pod is healthy, the logs say the watch was skipped, and the contract helm-charts#122 relies on
silently does not hold.

So there is now a sweep that needs no informer: an uncached List of WasmPlugins, once at
startup and then every resync interval, running the same gateway round for each key-auth it
finds. A missing kind is one failed List and the next round tries again, which is also what
makes a Higress installed later get picked up without restarting the pod. The watch stays
where the kind is served, for the immediate response to a key-auth being recreated.

The List goes through APIReader on purpose. A cached one would build an informer for a kind
that may not exist, which is the problem the gate exists to avoid - reintroducing it one layer
down would have been a neat way to undo the fix while the tests still passed.

Verified by reverting the sweep's write and watching it report the FAIL_CLOSE outcome, and by
a second test that a cluster with no WasmPlugin kind at all makes the sweep a quiet no-op
rather than an error every minute.

Claude-Session: https://claude.ai/code/session_01GVorddJkUMjYffPHXSDxop
…n any state

The discovery gate keeps the key-auth WATCH off a cluster without Higress, and the reads were
still going through the cached client - which builds an informer for a kind on first use. That
puts the dependency the gate exists to remove one layer down, where no test would notice until
a cluster without Higress fell over, and it made the one path I cannot measure on the test
cluster rest on an assumption: that a lazy informer starts cleanly when the CRD appears
mid-run, and does not block.

Uncached, the answer is the same in every state, and it is one I can state rather than argue:
a missing kind is an error isAbsent recognises, and a kind installed later works on the next
read. The cost is one GET per gateway per round.

The test gives the reconciler a client that refuses WasmPlugin reads and an APIReader that
works, so anything reaching for the cache shows up. Narrowed after the first version refused
EVERY read and failed because the APIConsumer list could not be read - which looked exactly
like the bug it was written to find. APIConsumer and Secret reads may use the cache; this
controller only runs where that CRD is served.

Claude-Session: https://claude.ai/code/session_01GVorddJkUMjYffPHXSDxop
Three comments still described the lookup design the gateway chart abandoned: the chart reads
nothing from the cluster now and renders no consumers at all, so fieldManagerName is an
internal detail again rather than an agreed contract, and the takeover is no longer something
the chart waits for. What the takeover is FOR is now said: clusters installed before that
change, where helm still owns the field from its last apply. A fresh install has nobody to
take it from.

Also writes down the quadratic cost rather than leaving it to be discovered - one round reads
every consumer's Secret uncached, so N consumers cost about N^2 GETs per interval - along with
the way out that does not involve a cluster-wide Secret informer, which is the thing this
controller deliberately does not have.
…onfigured the other way

The sweep wrote to every WasmPlugin named key-auth in the cluster, which means adding
`consumers: []` to a Higress another team runs in their own namespace, and taking SSA
ownership of a field on it - acting on an object nobody pointed this controller at. It is now
limited to gateway namespaces something here names: every APIConsumer's, every ModelFleet's
(fleets count because they are what puts match rules on a gateway), and the default one.

The default one is in the set because leaving it out broke the case the sweep exists for: a
fresh install has no APIConsumer and no fleet yet, while key-auth's defaultConfig is already
active - defaultConfigDisable is false - and therefore already has to parse. Both sweep tests
went red, which is how I found that out rather than by reasoning about it.

And a guard that matters more than the scoping: key_auth accepts `consumers` OR a top-level
`credentials` list and refuses a config carrying both, so adding consumers to a key-auth
configured the credentials way would take that gateway down. Such a gateway is by definition
not one autoconfig set up. It is left alone when there is nothing of ours to write there, and
refused with an explanation when there is.

That guard was in the wrong place first, after the ownership claim - and the claim had already
written `consumers: []` by then, so the test saw the error AND the damage. Moved ahead of it.

Claude-Session: https://claude.ai/code/session_01GVorddJkUMjYffPHXSDxop
Agreed with the chart side (modelsphere/helm-charts#122): it puts
`routing.modelsphere.dev/consumers: autoconfig` on the key-auth it installs, and that is the
signal this controller writes the consumer list. The label names the FIELD rather than just a
manager, which is the point - keys and global_auth on the same object stay with the chart.

It answers the case namespace-based scoping could not: a chart installed outside
higress-system, before any fleet or APIConsumer exists. That gateway would otherwise sit
FAIL_CLOSE until somebody created the first object, which is the fresh-install path.

The hardcoded default namespace stays for now, and the reason is written down next to it: a
chart release WITHOUT the label would leave a fresh install's gateway closed, and that is
worse than one release of a narrower intrusion - writing to an unlabelled key-auth in
higress-system that nothing names. It should go once the labelled chart has shipped, and the
comment and the README both say so, so it does not quietly become permanent.

The label value is checked, not just its presence: a key-auth labelled for a different manager
is not consent, and the test covers that alongside the labelled-elsewhere case.

Claude-Session: https://claude.ai/code/session_01GVorddJkUMjYffPHXSDxop
…n one caller

Found on the test cluster, not here: a probe for the label path reported that autoconfig wrote
to a key-auth labelled `routing.modelsphere.dev/consumers: somebody-else`, and to an
unlabelled one in a namespace nothing names. The check existed - I had added it to the
periodic sweep - and the key-auth WATCH, which fires for every key-auth in the cluster, went
straight past it. Two entry points, one check.

It now sits in programGateway, the one function that writes a consumer list, so every caller
gets it. The APIConsumer path cannot fail it by construction (the object names the gateway),
and it runs there anyway: a check only some callers make is one somebody will forget.

Moving it exposed a conflict between two invariants that the move test caught at once: "do not
touch gateways that are not ours" against "withdraw the credential from the gateway it was
programmed into". After a spec change, nothing names the old gateway any more - and the key is
still live there. So a gateway this controller HAS programmed counts as ours, by its own
record: every APIConsumer's status.appliedGatewayNamespace, and the managed-consumers
annotation on the key-auth itself. The second one is also what lets a revocation finish after
the last APIConsumer on a gateway is deleted.

The new test covers the watch path with a foreign gateway, which is what nothing covered
before - the sweep had a test, the watch did not, and that is exactly where the hole was.

Claude-Session: https://claude.ai/code/session_01GVorddJkUMjYffPHXSDxop
…leet opts out

ai-stream-guard could have been plugged in through gateway.extraPlugins with no controller
code at all - it is not a plugin this controller renders, and the plugin's parseRuleConfig
starts from the global config, so an empty passthrough rule would have worked. It is a plugin
of this controller's anyway, and the reason is a level rather than a mechanism: extraPlugins is
written per fleet by whoever creates it, so a protection that each caller has to remember to
switch on is missing from the next fleet somebody builds by copying an older one - silently,
with nothing in the object to say so. A default belongs to the controller; extraPlugins is for
what ONE fleet wants differently.

So: a rule for every fleet that has not said otherwise, and
gateway.streamGuard.disabled: true as the way to say it. The field is spelled as the negative
so the safe behaviour is what an absent field means.

The rule written is EMPTY, deliberately. The plugin reads an empty rule as "the global config
applies here" (parseRuleConfig starts from the global one and replaces only what the rule
names), so the detector parameters live in the gateway chart and in no second place, and
turning the guard off withdraws a rule rather than writing a different configuration. It is
overridable, so a fleet that wants different thresholds has extraPlugins - the escape hatch
ai-statistics has.

Read out of the plugin's config.go rather than assumed, because an empty rule was the part I
had flagged as unverified: parseConfigOver inherits the base config and then refuses
`detectors: []`. That makes one requirement on the chart side hard rather than advisory - its
defaultConfig must carry a non-empty detectors list - because a plugin that fails to load
stalls the config push for EVERY plugin on that gateway, not just this one. Said in the field
doc, in the plugin table and in the README.

A missing ai-stream-guard object is tolerated: its absence costs the guard and nothing else -
no 401, no route down, no missing metrics - so a cluster whose gateway chart predates the
plugin keeps publishing fleets. That puts it with ai-statistics rather than with
ai-backend-router and key-auth.

Claude-Session: https://claude.ai/code/session_01GVorddJkUMjYffPHXSDxop
…rned

The one that matters most came from the other side of the gateway, not from the review: with
`defaultConfigDisable: true` the Higress controller does not send `defaultConfig` to the
gateway at all - only `_rules_`. So the empty stream-guard rule this branch shipped two commits
ago reaches a plugin whose global config is EMPTY, and the plugin refuses it: `detectors: must
be a non-empty list`, the module fails to load, and under FAIL_OPEN that is invisible to
traffic. My reading of the plugin's parseRuleConfig was right and said nothing about what
reaches it; the layer above was never checked. Each rule now carries a copy of the plugin's
own defaultConfig, so the thresholds still live only in the chart.

The review's findings:

  * **stream-guard default-ON relied on a chart requirement nothing checked** (high). The
    object existing with no `detectors` is the dangerous middle case tolerateMissing never
    covered: the rule would be written, the plugin would fail to load, and the config push for
    EVERY plugin on that gateway would stall - so upgrading this controller without the
    matching chart would take a gateway's whole config plane down. A plugin can now declare
    its own config unusable; the rule is skipped, the fleet still publishes, and
    GatewaySynced says which protection is not running.

  * **The chart label was a hint, not an answer** (medium). `== "autoconfig"` granted
    ownership and any other value fell through to "is the namespace named" and "is it
    higress-system" - so a key-auth labelled for a different manager was still rewritten in
    higress-system. That is the first of the two cases the cluster probe caught and the one I
    thought I had fixed by moving the check rather than by making it decide. A label present
    is now the answer, whatever it says.

  * **An unreadable Secret for a live consumer froze the whole gateway** (medium) - nobody
    else addable, rotatable or revocable, and a deletion in flight gave up at the deadline
    with its key still live. The review's fix was to fail just that object, which revokes a
    working key because somebody deleted an unrelated Secret: a management-plane problem
    traded for a data-plane outage. Neither, then: that consumer's LIVE entry is carried over
    verbatim, so nobody loses access and everyone else's changes go through. Three tests
    asserted the old contract and now assert this one.

  * **Two incumbents for one name** (low) could make the collision check refuse the round for
    the whole gateway - the impostor-driven freeze that design exists to avoid. The
    managed-consumers annotation breaks the tie.

  * **Dead code from a superseded design** (low): `credentialsNotCovered`,
    `liveCredentialCount`, `credentialsReformatted`, `liveConsumerNames` and a `myCreds` map
    built and never read. One of them was a second copy of the prefix-normalising adoption
    check - two copies of a security rule that can drift apart silently.

  * **A discovery failure crash-looped the pod** (low): the gate's own plumbing returned the
    error, aborting startup and taking ModelRoute down - the exact outcome the gate exists to
    prevent. It fails closed to "no watch" now, and the sweep picks Higress up anyway.

  * **README** (docs): an annotation change does not bump `metadata.generation`, so
    observedGeneration cannot confirm an emergency rotation took effect. Says so, and what to
    look at instead.

Claude-Session: https://claude.ai/code/session_01GVorddJkUMjYffPHXSDxop
… just skip the write

Found by the probe written to check the one claim that replaced a watch, which then found
something else: clearing the gateway chart's `detectors` left the PREVIOUS stream-guard rule
in place. The chart had no detectors any more, the fleet reported "not written", and the
gateway went on cutting streams at a threshold that existed nowhere but in that stale rule -
the condition saying one thing while the gateway did another.

So an unusable config now falls through to the withdrawal path and the reason is returned
afterwards, when the rule is actually gone. The message was already accurate about intent; now
it is accurate about the gateway.

Two things the same probe said about the propagation claim itself:

  * A threshold change on the plugin does reach every fleet rule with no watch on that object,
    because each fleet's resync re-reads it and copies it again.
  * The first measurement - 1s - is not the steady-state answer and is not the one to quote.
    The fleet had just been created and was still in its initial rapid reconcile, so the patch
    landed in a round that was already queued. The probe now settles for 40s first, so the
    number it reports is the one the claim is about.

Claude-Session: https://claude.ai/code/session_01GVorddJkUMjYffPHXSDxop
@zhanghaohit
zhanghaohit requested a review from zoboth November 26, 2026 14:01
**A gateway this controller does not manage came back as success** (high). The ourGateway veto
returned no error and no reason, which Reconcile cannot tell from a write that happened: it
set Programmed=True, status.credentials=N and status.appliedGatewayNamespace for a consumer
whose key was never written. So an APIConsumer pointing at a key-auth labelled for another
manager said "N credential(s) accepted by the gateway" while every request with that key got
401. The comment claiming the APIConsumer path could not fail this check was simply wrong -
the label vetoes regardless of who names the namespace. The false appliedGatewayNamespace was
the worse half: it feeds claimed[], so removing the foreign label later would have let that
object take over a chart-rendered consumer name without carrying its credentials. The veto is
now reported on every object that wanted that gateway.

**Two brand-new objects claiming a chart-rendered name froze the whole gateway** (high). Each
sees a live entry under that name and no other object's STATUS claiming it, so both came out
as incumbents, the collision check hit "more than one incumbent" and refused the round for
everyone: no key addable, rotatable or revocable, and a deletion in flight giving up at the
deadline with its key still live. The earlier tiebreak only covered names this controller had
written, which a chart-rendered one is not. An entry with no status behind it is now
attributed to nobody while two objects claim it, so both are handled as newcomers and left
out - the chart's entry untouched, everyone else's round going through.

**A preserved name was dropped from the managed-consumers record** (medium). Preserved means
ours with a Secret that cannot be read right now; leaving it out of the annotation loses a
revocation in the one sequence the annotation exists for - gateway write landed, status write
did not, Secret broke, object deleted - after which its entry is carried over as somebody
else's and the revoked tenant's key keeps working.

**The unusable-plugin reason was lost on a conflict retry** (low). cfg is mutated inside the
retry closure, so a second attempt re-entered with cfg already nil, never consulted p.unusable
again, and returned nil: the rule withdrawn and the fleet reporting a clean "gateway objects
written". Exactly the silence that reason exists to break. Hoisted out of the closure.

**An upgraded release could leave the whole gateway closed, with no self-correction** (medium).
crds/ is not touched by helm upgrade and "is APIConsumer served" is decided once at startup,
so upgrading an existing release skips the reconciler AND the sweep, nothing writes
defaultConfig.consumers, and with the chart that no longer renders it that is FAIL_CLOSE for
every route. Applying the CRD afterwards changed nothing. There is now a watchdog: it exits
when the kind appears, which is how a leader-elected controller restarts, and the restart
redoes the decision. The quieter half of the same mechanism - an un-upgraded ModelFleet CRD
silently prunes spec.gateway.streamGuard, so disabled: true is accepted and ignored - cannot
be fixed in code and is in the README.

Each fix verified by reverting it: the first revert reproduced "says it was accepted", the
second the whole-gateway freeze, the third the dropped name.

Claude-Session: https://claude.ai/code/session_01GVorddJkUMjYffPHXSDxop
…gn this PR removed

**A preserved consumer defeated the "nothing changed, do not write" guard permanently.** The
annotation records mine ∪ preserve, the comparison used mine alone, so from the moment any
Secret became unreadable the recorded set was a strict superset forever: the check was false
on every round and the gateway object was written on every pass, with an Info log claiming a
change. The writes were content-identical, so nothing reached the data plane - which is why
the test counts writes instead of looking at the result, and why this survived every other
test in the suite.

**The CRD field doc and the README still described the empty-rule design.** They said this
writes an empty rule which the plugin reads as "the global config applies", while the code
copies the plugin's whole defaultConfig into each rule - the change made two commits earlier
precisely because the empty rule was measured not to work. `kubectl explain
modelfleet.spec.gateway.streamGuard` was handing out a wrong model of where the thresholds
come from. Both now say what the code does, and why the obvious design does not work.

**The empty-defaultConfig branch of copyDefaultConfig returned without withdrawing the rule**,
the same asymmetry the p.unusable path had been changed to avoid a few lines above: the fleet
would report "not written" while the gateway kept enforcing a stale rule. Unreachable for
ai-stream-guard today - its unusable hook rejects a missing defaultConfig first - but a trap
for the next plugin given copyDefaultConfig without one.

Also removed the claude.ai session link from the PR description. CLAUDE.md forbids it in
descriptions and comments and this repository is public; it only belongs in commit footers.

Claude-Session: https://claude.ai/code/session_01GVorddJkUMjYffPHXSDxop

@zoboth zoboth left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I read the whole diff. Two blockers, both in internal/controller/apiconsumer_controller.go. Anyone who can create an APIConsumer in their own namespace can trigger either one.

Blockers

1. When a Secret is unreadable, the live entry is kept by name only, so an impostor can keep, block or take over someone else's entry

In programGateway, when readCredentials fails, the first branch is:

if hasLiveEntry(liveNames, consumerName(c)) {
    preserve[consumerName(c)] = true
    ...
    continue
}

It never checks that the entry belongs to c. incumbent(c) is only consulted afterwards. Once a name is in preserve:

  • writeConsumers copies the live entry in before it skips managed or claimed names.
  • setManagedConsumerNames(obj, consumers, preserve) records the name as autoconfig-managed in the annotation.
  • From then on dropUnprovenAdoptions skips the proof-of-key check (liveManaged[v.Name]), and writeConsumers treats the name as already owned.

Scenario A: takeover of a chart-rendered name.

  1. The chart renders tenant-a, and no APIConsumer owns it yet.
  2. In team-x, someone creates an APIConsumer with consumerName: tenant-a and a credentialsSecretRef that doesn't exist.
  3. The entry is preserved. The next write to that gateway for any reason (another tenant adds or rotates a key) records tenant-a as managed.
  4. team-x then creates the Secret with its own key. incumbent is true (a live entry exists and no other status claims it), and the adoption-proof check is skipped because the name is now in the annotation.
  5. team-x's key replaces tenant-a's. The real tenant-a gets 401, and team-x gets every route tenant-a was allowed on.

This is the case TestConsumerCannotTakeOverANameWithoutItsKey is meant to prevent; it is just reached through the broken-Secret path. A simpler variant: delete the impostor afterwards, and the now-"managed" entry is dropped, which revokes the real tenant.

Scenario B: gateway freeze or a stale key.

  1. X is programmed as tenant-a.
  2. Y sets consumerName: tenant-a with a missing Secret. next now holds X's rendered entry plus the preserved live entry.
  3. If X's keys are unchanged, refuseDuplicateCredentials fails every round for the whole gateway: no consumer can be added, rotated or revoked, and deletions give up at the 15-minute deadline with their keys still live.
  4. If X has just rotated, the list is written with two tenant-a entries. X's old key stays accepted while X reports Programmed.

What I'd change: keep the entry only when incumbent(c) is true. Never preserve a name that is also in mine this round.

2. incumbent trusts the status gateway without checking the status name, so one renamed object freezes the gateway

if c.Status.AppliedGatewayNamespace == gwNS {
    return true
}

This does not check c.Status.ConsumerName == consumerName(c).

Scenario: X is programmed as tenant-x and Y as tenant-b on the same gateway. X's owner changes spec.consumerName to tenant-b, by typo or on purpose. Both now count as incumbents. dropCollidingNewcomers hits len(incumbents) > 1 and returns an error every round, which blocks every add, rotation and revocation on that gateway.

The comment ("One bad newcomer cannot produce this") and the error text ("dropping either revokes a working key") are both wrong here: X's tenant-b serves nothing. The same root cause hits the unreadable-Secret path: an object renamed to a name with no live entry and with a broken Secret fails the whole round (return round, fmt.Errorf(... nothing was written ...)).

What I'd change: take the status shortcut only when the status name matches the current spec name. Otherwise fall through to the live-entry check.

Non-blocking notes

  • Build depends on #21. statusSettled is used but not defined in this diff. You note the helper lives on #21. Please make sure #21 is on main first, or this does not compile.
  • "ModelFleet is unchanged" isn't quite true. The diff adds spec.gateway.streamGuard and, by default, an ai-stream-guard rule on every fleet route that copies the chart's defaultConfig. That is a behaviour change on upgrade and should go in the description and release notes. The sink.StreamGuardRule comment ("empty on purpose") also contradicts copyDefaultConfig.
  • Docs are behind the code. The description and README say one unreadable Secret stops the whole round. The code now keeps that consumer's live entry and writes everyone else's changes. The new behaviour is reasonable; please update the text.
  • Needless Updates while an entry is preserved. The early return compares managed against mine, but the annotation also contains preserved names. Every pass then issues an Update and logs "programming gateway consumers". That is probably a no-op on the API server, but it is noise.
  • Ownership is taken before the guards. claimConsumers force-applies ownership before the empty-list and duplicate-credential guards. A refused round still takes the field from helm. The value doesn't change, so this is cosmetic.
  • Duplicate key against a carried-over chart entry freezes the gateway. A newcomer whose key duplicates a carried-over chart entry freezes the gateway through refuseDuplicateCredentials instead of just being left out. That is inconsistent with how dropCollidingNewcomers treats newcomers.
  • Same-second tiebreak. The tiebreak uses CreationTimestamp.Before, which has one-second resolution. Two claimants created in the same second both count as incumbents. This is an edge case.
  • Status is trusted for ownership. status.appliedGatewayNamespace and status.consumerName decide ownership and skip the proof-of-key check. Please make sure tenants are never given apiconsumers/status write access.
  • Version bump. helm-charts#122 and modelsphere#90 require autoconfig 0.4.4, and this PR bumps no chart or app version. Presumably that happens at release time.
  • Weak test. TestKeyAuthWatchWantedOnDiscoveryFailure asserts nothing meaningful.

What I checked and found correct:

  • Deepcopy.
  • The two CRD copies are identical, and both RBAC copies match.
  • The controller is registered only when the CRD is served.
  • The Secret ref is a bare name, read only from the object's own namespace.
  • A duplicate name is refused with both objects named.
  • The finalizer withdraws credentials, with a deadline.
  • An empty consumers list is written when the field is missing.
  • The routing.modelsphere.dev/consumers: autoconfig label matches helm-charts#122.
  • The output is sorted and stable.

Two blockers, both reachable by anyone who can create an APIConsumer in their own namespace.

**Preserving an entry on the strength of its NAME was a takeover path.** When a Secret could
not be read, the live entry under that consumer name was kept and recorded as
autoconfig-managed - without establishing that the entry was this object's. So: point
consumerName at a chart-rendered consumer, give it a secretRef that does not exist, wait for
the next write to that gateway for any reason, and the name is now recorded as ours. From
then on the proof-of-key check is skipped for it, and creating the Secret with your own key
replaces the real tenant's: 401 for them, every route they were allowed on for you. The same
path let a second claimant put a duplicate entry in the list beside a rendered one, which
either freezes the gateway on the duplicate-credential guard or leaves a rotated-away key
accepted.

Fixing it meant fixing what "incumbent" means, because its fallback was name-based too and an
impostor satisfied that by construction. The annotation decides now: a gateway write records
the name in managed-consumers inside the same write, so an entry we actually wrote is always
in the annotation - status write or no status write, which is the case the fallback exists for
- while an entry the chart rendered never is.

**The status shortcut ignored the status NAME, so one renamed object froze the gateway.** It
compared only the gateway namespace, so changing spec.consumerName made an object an incumbent
for a name it has never served; renamed onto a name somebody else serves, that produced two
incumbents and the collision check refused the round, every round, blocking every add,
rotation and revocation. The error even said "dropping either revokes a working key", which
was false: the renamed object's new name served nothing.

Both judges had to be corrected before they held. The first version of the takeover test
passed against the reverted fix, because the impostor was the only consumer, the empty-list
guard refused the round, and nothing was recorded either way - the test could not see the bug
it was written for. zoboth's scenario says it plainly: it is the next write for any reason
that records the stolen name. A healthy consumer in the fixture is what makes the round write.

Also from that review, all non-blocking:

  * **A newcomer whose key duplicates a carried-over chart entry cost the whole gateway.** Same
    shape as every other freeze here, and on the documented migration path rather than in
    theory: a chart entry whose name cannot be adopted (consumerName is a DNS label, the
    chart's name may not be) gets a new APIConsumer carrying the SAME key, because the point
    is that no caller changes anything. It costs the newcomer now, with the reason on its own
    object, naming the entry and what to do about it. The write-path guard stays as a
    backstop: a guard that never fires is fine, a freeze on a normal path is not.
  * **Two objects created in the same second both came out incumbent** - CreationTimestamp has
    one-second resolution, so neither is Before the other. Broken deterministically.
  * **A test that restated its own argument.** `keyAuthWatchWanted(false)` returning false
    asserted nothing; it goes through discovery now, with the API server refusing to answer.
  * The README said one unreadable Secret stops the whole round, which stopped being true two
    commits ago, and said nothing about never granting tenants `apiconsumers/status` - the
    ownership record this commit now leans on harder. Both fixed.
  * The sink comment still called the stream-guard rule "empty on purpose".

One note from that review was already fixed in the commit it reviewed: the needless Update
while a consumer is preserved.

Claude-Session: https://claude.ai/code/session_01GVorddJkUMjYffPHXSDxop
@zhanghaohit

Copy link
Copy Markdown
Collaborator Author

@zoboth please review 1f65b19 — it is the fix for the two ownership blockers you raised on 2e2b0ae, and the part of this PR nobody has read.

What changed, so you can aim at the reasoning rather than rediscover it:

Blocker 1. Preserving no longer keys on the name, and incumbent's fallback does not either — fixing one without the other would have left the hole open, because an impostor satisfies a name-based fallback by construction. The record decides now: a gateway write puts the name in managed-consumers inside the same write, so an entry this controller actually wrote is always in the annotation whether or not the status write that follows succeeded (the case the fallback exists for), while a chart-rendered entry never is. Also: a name another view renders this round is never preserved, which is your Scenario B.

Blocker 2. The status shortcut requires status.consumerName == spec.consumerName, and the contested loop now treats another object's matching status as conclusive.

Worth a second look specifically:

  • My first judge for blocker 1 passed against the reverted fix — the impostor was the only consumer, the empty-list guard refused the round, and nothing was recorded either way. Your scenario is what corrected it ("the next write for any reason"), so the fixture now has a healthy consumer to make the round write. If that judge is still blind somewhere I would rather know now.
  • I took incumbent's fallback from "a live entry with no other claimant" to "the annotation says we wrote it". That is strictly narrower, so the question is whether it is now too narrow: is there a state where this controller's entry is live, its name is NOT in the annotation, and dropping it would revoke a working key?

Non-blocking items from your review, all done except where noted: duplicate-key-vs-carried-over-entry now costs only the newcomer (reason on its own object) with the write-path guard kept as a backstop; same-second tiebreak broken deterministically; TestKeyAuthWatchWantedOnDiscoveryFailure replaced with one that goes through discovery; the StreamGuardRule comment, the README's "one unreadable Secret stops the whole round", and the description's "ModelFleet is unchanged" all corrected; the README now says never to grant tenants apiconsumers/status.

Two I did not act on: ownership taken before the guards — left as is, since the value does not change and moving the claim after them would mean claiming on a round that may then refuse (say so if you disagree); and the version bump, which happens when 0.4.4 is cut. One note was already stale when you wrote it: the needless Update while an entry is preserved was fixed in 2e2b0ae itself.

#21 is on main, so statusSettled resolves and CI is green.

@zoboth zoboth left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review at 1f65b19, aimed at the ownership fix as asked. I read all of apiconsumer_controller.go (preserve/incumbent/collision paths, writeConsumers, the annotation helpers) and the new tests around it. The incumbent change itself is sound. The Scenario B guard still has a hole.

Blocker

renderedThisRound only sees the views built so far, so the Scenario B guard depends on list order (programGateway, the readCredentials error branch).

views is still being filled when the preserve decision is made, so renderedThisRound(views, name) only covers objects earlier in the List. List order is namespace/name, so it is predictable and anyone who picks the namespace controls it. Setup: incumbent A (status.appliedGatewayNamespace == gw, status.consumerName == "tenant-a"), whose Secret is unreadable for the moment, and newcomer B in another namespace with consumerName: tenant-a and a readable Secret holding its own key.

  • B after A: A is unreadable. incumbent(A) is true, the live entry exists, and nothing renders tenant-a yet, so A is preserved. B then becomes a view. incumbent(B) is false (A's status is conclusive), but dropCollidingNewcomers only sees views, so B is the only claimant of tenant-a and nothing collides. dropUnprovenAdoptions keeps B because liveManaged["tenant-a"] is true, so it is treated as a rotation. dropDuplicatesAgainstCarriedOver skips it as rendered. writeConsumers then carries A's live entry (preserve) and writes B's rendered entry. Result: two tenant-a entries, one with the real key and one with B's key. Either key-auth accepts both, and B authenticates as tenant-a on every route tenant-a is allowed on, or it rejects the duplicate name and the whole gateway fails closed. refuseDuplicateCredentials doesn't catch it because the credentials differ.
  • B before A: B is already a view, so A is not preserved. Then !incumbent(A) is false, so the loop hits the final return round, fmt.Errorf(...). The whole gateway's round is refused on every pass while A's Secret stays broken. That is the freeze the PR's first rule exists to prevent, and a newcomer triggers it.

Both outcomes come from the same cause. A preserved incumbent is a claimant on its name, but the newcomer-collision step never sees it. Suggested fix:

  1. Collect preserve candidates during the loop without consulting views.
  2. After the loop, treat each preserved name as held by its incumbent. Put any view with that name into round.skipped as a colliding newcomer ("already served by "). Never let it reach RenderConsumers beside the carried entry.
  3. Add a test with both orderings: the newcomer's namespace sorting before the broken incumbent, and after it. The fake client lists in a stable order, so each fixture can force one. Assert that the round writes, tenant-a has exactly one entry with the original credential, and B's object carries the reason.

TestConsumerCannotPreserveSomebodyElsesEntry does not exercise this, because its impostor is never an incumbent. That test looks sound to me: with the name-keyed fallback restored, chart-a would land in the annotation and the first assertion fails.

Your two questions

Is incumbent's fallback now too narrow? I could not find a state where narrowing it revokes a working key. When incumbent(c) is false for an object whose entry is live, there are two cases:

  • The name is in neither managed nor claimed. writeConsumers then carries the live entry over verbatim as foreign.
  • The name is in claimed. Some object's status says it is theirs.

So "our entry, not in the annotation, no matching status" degrades to "kept as foreign", not "dropped". The cost points the other way: in that state, deleting the APIConsumer would not revoke the key, because the name is neither managed nor claimed. Reaching it takes both a lost annotation (something outside rewrote or recreated key-auth's metadata) and a failed status write, so I'd treat it as a note, not a blocker.

The judge: covered above. The new fixture is right for the case it targets. The case it can't see is a preserved incumbent plus a newcomer on the same name.

Non-blocking notes

  • Older objects win the contested fallback. If A's gateway write landed and its status write failed, an older object B renamed onto A's name wins via CreationTimestamp (A has no status to be conclusive). B's view would then be written under A's name as a "rotation", because liveManaged skips the proof-of-key check. The window is narrow: a failed status write plus a rename landing inside it. Worth one line of thought: when no status claims the name, the fallback could also require that the incumbent's credentials already cover the live entry's, which is the same proof dropUnprovenAdoptions asks of an adopter.
  • Ownership claimed before the guards: fine with me as is, for the reason you give. The value is unchanged and a claim on a refused round costs nothing.
  • _ = ctx in dropCollidingNewcomers: the parameter is unused and could be dropped.

Verdict: request changes, for the order-dependent preserve/newcomer interaction above. Everything else in this round looks right to me.

The Scenario B guard from the previous commit asked "is another view already rendering this
name" while the view list was still being built, so it only saw objects earlier in the List.
List order is namespace/name, so whoever picks the namespace picks the outcome:

  * newcomer sorting AFTER the broken incumbent: the incumbent is preserved and the newcomer
    is also written, so one consumer name carries two entries - the newcomer's own key
    authenticating as that consumer on every route it is allowed on, or key-auth rejecting the
    duplicate name and failing the whole gateway closed. The duplicate-credential guard does
    not see it, because the credentials differ.
  * newcomer sorting BEFORE it: the incumbent is not preserved, falls through to the hard
    error, and the gateway's round is refused on every pass while that Secret stays broken -
    the freeze this PR keeps fixing, triggered by a newcomer.

A preserved incumbent still holds its name, so a view claiming it is a colliding newcomer -
but it is not in `views`, so the collision step cannot see it. That is settled after the loop
now, once every view exists, which is what makes the outcome independent of List order. The
newcomer is left out with the reason on its own object, naming the holder.

The test runs both orderings. Reverting the fix reproduces exactly the two outcomes above -
two entries in one, a refused round in the other - which is the first judge in this PR to
catch two different failure modes from one revert.

Also from that review: dropped the unused ctx parameter, and recorded a gap I am NOT closing
yet. If a gateway write lands and the status write does not, an older object renamed onto that
name wins the tiebreak and its key is written as a rotation. The tightening the review
suggests - require the proof whenever no status claims the name - can revoke a key, which is
worse: a write lands with K1, the owner rotates the Secret to K2, status still missing, the
rendered K2 does not cover the live K1, the proof fails, the view is dropped, and a managed
name with no view is the revocation path. A safe version prefers the object whose credentials
cover the live entry rather than requiring it, which needs credentials for both candidates
where one may be unreadable. The reasoning is in the code beside the tiebreak.

Claude-Session: https://claude.ai/code/session_01GVorddJkUMjYffPHXSDxop
@zhanghaohit

Copy link
Copy Markdown
Collaborator Author

@zoboth fixed in 83d1f17 — the preserve decision no longer consults views, and a preserved incumbent's name is defended after the loop, once every view exists.

Your reading was right in both directions, and the revert confirms it: restoring the half-built-views check makes the "sorts after" case write two tenant-a entries and the "sorts before" case refuse the round for the whole gateway. Same revert, two different failure modes — the first judge in this PR that catches both.

What I did with your three steps: (1) and (2) as you wrote them, with the holder named in the newcomer's reason; (3) the test is table-driven over zz-team and aa-team so each fixture forces one List order, asserting the round writes, the name has exactly one entry with the original credential, and the newcomer's object carries the reason.

On your note about older objects winning the contested fallback — I did not close it, and I think the suggested tightening is unsafe. Requiring the proof whenever no status claims the name can revoke a key: gateway write lands with K1, the owner then rotates the Secret to K2, the status write is still missing. The rendered K2 does not cover the live K1, the proof fails, the view is dropped — and a managed name with no view is exactly the revocation path. So that trade is a management-plane gap for a data-plane outage.

A safe version has to prefer the object whose credentials cover the live entry rather than require it, which needs credentials for both candidates at a point where one of them may be the unreadable one. I left the gap with the reasoning written beside the tiebreak rather than reach for the quick version. If you see a way to get the preference without reading both, I would take it — otherwise I would rather ship the known gap than risk the revocation.

Thanks for the answer on whether the fallback is now too narrow; "degrades to kept-as-foreign, not dropped" is what I wanted checked, and the direction you point out (deleting the APIConsumer would then not revoke the key) is the right thing to worry about instead. It needs a lost annotation AND a failed status write, so I am treating it as a note too.

Everything else from your review is in: unused ctx dropped, and the non-blocking items from the round before are in 1f65b19.

CI is green on 83d1f17. Please take another look when you can — this is the last outstanding change on my side, and 0.4.4 is waiting on this PR.

zhanghaohit added a commit that referenced this pull request Nov 26, 2026
The APIConsumer work in #22 adds a kind, a gateway-wide write path and a
stream-guard rule on every fleet route by default, so this is a minor
release rather than a patch.

Claude-Session: https://claude.ai/code/session_01GVorddJkUMjYffPHXSDxop

@zoboth zoboth left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed at 83d1f17. I read the whole diff and focused on the preserve/incumbent change. No blockers. Approving.

The 83d1f17 fix

  • The preserve decision now depends only on incumbent(c) && hasLiveEntry(...), so it no longer depends on List order. The post-loop pass drops any view whose name a preserved incumbent holds, once every view exists. That covers both orders: "sorts after" can no longer write two tenant-a entries, and "sorts before" can no longer fall through to the hard error.
  • With two status-conclusive incumbents on one name where one is unreadable, the readable one is now left out with "already served by …" instead of hitting the two-incumbents error. The live entry is kept as it is, so no working key is revoked. That is a better outcome than freezing the round.
  • Write path: a preserved name is handled before the managed || claimed skip, it is recorded through setManagedConsumerNames(…, preserve), and recorded = mine ∪ preserve keeps the no-op short-circuit working. In the test fixture the list is unchanged and ownedBefore is true from A's status, so the "round writes" assertion holds without an actual Update. Fine.
  • TestConsumerPreservedIncumbentBeatsANewcomerInEitherListOrder tests the right thing: one entry, the original key, and the reason on the newcomer, in both namespace orders.

The KNOWN GAP comment beside the tiebreak is a fair record. I agree that requiring the proof whenever no status claims the name would trade a management-plane gap for a revocation. I don't see a way to prefer the covering object without reading both Secrets. Leaving it documented is the right call for 0.4.4.

Non-blocking notes

  1. A preserved entry's credentials are not checked against newcomer views, so one object can still freeze the round. dropDuplicatesAgainstCarriedOver builds ownerOf only from live entries that are not rendered, liveManaged or claimed. A preserved name is always managed or claimed, so its live credentials are never in that map. dropCollidingNewcomers doesn't see them either, because the preserved object is not in views. Concrete sequence:

    • tenant-a is programmed with key K.
    • Its owner creates tenant-a-v2 with the same K, then deletes the old Secret before deleting the old APIConsumer.
    • tenant-a is now preserved with Bearer K live, and tenant-a-v2 renders Bearer K.
    • refuseDuplicateCredentials refuses the whole round.

    Nothing on that gateway can then be added, rotated or revoked until the old object is deleted or its Secret is fixed. It recovers, and the error names both consumers, but this is the "one object's problem becomes the gateway's" pattern the PR is built to avoid. Suggested fix: in dropDuplicatesAgainstCarriedOver, also add the live credentials of preserved names to ownerOf (pass preserve in and skip the managed/claimed exclusion for those names). The newcomer is then left out with a reason, and the write-path guard stays as the backstop. A table case with the shared key on a preserved incumbent would cover it.

  2. As you said: if the annotation is lost and the status write failed, the incumbent fallback returns false and the entry is kept as foreign rather than dropped, so deleting that APIConsumer would not revoke the key. Fine to ship as a documented note.

  3. The PR description still says commits after rc25 are covered only by unit tests. 83d1f17 changes the shared round that every consumer on a gateway goes through, so please run the rc before 0.4.4 as planned.

…k too

From zoboth's approving review: non-blocking, but a real freeze on ordinary sequencing rather
than anything adversarial. Create tenant-a-v2 with the same key so no caller has to change,
then delete the old Secret before the old APIConsumer. The old object is preserved with that
key live, the new one renders the same key, and the duplicate-credential guard in the write
path refuses the whole ROUND: nothing addable, rotatable or revocable on that gateway until
somebody deletes the old object.

Neither existing check could see it. The clash map was built only from live entries that are
neither managed nor claimed - and a preserved name is always one of those - while the object
holding the key is not in `views` at all, so the newcomer-collision step had nothing to
compare against either. Preserved names are included now, and the newcomer is left out with
the reason on its own object, which says the key is held by a consumer whose Secret cannot be
read rather than by a chart-rendered one.

That is the sixth instance of the same shape in this PR - one object's problem becoming the
whole gateway's - and the first one found in a review that approved.

Also from that review, not changed: the ownership gap when the annotation is lost AND the
status write failed (the entry is kept as foreign, so deleting the APIConsumer would not
revoke the key) stays a documented note, and the tiebreak gap stays as recorded. zoboth agrees
requiring the proof there would trade a management-plane gap for a revocation, and neither of
us sees a way to prefer the covering object without reading both Secrets.

Claude-Session: https://claude.ai/code/session_01GVorddJkUMjYffPHXSDxop
@zhanghaohit zhanghaohit mentioned this pull request Nov 26, 2026
@zhanghaohit
zhanghaohit merged commit 101de1b into main Nov 26, 2026
3 checks passed
@zhanghaohit
zhanghaohit deleted the feat/apiconsumer branch November 26, 2026 16:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants