From 658a66c6bb53fddd7b01747889525e2ce36cc0de Mon Sep 17 00:00:00 2001 From: zhanghao Date: Thu, 26 Nov 2026 10:28:23 +0800 Subject: [PATCH 01/28] APIConsumer: one object per caller, so adding or rotating a key is not a release MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- README.md | 39 ++ api/v1alpha1/apiconsumer_types.go | 121 +++++ api/v1alpha1/zz_generated.deepcopy.go | 126 +++++- cmd/main.go | 47 +- .../routing.modelsphere.dev_apiconsumers.yaml | 218 +++++++++ config/rbac/role.yaml | 20 +- config/samples/apiconsumer-tenant-a.yaml | 28 ++ .../routing.modelsphere.dev_apiconsumers.yaml | 218 +++++++++ .../autoconfig/files/controller-rules.yaml | 20 +- internal/controller/apiconsumer_controller.go | 364 +++++++++++++++ .../controller/apiconsumer_controller_test.go | 416 ++++++++++++++++++ internal/sink/consumer.go | 82 ++++ internal/sink/consumer_test.go | 80 ++++ 13 files changed, 1752 insertions(+), 27 deletions(-) create mode 100644 api/v1alpha1/apiconsumer_types.go create mode 100644 config/crd/bases/routing.modelsphere.dev_apiconsumers.yaml create mode 100644 config/samples/apiconsumer-tenant-a.yaml create mode 100644 deploy/helm/autoconfig/crds/routing.modelsphere.dev_apiconsumers.yaml create mode 100644 internal/controller/apiconsumer_controller.go create mode 100644 internal/controller/apiconsumer_controller_test.go create mode 100644 internal/sink/consumer.go create mode 100644 internal/sink/consumer_test.go diff --git a/README.md b/README.md index 84d801e2..55f57354 100644 --- a/README.md +++ b/README.md @@ -425,6 +425,45 @@ fleet 的 namespace 里就直接失败,根本到不了「容忍 ai-proxy 缺失 端到端验证脚本(测试集群 k8s-cpu-16)见 `tools/modelfleet/e2e_cpu16.sh`(在 vllm 仓)。 +## APIConsumer CRD + +「谁能调这个网关、用什么 key」。`ModelFleet.gateway.authConsumers` 只写**名字**(这条路由放谁进来), +而**有哪些调用方、各自的密钥是什么**是整个网关一份 —— 它在 key-auth 的 `defaultConfig.consumers` 里, +以前由网关 chart 渲染,**加一个租户 = 改 values + 发版**。`APIConsumer` 把它变成一个对象: + +```yaml +apiVersion: routing.modelsphere.dev/v1alpha1 +kind: APIConsumer +metadata: {name: tenant-a, namespace: llm-route} +spec: + gateway: {namespace: higress-system} # key-auth 所在 ns,也是聚合的分组键 + credentialsSecretRef: tenant-a-keys # 本 ns 的 Secret;【每个 value 都是一把可用的 key】 +``` + +reconciler 把同一个网关下所有 `APIConsumer` 聚合、按名字排序,一次写进那个 `key-auth` 的 +`defaultConfig.consumers`。**一个对象一个写入方、一个字段一个写入方**,和 ModelFleet 同一套模型。 + +**轮换**就是「Secret 里加第二个 value → 等调用方换过去 → 删掉旧的」,中间没有两把 key 都不好使的窗口。 +加 key 最慢一个 resync(60s)生效;改 `APIConsumer` 对象本身是立即的。**没有**对 Secret 的 watch: +那会给全集群 Secret 开 informer,正是这个 controller 刻意避开的(它只有 `secrets: get`、且不走缓存读)。 + +**两条写入安全规则**(这个改动最危险的地方,都是「宁可不写」): + +- **坏一个,全不写**。某个 `APIConsumer` 的 Secret 读不到时,**不会**把它从名单里摘掉再写剩下的 —— + 名单里少一个 consumer,就是那个调用方下一个请求 401。这一轮整个不写,网关保持上一份好名单, + 失败报在那个对象的 `Programmed` 上。 +- **不能把名单写空**,除非这个网关的名单**本来就是我们写的**(有 `APIConsumer` 的 + `status.appliedGatewayNamespace` 指着它)。「删掉最后一个 consumer」和「还没迁移、名单还是 chart 渲染的」 + 从期望态看一模一样(都是零个对象),而后者写空 = 全站所有路由对所有人 403。 + +⚠ **它给的是「源头唯一、可在线轮换、不用发版」,不是「密钥不可见」**:key-auth 的配置是经 ECDS 推下去的 +一段 blob,插件没有读 Secret 的能力,所以密钥最终仍然明文躺在 `WasmPlugin` 对象里 —— +能读网关 ns 下 WasmPlugin 的人就能读到所有 key。要真正隐藏得换插件能力,是另一件事。 + +**迁移要和网关 chart 一起做**:chart 摘掉 `consumers` 的渲染(保留 `keys` 占位与 `global_auth`), +和这次摘 `matchRules` 同一种拆法。在 chart 还在渲染、而 `APIConsumer` 一个都没建的中间状态下, +上面第二条规则保证这个 controller 不会去动那份名单。 + ## 消费方接入 autoconfig 只负责把配置**写进已有的 ConfigMap**(不创建 chart、不创建 ConfigMap);消费方各自 chart 建初始 diff --git a/api/v1alpha1/apiconsumer_types.go b/api/v1alpha1/apiconsumer_types.go new file mode 100644 index 00000000..80f745ba --- /dev/null +++ b/api/v1alpha1/apiconsumer_types.go @@ -0,0 +1,121 @@ +package v1alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// ConsumerGateway: which gateway this consumer may call. +type ConsumerGateway struct { + // Namespace holding the gateway's key-auth WasmPlugin. Defaults to higress-system, and + // must be the namespace the gateway chart installs into — the same field, with the same + // meaning, as ModelFleet's gateway.namespace. + // + // It is also the grouping key: every APIConsumer naming one namespace is rendered into + // that one plugin's consumer list, in one write. + // +optional + // +kubebuilder:validation:MinLength=1 + Namespace string `json:"namespace,omitempty"` +} + +// APIConsumerSpec names one caller of the gateway and where its credentials live. +type APIConsumerSpec struct { + // ConsumerName is what a route's ModelFleet names in gateway.authConsumers, and what + // appears in the gateway's access log as x-mse-consumer. Defaults to metadata.name. + // + // Separate from the object's name because consumer names are a gateway-wide namespace + // shared with whatever the chart still renders, while object names are per Kubernetes + // namespace: two teams could otherwise collide without either of them being able to see + // it. The reconciler refuses a duplicate rather than letting one silently win. + // +optional + // +kubebuilder:validation:MaxLength=63 + ConsumerName string `json:"consumerName,omitempty"` + // Gateway: which gateway's consumer list this belongs in. + // +optional + Gateway ConsumerGateway `json:"gateway,omitempty"` + // CredentialsSecretRef: a Secret in this object's namespace holding this consumer's API + // keys — EVERY value in it becomes an accepted credential, so a rotation is "add the new + // key, let both work, remove the old one" with no window where neither does. + // + // Only the fleet's own namespace, and only a Secret: the controller holds a cluster-wide + // `secrets: get`, so a ref that could name any namespace would turn "can write an + // APIConsumer here" into "can read every Secret in the cluster". + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=253 + CredentialsSecretRef string `json:"credentialsSecretRef"` +} + +// APIConsumerStatus is what the console reads to answer "is this key live yet". +type APIConsumerStatus struct { + // ObservedGeneration: equal to metadata.generation once this consumer is programmed into + // the gateway. Only advanced on a successful write, so it never claims a key is live + // while the plugin still carries the old list. + // +optional + ObservedGeneration int64 `json:"observedGeneration,omitempty"` + // ConsumerName actually programmed, with the default expanded. + // +optional + ConsumerName string `json:"consumerName,omitempty"` + // Credentials: how many keys this consumer currently has. The keys themselves are never + // copied here — status is world-readable to anyone who can read the CR, and the point of + // the Secret is that the key lives in one place. Two during a rotation, one otherwise. + // +optional + Credentials int32 `json:"credentials,omitempty"` + // AppliedGatewayNamespace: the gateway this consumer was last programmed into. Moving + // spec.gateway.namespace otherwise leaves the old gateway accepting these credentials + // forever, with nothing in the object pointing at it. + // +optional + AppliedGatewayNamespace string `json:"appliedGatewayNamespace,omitempty"` + // LastSyncTime: when this object was last reconciled, including rounds that wrote + // nothing. "Is the controller still looking at this", not "when did the gateway change". + // +optional + LastSyncTime *metav1.Time `json:"lastSyncTime,omitempty"` + // Conditions: Programmed (the gateway carries this consumer's credentials). + // +optional + // +listType=map + // +listMapKey=type + Conditions []metav1.Condition `json:"conditions,omitempty"` +} + +// APIConsumer is one caller of the gateway: a name and a set of API keys. +// +// It exists so that adding, rotating or removing a key is an object write rather than a helm +// release. Today consumers and their keys are rendered into key-auth's defaultConfig by the +// gateway chart, which means every new tenant is a change to a values file and a deploy. +// +// Why a separate kind rather than a field on ModelFleet: key-auth's `allow` (who may call +// THIS route) is per route and belongs to the fleet, but `consumers` (who exists at all, and +// with which keys) is one list for the whole gateway. Putting it on ModelFleet would have N +// fleets writing one field — the matchRules problem again, and worse, because defaultConfig +// is an opaque blob with no per-entry ownership under Server-Side Apply. +// +// ⚠ 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 itself, so the keys still end up in +// plain text inside the WasmPlugin object. Anyone who can read WasmPlugins in the gateway +// namespace can read every key. What it gives you is one source of truth, online rotation, +// and no release to add a tenant. +// +// +kubebuilder:object:root=true +// +kubebuilder:subresource:status +// +kubebuilder:resource:shortName=apicon +// +kubebuilder:printcolumn:name="Consumer",type=string,JSONPath=`.status.consumerName` +// +kubebuilder:printcolumn:name="Keys",type=integer,JSONPath=`.status.credentials` +// +kubebuilder:printcolumn:name="Gateway",type=string,JSONPath=`.status.appliedGatewayNamespace` +// +kubebuilder:printcolumn:name="Programmed",type=string,JSONPath=`.status.conditions[?(@.type=="Programmed")].status` +// +kubebuilder:printcolumn:name="Age",type=date,JSONPath=`.metadata.creationTimestamp` +type APIConsumer struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec APIConsumerSpec `json:"spec,omitempty"` + Status APIConsumerStatus `json:"status,omitempty"` +} + +// +kubebuilder:object:root=true +type APIConsumerList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []APIConsumer `json:"items"` +} + +func init() { + SchemeBuilder.Register(&APIConsumer{}, &APIConsumerList{}) +} diff --git a/api/v1alpha1/zz_generated.deepcopy.go b/api/v1alpha1/zz_generated.deepcopy.go index 4889b8b0..d9b2351d 100644 --- a/api/v1alpha1/zz_generated.deepcopy.go +++ b/api/v1alpha1/zz_generated.deepcopy.go @@ -5,11 +5,112 @@ package v1alpha1 import ( - "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" ) +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *APIConsumer) DeepCopyInto(out *APIConsumer) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + out.Spec = in.Spec + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIConsumer. +func (in *APIConsumer) DeepCopy() *APIConsumer { + if in == nil { + return nil + } + out := new(APIConsumer) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *APIConsumer) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *APIConsumerList) DeepCopyInto(out *APIConsumerList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]APIConsumer, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIConsumerList. +func (in *APIConsumerList) DeepCopy() *APIConsumerList { + if in == nil { + return nil + } + out := new(APIConsumerList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *APIConsumerList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *APIConsumerSpec) DeepCopyInto(out *APIConsumerSpec) { + *out = *in + out.Gateway = in.Gateway +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIConsumerSpec. +func (in *APIConsumerSpec) DeepCopy() *APIConsumerSpec { + if in == nil { + return nil + } + out := new(APIConsumerSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *APIConsumerStatus) DeepCopyInto(out *APIConsumerStatus) { + *out = *in + if in.LastSyncTime != nil { + in, out := &in.LastSyncTime, &out.LastSyncTime + *out = (*in).DeepCopy() + } + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIConsumerStatus. +func (in *APIConsumerStatus) DeepCopy() *APIConsumerStatus { + if in == nil { + return nil + } + out := new(APIConsumerStatus) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Capabilities) DeepCopyInto(out *Capabilities) { *out = *in @@ -40,6 +141,21 @@ func (in *CartSpec) DeepCopy() *CartSpec { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ConsumerGateway) DeepCopyInto(out *ConsumerGateway) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConsumerGateway. +func (in *ConsumerGateway) DeepCopy() *ConsumerGateway { + if in == nil { + return nil + } + out := new(ConsumerGateway) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Discovery) DeepCopyInto(out *Discovery) { *out = *in @@ -82,7 +198,7 @@ func (in *GatewaySpec) DeepCopyInto(out *GatewaySpec) { *out = *in if in.ExtraPlugins != nil { in, out := &in.ExtraPlugins, &out.ExtraPlugins - *out = make(map[string]v1.JSON, len(*in)) + *out = make(map[string]apiextensionsv1.JSON, len(*in)) for key, val := range *in { (*out)[key] = *val.DeepCopy() } @@ -267,7 +383,7 @@ func (in *ModelFleetStatus) DeepCopyInto(out *ModelFleetStatus) { } if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make([]metav1.Condition, len(*in)) + *out = make([]v1.Condition, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } @@ -389,7 +505,7 @@ func (in *ModelRouteStatus) DeepCopyInto(out *ModelRouteStatus) { } if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make([]metav1.Condition, len(*in)) + *out = make([]v1.Condition, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } diff --git a/cmd/main.go b/cmd/main.go index 821b62b1..31006a3a 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -93,11 +93,11 @@ func runController(leaderElect bool) error { // leaves the type missing - and watching a type that does not exist fails the manager, // which would take ModelRoute down with it. A cluster that never asked for ModelFleet // must not lose openresty peers, CART workers and monitor.conf over it. - has, err := hasModelFleetCRD(cs) + served, err := servedKinds(cs) if err != nil { return err } - if has { + if served["ModelFleet"] { if err := (&controller.ModelFleetReconciler{ Client: mgr.GetClient(), APIReader: mgr.GetAPIReader(), @@ -109,6 +109,21 @@ func runController(leaderElect bool) error { log.Print("ModelFleet CRD not installed: skipping that reconciler " + "(apply deploy/helm/autoconfig/crds/ and restart to enable it)") } + // APIConsumer: who may call the gateway, and with which keys. Gated on its own CRD for + // the same reason - a cluster that only uses ModelRoute must not lose openresty peers + // over a type it never asked for. + if served["APIConsumer"] { + if err := (&controller.APIConsumerReconciler{ + Client: mgr.GetClient(), + APIReader: mgr.GetAPIReader(), + Scheme: mgr.GetScheme(), + }).SetupWithManager(mgr); err != nil { + return err + } + } else { + log.Print("APIConsumer CRD not installed: skipping that reconciler " + + "(apply deploy/helm/autoconfig/crds/ and restart to enable it)") + } // controller-runtime 自带的 ping 检查:进程存活即通过。 // 注意它【不能】发现 reconcile 卡死 —— 要那个得看 metrics 的 workqueue_depth。 if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil { @@ -118,28 +133,32 @@ func runController(leaderElect bool) error { return err } - log.Printf("controller start: ModelRoute%s (routing.modelsphere.dev/v1alpha1)", - map[bool]string{true: " + ModelFleet"}[has]) + extra := "" + for _, k := range []string{"ModelFleet", "APIConsumer"} { + if served[k] { + extra += " + " + k + } + } + log.Printf("controller start: ModelRoute%s (routing.modelsphere.dev/v1alpha1)", extra) return mgr.Start(ctrl.SetupSignalHandler()) } -// hasModelFleetCRD asks the API server whether the type exists. Discovery rather than a -// Get on the CRD object: it needs no apiextensions permission, and "is this kind served" -// is exactly the question. -func hasModelFleetCRD(cs kubernetes.Interface) (bool, error) { +// servedKinds asks the API server which kinds of our group it serves. Discovery rather than +// a Get on each CRD object: it needs no apiextensions permission, and "is this kind served" +// is exactly the question. One call for every optional reconciler. +func servedKinds(cs kubernetes.Interface) (map[string]bool, error) { + out := map[string]bool{} list, err := cs.Discovery().ServerResourcesForGroupVersion(routingv1.GroupVersion.String()) if err != nil { if apierrors.IsNotFound(err) { - return false, nil // the whole group is absent: ModelRoute's CRD is missing too + return out, nil // the whole group is absent: ModelRoute's CRD is missing too } - return false, fmt.Errorf("discover %s: %w", routingv1.GroupVersion, err) + return nil, fmt.Errorf("discover %s: %w", routingv1.GroupVersion, err) } for _, r := range list.APIResources { - if r.Kind == "ModelFleet" { - return true, nil - } + out[r.Kind] = true } - return false, nil + return out, nil } func envOr(k, def string) string { diff --git a/config/crd/bases/routing.modelsphere.dev_apiconsumers.yaml b/config/crd/bases/routing.modelsphere.dev_apiconsumers.yaml new file mode 100644 index 00000000..7b5375e9 --- /dev/null +++ b/config/crd/bases/routing.modelsphere.dev_apiconsumers.yaml @@ -0,0 +1,218 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.16.4 + name: apiconsumers.routing.modelsphere.dev +spec: + group: routing.modelsphere.dev + names: + kind: APIConsumer + listKind: APIConsumerList + plural: apiconsumers + shortNames: + - apicon + singular: apiconsumer + scope: Namespaced + versions: + - additionalPrinterColumns: + - jsonPath: .status.consumerName + name: Consumer + type: string + - jsonPath: .status.credentials + name: Keys + type: integer + - jsonPath: .status.appliedGatewayNamespace + name: Gateway + type: string + - jsonPath: .status.conditions[?(@.type=="Programmed")].status + name: Programmed + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + APIConsumer is one caller of the gateway: a name and a set of API keys. + + It exists so that adding, rotating or removing a key is an object write rather than a helm + release. Today consumers and their keys are rendered into key-auth's defaultConfig by the + gateway chart, which means every new tenant is a change to a values file and a deploy. + + Why a separate kind rather than a field on ModelFleet: key-auth's `allow` (who may call + THIS route) is per route and belongs to the fleet, but `consumers` (who exists at all, and + with which keys) is one list for the whole gateway. Putting it on ModelFleet would have N + fleets writing one field — the matchRules problem again, and worse, because defaultConfig + is an opaque blob with no per-entry ownership under Server-Side Apply. + + ⚠ 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 itself, so the keys still end up in + plain text inside the WasmPlugin object. Anyone who can read WasmPlugins in the gateway + namespace can read every key. What it gives you is one source of truth, online rotation, + and no release to add a tenant. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: APIConsumerSpec names one caller of the gateway and where + its credentials live. + properties: + consumerName: + description: |- + ConsumerName is what a route's ModelFleet names in gateway.authConsumers, and what + appears in the gateway's access log as x-mse-consumer. Defaults to metadata.name. + + Separate from the object's name because consumer names are a gateway-wide namespace + shared with whatever the chart still renders, while object names are per Kubernetes + namespace: two teams could otherwise collide without either of them being able to see + it. The reconciler refuses a duplicate rather than letting one silently win. + maxLength: 63 + type: string + credentialsSecretRef: + description: |- + CredentialsSecretRef: a Secret in this object's namespace holding this consumer's API + keys — EVERY value in it becomes an accepted credential, so a rotation is "add the new + key, let both work, remove the old one" with no window where neither does. + + Only the fleet's own namespace, and only a Secret: the controller holds a cluster-wide + `secrets: get`, so a ref that could name any namespace would turn "can write an + APIConsumer here" into "can read every Secret in the cluster". + maxLength: 253 + minLength: 1 + type: string + gateway: + description: 'Gateway: which gateway''s consumer list this belongs + in.' + properties: + namespace: + description: |- + Namespace holding the gateway's key-auth WasmPlugin. Defaults to higress-system, and + must be the namespace the gateway chart installs into — the same field, with the same + meaning, as ModelFleet's gateway.namespace. + + It is also the grouping key: every APIConsumer naming one namespace is rendered into + that one plugin's consumer list, in one write. + minLength: 1 + type: string + type: object + required: + - credentialsSecretRef + type: object + status: + description: APIConsumerStatus is what the console reads to answer "is + this key live yet". + properties: + appliedGatewayNamespace: + description: |- + AppliedGatewayNamespace: the gateway this consumer was last programmed into. Moving + spec.gateway.namespace otherwise leaves the old gateway accepting these credentials + forever, with nothing in the object pointing at it. + type: string + conditions: + description: 'Conditions: Programmed (the gateway carries this consumer''s + credentials).' + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + consumerName: + description: ConsumerName actually programmed, with the default expanded. + type: string + credentials: + description: |- + Credentials: how many keys this consumer currently has. The keys themselves are never + copied here — status is world-readable to anyone who can read the CR, and the point of + the Secret is that the key lives in one place. Two during a rotation, one otherwise. + format: int32 + type: integer + lastSyncTime: + description: |- + LastSyncTime: when this object was last reconciled, including rounds that wrote + nothing. "Is the controller still looking at this", not "when did the gateway change". + format: date-time + type: string + observedGeneration: + description: |- + ObservedGeneration: equal to metadata.generation once this consumer is programmed into + the gateway. Only advanced on a successful write, so it never claims a key is live + while the plugin still carries the old list. + format: int64 + type: integer + type: object + type: object + served: true + storage: true + subresources: + status: {} diff --git a/config/rbac/role.yaml b/config/rbac/role.yaml index 7920b967..4520af79 100644 --- a/config/rbac/role.yaml +++ b/config/rbac/role.yaml @@ -98,11 +98,8 @@ rules: - apiGroups: - routing.modelsphere.dev resources: - - modelfleets - - modelroutes + - apiconsumers verbs: - - create - - delete - get - list - patch @@ -111,6 +108,7 @@ rules: - apiGroups: - routing.modelsphere.dev resources: + - apiconsumers/finalizers - modelfleets/finalizers - modelroutes/finalizers verbs: @@ -118,9 +116,23 @@ rules: - apiGroups: - routing.modelsphere.dev resources: + - apiconsumers/status - modelfleets/status - modelroutes/status verbs: - get - patch - update +- apiGroups: + - routing.modelsphere.dev + resources: + - modelfleets + - modelroutes + verbs: + - create + - delete + - get + - list + - patch + - update + - watch diff --git a/config/samples/apiconsumer-tenant-a.yaml b/config/samples/apiconsumer-tenant-a.yaml new file mode 100644 index 00000000..49ccc677 --- /dev/null +++ b/config/samples/apiconsumer-tenant-a.yaml @@ -0,0 +1,28 @@ +# One caller of the gateway, with its keys in a Secret. +# +# Adding a tenant is this object plus a Secret - no helm release, no values file. Rotating a +# key is adding a second value to the Secret, waiting for the caller to move over, then +# removing the old one: every value in the Secret is accepted, so there is no window where +# neither key works. +# +# kubectl -n llm-route create secret generic tenant-a-keys --from-literal=current=sk-xxxx +# kubectl apply -f apiconsumer-tenant-a.yaml +# kubectl -n llm-route get apiconsumer # Programmed=True once the gateway has it +# +# A fleet then lets this consumer in by name: +# +# spec.gateway.authConsumers: [tenant-a] +# +# ⚠ The keys end up in plain text inside the key-auth WasmPlugin: its config is a blob pushed +# to the data plane over ECDS and the plugin cannot read a Secret itself. This gives one +# source of truth, online rotation and no release to add a tenant - not secrecy. +apiVersion: routing.modelsphere.dev/v1alpha1 +kind: APIConsumer +metadata: + name: tenant-a + namespace: llm-route +spec: + # consumerName: tenant-a # defaults to metadata.name; what authConsumers references + gateway: + namespace: higress-system # where the key-auth WasmPlugin lives + credentialsSecretRef: tenant-a-keys # a Secret in THIS namespace; every value is a key diff --git a/deploy/helm/autoconfig/crds/routing.modelsphere.dev_apiconsumers.yaml b/deploy/helm/autoconfig/crds/routing.modelsphere.dev_apiconsumers.yaml new file mode 100644 index 00000000..7b5375e9 --- /dev/null +++ b/deploy/helm/autoconfig/crds/routing.modelsphere.dev_apiconsumers.yaml @@ -0,0 +1,218 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.16.4 + name: apiconsumers.routing.modelsphere.dev +spec: + group: routing.modelsphere.dev + names: + kind: APIConsumer + listKind: APIConsumerList + plural: apiconsumers + shortNames: + - apicon + singular: apiconsumer + scope: Namespaced + versions: + - additionalPrinterColumns: + - jsonPath: .status.consumerName + name: Consumer + type: string + - jsonPath: .status.credentials + name: Keys + type: integer + - jsonPath: .status.appliedGatewayNamespace + name: Gateway + type: string + - jsonPath: .status.conditions[?(@.type=="Programmed")].status + name: Programmed + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + APIConsumer is one caller of the gateway: a name and a set of API keys. + + It exists so that adding, rotating or removing a key is an object write rather than a helm + release. Today consumers and their keys are rendered into key-auth's defaultConfig by the + gateway chart, which means every new tenant is a change to a values file and a deploy. + + Why a separate kind rather than a field on ModelFleet: key-auth's `allow` (who may call + THIS route) is per route and belongs to the fleet, but `consumers` (who exists at all, and + with which keys) is one list for the whole gateway. Putting it on ModelFleet would have N + fleets writing one field — the matchRules problem again, and worse, because defaultConfig + is an opaque blob with no per-entry ownership under Server-Side Apply. + + ⚠ 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 itself, so the keys still end up in + plain text inside the WasmPlugin object. Anyone who can read WasmPlugins in the gateway + namespace can read every key. What it gives you is one source of truth, online rotation, + and no release to add a tenant. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: APIConsumerSpec names one caller of the gateway and where + its credentials live. + properties: + consumerName: + description: |- + ConsumerName is what a route's ModelFleet names in gateway.authConsumers, and what + appears in the gateway's access log as x-mse-consumer. Defaults to metadata.name. + + Separate from the object's name because consumer names are a gateway-wide namespace + shared with whatever the chart still renders, while object names are per Kubernetes + namespace: two teams could otherwise collide without either of them being able to see + it. The reconciler refuses a duplicate rather than letting one silently win. + maxLength: 63 + type: string + credentialsSecretRef: + description: |- + CredentialsSecretRef: a Secret in this object's namespace holding this consumer's API + keys — EVERY value in it becomes an accepted credential, so a rotation is "add the new + key, let both work, remove the old one" with no window where neither does. + + Only the fleet's own namespace, and only a Secret: the controller holds a cluster-wide + `secrets: get`, so a ref that could name any namespace would turn "can write an + APIConsumer here" into "can read every Secret in the cluster". + maxLength: 253 + minLength: 1 + type: string + gateway: + description: 'Gateway: which gateway''s consumer list this belongs + in.' + properties: + namespace: + description: |- + Namespace holding the gateway's key-auth WasmPlugin. Defaults to higress-system, and + must be the namespace the gateway chart installs into — the same field, with the same + meaning, as ModelFleet's gateway.namespace. + + It is also the grouping key: every APIConsumer naming one namespace is rendered into + that one plugin's consumer list, in one write. + minLength: 1 + type: string + type: object + required: + - credentialsSecretRef + type: object + status: + description: APIConsumerStatus is what the console reads to answer "is + this key live yet". + properties: + appliedGatewayNamespace: + description: |- + AppliedGatewayNamespace: the gateway this consumer was last programmed into. Moving + spec.gateway.namespace otherwise leaves the old gateway accepting these credentials + forever, with nothing in the object pointing at it. + type: string + conditions: + description: 'Conditions: Programmed (the gateway carries this consumer''s + credentials).' + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + consumerName: + description: ConsumerName actually programmed, with the default expanded. + type: string + credentials: + description: |- + Credentials: how many keys this consumer currently has. The keys themselves are never + copied here — status is world-readable to anyone who can read the CR, and the point of + the Secret is that the key lives in one place. Two during a rotation, one otherwise. + format: int32 + type: integer + lastSyncTime: + description: |- + LastSyncTime: when this object was last reconciled, including rounds that wrote + nothing. "Is the controller still looking at this", not "when did the gateway change". + format: date-time + type: string + observedGeneration: + description: |- + ObservedGeneration: equal to metadata.generation once this consumer is programmed into + the gateway. Only advanced on a successful write, so it never claims a key is live + while the plugin still carries the old list. + format: int64 + type: integer + type: object + type: object + served: true + storage: true + subresources: + status: {} diff --git a/deploy/helm/autoconfig/files/controller-rules.yaml b/deploy/helm/autoconfig/files/controller-rules.yaml index b166ecce..2fe2fb8c 100644 --- a/deploy/helm/autoconfig/files/controller-rules.yaml +++ b/deploy/helm/autoconfig/files/controller-rules.yaml @@ -92,11 +92,8 @@ - apiGroups: - routing.modelsphere.dev resources: - - modelfleets - - modelroutes + - apiconsumers verbs: - - create - - delete - get - list - patch @@ -105,6 +102,7 @@ - apiGroups: - routing.modelsphere.dev resources: + - apiconsumers/finalizers - modelfleets/finalizers - modelroutes/finalizers verbs: @@ -112,9 +110,23 @@ - apiGroups: - routing.modelsphere.dev resources: + - apiconsumers/status - modelfleets/status - modelroutes/status verbs: - get - patch - update +- apiGroups: + - routing.modelsphere.dev + resources: + - modelfleets + - modelroutes + verbs: + - create + - delete + - get + - list + - patch + - update + - watch diff --git a/internal/controller/apiconsumer_controller.go b/internal/controller/apiconsumer_controller.go new file mode 100644 index 00000000..39392bd9 --- /dev/null +++ b/internal/controller/apiconsumer_controller.go @@ -0,0 +1,364 @@ +// APIConsumer: who may call the gateway, and with which API keys. +// +// Every APIConsumer naming one gateway namespace is rendered, together, into that gateway's +// key-auth defaultConfig.consumers. One object per caller, one write per gateway. +package controller + +import ( + "context" + "fmt" + "sort" + "strings" + "time" + + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/util/retry" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + logf "sigs.k8s.io/controller-runtime/pkg/log" + + routingv1 "autoconfig/api/v1alpha1" + "autoconfig/internal/sink" +) + +const ( + consumerFinalizer = "routing.modelsphere.dev/apiconsumer" + condProgrammed = "Programmed" + consumerResyncTime = 60 * time.Second +) + +// ModelFleetReconciler already defines wasmPluginGVK, gatewayNamespace and isAbsent; this +// controller shares them deliberately — a second definition is a second thing to keep in step. + +type APIConsumerReconciler struct { + client.Client + // APIReader reads Secrets straight from the API server. The cached client would start an + // informer on every Secret in the cluster to serve a handful of reads. + APIReader client.Reader + Scheme *runtime.Scheme +} + +// +kubebuilder:rbac:groups=routing.modelsphere.dev,resources=apiconsumers,verbs=get;list;watch;update;patch +// +kubebuilder:rbac:groups=routing.modelsphere.dev,resources=apiconsumers/status,verbs=get;update;patch +// +kubebuilder:rbac:groups=routing.modelsphere.dev,resources=apiconsumers/finalizers,verbs=update + +func (r *APIConsumerReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + log := logf.FromContext(ctx) + + var consumer routingv1.APIConsumer + if err := r.Get(ctx, req.NamespacedName, &consumer); err != nil { + if apierrors.IsNotFound(err) { + return ctrl.Result{}, nil // deleted and finalized; the rewrite already happened + } + return ctrl.Result{}, err + } + + gwNS := consumerGatewayNamespace(&consumer) + + if !consumer.DeletionTimestamp.IsZero() { + if controllerutil.ContainsFinalizer(&consumer, consumerFinalizer) { + // Rewrite the list without this consumer BEFORE letting the object go: the + // reconciler only ever sees the objects that exist, so after the finalizer is + // gone nothing would remember that this credential is still accepted. Deleting + // an APIConsumer has to actually revoke the key. + for _, ns := range distinctNamespaces(gwNS, consumer.Status.AppliedGatewayNamespace) { + if err := r.programGateway(ctx, ns, &consumer); err != nil { + return ctrl.Result{}, err + } + } + if err := r.patchConsumerFinalizer(ctx, &consumer, false); err != nil { + return ctrl.Result{}, err + } + } + return ctrl.Result{}, nil + } + if !controllerutil.ContainsFinalizer(&consumer, consumerFinalizer) { + if err := r.patchConsumerFinalizer(ctx, &consumer, true); err != nil { + return ctrl.Result{}, err + } + return ctrl.Result{Requeue: true}, nil + } + + // Moving gateway.namespace must take the credentials out of the gateway they used to be + // in. Same reason ModelFleet records appliedGatewayNamespace: nothing else remembers. + if old := consumer.Status.AppliedGatewayNamespace; old != "" && old != gwNS { + if err := r.programGateway(ctx, old, nil); err != nil { + r.setConsumerStatus(ctx, req.NamespacedName, metav1.ConditionFalse, "WithdrawError", + fmt.Sprintf("could not take this consumer out of its previous gateway %q: %v", old, err), 0, "") + return ctrl.Result{RequeueAfter: consumerResyncTime}, nil + } + } + + if err := r.programGateway(ctx, gwNS, nil); err != nil { + r.setConsumerStatus(ctx, req.NamespacedName, metav1.ConditionFalse, "ProgramError", err.Error(), 0, "") + return ctrl.Result{RequeueAfter: consumerResyncTime}, nil + } + + name := consumerName(&consumer) + creds, err := r.readCredentials(ctx, &consumer) + if err != nil { + // Cannot happen: programGateway just read the same Secret successfully. Reported + // rather than ignored, because "cannot happen" and "is not checked" are different. + r.setConsumerStatus(ctx, req.NamespacedName, metav1.ConditionFalse, "SecretError", err.Error(), 0, name) + return ctrl.Result{RequeueAfter: consumerResyncTime}, nil + } + log.V(1).Info("consumer programmed", "consumer", name, "gateway", gwNS, "credentials", len(creds)) + r.setConsumerStatus(ctx, req.NamespacedName, metav1.ConditionTrue, "Programmed", + fmt.Sprintf("%d credential(s) accepted by the gateway in %s", len(creds), gwNS), + int32(len(creds)), name) + return ctrl.Result{RequeueAfter: consumerResyncTime}, nil +} + +// programGateway renders every APIConsumer that names this gateway namespace into its +// key-auth plugin, in one write. +// +// `excluding` is the object being deleted: it still exists in the API server while its +// finalizer runs, so it has to be left out explicitly. +func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, excluding *routingv1.APIConsumer) error { + var list routingv1.APIConsumerList + if err := r.List(ctx, &list); err != nil { + // A failed list renders an empty consumer list, which is the single most dangerous + // write this controller can make: it would lock every caller out of every route. + // Never guess from a partial read. + return fmt.Errorf("list APIConsumers: %w", err) + } + + // Has this controller ever programmed THIS gateway? It is the difference between "the + // last consumer was just revoked" and "nobody has migrated this gateway yet, and its list + // still belongs to the chart". Both look like "zero objects want this gateway", and only + // one of them may empty a live list. + ownedBefore := false + for i := range list.Items { + if list.Items[i].Status.AppliedGatewayNamespace == gwNS { + ownedBefore = true + break + } + } + + views := make([]sink.ConsumerView, 0, len(list.Items)) + for i := range list.Items { + c := &list.Items[i] + if consumerGatewayNamespace(c) != gwNS { + continue + } + if !c.DeletionTimestamp.IsZero() { + continue // on its way out; its own finalizer pass rewrites the list + } + if excluding != nil && c.Namespace == excluding.Namespace && c.Name == excluding.Name { + continue + } + creds, err := r.readCredentials(ctx, c) + if err != nil { + // Do NOT drop this consumer and write the rest. A consumer missing from the list + // is a caller that gets 401 on its next request, and a Secret that is briefly + // unreadable must not revoke someone's key. Refusing the whole write leaves the + // gateway on its last good list - every caller keeps working - and the failure + // is reported on the object that caused it. + return fmt.Errorf("%s/%s: %w (nothing was written; the gateway keeps its "+ + "current consumer list)", c.Namespace, c.Name, err) + } + views = append(views, sink.ConsumerView{ + Name: consumerName(c), + Credentials: creds, + Source: c.Namespace + "/" + c.Name, + }) + } + + consumers, err := sink.RenderConsumers(views) + if err != nil { + return err + } + return r.writeConsumers(ctx, gwNS, consumers, ownedBefore) +} + +// writeConsumers replaces defaultConfig.consumers in the gateway's key-auth plugin, leaving +// every other key in that config alone. +func (r *APIConsumerReconciler) writeConsumers(ctx context.Context, gwNS string, consumers []sink.KeyAuthConsumer, ownedBefore bool) error { + log := logf.FromContext(ctx) + return retry.RetryOnConflict(retry.DefaultRetry, func() error { + obj := &unstructured.Unstructured{} + obj.SetGroupVersionKind(wasmPluginGVK) + if err := r.Get(ctx, types.NamespacedName{Namespace: gwNS, Name: "key-auth"}, obj); err != nil { + return fmt.Errorf("key-auth in namespace %q: %w", gwNS, err) + } + live, _, err := unstructured.NestedSlice(obj.Object, "spec", "defaultConfig", "consumers") + if err != nil { + return fmt.Errorf("read defaultConfig.consumers: %w", err) + } + // THE guard. An empty list where the gateway has entries means every caller is + // refused on every route - the whole site's authentication, off, in one write. + // + // But emptying it is sometimes exactly right: revoking the last consumer, or moving + // every consumer to another gateway, both end here legitimately. The two cases look + // identical from the desired set alone - zero objects want this gateway - so the + // question asked instead is whether this controller has ever OWNED this list. + // If some APIConsumer records this gateway in status.appliedGatewayNamespace, the + // list is ours and emptying it is a revocation. If none does, the live entries came + // from somewhere else (the chart, during a half-finished migration) and wiping them + // would take the site's authentication down for a reason nobody asked for. + if len(consumers) == 0 && len(live) > 0 && !ownedBefore { + return fmt.Errorf("refusing to write an empty consumer list over %d live consumer(s) "+ + "in %s/key-auth: no APIConsumer has ever programmed this gateway, so those "+ + "entries belong to something else (the gateway chart renders them until the "+ + "migration is finished) and removing them would deny every caller on every route", + len(live), gwNS) + } + + next := make([]any, 0, len(consumers)) + for _, c := range consumers { + m, err := sink.ToMap(c) + if err != nil { + return err + } + next = append(next, m) + } + if sameRules(live, next) { + // Unchanged: do not write. Every write here is an ECDS push of key-auth to the + // whole data plane, and the console calls this on every key edit. + return nil + } + if err := unstructured.SetNestedSlice(obj.Object, next, "spec", "defaultConfig", "consumers"); err != nil { + return err + } + log.Info("programming gateway consumers", "gateway", gwNS, "consumers", len(next), "was", len(live)) + return r.Update(ctx, obj) + }) +} + +// readCredentials reads every value in the consumer's Secret. All of them are accepted, which +// is what makes a rotation possible: add the new key, let both work, remove the old one. +func (r *APIConsumerReconciler) readCredentials(ctx context.Context, c *routingv1.APIConsumer) ([]string, error) { + ref := c.Spec.CredentialsSecretRef + if strings.ContainsAny(ref, "/:") { + // No namespace prefix, and no "name:key" form: this controller holds a cluster-wide + // `secrets: get`, so a ref that could point elsewhere would turn "can write an + // APIConsumer in this namespace" into "can read any Secret in the cluster". + return nil, fmt.Errorf("credentialsSecretRef %q: must be the bare name of a Secret in "+ + "this object's own namespace", ref) + } + var sec corev1.Secret + reader := r.APIReader + if reader == nil { + reader = r.Client + } + if err := reader.Get(ctx, types.NamespacedName{Namespace: c.Namespace, Name: ref}, &sec); err != nil { + return nil, fmt.Errorf("credentialsSecretRef %q: %w", ref, err) + } + keys := make([]string, 0, len(sec.Data)) + for k := range sec.Data { + keys = append(keys, k) + } + sort.Strings(keys) // stable order, so an unchanged Secret renders an unchanged list + out := make([]string, 0, len(keys)) + for _, k := range keys { + v := strings.TrimSpace(string(sec.Data[k])) + if v == "" { + continue // an empty value would be a credential that matches nothing + } + out = append(out, v) + } + if len(out) == 0 { + return nil, fmt.Errorf("secret %q holds no usable credential", ref) + } + return out, nil +} + +func (r *APIConsumerReconciler) patchConsumerFinalizer(ctx context.Context, c *routingv1.APIConsumer, add bool) error { + // A merge patch, not an Update: a typed Update sends the object as THIS binary's types + // understand it and silently drops spec fields it does not know, which is how an older + // replica mid-rollout erases a field a newer CRD just accepted. + before := c.DeepCopy() + if add { + if !controllerutil.AddFinalizer(c, consumerFinalizer) { + return nil + } + } else if !controllerutil.RemoveFinalizer(c, consumerFinalizer) { + return nil + } + return r.Patch(ctx, c, client.MergeFrom(before)) +} + +func (r *APIConsumerReconciler) setConsumerStatus(ctx context.Context, nn types.NamespacedName, + status metav1.ConditionStatus, reason, msg string, creds int32, name string) { + log := logf.FromContext(ctx) + err := retry.RetryOnConflict(retry.DefaultRetry, func() error { + var c routingv1.APIConsumer + if err := r.Get(ctx, nn, &c); err != nil { + return err + } + st := &c.Status + if status == metav1.ConditionTrue { + // Only on success: observedGeneration is how the console answers "is this key + // live yet", and advancing it on a failed round says yes while the gateway still + // carries the old list. + st.ObservedGeneration = c.Generation + st.AppliedGatewayNamespace = consumerGatewayNamespace(&c) + st.ConsumerName = name + st.Credentials = creds + } + now := metav1.Now() + st.LastSyncTime = &now + setConsumerCond(st, status, reason, msg, c.Generation) + return r.Status().Update(ctx, &c) + }) + if err != nil && !apierrors.IsNotFound(err) { + log.Error(err, "update APIConsumer status") + } +} + +func setConsumerCond(st *routingv1.APIConsumerStatus, status metav1.ConditionStatus, reason, msg string, gen int64) { + meta := metav1.Condition{ + Type: condProgrammed, Status: status, Reason: reason, Message: msg, + ObservedGeneration: gen, LastTransitionTime: metav1.Now(), + } + for i := range st.Conditions { + if st.Conditions[i].Type == condProgrammed { + if st.Conditions[i].Status == status { + meta.LastTransitionTime = st.Conditions[i].LastTransitionTime + } + st.Conditions[i] = meta + return + } + } + st.Conditions = append(st.Conditions, meta) +} + +func consumerName(c *routingv1.APIConsumer) string { + if c.Spec.ConsumerName != "" { + return c.Spec.ConsumerName + } + return c.Name +} + +func consumerGatewayNamespace(c *routingv1.APIConsumer) string { + if c.Spec.Gateway.Namespace != "" { + return c.Spec.Gateway.Namespace + } + return defaultGatewayNamespace +} + +func distinctNamespaces(a, b string) []string { + if b == "" || a == b { + return []string{a} + } + return []string{a, b} +} + +func (r *APIConsumerReconciler) SetupWithManager(mgr ctrl.Manager) error { + // No watch on Secrets, deliberately. Watching them would pick up a rotated key the + // instant the Secret changed, but a Watches() on Secrets starts an informer over EVERY + // Secret in the cluster - the cache and the cluster-wide list/watch that this controller + // went out of its way not to need (it holds `secrets: get` and reads them uncached). A + // key added to a Secret therefore takes effect on the next resync, within + // consumerResyncTime; editing the APIConsumer itself is instant. Worth revisiting only if + // a minute turns out to be too long for a rotation. + return ctrl.NewControllerManagedBy(mgr). + For(&routingv1.APIConsumer{}). + Complete(r) +} diff --git a/internal/controller/apiconsumer_controller_test.go b/internal/controller/apiconsumer_controller_test.go new file mode 100644 index 00000000..9c52d671 --- /dev/null +++ b/internal/controller/apiconsumer_controller_test.go @@ -0,0 +1,416 @@ +package controller + +import ( + "context" + "strings" + "testing" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/types" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + ctrlfake "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + + routingv1 "autoconfig/api/v1alpha1" +) + +func consumerFixture(name, secret string) *routingv1.APIConsumer { + return &routingv1.APIConsumer{ + ObjectMeta: metav1.ObjectMeta{ + Name: name, Namespace: "llm-route", Generation: 1, + Finalizers: []string{consumerFinalizer}, + }, + Spec: routingv1.APIConsumerSpec{ + Gateway: routingv1.ConsumerGateway{Namespace: "higress-system"}, + CredentialsSecretRef: secret, + }, + } +} + +func credSecret(name string, keys map[string]string) *corev1.Secret { + data := map[string][]byte{} + for k, v := range keys { + data[k] = []byte(v) + } + return &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "llm-route"}, + Data: data, + } +} + +// keyAuthWith builds the gateway's key-auth plugin with an existing consumer list, the way +// the chart leaves it. +func keyAuthWith(consumers ...map[string]any) *unstructured.Unstructured { + o := wasmPlugin("key-auth") + list := make([]any, 0, len(consumers)) + for _, c := range consumers { + list = append(list, c) + } + _ = unstructured.SetNestedSlice(o.Object, list, "spec", "defaultConfig", "consumers") + _ = unstructured.SetNestedField(o.Object, false, "spec", "defaultConfig", "global_auth") + _ = unstructured.SetNestedStringSlice(o.Object, []string{"x-higress-dummy-key"}, "spec", "defaultConfig", "keys") + return o +} + +func liveConsumer(name string, creds ...string) map[string]any { + cs := make([]any, 0, len(creds)) + for _, c := range creds { + cs = append(cs, c) + } + return map[string]any{ + "name": name, "credentials": cs, "keys": []any{"Authorization"}, + "in_header": true, "in_query": false, + } +} + +func newConsumerReconciler(t *testing.T, objs ...client.Object) (*APIConsumerReconciler, client.Client) { + t.Helper() + s := fleetScheme(t) + c := ctrlfake.NewClientBuilder().WithScheme(s). + WithObjects(objs...). + WithStatusSubresource(&routingv1.APIConsumer{}). + Build() + return &APIConsumerReconciler{Client: c, APIReader: c, Scheme: s}, c +} + +func reconcileConsumer(t *testing.T, r *APIConsumerReconciler, name string) error { + t.Helper() + _, err := r.Reconcile(context.Background(), ctrl.Request{ + NamespacedName: types.NamespacedName{Namespace: "llm-route", Name: name}, + }) + return err +} + +func gatewayConsumers(t *testing.T, c client.Client, ns string) []any { + t.Helper() + o := &unstructured.Unstructured{} + o.SetGroupVersionKind(wasmPluginGVK) + if err := c.Get(context.Background(), types.NamespacedName{Namespace: ns, Name: "key-auth"}, o); err != nil { + t.Fatalf("get key-auth in %s: %v", ns, err) + } + list, _, _ := unstructured.NestedSlice(o.Object, "spec", "defaultConfig", "consumers") + return list +} + +func consumerNames(list []any) []string { + var out []string + for _, c := range list { + n, _, _ := unstructured.NestedString(c.(map[string]any), "name") + out = append(out, n) + } + return out +} + +// The ordinary case: a consumer with a Secret is programmed into the gateway, in the shape +// key-auth reads, and status says how many keys it has without ever carrying one. +func TestConsumerIsProgrammedIntoTheGateway(t *testing.T) { + r, c := newConsumerReconciler(t, + consumerFixture("tenant-a", "tenant-a-keys"), + credSecret("tenant-a-keys", map[string]string{"key": "sk-tenant-a"}), + keyAuthWith(), + ) + if err := reconcileConsumer(t, r, "tenant-a"); err != nil { + t.Fatal(err) + } + + list := gatewayConsumers(t, c, "higress-system") + if len(list) != 1 { + t.Fatalf("consumers = %v, want one", consumerNames(list)) + } + got := list[0].(map[string]any) + if n, _, _ := unstructured.NestedString(got, "name"); n != "tenant-a" { + t.Fatalf("name = %q", n) + } + creds, _, _ := unstructured.NestedStringSlice(got, "credentials") + if len(creds) != 1 || creds[0] != "sk-tenant-a" { + t.Fatalf("credentials = %v", creds) + } + // The extraction config the plugin needs, which nothing else in Go checks. + keys, _, _ := unstructured.NestedStringSlice(got, "keys") + inHeader, _, _ := unstructured.NestedBool(got, "in_header") + inQuery, _, _ := unstructured.NestedBool(got, "in_query") + if len(keys) != 1 || keys[0] != "Authorization" || !inHeader || inQuery { + t.Fatalf("extraction config = keys:%v in_header:%v in_query:%v", keys, inHeader, inQuery) + } + + var con routingv1.APIConsumer + _ = c.Get(context.Background(), types.NamespacedName{Namespace: "llm-route", Name: "tenant-a"}, &con) + if !condTrue(con.Status.Conditions, condProgrammed) { + t.Fatalf("not programmed: %+v", con.Status.Conditions) + } + if con.Status.Credentials != 1 || con.Status.ConsumerName != "tenant-a" { + t.Fatalf("status = %+v", con.Status) + } + if con.Status.ObservedGeneration != con.Generation { + t.Fatalf("observedGeneration = %d, want %d", con.Status.ObservedGeneration, con.Generation) + } + // The key itself must not be anywhere in status: the whole point of the Secret is that it + // lives in one place, and status is readable by anyone who can read the CR. + if strings.Contains(strings.ToLower(con.Status.ConsumerName+con.Status.AppliedGatewayNamespace), "sk-") { + t.Fatal("a credential leaked into status") + } +} + +// Every value in the Secret is accepted, which is what makes a rotation possible: add the new +// key, let both work, remove the old one. No window where neither does. +func TestConsumerAcceptsEveryKeyInTheSecret(t *testing.T) { + r, c := newConsumerReconciler(t, + consumerFixture("ops", "ops-keys"), + credSecret("ops-keys", map[string]string{"current": "sk-new", "previous": "sk-old"}), + keyAuthWith(), + ) + if err := reconcileConsumer(t, r, "ops"); err != nil { + t.Fatal(err) + } + creds, _, _ := unstructured.NestedStringSlice(gatewayConsumers(t, c, "higress-system")[0].(map[string]any), "credentials") + if len(creds) != 2 || creds[0] != "sk-new" || creds[1] != "sk-old" { + t.Fatalf("credentials = %v, want both keys, sorted", creds) + } +} + +// THE guard. An unreadable Secret must not quietly drop that consumer from the list: a +// consumer missing from key-auth is a caller that gets 401 on its next request. The gateway +// keeps its last good list and the failure is reported. +func TestConsumerUnreadableSecretDoesNotRevokeAnyone(t *testing.T) { + r, c := newConsumerReconciler(t, + consumerFixture("tenant-a", "tenant-a-keys"), + consumerFixture("tenant-b", "missing-secret"), // Secret does not exist + credSecret("tenant-a-keys", map[string]string{"key": "sk-tenant-a"}), + keyAuthWith(liveConsumer("tenant-a", "sk-tenant-a"), liveConsumer("tenant-b", "sk-tenant-b")), + ) + // Reconciling the healthy one must not publish a list that drops the broken one. The + // round reports the failure on the object and requeues rather than returning an error - + // returning one would hot-loop on a Secret that may be minutes from existing. + if err := reconcileConsumer(t, r, "tenant-a"); err != nil { + t.Fatalf("reconcile: %v", err) + } + var healthy routingv1.APIConsumer + _ = c.Get(context.Background(), types.NamespacedName{Namespace: "llm-route", Name: "tenant-a"}, &healthy) + if condTrue(healthy.Status.Conditions, condProgrammed) { + t.Fatal("the round reported success although one consumer could not be resolved") + } + names := consumerNames(gatewayConsumers(t, c, "higress-system")) + if len(names) != 2 { + t.Fatalf("the live consumer list was rewritten to %v - someone's key just stopped working", names) + } +} + +// The single most dangerous write this controller can make: an empty consumer list means +// every caller is refused on every route. It can only come from a bug or a half-finished +// migration, never from intent. +func TestConsumerRefusesToEmptyTheGateway(t *testing.T) { + r, c := newConsumerReconciler(t, + keyAuthWith(liveConsumer("tenant-a", "sk-a"), liveConsumer("ops", "sk-ops")), + ) + err := r.programGateway(context.Background(), "higress-system", nil) + if err == nil { + t.Fatal("an empty consumer list was written over a live gateway") + } + if !strings.Contains(err.Error(), "deny every caller") { + t.Fatalf("the error does not say what would have happened: %v", err) + } + if n := len(gatewayConsumers(t, c, "higress-system")); n != 2 { + t.Fatalf("live consumers = %d, want both still there", n) + } +} + +// Deleting an APIConsumer has to actually revoke the key, and that happens while the object +// still exists - under its finalizer - because afterwards nothing remembers the credential +// was ever accepted. +func TestConsumerDeleteRevokesTheKey(t *testing.T) { + now := metav1.Now() + doomed := consumerFixture("tenant-b", "tenant-b-keys") + doomed.DeletionTimestamp = &now + r, c := newConsumerReconciler(t, + consumerFixture("tenant-a", "tenant-a-keys"), + doomed, + credSecret("tenant-a-keys", map[string]string{"key": "sk-a"}), + credSecret("tenant-b-keys", map[string]string{"key": "sk-b"}), + keyAuthWith(liveConsumer("tenant-a", "sk-a"), liveConsumer("tenant-b", "sk-b")), + ) + if err := reconcileConsumer(t, r, "tenant-b"); err != nil { + t.Fatal(err) + } + names := consumerNames(gatewayConsumers(t, c, "higress-system")) + if len(names) != 1 || names[0] != "tenant-a" { + t.Fatalf("consumers = %v, want only tenant-a", names) + } + var con routingv1.APIConsumer + err := c.Get(context.Background(), types.NamespacedName{Namespace: "llm-route", Name: "tenant-b"}, &con) + if err == nil && len(con.Finalizers) > 0 { + t.Fatalf("finalizer still on the deleted object: %v", con.Finalizers) + } +} + +// Every write here is an ECDS push of key-auth to the whole data plane, and the console calls +// this on every key edit. An unchanged list must produce no write at all. +func TestConsumerUnchangedListIsNotRewritten(t *testing.T) { + r, c := newConsumerReconciler(t, + consumerFixture("tenant-a", "tenant-a-keys"), + credSecret("tenant-a-keys", map[string]string{"key": "sk-a"}), + keyAuthWith(), + ) + if err := reconcileConsumer(t, r, "tenant-a"); err != nil { + t.Fatal(err) + } + before := resourceVersionOf(t, c, "key-auth") + for i := 0; i < 3; i++ { + if err := reconcileConsumer(t, r, "tenant-a"); err != nil { + t.Fatal(err) + } + } + if after := resourceVersionOf(t, c, "key-auth"); after != before { + t.Fatalf("key-auth rewritten with nothing changed: %s -> %s (an ECDS push per resync)", before, after) + } +} + +// Two objects claiming one consumer name would each render an entry and the plugin would take +// one of them, with no way to tell which. Both names are reported rather than one silently +// winning. +func TestConsumerDuplicateNameIsRefused(t *testing.T) { + a := consumerFixture("team-a", "a-keys") + a.Spec.ConsumerName = "shared" + b := consumerFixture("team-b", "b-keys") + b.Spec.ConsumerName = "shared" + r, c := newConsumerReconciler(t, a, b, + credSecret("a-keys", map[string]string{"key": "sk-a"}), + credSecret("b-keys", map[string]string{"key": "sk-b"}), + keyAuthWith(), + ) + if err := reconcileConsumer(t, r, "team-a"); err != nil { + t.Fatalf("reconcile: %v", err) + } + var first routingv1.APIConsumer + _ = c.Get(context.Background(), types.NamespacedName{Namespace: "llm-route", Name: "team-a"}, &first) + if condTrue(first.Status.Conditions, condProgrammed) { + t.Fatal("two objects were allowed to claim one consumer name") + } + if !strings.Contains(condMessage(first.Status.Conditions, condProgrammed), "team-b") { + t.Fatalf("the other claimant is not named: %q", condMessage(first.Status.Conditions, condProgrammed)) + } + if n := len(gatewayConsumers(t, c, "higress-system")); n != 0 { + t.Fatalf("something was written anyway: %d consumers", n) + } +} + +// credentialsSecretRef is a bare name on purpose: this controller holds a cluster-wide +// `secrets: get`, so a ref that could name another namespace would turn "can write an +// APIConsumer here" into "can read every Secret in the cluster". +func TestConsumerSecretRefCannotLeaveTheNamespace(t *testing.T) { + bad := consumerFixture("tenant-a", "kube-system/stolen") + r, c := newConsumerReconciler(t, bad, + &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: "stolen", Namespace: "kube-system"}, + Data: map[string][]byte{"key": []byte("sk-not-yours")}}, + keyAuthWith(), + ) + if err := reconcileConsumer(t, r, "tenant-a"); err != nil { + t.Fatalf("reconcile: %v", err) + } + var con routingv1.APIConsumer + _ = c.Get(context.Background(), types.NamespacedName{Namespace: "llm-route", Name: "tenant-a"}, &con) + if condTrue(con.Status.Conditions, condProgrammed) { + t.Fatal("a cross-namespace Secret ref was accepted") + } + for _, item := range gatewayConsumers(t, c, "higress-system") { + if strings.Contains(strings.ToLower(strings.Join(consumerNames([]any{item}), "")), "tenant-a") { + t.Fatal("the consumer was programmed from a Secret in another namespace") + } + } +} + +// A Secret with no usable value is an error, not an entry with an empty credentials list: an +// empty list is accepted by the plugin and then matches nothing, so that tenant gets 401 on +// every request while the CR reports success. +func TestConsumerEmptySecretIsAnError(t *testing.T) { + r, c := newConsumerReconciler(t, + consumerFixture("tenant-a", "empty-keys"), + credSecret("empty-keys", map[string]string{"key": " "}), + keyAuthWith(), + ) + _ = reconcileConsumer(t, r, "tenant-a") + var con routingv1.APIConsumer + _ = c.Get(context.Background(), types.NamespacedName{Namespace: "llm-route", Name: "tenant-a"}, &con) + if condTrue(con.Status.Conditions, condProgrammed) { + t.Fatal("a consumer with no usable credential was reported as programmed") + } + if n := len(gatewayConsumers(t, c, "higress-system")); n != 0 { + t.Fatalf("an entry was written anyway: %d", n) + } +} + +// Moving gateway.namespace has to take the credentials out of the gateway they used to be in, +// or that gateway keeps accepting them forever with nothing in the object pointing at it. +func TestConsumerMovingGatewayWithdrawsFromTheOldOne(t *testing.T) { + con := consumerFixture("tenant-a", "tenant-a-keys") + con.Status.AppliedGatewayNamespace = "higress-old" + r, c := newConsumerReconciler(t, con, + credSecret("tenant-a-keys", map[string]string{"key": "sk-a"}), + keyAuthWith(), + keyAuthInNamespace("higress-old", liveConsumer("tenant-a", "sk-a")), + ) + if err := reconcileConsumer(t, r, "tenant-a"); err != nil { + t.Fatal(err) + } + if n := len(gatewayConsumers(t, c, "higress-system")); n != 1 { + t.Fatalf("new gateway has %d consumers, want 1", n) + } + if n := len(gatewayConsumers(t, c, "higress-old")); n != 0 { + t.Fatalf("the old gateway still accepts %d consumer(s)", n) + } +} + +// A failed list must never be read as "there are no consumers": that renders an empty list, +// and an empty list locks every caller out of every route. +func TestConsumerListFailureWritesNothing(t *testing.T) { + s := fleetScheme(t) + c := ctrlfake.NewClientBuilder().WithScheme(s). + WithObjects(consumerFixture("tenant-a", "tenant-a-keys"), + credSecret("tenant-a-keys", map[string]string{"key": "sk-a"}), + keyAuthWith(liveConsumer("tenant-a", "sk-a"))). + WithStatusSubresource(&routingv1.APIConsumer{}). + WithInterceptorFuncs(interceptor.Funcs{ + List: func(ctx context.Context, cl client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { + if _, ok := list.(*routingv1.APIConsumerList); ok { + return context.DeadlineExceeded + } + return cl.List(ctx, list, opts...) + }, + }).Build() + r := &APIConsumerReconciler{Client: c, APIReader: c, Scheme: s} + + err := r.programGateway(context.Background(), "higress-system", nil) + if err == nil { + t.Fatal("a failed list was treated as an empty consumer set") + } + // It has to fail AS a list failure. The empty-list guard would also stop this write, so + // an error alone proves nothing about the path taken - and that guard does not apply once + // this controller owns the gateway's list, which is the state every migrated cluster is + // in. Then only this check stands between a transient API error and a wiped consumer list. + if !strings.Contains(err.Error(), "list APIConsumers") { + t.Fatalf("the write was stopped by something other than the failed list: %v", err) + } + if n := len(gatewayConsumers(t, c, "higress-system")); n != 1 { + t.Fatalf("live consumers = %d, want the list untouched", n) + } +} + +// keyAuthInNamespace: a second gateway, for the "moved to another namespace" case. +func keyAuthInNamespace(ns string, consumers ...map[string]any) *unstructured.Unstructured { + o := keyAuthWith(consumers...) + o.SetNamespace(ns) + return o +} + +// condMessage: a condition's message, for tests that check the failure NAMES what went wrong +// rather than just that something did. +func condMessage(conds []metav1.Condition, typ string) string { + for i := range conds { + if conds[i].Type == typ { + return conds[i].Message + } + } + return "" +} diff --git a/internal/sink/consumer.go b/internal/sink/consumer.go new file mode 100644 index 00000000..eb56ebda --- /dev/null +++ b/internal/sink/consumer.go @@ -0,0 +1,82 @@ +package sink + +import ( + "fmt" + "sort" +) + +// KeyAuthConsumer is one entry of key-auth's defaultConfig.consumers: a caller, the +// credentials it may present, and where in the request to look for them. +// +// The shape is the plugin's, not ours, and it is checked at the gateway rather than by the +// API server — a renamed field here applies cleanly and then fails when the plugin loads, +// which stalls the config push for every plugin on that gateway. It matches what the chart +// renders today, field for field. +type KeyAuthConsumer struct { + Name string `json:"name"` + Credentials []string `json:"credentials"` + // Keys: which header or query parameter carries the credential. Per consumer, because + // key-auth's global `keys` is a placeholder on these gateways (a dummy header) precisely + // so that extraction is decided per consumer. + Keys []string `json:"keys"` + InHeader bool `json:"in_header"` + InQuery bool `json:"in_query"` +} + +// credentialHeader is where every consumer's credential is read from. Fixed rather than a CRD +// field: it is what the chart renders for every consumer today, and a per-consumer choice is +// a thing to add when something actually needs it, not before. +const credentialHeader = "Authorization" + +// ConsumerView is one APIConsumer flattened for rendering: the name it claims and the keys +// read out of its Secret. +type ConsumerView struct { + // Name as it appears in the gateway's consumer list and in a fleet's authConsumers. + Name string + // Credentials, in the order they should be written. Several means a rotation is in + // flight and both the old and the new key work. + Credentials []string + // Source identifies the object this came from, for error messages that name the CR + // rather than the consumer. + Source string +} + +// RenderConsumers builds key-auth's defaultConfig.consumers from every APIConsumer on one +// gateway. +// +// Sorted by name so the rendered list is stable: an unstable order rewrites the WasmPlugin on +// every resync, and every rewrite is an ECDS push of that plugin to the whole data plane. +// +// A consumer with no credentials is an error rather than an entry with an empty list: an +// empty credentials array is accepted by the plugin and then matches nothing, so that tenant +// gets 401 on every request while the CR says it was programmed. +func RenderConsumers(views []ConsumerView) ([]KeyAuthConsumer, error) { + out := make([]KeyAuthConsumer, 0, len(views)) + seen := map[string]string{} + for _, v := range views { + if v.Name == "" { + return nil, fmt.Errorf("%s: empty consumer name", v.Source) + } + if len(v.Credentials) == 0 { + return nil, fmt.Errorf("%s: consumer %q has no credentials", v.Source, v.Name) + } + // Two objects claiming one consumer name would each render an entry, the plugin would + // take one of them, and which one is not defined. Refusing names both objects, which + // is the only way the operator can tell what happened. + if prev, dup := seen[v.Name]; dup { + return nil, fmt.Errorf("consumer name %q is claimed by both %s and %s", v.Name, prev, v.Source) + } + seen[v.Name] = v.Source + creds := append([]string(nil), v.Credentials...) + sort.Strings(creds) + out = append(out, KeyAuthConsumer{ + Name: v.Name, + Credentials: creds, + Keys: []string{credentialHeader}, + InHeader: true, + InQuery: false, + }) + } + sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) + return out, nil +} diff --git a/internal/sink/consumer_test.go b/internal/sink/consumer_test.go new file mode 100644 index 00000000..8410b714 --- /dev/null +++ b/internal/sink/consumer_test.go @@ -0,0 +1,80 @@ +package sink + +import ( + "encoding/json" + "strings" + "testing" +) + +func view(name string, creds ...string) ConsumerView { + return ConsumerView{Name: name, Credentials: creds, Source: "llm-route/" + name} +} + +// The shape is key-auth's, and it is validated at the gateway rather than by the API server: +// a renamed field applies cleanly and then fails when the plugin loads, which stalls the +// config push for every plugin on that gateway. Checked field for field against what the +// chart renders today. +func TestRenderConsumersWireShape(t *testing.T) { + got, err := RenderConsumers([]ConsumerView{view("tenant-a", "sk-a")}) + if err != nil { + t.Fatal(err) + } + b, _ := json.Marshal(got) + const want = `[{"name":"tenant-a","credentials":["sk-a"],"keys":["Authorization"],` + + `"in_header":true,"in_query":false}]` + if string(b) != want { + t.Fatalf("rendered %s\nwant %s", b, want) + } +} + +// Stable output, or every resync rewrites the plugin and every rewrite is an ECDS push of +// key-auth to the whole data plane. +func TestRenderConsumersIsSorted(t *testing.T) { + got, err := RenderConsumers([]ConsumerView{ + view("tenant-b", "sk-b"), view("ops", "sk-2", "sk-1"), view("tenant-a", "sk-a"), + }) + if err != nil { + t.Fatal(err) + } + if got[0].Name != "ops" || got[1].Name != "tenant-a" || got[2].Name != "tenant-b" { + t.Fatalf("order = %s/%s/%s", got[0].Name, got[1].Name, got[2].Name) + } + // ...credentials too: a Secret whose keys are read in map order would otherwise churn. + if got[0].Credentials[0] != "sk-1" || got[0].Credentials[1] != "sk-2" { + t.Fatalf("credentials unsorted: %v", got[0].Credentials) + } +} + +// A consumer with no credentials is an error, not an entry with an empty list: the plugin +// accepts an empty credentials array and then matches nothing, so that tenant gets 401 on +// every request while the CR reports it was programmed. +func TestRenderConsumersRejectsAnEmptyCredentialList(t *testing.T) { + if _, err := RenderConsumers([]ConsumerView{view("tenant-a")}); err == nil { + t.Fatal("a consumer with no credentials was rendered") + } +} + +// Two objects claiming one name would each render an entry and the plugin would take one of +// them, with no way to tell which. The error has to name both, or the operator cannot find +// the other one. +func TestRenderConsumersRefusesDuplicateNames(t *testing.T) { + _, err := RenderConsumers([]ConsumerView{ + {Name: "shared", Credentials: []string{"sk-a"}, Source: "llm-route/team-a"}, + {Name: "shared", Credentials: []string{"sk-b"}, Source: "llm-route/team-b"}, + }) + if err == nil { + t.Fatal("two consumers were allowed to share a name") + } + if !strings.Contains(err.Error(), "team-a") || !strings.Contains(err.Error(), "team-b") { + t.Fatalf("the error names only one claimant: %v", err) + } +} + +// Nothing to render is not an error here - whether an empty list may be WRITTEN is the +// controller's decision, and it depends on who owns the gateway's list. +func TestRenderConsumersEmptyInputIsEmptyOutput(t *testing.T) { + got, err := RenderConsumers(nil) + if err != nil || len(got) != 0 { + t.Fatalf("got %v, %v", got, err) + } +} From 04dd6849349c8bd6e252813f3d9b539aca62fb80 Mon Sep 17 00:00:00 2001 From: zhanghao Date: Thu, 26 Nov 2026 14:13:50 +0800 Subject: [PATCH 02/28] APIConsumer: do not revoke keys this controller never issued, and do 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 --- internal/controller/apiconsumer_controller.go | 137 ++++++++++++++- .../controller/apiconsumer_controller_test.go | 157 +++++++++++++++++- 2 files changed, 289 insertions(+), 5 deletions(-) diff --git a/internal/controller/apiconsumer_controller.go b/internal/controller/apiconsumer_controller.go index 39392bd9..54f5f437 100644 --- a/internal/controller/apiconsumer_controller.go +++ b/internal/controller/apiconsumer_controller.go @@ -6,6 +6,7 @@ package controller import ( "context" + "errors" "fmt" "sort" "strings" @@ -31,6 +32,13 @@ const ( consumerFinalizer = "routing.modelsphere.dev/apiconsumer" condProgrammed = "Programmed" consumerResyncTime = 60 * time.Second + // How long deletion keeps trying to revoke the key before it releases the object anyway. + // Long enough to ride out a gateway rollout or a Secret that is briefly unreadable, short + // enough that nobody has to hand-edit a finalizer. + consumerRevokeDeadline = 15 * time.Minute + + // Records which consumer names in key-auth came from APIConsumers. + managedConsumersAnnotation = "routing.modelsphere.dev/managed-consumers" ) // ModelFleetReconciler already defines wasmPluginGVK, gatewayNamespace and isAbsent; this @@ -68,9 +76,28 @@ func (r *APIConsumerReconciler) Reconcile(ctx context.Context, req ctrl.Request) // gone nothing would remember that this credential is still accepted. Deleting // an APIConsumer has to actually revoke the key. for _, ns := range distinctNamespaces(gwNS, consumer.Status.AppliedGatewayNamespace) { - if err := r.programGateway(ctx, ns, &consumer); err != nil { - return ctrl.Result{}, err + err := r.programGateway(ctx, ns, &consumer) + // A gateway that is GONE needs no rewrite, and neither does one whose CRD + // has been uninstalled: there is nothing left to revoke the key from. + // Anything else - a misspelled namespace, an unreadable Secret belonging to + // ANOTHER consumer on the same gateway ("one broken Secret stops the whole + // round") - would otherwise block the finalizer on every pass and leave this + // object in Terminating for good, needing a hand-edited finalizer to free. + // Deletion keeps retrying for a while and then gives up and lets go, with + // the reason on the object: a stuck object is worse than a stale entry + // nobody can point at. + if err == nil || errors.Is(err, errGatewayAbsent) { + continue + } + if time.Since(consumer.DeletionTimestamp.Time) < consumerRevokeDeadline { + r.setConsumerStatus(ctx, req.NamespacedName, metav1.ConditionFalse, "RevokeError", + fmt.Sprintf("could not take this consumer out of gateway %q: %v "+ + "(still retrying; the object is held until this succeeds or "+ + "%s has passed)", ns, err, consumerRevokeDeadline), 0, "") + return ctrl.Result{RequeueAfter: consumerResyncTime}, nil } + log.Error(err, "giving up on revoking a consumer; releasing the object anyway", + "gateway", ns, "deadline", consumerRevokeDeadline) } if err := r.patchConsumerFinalizer(ctx, &consumer, false); err != nil { return ctrl.Result{}, err @@ -88,7 +115,10 @@ func (r *APIConsumerReconciler) Reconcile(ctx context.Context, req ctrl.Request) // Moving gateway.namespace must take the credentials out of the gateway they used to be // in. Same reason ModelFleet records appliedGatewayNamespace: nothing else remembers. if old := consumer.Status.AppliedGatewayNamespace; old != "" && old != gwNS { - if err := r.programGateway(ctx, old, nil); err != nil { + // isAbsent: the gateway it used to be in has been uninstalled, so there is nothing + // to take it out of. Retrying that forever would mean this consumer's key never + // reaches its NEW gateway - the one failure mode worse than a stale entry. + if err := r.programGateway(ctx, old, nil); err != nil && !errors.Is(err, errGatewayAbsent) { r.setConsumerStatus(ctx, req.NamespacedName, metav1.ConditionFalse, "WithdrawError", fmt.Sprintf("could not take this consumer out of its previous gateway %q: %v", old, err), 0, "") return ctrl.Result{RequeueAfter: consumerResyncTime}, nil @@ -120,6 +150,10 @@ func (r *APIConsumerReconciler) Reconcile(ctx context.Context, req ctrl.Request) // // `excluding` is the object being deleted: it still exists in the API server while its // finalizer runs, so it has to be left out explicitly. +// errGatewayAbsent: this gateway's key-auth, or the WasmPlugin CRD itself, is not there. The +// only failure that means "there is nothing left to revoke a key from". +var errGatewayAbsent = errors.New("the gateway's key-auth is not present") + func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, excluding *routingv1.APIConsumer) error { var list routingv1.APIConsumerList if err := r.List(ctx, &list); err != nil { @@ -185,6 +219,14 @@ func (r *APIConsumerReconciler) writeConsumers(ctx context.Context, gwNS string, obj := &unstructured.Unstructured{} obj.SetGroupVersionKind(wasmPluginGVK) if err := r.Get(ctx, types.NamespacedName{Namespace: gwNS, Name: "key-auth"}, obj); err != nil { + if isAbsent(err) { + // Distinguished by a sentinel rather than by IsNotFound on whatever came + // back: a MISSING SECRET is also NotFound, and treating that as "the gateway + // is gone" would let a deletion release its object while the credential is + // still live in key-auth. The one case that must be told apart from every + // other failure deserves its own signal, not a shared error class. + return fmt.Errorf("key-auth in namespace %q: %w", gwNS, errGatewayAbsent) + } return fmt.Errorf("key-auth in namespace %q: %w", gwNS, err) } live, _, err := unstructured.NestedSlice(obj.Object, "spec", "defaultConfig", "consumers") @@ -211,13 +253,47 @@ func (r *APIConsumerReconciler) writeConsumers(ctx context.Context, gwNS string, } next := make([]any, 0, len(consumers)) + mine := make(map[string]bool, len(consumers)) for _, c := range consumers { m, err := sink.ToMap(c) if err != nil { return err } + mine[c.Name] = true next = append(next, m) } + // Carry over the live entries this controller did not write. The empty-list guard + // above only catches a write that renders NOTHING, which left the much more likely + // case open: the gateway chart renders three tenants, someone creates their first + // APIConsumer, and a full replacement with one entry revokes the other three - a 401 + // for each of them, from the first step the documentation tells people to take. + // + // Anything whose name is not in managedConsumerNames is somebody else's and is kept + // verbatim. A name this controller HAS managed is not carried over, because that is + // what deleting an APIConsumer has to mean: the key stops working. + managed, err := managedConsumerNames(obj) + if err != nil { + return err + } + var foreign []string + for _, lc := range live { + m, ok := lc.(map[string]any) + if !ok { + return fmt.Errorf("%s/key-auth: defaultConfig.consumers holds a %T, not an "+ + "object; refusing to rewrite a list this controller cannot read", gwNS, lc) + } + name, _ := m["name"].(string) + if name == "" { + return fmt.Errorf("%s/key-auth: a live consumer has no name; refusing to "+ + "rewrite a list this controller cannot account for", gwNS) + } + if mine[name] || managed[name] { + continue + } + foreign = append(foreign, name) + next = append(next, lc) + } + sortConsumerList(next) if sameRules(live, next) { // Unchanged: do not write. Every write here is an ECDS push of key-auth to the // whole data plane, and the console calls this on every key edit. @@ -226,7 +302,12 @@ func (r *APIConsumerReconciler) writeConsumers(ctx context.Context, gwNS string, if err := unstructured.SetNestedSlice(obj.Object, next, "spec", "defaultConfig", "consumers"); err != nil { return err } - log.Info("programming gateway consumers", "gateway", gwNS, "consumers", len(next), "was", len(live)) + // Written next to the data it describes, because nothing else can tell the two apart + // later: once an APIConsumer is deleted, its object is gone and its entry would look + // exactly like one of the chart's. + setManagedConsumerNames(obj, consumers) + log.Info("programming gateway consumers", "gateway", gwNS, + "mine", len(consumers), "carried over", len(foreign), "was", len(live)) return r.Update(ctx, obj) }) } @@ -362,3 +443,51 @@ func (r *APIConsumerReconciler) SetupWithManager(mgr ctrl.Manager) error { For(&routingv1.APIConsumer{}). Complete(r) } + +// managedConsumerNames: the consumer names this controller wrote last time, recorded on the +// WasmPlugin itself. It is the only way to tell "an entry I own, whose APIConsumer has since +// been deleted, and which must now stop working" from "an entry somebody else owns, which I +// must not touch". Both are just names in a list with no object behind them. +func managedConsumerNames(obj *unstructured.Unstructured) (map[string]bool, error) { + out := map[string]bool{} + raw := obj.GetAnnotations()[managedConsumersAnnotation] + if raw == "" { + return out, nil + } + for _, n := range strings.Split(raw, ",") { + if n = strings.TrimSpace(n); n != "" { + out[n] = true + } + } + return out, nil +} + +func setManagedConsumerNames(obj *unstructured.Unstructured, consumers []sink.KeyAuthConsumer) { + names := make([]string, 0, len(consumers)) + for _, c := range consumers { + names = append(names, c.Name) + } + sort.Strings(names) + ann := obj.GetAnnotations() + if ann == nil { + ann = map[string]string{} + } + if len(names) == 0 { + delete(ann, managedConsumersAnnotation) + } else { + ann[managedConsumersAnnotation] = strings.Join(names, ",") + } + obj.SetAnnotations(ann) +} + +// Stable order, so that carrying foreign entries over does not produce a different list every +// round and an ECDS push with it. +func sortConsumerList(list []any) { + sort.SliceStable(list, func(i, j int) bool { + a, _ := list[i].(map[string]any) + b, _ := list[j].(map[string]any) + an, _ := a["name"].(string) + bn, _ := b["name"].(string) + return an < bn + }) +} diff --git a/internal/controller/apiconsumer_controller_test.go b/internal/controller/apiconsumer_controller_test.go index 9c52d671..a3aaeb11 100644 --- a/internal/controller/apiconsumer_controller_test.go +++ b/internal/controller/apiconsumer_controller_test.go @@ -2,8 +2,10 @@ package controller import ( "context" + "sort" "strings" "testing" + "time" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -55,6 +57,16 @@ func keyAuthWith(consumers ...map[string]any) *unstructured.Unstructured { return o } +// ...and the same key-auth with those entries recorded as this controller's own, which is +// what it looks like after a previous programming round. Entries with no such record are +// somebody else's (the gateway chart's, mid-migration) and are carried over untouched, so a +// test about revoking OUR entry has to say that it is ours. +func keyAuthManagedBy(names string, consumers ...map[string]any) *unstructured.Unstructured { + o := keyAuthWith(consumers...) + o.SetAnnotations(map[string]string{managedConsumersAnnotation: names}) + return o +} + func liveConsumer(name string, creds ...string) map[string]any { cs := make([]any, 0, len(creds)) for _, c := range creds { @@ -229,7 +241,8 @@ func TestConsumerDeleteRevokesTheKey(t *testing.T) { doomed, credSecret("tenant-a-keys", map[string]string{"key": "sk-a"}), credSecret("tenant-b-keys", map[string]string{"key": "sk-b"}), - keyAuthWith(liveConsumer("tenant-a", "sk-a"), liveConsumer("tenant-b", "sk-b")), + keyAuthManagedBy("tenant-a,tenant-b", + liveConsumer("tenant-a", "sk-a"), liveConsumer("tenant-b", "sk-b")), ) if err := reconcileConsumer(t, r, "tenant-b"); err != nil { t.Fatal(err) @@ -401,6 +414,17 @@ func TestConsumerListFailureWritesNothing(t *testing.T) { func keyAuthInNamespace(ns string, consumers ...map[string]any) *unstructured.Unstructured { o := keyAuthWith(consumers...) o.SetNamespace(ns) + // Recorded as this controller's own: the consumer being moved was programmed into this + // gateway by a previous round, which is the only reason withdrawing it is allowed to + // remove the entry. + names := make([]string, 0, len(consumers)) + for _, c := range consumers { + names = append(names, c["name"].(string)) + } + sort.Strings(names) + if len(names) > 0 { + o.SetAnnotations(map[string]string{managedConsumersAnnotation: strings.Join(names, ",")}) + } return o } @@ -414,3 +438,134 @@ func condMessage(conds []metav1.Condition, typ string) string { } return "" } + +// The migration case, and the first step the documentation tells people to take: the gateway +// chart renders the tenants, somebody creates ONE APIConsumer. A full replacement of the list +// would revoke everyone else - a 401 each, with nothing but a healthy-looking CR to show for +// it. The empty-list guard does not catch this, because the rendered list is not empty. +func TestConsumerDoesNotRevokeEntriesItDoesNotOwn(t *testing.T) { + r, c := newConsumerReconciler(t, + consumerFixture("tenant-new", "tenant-new-keys"), + credSecret("tenant-new-keys", map[string]string{"key": "sk-new"}), + // Rendered by the chart: no managed-consumers record, so not ours. + keyAuthWith(liveConsumer("tenant-a", "sk-a"), liveConsumer("tenant-b", "sk-b"), + liveConsumer("ops", "sk-ops")), + ) + if err := reconcileConsumer(t, r, "tenant-new"); err != nil { + t.Fatal(err) + } + names := consumerNames(gatewayConsumers(t, c, "higress-system")) + want := []string{"ops", "tenant-a", "tenant-b", "tenant-new"} + if strings.Join(names, ",") != strings.Join(want, ",") { + t.Fatalf("consumers = %v, want %v - the chart's tenants must survive", names, want) + } + // Their credentials have to survive too, not just their names: an entry carried over + // with an empty credential list is a 403 rather than a 401, which is not an improvement. + for _, lc := range gatewayConsumers(t, c, "higress-system") { + m := lc.(map[string]any) + if creds, _ := m["credentials"].([]any); len(creds) == 0 { + t.Fatalf("consumer %v was carried over without its credentials", m["name"]) + } + } + // ...and only the new one is recorded as ours, so deleting it later revokes exactly it. + var ka unstructured.Unstructured + ka.SetGroupVersionKind(wasmPluginGVK) + if err := c.Get(context.Background(), types.NamespacedName{ + Namespace: "higress-system", Name: "key-auth"}, &ka); err != nil { + t.Fatal(err) + } + if got := ka.GetAnnotations()[managedConsumersAnnotation]; got != "tenant-new" { + t.Fatalf("managed-consumers = %q, want just tenant-new", got) + } +} + +// A list this controller cannot account for is not rewritten at all. Carrying entries over +// means reproducing them verbatim, and an entry that is not an object, or has no name, cannot +// be told apart from one of ours - so the safe move is to refuse rather than to guess. +func TestConsumerRefusesAnUnreadableLiveList(t *testing.T) { + r, _ := newConsumerReconciler(t, + consumerFixture("tenant-new", "tenant-new-keys"), + credSecret("tenant-new-keys", map[string]string{"key": "sk-new"}), + keyAuthWith(map[string]any{"credentials": []any{"sk-x"}}), // no name + ) + err := r.programGateway(context.Background(), "higress-system", nil) + if err == nil || !strings.Contains(err.Error(), "no name") { + t.Fatalf("expected a refusal naming the problem, got %v", err) + } +} + +// Deleting a consumer must not be able to wedge the object. The rewrite that revokes the key +// goes through programGateway, which refuses the whole round if ANY consumer on that gateway +// has an unreadable Secret - so somebody else's broken Secret used to hold this object in +// Terminating for good, freeable only by hand-editing a finalizer. +func TestConsumerDeleteIsNotWedgedByAnotherConsumersSecret(t *testing.T) { + stale := metav1.NewTime(time.Now().Add(-20 * time.Minute)) // past the revoke deadline + doomed := consumerFixture("tenant-b", "tenant-b-keys") + doomed.DeletionTimestamp = &stale + broken := consumerFixture("tenant-a", "secret-that-does-not-exist") + r, c := newConsumerReconciler(t, doomed, broken, + credSecret("tenant-b-keys", map[string]string{"key": "sk-b"}), + keyAuthManagedBy("tenant-a,tenant-b", + liveConsumer("tenant-a", "sk-a"), liveConsumer("tenant-b", "sk-b")), + ) + if err := reconcileConsumer(t, r, "tenant-b"); err != nil { + t.Fatalf("deletion returned an error instead of letting the object go: %v", err) + } + var con routingv1.APIConsumer + err := c.Get(context.Background(), types.NamespacedName{Namespace: "llm-route", Name: "tenant-b"}, &con) + if err == nil && len(con.Finalizers) > 0 { + t.Fatalf("object still held by %v after the revoke deadline", con.Finalizers) + } +} + +// ...but before the deadline it keeps trying, and says so. Giving up immediately would make +// "delete" mean "the key may or may not still work", which is worse than a slow delete. +func TestConsumerDeleteKeepsTryingBeforeTheDeadline(t *testing.T) { + now := metav1.Now() + doomed := consumerFixture("tenant-b", "tenant-b-keys") + doomed.DeletionTimestamp = &now + broken := consumerFixture("tenant-a", "secret-that-does-not-exist") + r, c := newConsumerReconciler(t, doomed, broken, + credSecret("tenant-b-keys", map[string]string{"key": "sk-b"}), + keyAuthManagedBy("tenant-a,tenant-b", + liveConsumer("tenant-a", "sk-a"), liveConsumer("tenant-b", "sk-b")), + ) + if err := reconcileConsumer(t, r, "tenant-b"); err != nil { + t.Fatal(err) + } + var con routingv1.APIConsumer + if err := c.Get(context.Background(), types.NamespacedName{ + Namespace: "llm-route", Name: "tenant-b"}, &con); err != nil { + t.Fatalf("the object was released although the key was never revoked: %v", err) + } + if len(con.Finalizers) == 0 { + t.Fatal("the finalizer was dropped although the key was never revoked") + } + if msg := condMessage(con.Status.Conditions, condProgrammed); !strings.Contains(msg, "still retrying") { + t.Fatalf("the condition does not say it is still trying: %q", msg) + } + // The key is still live, which is the honest state - and the reason the object is held. + if n := len(consumerNames(gatewayConsumers(t, c, "higress-system"))); n != 2 { + t.Fatalf("live consumers = %d, want both (nothing was written)", n) + } +} + +// A gateway that is gone, or whose CRD has been uninstalled, needs no rewrite: there is +// nothing left to revoke the key from, so the object goes immediately rather than waiting out +// a deadline for a write that can never succeed. +func TestConsumerDeleteReleasesWhenTheGatewayIsGone(t *testing.T) { + now := metav1.Now() + doomed := consumerFixture("tenant-b", "tenant-b-keys") + doomed.DeletionTimestamp = &now + r, c := newConsumerReconciler(t, doomed, + credSecret("tenant-b-keys", map[string]string{"key": "sk-b"}), + ) // no key-auth anywhere + if err := reconcileConsumer(t, r, "tenant-b"); err != nil { + t.Fatal(err) + } + var con routingv1.APIConsumer + err := c.Get(context.Background(), types.NamespacedName{Namespace: "llm-route", Name: "tenant-b"}, &con) + if err == nil && len(con.Finalizers) > 0 { + t.Fatalf("held on a gateway that does not exist: %v", con.Finalizers) + } +} From 018248e6eb16c259fdc63efc56b40c8e382c65c7 Mon Sep 17 00:00:00 2001 From: zhanghao Date: Thu, 26 Nov 2026 14:25:11 +0800 Subject: [PATCH 03/28] APIConsumer: the credential is the whole Authorization header, prefix 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 --- .../controller/apiconsumer_controller_test.go | 11 ++-- internal/sink/consumer.go | 39 ++++++++++- internal/sink/consumer_test.go | 64 ++++++++++++++++++- 3 files changed, 106 insertions(+), 8 deletions(-) diff --git a/internal/controller/apiconsumer_controller_test.go b/internal/controller/apiconsumer_controller_test.go index a3aaeb11..ef331abb 100644 --- a/internal/controller/apiconsumer_controller_test.go +++ b/internal/controller/apiconsumer_controller_test.go @@ -136,9 +136,12 @@ func TestConsumerIsProgrammedIntoTheGateway(t *testing.T) { if n, _, _ := unstructured.NestedString(got, "name"); n != "tenant-a" { t.Fatalf("name = %q", n) } + // With the Bearer prefix, because that is what key_auth compares against: it takes the + // WHOLE Authorization header value and looks it up exactly. A bare key here would 401 + // every standard client while this CR reported success. creds, _, _ := unstructured.NestedStringSlice(got, "credentials") - if len(creds) != 1 || creds[0] != "sk-tenant-a" { - t.Fatalf("credentials = %v", creds) + if len(creds) != 1 || creds[0] != "Bearer sk-tenant-a" { + t.Fatalf("credentials = %v, want the key with the Bearer prefix", creds) } // The extraction config the plugin needs, which nothing else in Go checks. keys, _, _ := unstructured.NestedStringSlice(got, "keys") @@ -178,8 +181,8 @@ func TestConsumerAcceptsEveryKeyInTheSecret(t *testing.T) { t.Fatal(err) } creds, _, _ := unstructured.NestedStringSlice(gatewayConsumers(t, c, "higress-system")[0].(map[string]any), "credentials") - if len(creds) != 2 || creds[0] != "sk-new" || creds[1] != "sk-old" { - t.Fatalf("credentials = %v, want both keys, sorted", creds) + if len(creds) != 2 || creds[0] != "Bearer sk-new" || creds[1] != "Bearer sk-old" { + t.Fatalf("credentials = %v, want both keys with the Bearer prefix, sorted", creds) } } diff --git a/internal/sink/consumer.go b/internal/sink/consumer.go index eb56ebda..afcfb6b9 100644 --- a/internal/sink/consumer.go +++ b/internal/sink/consumer.go @@ -3,6 +3,7 @@ package sink import ( "fmt" "sort" + "strings" ) // KeyAuthConsumer is one entry of key-auth's defaultConfig.consumers: a caller, the @@ -26,7 +27,12 @@ type KeyAuthConsumer struct { // credentialHeader is where every consumer's credential is read from. Fixed rather than a CRD // field: it is what the chart renders for every consumer today, and a per-consumer choice is // a thing to add when something actually needs it, not before. -const credentialHeader = "Authorization" +const ( + credentialHeader = "Authorization" + // What key_auth compares against is the whole header value, so the credential it is + // configured with has to include this. + bearerPrefix = "Bearer " +) // ConsumerView is one APIConsumer flattened for rendering: the name it claims and the keys // read out of its Secret. @@ -53,6 +59,11 @@ type ConsumerView struct { func RenderConsumers(views []ConsumerView) ([]KeyAuthConsumer, error) { out := make([]KeyAuthConsumer, 0, len(views)) seen := map[string]string{} + // Which consumer claims which credential. One value under two consumers is not "one of + // them wins": key_auth logs `duplicate consumer credential` and returns false, the whole + // defaultConfig fails to parse, and the plugin is FAIL_CLOSE - so two tenants sharing a + // key takes the entire gateway down, every route, every caller. + credOwner := map[string]string{} for _, v := range views { if v.Name == "" { return nil, fmt.Errorf("%s: empty consumer name", v.Source) @@ -67,7 +78,31 @@ func RenderConsumers(views []ConsumerView) ([]KeyAuthConsumer, error) { return nil, fmt.Errorf("consumer name %q is claimed by both %s and %s", v.Name, prev, v.Source) } seen[v.Name] = v.Source - creds := append([]string(nil), v.Credentials...) + creds := make([]string, 0, len(v.Credentials)) + for i, c := range v.Credentials { + // The credential has to be the ENTIRE Authorization header value, because that + // is what is compared: extractCredential returns header->toString() verbatim - + // no prefix stripped, nothing trimmed - and the lookup into the credentials set + // is exact. A bare key would therefore 401 every standard client (which all send + // `Authorization: Bearer `) while the CR reports it was programmed. + // + // The Secret holds the key itself, in openresty's key-file format, so the prefix + // is added here; one that already carries it is left alone rather than doubled. + if !strings.HasPrefix(c, bearerPrefix) { + c = bearerPrefix + c + } + if prev, dup := credOwner[c]; dup { + // The credential is NOT in this message. A rendering error surfaces on the + // CR, in logs, and in whatever collects them; a key does not belong in any + // of those. The position identifies it well enough to fix. + return nil, fmt.Errorf("consumer %q (%s) shares credential #%d with consumer "+ + "%s: key-auth refuses a duplicate credential and fails to parse its whole "+ + "configuration, which denies every caller on every route - give each "+ + "consumer its own key", v.Name, v.Source, i+1, prev) + } + credOwner[c] = fmt.Sprintf("%q (%s)", v.Name, v.Source) + creds = append(creds, c) + } sort.Strings(creds) out = append(out, KeyAuthConsumer{ Name: v.Name, diff --git a/internal/sink/consumer_test.go b/internal/sink/consumer_test.go index 8410b714..b146e5d6 100644 --- a/internal/sink/consumer_test.go +++ b/internal/sink/consumer_test.go @@ -20,7 +20,9 @@ func TestRenderConsumersWireShape(t *testing.T) { t.Fatal(err) } b, _ := json.Marshal(got) - const want = `[{"name":"tenant-a","credentials":["sk-a"],"keys":["Authorization"],` + + // Byte for byte what the chart renders today, including the Bearer prefix on the + // credential - the plugin compares the whole Authorization header value. + const want = `[{"name":"tenant-a","credentials":["Bearer sk-a"],"keys":["Authorization"],` + `"in_header":true,"in_query":false}]` if string(b) != want { t.Fatalf("rendered %s\nwant %s", b, want) @@ -40,7 +42,7 @@ func TestRenderConsumersIsSorted(t *testing.T) { t.Fatalf("order = %s/%s/%s", got[0].Name, got[1].Name, got[2].Name) } // ...credentials too: a Secret whose keys are read in map order would otherwise churn. - if got[0].Credentials[0] != "sk-1" || got[0].Credentials[1] != "sk-2" { + if got[0].Credentials[0] != "Bearer sk-1" || got[0].Credentials[1] != "Bearer sk-2" { t.Fatalf("credentials unsorted: %v", got[0].Credentials) } } @@ -78,3 +80,61 @@ func TestRenderConsumersEmptyInputIsEmptyOutput(t *testing.T) { t.Fatalf("got %v, %v", got, err) } } + +// key_auth compares the ENTIRE Authorization header value against its credentials set, so a +// consumer configured with a bare key refuses every standard client - all of which send +// `Authorization: Bearer ` - while the object that configured it reports success. The +// Secret holds the key, so the prefix is added here. +func TestRenderConsumersAddsTheBearerPrefix(t *testing.T) { + out, err := RenderConsumers([]ConsumerView{ + {Name: "a", Credentials: []string{"sk-plain"}, Source: "llm-route/a"}, + // One that already carries it must not get a second one. + {Name: "b", Credentials: []string{"Bearer sk-already"}, Source: "llm-route/b"}, + }) + if err != nil { + t.Fatal(err) + } + if got := out[0].Credentials[0]; got != "Bearer sk-plain" { + t.Fatalf("credential = %q, want the Bearer prefix added", got) + } + if got := out[1].Credentials[0]; got != "Bearer sk-already" { + t.Fatalf("credential = %q, want the existing prefix left alone", got) + } +} + +// Two consumers sharing a key is not "one of them wins": key_auth logs `duplicate consumer +// credential`, returns false, and the whole defaultConfig fails to parse - with the plugin +// FAIL_CLOSE, that denies every caller on every route of that gateway. +func TestRenderConsumersRefusesASharedCredential(t *testing.T) { + _, err := RenderConsumers([]ConsumerView{ + {Name: "a", Credentials: []string{"sk-shared"}, Source: "llm-route/a"}, + {Name: "b", Credentials: []string{"sk-shared"}, Source: "llm-route/b"}, + }) + if err == nil { + t.Fatal("rendered a configuration that key-auth refuses to parse at all") + } + // The failure names both consumers and what it would have caused... + for _, want := range []string{`"b"`, "llm-route/a", "every caller on every route"} { + if !strings.Contains(err.Error(), want) { + t.Fatalf("the error does not mention %s: %v", want, err) + } + } + // ...but never the key itself. This text reaches a CR, the logs, and whatever ships them. + if strings.Contains(err.Error(), "sk-shared") { + t.Fatalf("the error leaks the credential: %v", err) + } + // The same key twice under ONE consumer is the same parse failure. + if _, err := RenderConsumers([]ConsumerView{ + {Name: "a", Credentials: []string{"sk-dup", "sk-dup"}, Source: "llm-route/a"}, + }); err == nil { + t.Fatal("accepted the same credential twice in one consumer") + } + // A bare key and the same key with the prefix collapse to one value, so they collide too + // - and silently, if the prefix were added after the duplicate check rather than before. + if _, err := RenderConsumers([]ConsumerView{ + {Name: "a", Credentials: []string{"sk-x"}, Source: "llm-route/a"}, + {Name: "b", Credentials: []string{"Bearer sk-x"}, Source: "llm-route/b"}, + }); err == nil { + t.Fatal("accepted the same key written two ways under two consumers") + } +} From d961f95d32e5e090bdb3b6db1761a15f305fc4d7 Mon Sep 17 00:00:00 2001 From: zhanghao Date: Thu, 26 Nov 2026 14:35:45 +0800 Subject: [PATCH 04/28] APIConsumer: stop rewriting a settled status, and the rest of the review 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 --- README.md | 12 ++++ api/v1alpha1/apiconsumer_types.go | 7 +- .../routing.modelsphere.dev_apiconsumers.yaml | 7 +- .../routing.modelsphere.dev_apiconsumers.yaml | 7 +- internal/controller/apiconsumer_controller.go | 20 +++++- .../controller/apiconsumer_controller_test.go | 69 +++++++++++++++++++ internal/controller/status_settled.go | 56 +++++++++++++++ 7 files changed, 172 insertions(+), 6 deletions(-) create mode 100644 internal/controller/status_settled.go diff --git a/README.md b/README.md index 55f57354..cbf1df18 100644 --- a/README.md +++ b/README.md @@ -447,6 +447,18 @@ reconciler 把同一个网关下所有 `APIConsumer` 聚合、按名字排序, 加 key 最慢一个 resync(60s)生效;改 `APIConsumer` 对象本身是立即的。**没有**对 Secret 的 watch: 那会给全集群 Secret 开 informer,正是这个 controller 刻意避开的(它只有 `secrets: get`、且不走缓存读)。 +⚠️ **撤销(从 Secret 里删掉一个 value)也是同一个 60s 口径** —— 这件事比"加 key 慢一分钟"要紧: +key 泄露要立刻失效时,光改 Secret 最长还有一分钟能继续用。**要立刻生效就动对象本身** +(改一个 annotation 即可,如 `kubectl annotate apiconsumer <名字> rotated-at=$(date +%s) --overwrite`), +那是 generation 变化、下一秒就 reconcile。更彻底的是直接 `kubectl delete apiconsumer <名字>`: +删除走 finalizer,key 在对象消失之前就已经从网关名单里撤掉了。 + +渲染出的 credential 带 `Bearer ` 前缀(Secret 里存裸 key 即可):key-auth 比较的是 +**整个 Authorization header 原值**,不剥前缀、不 trim,配裸 key 的话标准客户端全部 401。 +⚠️ **同一个 key 不能给两个 consumer 用** —— key-auth 遇到重复 credential 会 +`return false` 整份配置解析失败,而插件是 `FAIL_CLOSE`,后果是**整个网关所有路由全部拒绝**, +不是"其中一个不生效"。渲染层会拒掉这种配置(报错只给 consumer 名和下标,不带 key 值)。 + **两条写入安全规则**(这个改动最危险的地方,都是「宁可不写」): - **坏一个,全不写**。某个 `APIConsumer` 的 Secret 读不到时,**不会**把它从名单里摘掉再写剩下的 —— diff --git a/api/v1alpha1/apiconsumer_types.go b/api/v1alpha1/apiconsumer_types.go index 80f745ba..23512e2a 100644 --- a/api/v1alpha1/apiconsumer_types.go +++ b/api/v1alpha1/apiconsumer_types.go @@ -26,8 +26,13 @@ type APIConsumerSpec struct { // shared with whatever the chart still renders, while object names are per Kubernetes // namespace: two teams could otherwise collide without either of them being able to see // it. The reconciler refuses a duplicate rather than letting one silently win. + // + // Restricted to a DNS label: this name is written into the gateway's allow lists and + // turns up in the X-Mse-Consumer header and the access log, so a value with a comma, a + // quote or a space in it would land in all three. // +optional // +kubebuilder:validation:MaxLength=63 + // +kubebuilder:validation:Pattern=`^[a-z0-9]([-a-z0-9]*[a-z0-9])?$` ConsumerName string `json:"consumerName,omitempty"` // Gateway: which gateway's consumer list this belongs in. // +optional @@ -36,7 +41,7 @@ type APIConsumerSpec struct { // keys — EVERY value in it becomes an accepted credential, so a rotation is "add the new // key, let both work, remove the old one" with no window where neither does. // - // Only the fleet's own namespace, and only a Secret: the controller holds a cluster-wide + // Only this object's own namespace, and only a Secret: the controller holds a cluster-wide // `secrets: get`, so a ref that could name any namespace would turn "can write an // APIConsumer here" into "can read every Secret in the cluster". // +kubebuilder:validation:MinLength=1 diff --git a/config/crd/bases/routing.modelsphere.dev_apiconsumers.yaml b/config/crd/bases/routing.modelsphere.dev_apiconsumers.yaml index 7b5375e9..ea102643 100644 --- a/config/crd/bases/routing.modelsphere.dev_apiconsumers.yaml +++ b/config/crd/bases/routing.modelsphere.dev_apiconsumers.yaml @@ -84,7 +84,12 @@ spec: shared with whatever the chart still renders, while object names are per Kubernetes namespace: two teams could otherwise collide without either of them being able to see it. The reconciler refuses a duplicate rather than letting one silently win. + + Restricted to a DNS label: this name is written into the gateway's allow lists and + turns up in the X-Mse-Consumer header and the access log, so a value with a comma, a + quote or a space in it would land in all three. maxLength: 63 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?$ type: string credentialsSecretRef: description: |- @@ -92,7 +97,7 @@ spec: keys — EVERY value in it becomes an accepted credential, so a rotation is "add the new key, let both work, remove the old one" with no window where neither does. - Only the fleet's own namespace, and only a Secret: the controller holds a cluster-wide + Only this object's own namespace, and only a Secret: the controller holds a cluster-wide `secrets: get`, so a ref that could name any namespace would turn "can write an APIConsumer here" into "can read every Secret in the cluster". maxLength: 253 diff --git a/deploy/helm/autoconfig/crds/routing.modelsphere.dev_apiconsumers.yaml b/deploy/helm/autoconfig/crds/routing.modelsphere.dev_apiconsumers.yaml index 7b5375e9..ea102643 100644 --- a/deploy/helm/autoconfig/crds/routing.modelsphere.dev_apiconsumers.yaml +++ b/deploy/helm/autoconfig/crds/routing.modelsphere.dev_apiconsumers.yaml @@ -84,7 +84,12 @@ spec: shared with whatever the chart still renders, while object names are per Kubernetes namespace: two teams could otherwise collide without either of them being able to see it. The reconciler refuses a duplicate rather than letting one silently win. + + Restricted to a DNS label: this name is written into the gateway's allow lists and + turns up in the X-Mse-Consumer header and the access log, so a value with a comma, a + quote or a space in it would land in all three. maxLength: 63 + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?$ type: string credentialsSecretRef: description: |- @@ -92,7 +97,7 @@ spec: keys — EVERY value in it becomes an accepted credential, so a rotation is "add the new key, let both work, remove the old one" with no window where neither does. - Only the fleet's own namespace, and only a Secret: the controller holds a cluster-wide + Only this object's own namespace, and only a Secret: the controller holds a cluster-wide `secrets: get`, so a ref that could name any namespace would turn "can write an APIConsumer here" into "can read every Secret in the cluster". maxLength: 253 diff --git a/internal/controller/apiconsumer_controller.go b/internal/controller/apiconsumer_controller.go index 54f5f437..f16fe3dc 100644 --- a/internal/controller/apiconsumer_controller.go +++ b/internal/controller/apiconsumer_controller.go @@ -41,8 +41,10 @@ const ( managedConsumersAnnotation = "routing.modelsphere.dev/managed-consumers" ) -// ModelFleetReconciler already defines wasmPluginGVK, gatewayNamespace and isAbsent; this -// controller shares them deliberately — a second definition is a second thing to keep in step. +// ModelFleetReconciler already defines wasmPluginGVK, isAbsent and sameRules; this controller +// shares them deliberately — a second definition is a second thing to keep in step. The +// gateway namespace is resolved separately (consumerGatewayNamespace), because an APIConsumer +// has no fleet to inherit one from. type APIConsumerReconciler struct { client.Client @@ -75,6 +77,14 @@ func (r *APIConsumerReconciler) Reconcile(ctx context.Context, req ctrl.Request) // reconciler only ever sees the objects that exist, so after the finalizer is // gone nothing would remember that this credential is still accepted. Deleting // an APIConsumer has to actually revoke the key. + // Not trusting status.appliedGatewayNamespace alone to decide there is nothing + // to revoke, tempting as it is for an object that was never programmed: a round + // that wrote the credential and then failed to write its own status leaves the + // key live with no record of it, and skipping the withdrawal would strand that + // key in key-auth for good. The two cases this would have saved are already + // covered - a misspelled gateway namespace has no key-auth to Get, which is the + // absent sentinel and releases at once, and anything else gives up at the + // deadline. for _, ns := range distinctNamespaces(gwNS, consumer.Status.AppliedGatewayNamespace) { err := r.programGateway(ctx, ns, &consumer) // A gateway that is GONE needs no rewrite, and neither does one whose CRD @@ -374,6 +384,7 @@ func (r *APIConsumerReconciler) setConsumerStatus(ctx context.Context, nn types. return err } st := &c.Status + prev := st.DeepCopy() if status == metav1.ConditionTrue { // Only on success: observedGeneration is how the console answers "is this key // live yet", and advancing it on a failed round says yes while the gateway still @@ -383,9 +394,12 @@ func (r *APIConsumerReconciler) setConsumerStatus(ctx context.Context, nn types. st.ConsumerName = name st.Credentials = creds } + setConsumerCond(st, status, reason, msg, c.Generation) + if statusSettled(prev, st, consumerResyncTime, prev.LastSyncTime) { + return nil + } now := metav1.Now() st.LastSyncTime = &now - setConsumerCond(st, status, reason, msg, c.Generation) return r.Status().Update(ctx, &c) }) if err != nil && !apierrors.IsNotFound(err) { diff --git a/internal/controller/apiconsumer_controller_test.go b/internal/controller/apiconsumer_controller_test.go index ef331abb..84e13e2b 100644 --- a/internal/controller/apiconsumer_controller_test.go +++ b/internal/controller/apiconsumer_controller_test.go @@ -572,3 +572,72 @@ func TestConsumerDeleteReleasesWhenTheGatewayIsGone(t *testing.T) { t.Fatalf("held on a gateway that does not exist: %v", con.Finalizers) } } + +// A settled consumer must not be rewritten on every pass. The 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 - lastSyncTime used to be stamped unconditionally - makes each round enqueue +// the next one. Here that costs an uncached Secret GET for every consumer on the gateway, +// every iteration. +func TestConsumerSettledStatusIsNotRewritten(t *testing.T) { + r, c := newConsumerReconciler(t, + consumerFixture("tenant-a", "tenant-a-keys"), + credSecret("tenant-a-keys", map[string]string{"key": "sk-a"}), + keyAuthWith(), + ) + nn := types.NamespacedName{Namespace: "llm-route", Name: "tenant-a"} + version := func() string { + var con routingv1.APIConsumer + if err := c.Get(context.Background(), nn, &con); err != nil { + t.Fatal(err) + } + return con.ResourceVersion + } + if err := reconcileConsumer(t, r, "tenant-a"); err != nil { + t.Fatal(err) + } + settled := version() + for i := 0; i < 3; i++ { + if err := reconcileConsumer(t, r, "tenant-a"); err != nil { + t.Fatal(err) + } + } + if v := version(); v != settled { + t.Fatalf("the object was rewritten with nothing to say (resourceVersion %s -> %s)", settled, v) + } + + // ...but a real change still gets written. + var con routingv1.APIConsumer + if err := c.Get(context.Background(), nn, &con); err != nil { + t.Fatal(err) + } + con.Spec.ConsumerName = "renamed" + con.Generation = 2 + if err := c.Update(context.Background(), &con); err != nil { + t.Fatal(err) + } + before := version() + if err := reconcileConsumer(t, r, "tenant-a"); err != nil { + t.Fatal(err) + } + if version() == before { + t.Fatal("a changed consumer did not update its status") + } + + // ...and so does a stale heartbeat, so that lastSyncTime does not freeze on a settled + // object and read as a dead controller. + if err := c.Get(context.Background(), nn, &con); err != nil { + t.Fatal(err) + } + stale := metav1.NewTime(time.Now().Add(-2 * consumerResyncTime)) + con.Status.LastSyncTime = &stale + if err := c.Status().Update(context.Background(), &con); err != nil { + t.Fatal(err) + } + before = version() + if err := reconcileConsumer(t, r, "tenant-a"); err != nil { + t.Fatal(err) + } + if version() == before { + t.Fatal("lastSyncTime was left stale: nothing would show the controller is still alive") + } +} diff --git a/internal/controller/status_settled.go b/internal/controller/status_settled.go new file mode 100644 index 00000000..00f09357 --- /dev/null +++ b/internal/controller/status_settled.go @@ -0,0 +1,56 @@ +package controller + +import ( + "reflect" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// statusSettled reports whether a status write can be skipped. +// +// Every reconcile used to end in a Status().Update, because lastSyncTime was stamped +// unconditionally and therefore ALWAYS differed. That write is an update event on the object +// itself, and the controllers watch their own kind with no predicate, so each round enqueued +// the next one: a loop paced only by how long a reconcile takes, rather than by the resync +// interval. It is worst where a round is expensive - APIConsumer reads every consumer's +// Secret uncached, so N consumers cost N^2 GETs per iteration. +// +// Skipping the write when only lastSyncTime would move breaks that cycle. The field keeps a +// heartbeat anyway: once it is older than the resync interval it is written even if nothing +// else changed, which is one write and one extra reconcile per interval instead of a +// continuous stream. Without that, a settled object's lastSyncTime would freeze and anyone +// using it to answer "is this still being reconciled" would read it as a dead controller. +// +// prev is the status as read from the API server, next the one about to be written. Both are +// compared with lastSyncTime zeroed, so every other field - conditions included, with their +// own observedGeneration and transition times - still forces a write. +func statusSettled(prev, next any, resyncEvery time.Duration, lastSync *metav1.Time) bool { + if !sameIgnoringLastSync(prev, next) { + return false + } + // Nothing changed. Write only if the heartbeat has gone stale. + return lastSync != nil && time.Since(lastSync.Time) < resyncEvery +} + +// sameIgnoringLastSync compares two *Status values field for field with LastSyncTime cleared. +// Reflection rather than a hand-written comparison per type: a field added to either status +// would otherwise be left out of the comparison silently, and the symptom - a status that +// stops updating for one particular field - is nothing like the cause. +func sameIgnoringLastSync(prev, next any) bool { + a, b := zeroLastSync(prev), zeroLastSync(next) + return reflect.DeepEqual(a, b) +} + +func zeroLastSync(v any) any { + rv := reflect.ValueOf(v) + if rv.Kind() != reflect.Pointer || rv.IsNil() { + return v + } + cp := reflect.New(rv.Elem().Type()) + cp.Elem().Set(rv.Elem()) + if f := cp.Elem().FieldByName("LastSyncTime"); f.IsValid() && f.CanSet() { + f.Set(reflect.Zero(f.Type())) + } + return cp.Elem().Interface() +} From dc934e9bceb571bbc8b450ff811c6d88dd962f6b Mon Sep 17 00:00:00 2001 From: zhanghao Date: Thu, 26 Nov 2026 14:48:46 +0800 Subject: [PATCH 05/28] APIConsumer: take ownership of the consumer list with one force apply 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 --- internal/controller/apiconsumer_controller.go | 81 +++++++++ .../controller/apiconsumer_controller_test.go | 170 +++++++++++++++++- 2 files changed, 250 insertions(+), 1 deletion(-) diff --git a/internal/controller/apiconsumer_controller.go b/internal/controller/apiconsumer_controller.go index f16fe3dc..28c8a77b 100644 --- a/internal/controller/apiconsumer_controller.go +++ b/internal/controller/apiconsumer_controller.go @@ -6,6 +6,7 @@ package controller import ( "context" + "encoding/json" "errors" "fmt" "sort" @@ -243,6 +244,33 @@ func (r *APIConsumerReconciler) writeConsumers(ctx context.Context, gwNS string, if err != nil { return fmt.Errorf("read defaultConfig.consumers: %w", err) } + // Take ownership of the field before writing it, if it is not ours yet. + // + // Why this cannot be left to the write itself: a non-apply Update only takes + // ownership of the fields whose VALUES it changes, and the first thing this + // controller does on an already-populated gateway is adopt the live entries + // unchanged. Measured on the test cluster, a same-value Update moves nothing, so the + // field stays helm's for as long as the rendered list happens to match - and the + // gateway chart holds its upgrade back until a non-helm manager owns the field, + // which would then never happen. + // + // A force apply of just this field is enough: it leaves the value alone and makes + // autoconfig a CO-OWNER alongside helm (also measured - it does not dispossess + // helm), which is what the chart waits for. The chart then stops rendering the + // field, helm's claim on it lapses, and this controller is left as the only owner. + // `keys` and `global_auth` are untouched and stay helm's: defaultConfig is tracked + // field by field, not as one atomic blob. + if len(consumers) > 0 && !ownsConsumers(obj) { + if err := r.claimConsumers(ctx, gwNS, live); err != nil { + return fmt.Errorf("take ownership of %s/key-auth defaultConfig.consumers: %w", gwNS, err) + } + // Re-read: the apply bumped resourceVersion, and the Update below would be + // refused on the stale one. + if err := r.Get(ctx, types.NamespacedName{Namespace: gwNS, Name: "key-auth"}, obj); err != nil { + return fmt.Errorf("key-auth in namespace %q after taking ownership: %w", gwNS, err) + } + } + // THE guard. An empty list where the gateway has entries means every caller is // refused on every route - the whole site's authentication, off, in one write. // @@ -505,3 +533,56 @@ func sortConsumerList(list []any) { return an < bn }) } + +// fieldManagerName is the manager this controller writes under. It is what the gateway chart +// looks for before it yields defaultConfig.consumers, so it is part of an agreed contract +// with that chart, not an internal detail - see modelsphere/modelsphere#90. +const fieldManagerName = "autoconfig" + +// ownsConsumers: does this controller already own defaultConfig.consumers? Any entry under +// its own manager counts, whether recorded by an apply or by an update - the chart yields to +// any manager that is not helm. +func ownsConsumers(obj *unstructured.Unstructured) bool { + for _, mf := range obj.GetManagedFields() { + if mf.Manager != fieldManagerName || mf.FieldsV1 == nil { + continue + } + var fields map[string]any + if err := json.Unmarshal(mf.FieldsV1.Raw, &fields); err != nil { + continue + } + spec, _ := fields["f:spec"].(map[string]any) + def, _ := spec["f:defaultConfig"].(map[string]any) + if _, ok := def["f:consumers"]; ok { + return true + } + } + return false +} + +// claimConsumers applies defaultConfig.consumers with its CURRENT value, which changes +// nothing and makes this controller an owner of the field. force, because the point is to +// claim a field somebody else owns; without it the apply is refused with a conflict. +// +// Only this one field is sent. defaultConfig's other keys are not named, and an apply does +// not remove fields it never claimed, so keys and global_auth stay exactly as they are - +// which matters, since a key-auth without a consumers OR credentials key fails to parse +// altogether and the plugin is FAIL_CLOSE. +func (r *APIConsumerReconciler) claimConsumers(ctx context.Context, gwNS string, live []any) error { + claim := &unstructured.Unstructured{} + claim.SetGroupVersionKind(wasmPluginGVK) + claim.SetNamespace(gwNS) + claim.SetName("key-auth") + value := live + if value == nil { + // Absent rather than empty: claim it as the empty list, which is also the value a + // gateway needs to have at all for its config to parse. + value = []any{} + } + if err := unstructured.SetNestedSlice(claim.Object, value, "spec", "defaultConfig", "consumers"); err != nil { + return err + } + logf.FromContext(ctx).Info("taking ownership of the gateway consumer list", + "gateway", gwNS, "entries", len(value)) + return r.Patch(ctx, claim, client.Apply, client.ForceOwnership, client.FieldOwner(fieldManagerName)) +} diff --git a/internal/controller/apiconsumer_controller_test.go b/internal/controller/apiconsumer_controller_test.go index 84e13e2b..1c2ad1a6 100644 --- a/internal/controller/apiconsumer_controller_test.go +++ b/internal/controller/apiconsumer_controller_test.go @@ -2,6 +2,7 @@ package controller import ( "context" + "encoding/json" "sort" "strings" "testing" @@ -78,14 +79,57 @@ func liveConsumer(name string, creds ...string) map[string]any { } } +// appliedFields records every server-side-apply this controller made, per object. The fake +// client refuses apply patches outright ("apply patches are not supported in the fake +// client"), so they are translated into the merge patch that has the same effect on the +// stored object and counted here. Without the translation the ownership takeover - the one +// write that MUST be an apply - could not be exercised at all; without the counting, a test +// could not tell "took ownership once" from "re-applies on every pass", which is an ECDS +// push of key-auth to the whole data plane each time. +type appliedFields struct { + byObject map[string][]string +} + +func (a *appliedFields) count(name string) int { return len(a.byObject[name]) } + func newConsumerReconciler(t *testing.T, objs ...client.Object) (*APIConsumerReconciler, client.Client) { + r, c, _ := newConsumerReconcilerRecording(t, objs...) + return r, c +} + +func newConsumerReconcilerRecording(t *testing.T, objs ...client.Object) ( + *APIConsumerReconciler, client.Client, *appliedFields) { t.Helper() s := fleetScheme(t) + applies := &appliedFields{byObject: map[string][]string{}} c := ctrlfake.NewClientBuilder().WithScheme(s). WithObjects(objs...). WithStatusSubresource(&routingv1.APIConsumer{}). + WithInterceptorFuncs(interceptor.Funcs{ + Patch: func(ctx context.Context, cl client.WithWatch, obj client.Object, + patch client.Patch, opts ...client.PatchOption) error { + if patch.Type() != types.ApplyPatchType { + return cl.Patch(ctx, obj, patch, opts...) + } + data, err := patch.Data(obj) + if err != nil { + return err + } + key := obj.GetNamespace() + "/" + obj.GetName() + applies.byObject[key] = append(applies.byObject[key], string(data)) + if err := cl.Patch(ctx, obj, client.RawPatch(types.MergePatchType, data), + &client.PatchOptions{}); err != nil { + return err + } + // The fake client keeps no managedFields, and the code under test asks + // whether it already owns a field before claiming it. Without this, that + // question answers "no" forever and the takeover repeats on every pass - + // which is exactly what TestConsumerUnchangedListIsNotRewritten caught. + return recordApplyOwnership(ctx, cl, obj, data, fieldManagerName) + }, + }). Build() - return &APIConsumerReconciler{Client: c, APIReader: c, Scheme: s}, c + return &APIConsumerReconciler{Client: c, APIReader: c, Scheme: s}, c, applies } func reconcileConsumer(t *testing.T, r *APIConsumerReconciler, name string) error { @@ -641,3 +685,127 @@ func TestConsumerSettledStatusIsNotRewritten(t *testing.T) { t.Fatal("lastSyncTime was left stale: nothing would show the controller is still alive") } } + +// recordApplyOwnership writes the managedFields entry a real API server would have recorded +// for this apply: the paths the patch names, under the given manager. +func recordApplyOwnership(ctx context.Context, cl client.Client, obj client.Object, + patch []byte, manager string) error { + var body map[string]any + if err := json.Unmarshal(patch, &body); err != nil { + return err + } + fields := toFieldSet(body) + delete(fields, "f:apiVersion") + delete(fields, "f:kind") + delete(fields, "f:metadata") + raw, err := json.Marshal(fields) + if err != nil { + return err + } + live := &unstructured.Unstructured{} + live.SetGroupVersionKind(obj.GetObjectKind().GroupVersionKind()) + if err := cl.Get(ctx, client.ObjectKeyFromObject(obj), live); err != nil { + return err + } + mfs := live.GetManagedFields() + for i := range mfs { + if mfs[i].Manager == manager && mfs[i].Operation == metav1.ManagedFieldsOperationApply { + mfs[i].FieldsV1 = &metav1.FieldsV1{Raw: raw} + live.SetManagedFields(mfs) + return cl.Update(ctx, live) + } + } + live.SetManagedFields(append(mfs, metav1.ManagedFieldsEntry{ + Manager: manager, + Operation: metav1.ManagedFieldsOperationApply, + APIVersion: live.GetAPIVersion(), + FieldsType: "FieldsV1", + FieldsV1: &metav1.FieldsV1{Raw: raw}, + })) + return cl.Update(ctx, live) +} + +// toFieldSet turns {"spec":{"defaultConfig":{"consumers":[...]}}} into +// {"f:spec":{"f:defaultConfig":{"f:consumers":{}}}} - the shape managedFields uses, with +// leaves (including whole lists, which are atomic here) as empty objects. +func toFieldSet(v map[string]any) map[string]any { + out := map[string]any{} + for k, val := range v { + if child, ok := val.(map[string]any); ok { + out["f:"+k] = toFieldSet(child) + continue + } + out["f:"+k] = map[string]any{} + } + return out +} + +// The takeover. Until a manager other than helm owns defaultConfig.consumers, the gateway +// chart refuses to stop rendering it (modelsphere/modelsphere#90) - and a non-apply Update +// only takes ownership of fields whose VALUE it changes, so adopting the live entries +// unchanged, which is the first thing this controller does on a populated gateway, moves +// nothing. Hence one force apply of just that field, with its current value. +func TestConsumerTakesOwnershipOfTheConsumerList(t *testing.T) { + r, c, applies := newConsumerReconcilerRecording(t, + consumerFixture("tenant-a", "tenant-a-keys"), + credSecret("tenant-a-keys", map[string]string{"key": "sk-a"}), + // The chart's list, owned by helm, with tenant-a already in it: the migration case, + // where the rendered list matches live and an Update would therefore change nothing. + keyAuthWith(liveConsumer("tenant-a", "Bearer sk-a"), liveConsumer("ops", "Bearer sk-ops")), + ) + if err := reconcileConsumer(t, r, "tenant-a"); err != nil { + t.Fatal(err) + } + if n := applies.count("higress-system/key-auth"); n != 1 { + t.Fatalf("server-side applies = %d, want exactly 1 (the ownership claim)", n) + } + // The claim must name ONLY consumers. defaultConfig is tracked field by field, but an + // apply that named keys or global_auth would take those from helm too, and one that + // dropped them while owning the parent would leave a key-auth that cannot parse at all + // - and the plugin is FAIL_CLOSE. + // Parsed, not grepped: "keys" also appears INSIDE each consumer entry, where it belongs, + // so a substring check reports a problem that is not there (it did). + var claim map[string]any + if err := json.Unmarshal([]byte(applies.byObject["higress-system/key-auth"][0]), &claim); err != nil { + t.Fatal(err) + } + spec, _ := claim["spec"].(map[string]any) + def, _ := spec["defaultConfig"].(map[string]any) + if len(spec) != 1 || len(def) != 1 { + t.Fatalf("the claim names more than defaultConfig.consumers: spec=%v", spec) + } + if _, ok := def["consumers"]; !ok { + t.Fatalf("the claim does not name consumers: %v", def) + } + + // Nothing else changed: the claim carries the CURRENT value, so the gateway's list is + // not disturbed by taking ownership of it... + names := consumerNames(gatewayConsumers(t, c, "higress-system")) + if strings.Join(names, ",") != "ops,tenant-a" { + t.Fatalf("consumers = %v, want the live list untouched", names) + } + // ...and keys/global_auth are still there, which is what a FAIL_CLOSE plugin needs. + var ka unstructured.Unstructured + ka.SetGroupVersionKind(wasmPluginGVK) + if err := c.Get(context.Background(), types.NamespacedName{ + Namespace: "higress-system", Name: "key-auth"}, &ka); err != nil { + t.Fatal(err) + } + if keys, found, _ := unstructured.NestedStringSlice(ka.Object, "spec", "defaultConfig", "keys"); !found || len(keys) == 0 { + t.Fatal("the claim removed defaultConfig.keys: key-auth can no longer parse its config") + } + if _, found, _ := unstructured.NestedBool(ka.Object, "spec", "defaultConfig", "global_auth"); !found { + t.Fatal("the claim removed defaultConfig.global_auth") + } + + // Claimed once, not once per pass: every apply that changes something is an ECDS push of + // key-auth to the whole data plane. + for i := 0; i < 3; i++ { + if err := reconcileConsumer(t, r, "tenant-a"); err != nil { + t.Fatal(err) + } + } + if n := applies.count("higress-system/key-auth"); n != 1 { + t.Fatalf("server-side applies = %d after four passes, want 1: the claim repeats", n) + } +} From 625a78dc8d2a5e4b7009b187ea4e3faee52103fa Mon Sep 17 00:00:00 2001 From: zhanghao Date: Thu, 26 Nov 2026 15:00:36 +0800 Subject: [PATCH 06/28] APIConsumer: say in the field doc that lastSyncTime is not stamped every 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 --- api/v1alpha1/apiconsumer_types.go | 12 ++++++++++-- .../bases/routing.modelsphere.dev_apiconsumers.yaml | 12 ++++++++++-- .../crds/routing.modelsphere.dev_apiconsumers.yaml | 12 ++++++++++-- 3 files changed, 30 insertions(+), 6 deletions(-) diff --git a/api/v1alpha1/apiconsumer_types.go b/api/v1alpha1/apiconsumer_types.go index 23512e2a..13fd5f9f 100644 --- a/api/v1alpha1/apiconsumer_types.go +++ b/api/v1alpha1/apiconsumer_types.go @@ -69,8 +69,16 @@ type APIConsumerStatus struct { // forever, with nothing in the object pointing at it. // +optional AppliedGatewayNamespace string `json:"appliedGatewayNamespace,omitempty"` - // LastSyncTime: when this object was last reconciled, including rounds that wrote - // nothing. "Is the controller still looking at this", not "when did the gateway change". + // LastSyncTime: when this object's status was last written — on every pass that changed + // something, including the ones that failed before touching the gateway, and otherwise + // once per resync interval as a heartbeat. It is NOT stamped on every pass: that write + // is an update event on this object, which the controller watches, so an unconditional + // stamp made each round trigger the next one — and a round here reads every consumer's + // Secret uncached. + // + // So a value a little older than the resync interval means "settled, nothing to say", + // not "stalled". It answers "is the controller still looking at this", not "when did the + // gateway change"; observedGeneration and Programmed answer the latter. // +optional LastSyncTime *metav1.Time `json:"lastSyncTime,omitempty"` // Conditions: Programmed (the gateway carries this consumer's credentials). diff --git a/config/crd/bases/routing.modelsphere.dev_apiconsumers.yaml b/config/crd/bases/routing.modelsphere.dev_apiconsumers.yaml index ea102643..d5512fb4 100644 --- a/config/crd/bases/routing.modelsphere.dev_apiconsumers.yaml +++ b/config/crd/bases/routing.modelsphere.dev_apiconsumers.yaml @@ -204,8 +204,16 @@ spec: type: integer lastSyncTime: description: |- - LastSyncTime: when this object was last reconciled, including rounds that wrote - nothing. "Is the controller still looking at this", not "when did the gateway change". + LastSyncTime: when this object's status was last written — on every pass that changed + something, including the ones that failed before touching the gateway, and otherwise + once per resync interval as a heartbeat. It is NOT stamped on every pass: that write + is an update event on this object, which the controller watches, so an unconditional + stamp made each round trigger the next one — and a round here reads every consumer's + Secret uncached. + + So a value a little older than the resync interval means "settled, nothing to say", + not "stalled". It answers "is the controller still looking at this", not "when did the + gateway change"; observedGeneration and Programmed answer the latter. format: date-time type: string observedGeneration: diff --git a/deploy/helm/autoconfig/crds/routing.modelsphere.dev_apiconsumers.yaml b/deploy/helm/autoconfig/crds/routing.modelsphere.dev_apiconsumers.yaml index ea102643..d5512fb4 100644 --- a/deploy/helm/autoconfig/crds/routing.modelsphere.dev_apiconsumers.yaml +++ b/deploy/helm/autoconfig/crds/routing.modelsphere.dev_apiconsumers.yaml @@ -204,8 +204,16 @@ spec: type: integer lastSyncTime: description: |- - LastSyncTime: when this object was last reconciled, including rounds that wrote - nothing. "Is the controller still looking at this", not "when did the gateway change". + LastSyncTime: when this object's status was last written — on every pass that changed + something, including the ones that failed before touching the gateway, and otherwise + once per resync interval as a heartbeat. It is NOT stamped on every pass: that write + is an update event on this object, which the controller watches, so an unconditional + stamp made each round trigger the next one — and a round here reads every consumer's + Secret uncached. + + So a value a little older than the resync interval means "settled, nothing to say", + not "stalled". It answers "is the controller still looking at this", not "when did the + gateway change"; observedGeneration and Programmed answer the latter. format: date-time type: string observedGeneration: From de41e51dc3ef34a81730ca266bccc1e24aa06d5e Mon Sep 17 00:00:00 2001 From: zhanghao Date: Thu, 26 Nov 2026 15:44:00 +0800 Subject: [PATCH 07/28] APIConsumer: record an adoption even when it leaves the list unchanged 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 --- internal/controller/apiconsumer_controller.go | 28 ++++++++-- .../controller/apiconsumer_controller_test.go | 51 +++++++++++++++++++ 2 files changed, 76 insertions(+), 3 deletions(-) diff --git a/internal/controller/apiconsumer_controller.go b/internal/controller/apiconsumer_controller.go index 28c8a77b..6ad5a454 100644 --- a/internal/controller/apiconsumer_controller.go +++ b/internal/controller/apiconsumer_controller.go @@ -332,9 +332,18 @@ func (r *APIConsumerReconciler) writeConsumers(ctx context.Context, gwNS string, next = append(next, lc) } sortConsumerList(next) - if sameRules(live, next) { - // Unchanged: do not write. Every write here is an ECDS push of key-auth to the - // whole data plane, and the console calls this on every key edit. + // Unchanged AND already attributed: do not write. Every write here is an ECDS push + // of key-auth to the whole data plane, and the console calls this on every key edit. + // + // The second half is not decoration. Adopting a consumer whose entry the chart + // already renders, with the same credential, leaves the list byte-identical - so a + // check on the list alone returns early and never records that the entry is now + // OURS. That is how the live migration ended up with an annotation naming one of + // three adopted consumers: the first write recorded itself, and the next two were + // skipped as no-ops. Deleting either of those two would then have left its entry in + // place as somebody else's, and the key would have kept working - the one thing + // deleting an APIConsumer must never do. + if sameRules(live, next) && sameNames(managed, mine) { return nil } if err := unstructured.SetNestedSlice(obj.Object, next, "spec", "defaultConfig", "consumers"); err != nil { @@ -586,3 +595,16 @@ func (r *APIConsumerReconciler) claimConsumers(ctx context.Context, gwNS string, "gateway", gwNS, "entries", len(value)) return r.Patch(ctx, claim, client.Apply, client.ForceOwnership, client.FieldOwner(fieldManagerName)) } + +// sameNames: do the two name sets hold the same names? +func sameNames(a, b map[string]bool) bool { + if len(a) != len(b) { + return false + } + for n := range a { + if !b[n] { + return false + } + } + return true +} diff --git a/internal/controller/apiconsumer_controller_test.go b/internal/controller/apiconsumer_controller_test.go index 1c2ad1a6..595a27a6 100644 --- a/internal/controller/apiconsumer_controller_test.go +++ b/internal/controller/apiconsumer_controller_test.go @@ -809,3 +809,54 @@ func TestConsumerTakesOwnershipOfTheConsumerList(t *testing.T) { t.Fatalf("server-side applies = %d after four passes, want 1: the claim repeats", n) } } + +// Adopting a consumer whose entry the chart already renders, with the same credential, leaves +// the list byte-identical - so the "nothing changed, do not write" check returns early and the +// entry is never recorded as ours. Deleting that APIConsumer afterwards leaves its entry in +// place as somebody else's and the key keeps working, which is the one thing deleting a +// consumer must never do. +// +// Found on the live migration: three consumers were adopted and the annotation named one. +func TestConsumerAdoptionIsRecordedEvenWhenTheListDoesNotChange(t *testing.T) { + r, c := newConsumerReconciler(t, + consumerFixture("tenant-a", "tenant-a-keys"), + consumerFixture("tenant-b", "tenant-b-keys"), + credSecret("tenant-a-keys", map[string]string{"key": "sk-a"}), + credSecret("tenant-b-keys", map[string]string{"key": "sk-b"}), + // Exactly what the two APIConsumers render, so no round changes the list at all. + keyAuthWith(liveConsumer("tenant-a", "Bearer sk-a"), liveConsumer("tenant-b", "Bearer sk-b")), + ) + for _, n := range []string{"tenant-a", "tenant-b"} { + if err := reconcileConsumer(t, r, n); err != nil { + t.Fatal(err) + } + } + var ka unstructured.Unstructured + ka.SetGroupVersionKind(wasmPluginGVK) + if err := c.Get(context.Background(), types.NamespacedName{ + Namespace: "higress-system", Name: "key-auth"}, &ka); err != nil { + t.Fatal(err) + } + if got := ka.GetAnnotations()[managedConsumersAnnotation]; got != "tenant-a,tenant-b" { + t.Fatalf("managed-consumers = %q, want both: the second adoption was skipped as a no-op", got) + } + + // And the point of recording it: deleting one revokes its key. deletionTimestamp is + // immutable on an existing object, so the deletion is made the way the API server makes + // it - a Delete, which parks the object on its finalizer. + nn := types.NamespacedName{Namespace: "llm-route", Name: "tenant-b"} + var con routingv1.APIConsumer + if err := c.Get(context.Background(), nn, &con); err != nil { + t.Fatal(err) + } + if err := c.Delete(context.Background(), &con); err != nil { + t.Fatal(err) + } + if err := reconcileConsumer(t, r, "tenant-b"); err != nil { + t.Fatal(err) + } + names := consumerNames(gatewayConsumers(t, c, "higress-system")) + if strings.Join(names, ",") != "tenant-a" { + t.Fatalf("consumers = %v, want only tenant-a: the adopted entry was not revoked", names) + } +} From 249ae4eefa255bbebd6e6eccb0d0ab79d6f82897 Mon Sep 17 00:00:00 2001 From: zhanghao Date: Thu, 26 Nov 2026 15:46:07 +0800 Subject: [PATCH 08/28] APIConsumer: rename the test helper that collides with the fleet suite 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. --- .../controller/apiconsumer_controller_test.go | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/internal/controller/apiconsumer_controller_test.go b/internal/controller/apiconsumer_controller_test.go index 595a27a6..787f44f4 100644 --- a/internal/controller/apiconsumer_controller_test.go +++ b/internal/controller/apiconsumer_controller_test.go @@ -348,8 +348,8 @@ func TestConsumerDuplicateNameIsRefused(t *testing.T) { if condTrue(first.Status.Conditions, condProgrammed) { t.Fatal("two objects were allowed to claim one consumer name") } - if !strings.Contains(condMessage(first.Status.Conditions, condProgrammed), "team-b") { - t.Fatalf("the other claimant is not named: %q", condMessage(first.Status.Conditions, condProgrammed)) + if !strings.Contains(consumerCondMessage(first.Status.Conditions, condProgrammed), "team-b") { + t.Fatalf("the other claimant is not named: %q", consumerCondMessage(first.Status.Conditions, condProgrammed)) } if n := len(gatewayConsumers(t, c, "higress-system")); n != 0 { t.Fatalf("something was written anyway: %d consumers", n) @@ -475,9 +475,14 @@ func keyAuthInNamespace(ns string, consumers ...map[string]any) *unstructured.Un return o } -// condMessage: a condition's message, for tests that check the failure NAMES what went wrong -// rather than just that something did. -func condMessage(conds []metav1.Condition, typ string) string { +// consumerCondMessage: a condition's message, for tests that check the failure NAMES what +// went wrong rather than just that something did. +// +// Not called condMessage: the ModelFleet suite declares a helper of that name, and two files +// in one package cannot both declare it. On separate branches each builds fine and whichever +// merged second would fail on main - a collision git never reports as a conflict, because the +// two branches never touch the same file. +func consumerCondMessage(conds []metav1.Condition, typ string) string { for i := range conds { if conds[i].Type == typ { return conds[i].Message @@ -588,7 +593,7 @@ func TestConsumerDeleteKeepsTryingBeforeTheDeadline(t *testing.T) { if len(con.Finalizers) == 0 { t.Fatal("the finalizer was dropped although the key was never revoked") } - if msg := condMessage(con.Status.Conditions, condProgrammed); !strings.Contains(msg, "still retrying") { + if msg := consumerCondMessage(con.Status.Conditions, condProgrammed); !strings.Contains(msg, "still retrying") { t.Fatalf("the condition does not say it is still trying: %q", msg) } // The key is still live, which is the honest state - and the reason the object is held. From 4b3e5376fafba4c639e9612538f11b8c8f709fee Mon Sep 17 00:00:00 2001 From: zhanghao Date: Thu, 26 Nov 2026 17:03:32 +0800 Subject: [PATCH 09/28] APIConsumer: four review findings, the first of which could close the 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 --- internal/controller/apiconsumer_controller.go | 155 +++++++++++++--- .../controller/apiconsumer_controller_test.go | 167 ++++++++++++++++++ 2 files changed, 302 insertions(+), 20 deletions(-) diff --git a/internal/controller/apiconsumer_controller.go b/internal/controller/apiconsumer_controller.go index 6ad5a454..46836565 100644 --- a/internal/controller/apiconsumer_controller.go +++ b/internal/controller/apiconsumer_controller.go @@ -78,14 +78,29 @@ func (r *APIConsumerReconciler) Reconcile(ctx context.Context, req ctrl.Request) // reconciler only ever sees the objects that exist, so after the finalizer is // gone nothing would remember that this credential is still accepted. Deleting // an APIConsumer has to actually revoke the key. - // Not trusting status.appliedGatewayNamespace alone to decide there is nothing - // to revoke, tempting as it is for an object that was never programmed: a round - // that wrote the credential and then failed to write its own status leaves the - // key live with no record of it, and skipping the withdrawal would strand that - // key in key-auth for good. The two cases this would have saved are already - // covered - a misspelled gateway namespace has no key-auth to Get, which is the - // absent sentinel and releases at once, and anything else gives up at the - // deadline. + // Is there anything to revoke at all? status.appliedGatewayNamespace alone is + // not enough to say no - a round that wrote the credential and then failed to + // write its own status leaves the key live with no record of it, and skipping + // the withdrawal would strand that key for good. But status says nothing AND + // the live list holds no entry under this consumer's name is conclusive: there + // is no credential of ours in that gateway, so there is nothing to take out. + // + // Without this, the first APIConsumer on a not-yet-migrated gateway - created + // with a typo'd secret ref, so never programmed - sat in Terminating for the + // full revoke deadline when someone deleted it to try again: the round renders + // zero consumers over a non-empty chart-rendered list, which the empty-list + // guard refuses every time, reporting that a key could not be withdrawn when + // none was ever granted. + if consumer.Status.AppliedGatewayNamespace == "" { + if absent, err := r.hasNoLiveEntry(ctx, gwNS, consumerName(&consumer)); err == nil && absent { + log.V(1).Info("nothing to revoke: never programmed and no entry in the gateway", + "gateway", gwNS, "consumer", consumerName(&consumer)) + if err := r.patchConsumerFinalizer(ctx, &consumer, false); err != nil { + return ctrl.Result{}, err + } + return ctrl.Result{}, nil + } + } for _, ns := range distinctNamespaces(gwNS, consumer.Status.AppliedGatewayNamespace) { err := r.programGateway(ctx, ns, &consumer) // A gateway that is GONE needs no rewrite, and neither does one whose CRD @@ -104,7 +119,7 @@ func (r *APIConsumerReconciler) Reconcile(ctx context.Context, req ctrl.Request) r.setConsumerStatus(ctx, req.NamespacedName, metav1.ConditionFalse, "RevokeError", fmt.Sprintf("could not take this consumer out of gateway %q: %v "+ "(still retrying; the object is held until this succeeds or "+ - "%s has passed)", ns, err, consumerRevokeDeadline), 0, "") + "%s has passed)", ns, err, consumerRevokeDeadline), 0, "", "") return ctrl.Result{RequeueAfter: consumerResyncTime}, nil } log.Error(err, "giving up on revoking a consumer; releasing the object anyway", @@ -131,13 +146,13 @@ func (r *APIConsumerReconciler) Reconcile(ctx context.Context, req ctrl.Request) // reaches its NEW gateway - the one failure mode worse than a stale entry. if err := r.programGateway(ctx, old, nil); err != nil && !errors.Is(err, errGatewayAbsent) { r.setConsumerStatus(ctx, req.NamespacedName, metav1.ConditionFalse, "WithdrawError", - fmt.Sprintf("could not take this consumer out of its previous gateway %q: %v", old, err), 0, "") + fmt.Sprintf("could not take this consumer out of its previous gateway %q: %v", old, err), 0, "", "") return ctrl.Result{RequeueAfter: consumerResyncTime}, nil } } if err := r.programGateway(ctx, gwNS, nil); err != nil { - r.setConsumerStatus(ctx, req.NamespacedName, metav1.ConditionFalse, "ProgramError", err.Error(), 0, "") + r.setConsumerStatus(ctx, req.NamespacedName, metav1.ConditionFalse, "ProgramError", err.Error(), 0, "", "") return ctrl.Result{RequeueAfter: consumerResyncTime}, nil } @@ -146,13 +161,13 @@ func (r *APIConsumerReconciler) Reconcile(ctx context.Context, req ctrl.Request) if err != nil { // Cannot happen: programGateway just read the same Secret successfully. Reported // rather than ignored, because "cannot happen" and "is not checked" are different. - r.setConsumerStatus(ctx, req.NamespacedName, metav1.ConditionFalse, "SecretError", err.Error(), 0, name) + r.setConsumerStatus(ctx, req.NamespacedName, metav1.ConditionFalse, "SecretError", err.Error(), 0, name, "") return ctrl.Result{RequeueAfter: consumerResyncTime}, nil } log.V(1).Info("consumer programmed", "consumer", name, "gateway", gwNS, "credentials", len(creds)) r.setConsumerStatus(ctx, req.NamespacedName, metav1.ConditionTrue, "Programmed", fmt.Sprintf("%d credential(s) accepted by the gateway in %s", len(creds), gwNS), - int32(len(creds)), name) + int32(len(creds)), name, gwNS) return ctrl.Result{RequeueAfter: consumerResyncTime}, nil } @@ -179,10 +194,22 @@ func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, // still belongs to the chart". Both look like "zero objects want this gateway", and only // one of them may empty a live list. ownedBefore := false + // A second source of attribution, independent of the annotation on key-auth: the names + // APIConsumers themselves report having programmed into this gateway. The annotation is + // the only record for an object that is already gone, but it lives on an object we do + // not own - recreate or kubectl replace that WasmPlugin and it is lost. With only the + // annotation, deleting an APIConsumer after that would classify its own entry as + // somebody else's, carry it over, release the object without an error, and leave the + // revoked tenant's key working. Statuses cover every object that still exists, including + // the one being deleted. + claimed := map[string]bool{} for i := range list.Items { - if list.Items[i].Status.AppliedGatewayNamespace == gwNS { + c := &list.Items[i] + if c.Status.AppliedGatewayNamespace == gwNS { ownedBefore = true - break + if c.Status.ConsumerName != "" { + claimed[c.Status.ConsumerName] = true + } } } @@ -219,12 +246,13 @@ func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, if err != nil { return err } - return r.writeConsumers(ctx, gwNS, consumers, ownedBefore) + return r.writeConsumers(ctx, gwNS, consumers, ownedBefore, claimed) } // writeConsumers replaces defaultConfig.consumers in the gateway's key-auth plugin, leaving // every other key in that config alone. -func (r *APIConsumerReconciler) writeConsumers(ctx context.Context, gwNS string, consumers []sink.KeyAuthConsumer, ownedBefore bool) error { +func (r *APIConsumerReconciler) writeConsumers(ctx context.Context, gwNS string, + consumers []sink.KeyAuthConsumer, ownedBefore bool, claimed map[string]bool) error { log := logf.FromContext(ctx) return retry.RetryOnConflict(retry.DefaultRetry, func() error { obj := &unstructured.Unstructured{} @@ -325,13 +353,28 @@ func (r *APIConsumerReconciler) writeConsumers(ctx context.Context, gwNS string, return fmt.Errorf("%s/key-auth: a live consumer has no name; refusing to "+ "rewrite a list this controller cannot account for", gwNS) } - if mine[name] || managed[name] { + if mine[name] || managed[name] || claimed[name] { continue } foreign = append(foreign, name) next = append(next, lc) } sortConsumerList(next) + + // The duplicate-credential check has to run over the FINAL list, not only over the + // APIConsumers. sink.RenderConsumers refuses two APIConsumers sharing a key, but a + // carried-over entry is copied in verbatim and was never compared against ours - and + // key-auth does not care where a duplicate came from: it logs `duplicate consumer + // credential`, fails to parse the whole defaultConfig, and the plugin is FAIL_CLOSE, + // so every route on the gateway denies every caller. + // + // It is reachable on the documented migration path, not in theory: a chart entry + // whose name cannot be adopted (consumerName is pinned to a DNS label, and the + // chart's might not be one) gets a new APIConsumer carrying the SAME key, because + // the point is not to make the caller change anything. Both entries then exist. + if err := refuseDuplicateCredentials(gwNS, next); err != nil { + return err + } // Unchanged AND already attributed: do not write. Every write here is an ECDS push // of key-auth to the whole data plane, and the console calls this on every key edit. // @@ -412,8 +455,16 @@ func (r *APIConsumerReconciler) patchConsumerFinalizer(ctx context.Context, c *r return r.Patch(ctx, c, client.MergeFrom(before)) } +// setConsumerStatus records the outcome of one round. appliedGateway is the namespace this +// round actually programmed, passed in rather than re-read from the spec: the object is +// re-Get here, and a spec edit that lands between the write and this status update would +// otherwise record a gateway that was never programmed. The next round then compares +// status.appliedGatewayNamespace against the new spec, finds them equal, and never withdraws +// the credential from the gateway that really has it - the one failure this field exists to +// prevent. Empty means "no gateway was programmed in this round", which leaves the recorded +// one alone. func (r *APIConsumerReconciler) setConsumerStatus(ctx context.Context, nn types.NamespacedName, - status metav1.ConditionStatus, reason, msg string, creds int32, name string) { + status metav1.ConditionStatus, reason, msg string, creds int32, name, appliedGateway string) { log := logf.FromContext(ctx) err := retry.RetryOnConflict(retry.DefaultRetry, func() error { var c routingv1.APIConsumer @@ -427,7 +478,9 @@ func (r *APIConsumerReconciler) setConsumerStatus(ctx context.Context, nn types. // live yet", and advancing it on a failed round says yes while the gateway still // carries the old list. st.ObservedGeneration = c.Generation - st.AppliedGatewayNamespace = consumerGatewayNamespace(&c) + if appliedGateway != "" { + st.AppliedGatewayNamespace = appliedGateway + } st.ConsumerName = name st.Credentials = creds } @@ -608,3 +661,65 @@ func sameNames(a, b map[string]bool) bool { } return true } + +// refuseDuplicateCredentials rejects a list in which one credential appears under two +// consumers. Never written rather than written and hoped about: key-auth treats it as a parse +// error for the entire defaultConfig, and FAIL_CLOSE turns that into "no caller gets through +// on any route of this gateway". +// +// The message names the two consumers and never the credential: it lands on a CR, in the +// controller log, and in whatever ships those. +func refuseDuplicateCredentials(gwNS string, list []any) error { + owner := map[string]string{} + for _, entry := range list { + m, ok := entry.(map[string]any) + if !ok { + continue // already refused above; keep this function total + } + name, _ := m["name"].(string) + creds, _ := m["credentials"].([]any) + for i, c := range creds { + key, ok := c.(string) + if !ok { + return fmt.Errorf("%s/key-auth: consumer %q has a non-string credential at "+ + "position %d; refusing to write a list key-auth would reject", gwNS, name, i+1) + } + if prev, dup := owner[key]; dup { + return fmt.Errorf("%s/key-auth: consumers %q and %q share credential #%d. "+ + "key-auth refuses a duplicate credential and fails to parse its whole "+ + "configuration, which denies every caller on every route of this gateway, "+ + "so nothing was written. If %q is an entry this controller does not manage "+ + "(the gateway chart still renders it), give the APIConsumer its own key, or "+ + "adopt that entry by naming the APIConsumer after it", + gwNS, prev, name, i+1, prev) + } + owner[key] = name + } + } + return nil +} + +// hasNoLiveEntry: does this gateway's key-auth hold no consumer under this name? Used only to +// decide that a deletion has nothing to revoke, so an error or a missing gateway answers +// "cannot say" and the caller falls back to withdrawing properly. +func (r *APIConsumerReconciler) hasNoLiveEntry(ctx context.Context, gwNS, name string) (bool, error) { + obj := &unstructured.Unstructured{} + obj.SetGroupVersionKind(wasmPluginGVK) + if err := r.Get(ctx, types.NamespacedName{Namespace: gwNS, Name: "key-auth"}, obj); err != nil { + return false, err + } + live, _, err := unstructured.NestedSlice(obj.Object, "spec", "defaultConfig", "consumers") + if err != nil { + return false, err + } + for _, lc := range live { + m, ok := lc.(map[string]any) + if !ok { + return false, fmt.Errorf("unreadable consumer entry") + } + if n, _ := m["name"].(string); n == name { + return false, nil + } + } + return true, nil +} diff --git a/internal/controller/apiconsumer_controller_test.go b/internal/controller/apiconsumer_controller_test.go index 787f44f4..c8a57e8c 100644 --- a/internal/controller/apiconsumer_controller_test.go +++ b/internal/controller/apiconsumer_controller_test.go @@ -865,3 +865,170 @@ func TestConsumerAdoptionIsRecordedEvenWhenTheListDoesNotChange(t *testing.T) { t.Fatalf("consumers = %v, want only tenant-a: the adopted entry was not revoked", names) } } + +// A carried-over entry is copied in verbatim, so it was never compared against the +// credentials this controller renders - and key-auth does not care where a duplicate came +// from: it fails to parse the whole defaultConfig, and the plugin is FAIL_CLOSE, so every +// route on the gateway denies every caller. +// +// Reachable on the documented migration path: a chart entry whose name is not a DNS label +// cannot be adopted under that name (consumerName is pinned to one), so it gets a new +// APIConsumer carrying the SAME key - the whole point being that the caller changes nothing. +func TestConsumerRefusesACredentialSharedWithAForeignEntry(t *testing.T) { + r, c := newConsumerReconciler(t, + consumerFixture("tenant-a", "tenant-a-keys"), + credSecret("tenant-a-keys", map[string]string{"key": "sk-shared"}), + // The chart's entry, under a name no APIConsumer can take, with the same key. + keyAuthWith(liveConsumer("tenant_a", "Bearer sk-shared")), + ) + err := r.programGateway(context.Background(), "higress-system", nil) + if err == nil { + t.Fatal("wrote a list key-auth refuses to parse: every caller on the gateway would be denied") + } + for _, want := range []string{"tenant_a", "tenant-a", "every caller on every route"} { + if !strings.Contains(err.Error(), want) { + t.Fatalf("the error does not mention %s: %v", want, err) + } + } + if strings.Contains(err.Error(), "sk-shared") { + t.Fatalf("the error leaks the credential: %v", err) + } + // Nothing was written: the gateway keeps the list it had. + names := consumerNames(gatewayConsumers(t, c, "higress-system")) + if strings.Join(names, ",") != "tenant_a" { + t.Fatalf("consumers = %v, want the live list untouched", names) + } +} + +// status.appliedGatewayNamespace must record the gateway the round actually programmed, not +// the one the spec names when the status write lands. Otherwise a spec edit arriving in +// between makes the next round believe the credential is already where it should be, and it +// is never withdrawn from the gateway that really has it. +func TestConsumerStatusRecordsTheGatewayItProgrammed(t *testing.T) { + r, c := newConsumerReconciler(t, + consumerFixture("tenant-a", "tenant-a-keys"), + credSecret("tenant-a-keys", map[string]string{"key": "sk-a"}), + keyAuthWith(), + keyAuthInNamespace("higress-other"), + ) + if err := reconcileConsumer(t, r, "tenant-a"); err != nil { + t.Fatal(err) + } + nn := types.NamespacedName{Namespace: "llm-route", Name: "tenant-a"} + var con routingv1.APIConsumer + if err := c.Get(context.Background(), nn, &con); err != nil { + t.Fatal(err) + } + if got := con.Status.AppliedGatewayNamespace; got != "higress-system" { + t.Fatalf("appliedGatewayNamespace = %q, want higress-system", got) + } + // Now move it, and confirm the recorded value is what the NEW round programmed - which + // is also what makes the withdrawal from the old gateway happen. + con.Spec.Gateway.Namespace = "higress-other" + con.Generation = 2 + if err := c.Update(context.Background(), &con); err != nil { + t.Fatal(err) + } + if err := reconcileConsumer(t, r, "tenant-a"); err != nil { + t.Fatal(err) + } + if err := c.Get(context.Background(), nn, &con); err != nil { + t.Fatal(err) + } + if got := con.Status.AppliedGatewayNamespace; got != "higress-other" { + t.Fatalf("appliedGatewayNamespace = %q, want higress-other", got) + } + + // The failure this guards against is an interleaving inside ONE round - the gateway is + // programmed, then the spec changes, then the status write lands - which two sequential + // reconciles cannot reproduce: by the time the second one writes its status, the spec + // already says what it is about to record either way. So the contract is checked + // directly: what gets recorded is the gateway that was PROGRAMMED, even when the spec + // now names another one. + con.Spec.Gateway.Namespace = "higress-elsewhere" + if err := c.Update(context.Background(), &con); err != nil { + t.Fatal(err) + } + r.setConsumerStatus(context.Background(), nn, metav1.ConditionTrue, "Programmed", + "1 credential(s) accepted by the gateway in higress-other", 1, "tenant-a", "higress-other") + if err := c.Get(context.Background(), nn, &con); err != nil { + t.Fatal(err) + } + if got := con.Status.AppliedGatewayNamespace; got != "higress-other" { + t.Fatalf("appliedGatewayNamespace = %q, want the gateway that was programmed "+ + "(higress-other), not the one the spec now names - otherwise the next round "+ + "never withdraws the credential from where it actually is", got) + } + if n := len(consumerNames(gatewayConsumers(t, c, "higress-system"))); n != 0 { + t.Fatalf("the old gateway still accepts %d consumer(s)", n) + } + if n := len(consumerNames(gatewayConsumers(t, c, "higress-other"))); n != 1 { + t.Fatalf("the new gateway has %d consumer(s), want 1", n) + } +} + +// The annotation on key-auth is the only record for an object that is already gone, but it +// lives on an object this controller does not own: recreate that WasmPlugin and it is lost. +// With only the annotation, deleting an APIConsumer afterwards classifies its own entry as +// somebody else's, carries it over, and releases the object with no error - the revoked +// tenant's key keeps working. Every object that still exists reports its own name in status, +// so that is the second source. +func TestConsumerRevokesWhenTheAnnotationWasLost(t *testing.T) { + doomed := consumerFixture("tenant-b", "tenant-b-keys") + doomed.Status.ConsumerName = "tenant-b" + doomed.Status.AppliedGatewayNamespace = "higress-system" + r, c := newConsumerReconciler(t, + consumerFixture("tenant-a", "tenant-a-keys"), + doomed, + credSecret("tenant-a-keys", map[string]string{"key": "sk-a"}), + credSecret("tenant-b-keys", map[string]string{"key": "sk-b"}), + // Recreated key-auth: the entries are there, the annotation is not. + keyAuthWith(liveConsumer("tenant-a", "Bearer sk-a"), liveConsumer("tenant-b", "Bearer sk-b")), + ) + var con routingv1.APIConsumer + nn := types.NamespacedName{Namespace: "llm-route", Name: "tenant-b"} + if err := c.Get(context.Background(), nn, &con); err != nil { + t.Fatal(err) + } + if err := c.Delete(context.Background(), &con); err != nil { + t.Fatal(err) + } + if err := reconcileConsumer(t, r, "tenant-b"); err != nil { + t.Fatal(err) + } + names := consumerNames(gatewayConsumers(t, c, "higress-system")) + if strings.Join(names, ",") != "tenant-a" { + t.Fatalf("consumers = %v, want only tenant-a: the deleted tenant's key still works", names) + } +} + +// Deleting a consumer that was never programmed, on a gateway whose list still belongs to the +// chart, must not sit in Terminating waiting out the revoke deadline: rendering zero consumers +// over a non-empty list is refused by the empty-list guard on every pass, and it would report +// that a key could not be withdrawn when none was ever granted. +func TestConsumerDeleteOfANeverProgrammedObjectIsImmediate(t *testing.T) { + broken := consumerFixture("tenant-new", "secret-that-does-not-exist") + r, c := newConsumerReconciler(t, broken, + // The chart's list: non-empty, and nothing of ours in it. + keyAuthWith(liveConsumer("chart-a", "Bearer sk-chart-a")), + ) + var con routingv1.APIConsumer + nn := types.NamespacedName{Namespace: "llm-route", Name: "tenant-new"} + if err := c.Get(context.Background(), nn, &con); err != nil { + t.Fatal(err) + } + if err := c.Delete(context.Background(), &con); err != nil { + t.Fatal(err) + } + if err := reconcileConsumer(t, r, "tenant-new"); err != nil { + t.Fatal(err) + } + err := c.Get(context.Background(), nn, &con) + if err == nil && len(con.Finalizers) > 0 { + t.Fatalf("held in Terminating with nothing to revoke: %v", con.Finalizers) + } + // ...and the chart's list is untouched. + if n := len(consumerNames(gatewayConsumers(t, c, "higress-system"))); n != 1 { + t.Fatalf("the chart's list has %d entries, want 1", n) + } +} From fe63c8b8a5e8be9293955daca00cc913050dc199 Mon Sep 17 00:00:00 2001 From: zhanghao Date: Thu, 26 Nov 2026 17:12:11 +0800 Subject: [PATCH 10/28] APIConsumer: a name cannot be taken over without the key it already accepts 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 --- internal/controller/apiconsumer_controller.go | 149 +++++++++++++++-- .../controller/apiconsumer_controller_test.go | 152 ++++++++++++++++++ 2 files changed, 290 insertions(+), 11 deletions(-) diff --git a/internal/controller/apiconsumer_controller.go b/internal/controller/apiconsumer_controller.go index 46836565..965cebd8 100644 --- a/internal/controller/apiconsumer_controller.go +++ b/internal/controller/apiconsumer_controller.go @@ -213,6 +213,15 @@ func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, } } + // The names already in this gateway's list. Needed before rendering, to tell "this + // consumer's Secret is unreadable and it has a key in there" (fail closed) from "...and + // it has nothing in there" (skip it rather than freeze everyone else). + liveNames, err := r.liveConsumerNames(ctx, gwNS) + if err != nil && !errors.Is(err, errGatewayAbsent) { + return err + } + + var skipped []string views := make([]sink.ConsumerView, 0, len(list.Items)) for i := range list.Items { c := &list.Items[i] @@ -227,11 +236,24 @@ func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, } creds, err := r.readCredentials(ctx, c) if err != nil { - // Do NOT drop this consumer and write the rest. A consumer missing from the list - // is a caller that gets 401 on its next request, and a Secret that is briefly - // unreadable must not revoke someone's key. Refusing the whole write leaves the - // gateway on its last good list - every caller keeps working - and the failure - // is reported on the object that caused it. + // Fail closed for a consumer that HAS a key in this gateway: dropping it from + // the list is a 401 on its next request, and a Secret that is briefly + // unreadable must not revoke anyone. The whole round is refused, the gateway + // keeps its last good list, and the failure is reported on the object that + // caused it. + // + // But a consumer that was never programmed here has nothing in the list to + // lose, and refusing the round on its behalf freezes the gateway for everybody + // else: while a fresh object with a typo'd secretRef exists, no other consumer + // can be added, rotated or REVOKED - including removing a leaked key, and + // including a deletion, which then retries for the revoke deadline and + // releases with the key still live. One new broken object must not hold the + // rest hostage, so it is skipped, with the error on its own object. + if c.Status.AppliedGatewayNamespace != gwNS && + !claimed[consumerName(c)] && !hasLiveEntry(liveNames, consumerName(c)) { + skipped = append(skipped, fmt.Sprintf("%s/%s (%v)", c.Namespace, c.Name, err)) + continue + } return fmt.Errorf("%s/%s: %w (nothing was written; the gateway keeps its "+ "current consumer list)", c.Namespace, c.Name, err) } @@ -242,6 +264,10 @@ func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, }) } + if len(skipped) > 0 { + logf.FromContext(ctx).Info("skipped consumers that have nothing in this gateway yet", + "gateway", gwNS, "skipped", skipped) + } consumers, err := sink.RenderConsumers(views) if err != nil { return err @@ -310,6 +336,22 @@ func (r *APIConsumerReconciler) writeConsumers(ctx context.Context, gwNS string, // list is ours and emptying it is a revocation. If none does, the live entries came // from somewhere else (the chart, during a half-finished migration) and wiping them // would take the site's authentication down for a reason nobody asked for. + // Which names this controller wrote last time, read before the guard below because + // the guard needs it. + managed, err := managedConsumerNames(obj) + if err != nil { + return err + } + + // The annotation counts as ownership too, not only a status. Otherwise the last + // consumer on a gateway cannot be revoked in one specific case: its gateway write + // succeeded, its status write did not, and it is then deleted - no status claims the + // gateway, so ownedBefore is false, the guard refuses, the finalizer gives up at the + // deadline, and the key stays live with no APIConsumer left to clean it up. If the + // annotation says the live entries are ours, emptying the list IS the revocation. + if len(managed) > 0 { + ownedBefore = true + } if len(consumers) == 0 && len(live) > 0 && !ownedBefore { return fmt.Errorf("refusing to write an empty consumer list over %d live consumer(s) "+ "in %s/key-auth: no APIConsumer has ever programmed this gateway, so those "+ @@ -320,12 +362,17 @@ func (r *APIConsumerReconciler) writeConsumers(ctx context.Context, gwNS string, next := make([]any, 0, len(consumers)) mine := make(map[string]bool, len(consumers)) + myCreds := make(map[string]map[string]bool, len(consumers)) for _, c := range consumers { m, err := sink.ToMap(c) if err != nil { return err } mine[c.Name] = true + myCreds[c.Name] = make(map[string]bool, len(c.Credentials)) + for _, cred := range c.Credentials { + myCreds[c.Name][cred] = true + } next = append(next, m) } // Carry over the live entries this controller did not write. The empty-list guard @@ -337,10 +384,6 @@ func (r *APIConsumerReconciler) writeConsumers(ctx context.Context, gwNS string, // Anything whose name is not in managedConsumerNames is somebody else's and is kept // verbatim. A name this controller HAS managed is not carried over, because that is // what deleting an APIConsumer has to mean: the key stops working. - managed, err := managedConsumerNames(obj) - if err != nil { - return err - } var foreign []string for _, lc := range live { m, ok := lc.(map[string]any) @@ -353,7 +396,38 @@ func (r *APIConsumerReconciler) writeConsumers(ctx context.Context, gwNS string, return fmt.Errorf("%s/key-auth: a live consumer has no name; refusing to "+ "rewrite a list this controller cannot account for", gwNS) } - if mine[name] || managed[name] || claimed[name] { + if managed[name] || claimed[name] { + continue // already ours; this is a rotation, not an adoption + } + if mine[name] { + // Adopting an entry nobody has claimed before, by NAME. Taking it over has + // to require proof that the writer already holds the key, or the name is a + // free identity: an APIConsumer can be created in any namespace, its + // consumerName is free-form, and whatever it renders replaces the entry. A + // writer who put consumerName: tenant-a and their own key in their own + // Secret would inherit every route tenant-a is allowed on, and the real + // tenant-a would get 401 on its next request. Nothing else would notice: + // the names do not collide between APIConsumers, and no credential is + // shared, so neither existing guard fires. + // + // credentialsSecretRef is pinned to the object's own namespace for exactly + // this reason - a namespace-scoped writer is not trusted with other + // people's credentials - and an identity is worth no less than a key. + // + // The proof is: carry every credential the live entry already has. That is + // what a migration does anyway, because the point is that the caller + // changes nothing. Dropping an old key comes after adoption, as a rotation, + // when the entry is ours and no proof is needed. + if missing := credentialsNotCovered(m, myCreds[name]); missing > 0 { + return fmt.Errorf("%s/key-auth: consumer %q already exists in this "+ + "gateway and is not managed by any APIConsumer, and the APIConsumer "+ + "claiming that name does not carry %d of its %d existing "+ + "credential(s). Adopting an existing consumer requires its current "+ + "key(s), so that taking over a name cannot grant someone else's "+ + "access; nothing was written. Add the existing key to the Secret to "+ + "adopt it, then rotate, or give this APIConsumer a different "+ + "consumerName", gwNS, name, missing, liveCredentialCount(m)) + } continue } foreign = append(foreign, name) @@ -398,7 +472,14 @@ func (r *APIConsumerReconciler) writeConsumers(ctx context.Context, gwNS string, setManagedConsumerNames(obj, consumers) log.Info("programming gateway consumers", "gateway", gwNS, "mine", len(consumers), "carried over", len(foreign), "was", len(live)) - return r.Update(ctx, obj) + // FieldOwner spelled out, although the client's default manager happens to be this + // same name (measured on the test cluster: managedFields carries `autoconfig + // Update`). consumers is an atomic field, so if the default were ever something + // else - it is derived from the user agent, which a binary name or a library bump + // can change - each changing Update would move ownership away from the name + // ownsConsumers looks for, and every change would then cost a force-apply plus an + // Update: two config pushes where one belongs. + return r.Update(ctx, obj, client.FieldOwner(fieldManagerName)) }) } @@ -723,3 +804,49 @@ func (r *APIConsumerReconciler) hasNoLiveEntry(ctx context.Context, gwNS, name s } return true, nil } + +// credentialsNotCovered: how many of a live entry's credentials the rendered consumer does not +// carry. 0 means the writer demonstrably holds every key that entry already accepts. +func credentialsNotCovered(live map[string]any, rendered map[string]bool) int { + creds, _ := live["credentials"].([]any) + missing := 0 + for _, c := range creds { + key, ok := c.(string) + if !ok || !rendered[key] { + missing++ + } + } + return missing +} + +func liveCredentialCount(live map[string]any) int { + creds, _ := live["credentials"].([]any) + return len(creds) +} + +// liveConsumerNames: the consumer names this gateway's key-auth currently holds. +func (r *APIConsumerReconciler) liveConsumerNames(ctx context.Context, gwNS string) (map[string]bool, error) { + out := map[string]bool{} + obj := &unstructured.Unstructured{} + obj.SetGroupVersionKind(wasmPluginGVK) + if err := r.Get(ctx, types.NamespacedName{Namespace: gwNS, Name: "key-auth"}, obj); err != nil { + if isAbsent(err) { + return out, fmt.Errorf("key-auth in namespace %q: %w", gwNS, errGatewayAbsent) + } + return out, err + } + live, _, err := unstructured.NestedSlice(obj.Object, "spec", "defaultConfig", "consumers") + if err != nil { + return out, err + } + for _, lc := range live { + if m, ok := lc.(map[string]any); ok { + if n, _ := m["name"].(string); n != "" { + out[n] = true + } + } + } + return out, nil +} + +func hasLiveEntry(names map[string]bool, name string) bool { return names[name] } diff --git a/internal/controller/apiconsumer_controller_test.go b/internal/controller/apiconsumer_controller_test.go index c8a57e8c..80a1741c 100644 --- a/internal/controller/apiconsumer_controller_test.go +++ b/internal/controller/apiconsumer_controller_test.go @@ -1032,3 +1032,155 @@ func TestConsumerDeleteOfANeverProgrammedObjectIsImmediate(t *testing.T) { t.Fatalf("the chart's list has %d entries, want 1", n) } } + +// Taking over a consumer NAME that already exists in the gateway and belongs to nobody must +// require proof that the writer holds the key it already accepts. An APIConsumer can be +// created in any namespace with any consumerName, and whatever it renders replaces the entry +// - so without this, putting consumerName: tenant-a and your own key in your own Secret +// inherits every route tenant-a is allowed on, and the real tenant-a gets 401. Neither +// existing guard fires: the names do not collide between APIConsumers, and no credential is +// shared. +func TestConsumerCannotTakeOverANameWithoutItsKey(t *testing.T) { + r, c := newConsumerReconciler(t, + // Created in some other namespace, claiming the chart's consumer name. + func() client.Object { + o := consumerFixture("team-x-impostor", "team-x-keys") + o.Namespace = "team-x" + o.Spec.ConsumerName = "tenant-a" + return o + }(), + func() client.Object { + s := credSecret("team-x-keys", map[string]string{"key": "sk-attacker"}) + s.Namespace = "team-x" + return s + }(), + // The chart's entry, with the real key, managed by nobody. + keyAuthWith(liveConsumer("tenant-a", "Bearer sk-the-real-key")), + ) + err := r.programGateway(context.Background(), "higress-system", nil) + if err == nil { + t.Fatal("a foreign consumer name was taken over with a different key") + } + for _, want := range []string{"tenant-a", "existing", "consumerName"} { + if !strings.Contains(err.Error(), want) { + t.Fatalf("the error does not explain the refusal (%s missing): %v", want, err) + } + } + if strings.Contains(err.Error(), "sk-the-real-key") || strings.Contains(err.Error(), "sk-attacker") { + t.Fatalf("the error leaks a credential: %v", err) + } + // The real key still works: nothing was written. + creds := creds0Of(t, c, "higress-system", "tenant-a") + if strings.Join(creds, ",") != "Bearer sk-the-real-key" { + t.Fatalf("live credentials = %v, want the original untouched", creds) + } + + // ...and carrying the existing key DOES adopt it, which is what a migration does. + var imp routingv1.APIConsumer + if err := c.Get(context.Background(), types.NamespacedName{ + Namespace: "team-x", Name: "team-x-impostor"}, &imp); err != nil { + t.Fatal(err) + } + sec := credSecret("team-x-keys", map[string]string{"key": "sk-the-real-key"}) + sec.Namespace = "team-x" + if err := c.Update(context.Background(), sec); err != nil { + t.Fatal(err) + } + if err := r.programGateway(context.Background(), "higress-system", nil); err != nil { + t.Fatalf("adoption with the existing key was refused: %v", err) + } + if got := creds0Of(t, c, "higress-system", "tenant-a"); strings.Join(got, ",") != "Bearer sk-the-real-key" { + t.Fatalf("after adoption the credentials are %v", got) + } +} + +// A fresh object that has never been programmed must not stop every OTHER consumer on the +// gateway from being added, rotated or revoked. Fail-closed is for a consumer that has a key +// in the list and would lose it; one that has nothing in there loses nothing by being skipped, +// and holding the whole gateway hostage blocks exactly the operation you need in a hurry - +// removing a leaked key. +func TestConsumerBrokenNewObjectDoesNotFreezeTheGateway(t *testing.T) { + broken := consumerFixture("tenant-new", "secret-that-does-not-exist") + existing := consumerFixture("tenant-a", "tenant-a-keys") + existing.Status.ConsumerName = "tenant-a" + existing.Status.AppliedGatewayNamespace = "higress-system" + r, c := newConsumerReconciler(t, broken, existing, + credSecret("tenant-a-keys", map[string]string{"key": "sk-rotated"}), + keyAuthManagedBy("tenant-a", liveConsumer("tenant-a", "Bearer sk-old")), + ) + if err := r.programGateway(context.Background(), "higress-system", nil); err != nil { + t.Fatalf("one never-programmed object blocked the whole round: %v", err) + } + // tenant-a's rotation went through... + if got := creds0Of(t, c, "higress-system", "tenant-a"); strings.Join(got, ",") != "Bearer sk-rotated" { + t.Fatalf("tenant-a credentials = %v, want the rotated key", got) + } + // ...and the broken one is simply not in the list. + names := consumerNames(gatewayConsumers(t, c, "higress-system")) + if strings.Join(names, ",") != "tenant-a" { + t.Fatalf("consumers = %v, want only tenant-a", names) + } + + // But a consumer that IS in the list and whose Secret breaks still fails the round + // closed, because dropping it would revoke a working key. + if err := c.Delete(context.Background(), credSecret("tenant-a-keys", map[string]string{"key": "x"})); err != nil { + t.Fatal(err) + } + if err := r.programGateway(context.Background(), "higress-system", nil); err == nil { + t.Fatal("an unreadable Secret for a consumer that HAS a key did not fail the round") + } +} + +// creds0Of: one live consumer's credentials. +func creds0Of(t *testing.T, c client.Client, gwNS, name string) []string { + t.Helper() + for _, lc := range gatewayConsumers(t, c, gwNS) { + m := lc.(map[string]any) + if n, _ := m["name"].(string); n == name { + raw, _ := m["credentials"].([]any) + out := make([]string, 0, len(raw)) + for _, v := range raw { + out = append(out, v.(string)) + } + return out + } + } + return nil +} + +// Revoking the LAST consumer on a gateway, when no status claims that gateway any more. +// +// It happens when the gateway write succeeded and the status write that follows it did not - +// the key is live with no record on the object - and that object is then deleted. No status +// names the gateway, so "has this controller ever owned this list" cannot be answered from +// statuses alone, and the empty-list guard refuses: the finalizer gives up at the revoke +// deadline and the key stays live, with no APIConsumer left to ever clean it up. The +// annotation on key-auth knows better, and emptying a list that it says is ours IS the +// revocation. +func TestConsumerRevokesTheLastConsumerWithoutAStatus(t *testing.T) { + doomed := consumerFixture("tenant-a", "tenant-a-keys") + // Programmed, then the status write failed: no appliedGatewayNamespace. + doomed.Status.AppliedGatewayNamespace = "" + r, c := newConsumerReconciler(t, doomed, + credSecret("tenant-a-keys", map[string]string{"key": "sk-a"}), + // ...but the gateway's own annotation records the entry as ours. + keyAuthManagedBy("tenant-a", liveConsumer("tenant-a", "Bearer sk-a")), + ) + var con routingv1.APIConsumer + nn := types.NamespacedName{Namespace: "llm-route", Name: "tenant-a"} + if err := c.Get(context.Background(), nn, &con); err != nil { + t.Fatal(err) + } + if err := c.Delete(context.Background(), &con); err != nil { + t.Fatal(err) + } + if err := reconcileConsumer(t, r, "tenant-a"); err != nil { + t.Fatal(err) + } + if n := len(consumerNames(gatewayConsumers(t, c, "higress-system"))); n != 0 { + t.Fatalf("the gateway still accepts %d consumer(s): the key was never revoked", n) + } + if err := c.Get(context.Background(), nn, &con); err == nil && len(con.Finalizers) > 0 { + t.Fatalf("still held: %v", con.Finalizers) + } +} From ac23adfeea8611b622fb9cda867632d3d6662e2f Mon Sep 17 00:00:00 2001 From: zhanghao Date: Thu, 26 Nov 2026 17:22:35 +0800 Subject: [PATCH 11/28] APIConsumer: own the consumers key outright, including when no APIConsumer 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 --- cmd/main.go | 15 ++- internal/controller/apiconsumer_controller.go | 64 ++++++++++++- .../controller/apiconsumer_controller_test.go | 93 +++++++++++++++++++ 3 files changed, 168 insertions(+), 4 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 31006a3a..7d6b0a50 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -113,11 +113,22 @@ func runController(leaderElect bool) error { // the same reason - a cluster that only uses ModelRoute must not lose openresty peers // over a type it never asked for. if served["APIConsumer"] { - if err := (&controller.APIConsumerReconciler{ + consumers := &controller.APIConsumerReconciler{ Client: mgr.GetClient(), APIReader: mgr.GetAPIReader(), Scheme: mgr.GetScheme(), - }).SetupWithManager(mgr); err != nil { + } + if err := consumers.SetupWithManager(mgr); err != nil { + return err + } + // ...and a watch on the gateways' key-auth plugin itself. The gateway chart no + // longer renders defaultConfig.consumers, so this controller is the only thing that + // can create it - and key_auth cannot parse a defaultConfig without it (FAIL_CLOSE: + // the gateway refuses everything). A fresh install has zero APIConsumers, so the + // APIConsumer watch would never fire; this one does, and the event also says which + // namespace, so no default has to be configured or guessed. + if err := (&controller.KeyAuthReconciler{APIConsumerReconciler: consumers}). + SetupWithManager(mgr); err != nil { return err } } else { diff --git a/internal/controller/apiconsumer_controller.go b/internal/controller/apiconsumer_controller.go index 965cebd8..74055e2d 100644 --- a/internal/controller/apiconsumer_controller.go +++ b/internal/controller/apiconsumer_controller.go @@ -21,9 +21,11 @@ import ( "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/util/retry" ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/builder" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" logf "sigs.k8s.io/controller-runtime/pkg/log" + "sigs.k8s.io/controller-runtime/pkg/predicate" routingv1 "autoconfig/api/v1alpha1" "autoconfig/internal/sink" @@ -294,7 +296,7 @@ func (r *APIConsumerReconciler) writeConsumers(ctx context.Context, gwNS string, } return fmt.Errorf("key-auth in namespace %q: %w", gwNS, err) } - live, _, err := unstructured.NestedSlice(obj.Object, "spec", "defaultConfig", "consumers") + live, found, err := unstructured.NestedSlice(obj.Object, "spec", "defaultConfig", "consumers") if err != nil { return fmt.Errorf("read defaultConfig.consumers: %w", err) } @@ -460,7 +462,16 @@ func (r *APIConsumerReconciler) writeConsumers(ctx context.Context, gwNS string, // skipped as no-ops. Deleting either of those two would then have left its entry in // place as somebody else's, and the key would have kept working - the one thing // deleting an APIConsumer must never do. - if sameRules(live, next) && sameNames(managed, mine) { + // `found` first: an ABSENT consumers key is not the same as an empty one. key_auth's + // parsePluginConfig returns false when neither consumers nor credentials is present, + // and the plugin is FAIL_CLOSE - so a gateway whose key-auth has no consumers key at + // all refuses every request on every route. Writing the key, even empty, is what + // makes that config parse. Without this the early return fires (sameRules treats + // nil and [] as equal) and the key is never created. + // + // This is the gateway chart's side of the contract: it stopped rendering the field, + // so this controller is the only thing that can put it there. + if found && sameRules(live, next) && sameNames(managed, mine) { return nil } if err := unstructured.SetNestedSlice(obj.Object, next, "spec", "defaultConfig", "consumers"); err != nil { @@ -850,3 +861,52 @@ func (r *APIConsumerReconciler) liveConsumerNames(ctx context.Context, gwNS stri } func hasLiveEntry(names map[string]bool, name string) bool { return names[name] } + +// KeyAuthReconciler watches each gateway's key-auth WasmPlugin, which is what makes this +// controller responsible for a field no APIConsumer may exist to trigger. +// +// Three things need it, and the APIConsumer watch covers none of them: +// +// - A fresh install. helm creates key-auth WITHOUT a consumers key (the chart stopped +// rendering it), and nobody has created an APIConsumer yet. key_auth cannot parse a +// defaultConfig with neither consumers nor credentials, and the plugin is FAIL_CLOSE, so +// the gateway refuses everything until the key exists. With only an APIConsumer watch, +// zero objects means zero reconciles and it never does. +// - key-auth being deleted and recreated (uninstall/install, or by hand). Every consumer +// entry goes with it. The objects still exist, so their own resync would restore them +// within the resync interval, but a watch makes it immediate - and with zero objects the +// missing key would again never be written. +// - The namespace question. With no APIConsumer there is nothing to say WHICH gateway to +// look at. The event answers it: this fires for every key-auth in the cluster, so no +// configured default is needed and none is guessed. +type KeyAuthReconciler struct { + *APIConsumerReconciler +} + +func (r *KeyAuthReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + log := logf.FromContext(ctx) + // Same path as an APIConsumer round, deliberately: it renders every APIConsumer for this + // gateway AND guarantees the consumers key exists. Re-deriving a smaller "just ensure the + // key" write here would be a second way to write one field. + if err := r.programGateway(ctx, req.Namespace, nil); err != nil { + if errors.Is(err, errGatewayAbsent) { + return ctrl.Result{}, nil // deleted again; the next create re-triggers this + } + log.Error(err, "could not program the gateway from a key-auth event", "gateway", req.Namespace) + return ctrl.Result{RequeueAfter: consumerResyncTime}, nil + } + return ctrl.Result{}, nil +} + +func (r *KeyAuthReconciler) SetupWithManager(mgr ctrl.Manager) error { + keyAuth := &unstructured.Unstructured{} + keyAuth.SetGroupVersionKind(wasmPluginGVK) + return ctrl.NewControllerManagedBy(mgr). + For(keyAuth, builder.WithPredicates(predicate.NewPredicateFuncs(func(o client.Object) bool { + // Only the plugin this controller writes. Every other WasmPlugin on the cluster + // would otherwise enqueue a gateway round that has nothing to do. + return o.GetName() == "key-auth" + }))). + Named("keyauth"). + Complete(r) +} diff --git a/internal/controller/apiconsumer_controller_test.go b/internal/controller/apiconsumer_controller_test.go index 80a1741c..2623dcd1 100644 --- a/internal/controller/apiconsumer_controller_test.go +++ b/internal/controller/apiconsumer_controller_test.go @@ -1184,3 +1184,96 @@ func TestConsumerRevokesTheLastConsumerWithoutAStatus(t *testing.T) { t.Fatalf("still held: %v", con.Finalizers) } } + +// keyAuthWithoutConsumers: what the gateway chart creates now that it no longer renders the +// field - a key-auth with keys and global_auth and NO consumers key at all. +func keyAuthWithoutConsumers() *unstructured.Unstructured { + o := wasmPlugin("key-auth") + _ = unstructured.SetNestedField(o.Object, false, "spec", "defaultConfig", "global_auth") + _ = unstructured.SetNestedStringSlice(o.Object, []string{"x-higress-dummy-key"}, + "spec", "defaultConfig", "keys") + return o +} + +// The gateway chart stopped rendering defaultConfig.consumers, so this controller is the only +// thing that can create it - and key_auth's parsePluginConfig returns false when neither +// consumers nor credentials is present, with the plugin FAIL_CLOSE: the gateway refuses every +// request on every route until the key exists. +// +// The hard part is the trigger. A fresh install has ZERO APIConsumers, so the APIConsumer +// watch never fires; the key-auth watch does, and the event also says which namespace, so +// nothing has to be configured or guessed. +func TestKeyAuthWithoutConsumersGetsAnEmptyList(t *testing.T) { + r, c := newConsumerReconciler(t, keyAuthWithoutConsumers()) // no APIConsumer anywhere + kr := &KeyAuthReconciler{APIConsumerReconciler: r} + if _, err := kr.Reconcile(context.Background(), ctrl.Request{ + NamespacedName: types.NamespacedName{Namespace: "higress-system", Name: "key-auth"}, + }); err != nil { + t.Fatal(err) + } + var ka unstructured.Unstructured + ka.SetGroupVersionKind(wasmPluginGVK) + if err := c.Get(context.Background(), types.NamespacedName{ + Namespace: "higress-system", Name: "key-auth"}, &ka); err != nil { + t.Fatal(err) + } + live, found, err := unstructured.NestedSlice(ka.Object, "spec", "defaultConfig", "consumers") + if err != nil { + t.Fatal(err) + } + if !found { + t.Fatal("consumers is still absent: key_auth cannot parse this config and the " + + "gateway refuses every request (FAIL_CLOSE)") + } + if len(live) != 0 { + t.Fatalf("consumers = %v, want an empty list", live) + } + // The rest of defaultConfig is untouched - writing the key must not cost the others. + if keys, ok, _ := unstructured.NestedStringSlice(ka.Object, "spec", "defaultConfig", "keys"); !ok || len(keys) != 1 { + t.Fatal("defaultConfig.keys was lost") + } + if _, ok, _ := unstructured.NestedBool(ka.Object, "spec", "defaultConfig", "global_auth"); !ok { + t.Fatal("defaultConfig.global_auth was lost") + } +} + +// key-auth deleted and recreated takes every consumer entry with it. The objects still exist, +// so their own resync would restore them within the interval, but the watch makes it the next +// event instead - and the same path covers it, so there is no second way to write this field. +func TestKeyAuthRecreatedRestoresTheConsumers(t *testing.T) { + existing := consumerFixture("tenant-a", "tenant-a-keys") + existing.Status.ConsumerName = "tenant-a" + existing.Status.AppliedGatewayNamespace = "higress-system" + r, c := newConsumerReconciler(t, existing, + credSecret("tenant-a-keys", map[string]string{"key": "sk-a"}), + keyAuthWithoutConsumers(), // as helm just recreated it: no entries at all + ) + kr := &KeyAuthReconciler{APIConsumerReconciler: r} + if _, err := kr.Reconcile(context.Background(), ctrl.Request{ + NamespacedName: types.NamespacedName{Namespace: "higress-system", Name: "key-auth"}, + }); err != nil { + t.Fatal(err) + } + names := consumerNames(gatewayConsumers(t, c, "higress-system")) + if strings.Join(names, ",") != "tenant-a" { + t.Fatalf("consumers = %v, want tenant-a restored after the recreation", names) + } + if got := creds0Of(t, c, "higress-system", "tenant-a"); strings.Join(got, ",") != "Bearer sk-a" { + t.Fatalf("credentials = %v", got) + } +} + +// A key-auth that is gone again between the event and the round is not an error to retry. +func TestKeyAuthEventForAMissingGatewayIsNotAnError(t *testing.T) { + r, _ := newConsumerReconciler(t) + kr := &KeyAuthReconciler{APIConsumerReconciler: r} + res, err := kr.Reconcile(context.Background(), ctrl.Request{ + NamespacedName: types.NamespacedName{Namespace: "higress-gone", Name: "key-auth"}, + }) + if err != nil { + t.Fatalf("a deleted gateway was reported as an error: %v", err) + } + if res.RequeueAfter != 0 { + t.Fatalf("requeued after %v for a gateway that does not exist", res.RequeueAfter) + } +} From 7b6d79b26b81fd1acd9c3d366822b6ffa78dfe1f Mon Sep 17 00:00:00 2001 From: zhanghao Date: Thu, 26 Nov 2026 17:32:15 +0800 Subject: [PATCH 12/28] APIConsumer: a collision costs the newcomer, not the gateway 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 `, 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 --- internal/controller/apiconsumer_controller.go | 283 ++++++++++++++++-- .../controller/apiconsumer_controller_test.go | 124 +++++++- 2 files changed, 381 insertions(+), 26 deletions(-) diff --git a/internal/controller/apiconsumer_controller.go b/internal/controller/apiconsumer_controller.go index 74055e2d..0824fc25 100644 --- a/internal/controller/apiconsumer_controller.go +++ b/internal/controller/apiconsumer_controller.go @@ -104,7 +104,7 @@ func (r *APIConsumerReconciler) Reconcile(ctx context.Context, req ctrl.Request) } } for _, ns := range distinctNamespaces(gwNS, consumer.Status.AppliedGatewayNamespace) { - err := r.programGateway(ctx, ns, &consumer) + _, err := r.programGateway(ctx, ns, &consumer) // A gateway that is GONE needs no rewrite, and neither does one whose CRD // has been uninstalled: there is nothing left to revoke the key from. // Anything else - a misspelled namespace, an unreadable Secret belonging to @@ -146,17 +146,27 @@ func (r *APIConsumerReconciler) Reconcile(ctx context.Context, req ctrl.Request) // isAbsent: the gateway it used to be in has been uninstalled, so there is nothing // to take it out of. Retrying that forever would mean this consumer's key never // reaches its NEW gateway - the one failure mode worse than a stale entry. - if err := r.programGateway(ctx, old, nil); err != nil && !errors.Is(err, errGatewayAbsent) { + if _, err := r.programGateway(ctx, old, nil); err != nil && !errors.Is(err, errGatewayAbsent) { r.setConsumerStatus(ctx, req.NamespacedName, metav1.ConditionFalse, "WithdrawError", fmt.Sprintf("could not take this consumer out of its previous gateway %q: %v", old, err), 0, "", "") return ctrl.Result{RequeueAfter: consumerResyncTime}, nil } } - if err := r.programGateway(ctx, gwNS, nil); err != nil { + round, err := r.programGateway(ctx, gwNS, nil) + if err != nil { r.setConsumerStatus(ctx, req.NamespacedName, metav1.ConditionFalse, "ProgramError", err.Error(), 0, "", "") return ctrl.Result{RequeueAfter: consumerResyncTime}, nil } + // This object was left out of the round on purpose - a collision with somebody already + // serving traffic, or a Secret this controller cannot read. The round succeeded for + // everyone else, so there is nothing to retry quickly; the reason goes on this object, + // where whoever created it will look. + if why := round.reasonFor(&consumer); why != "" { + r.setConsumerStatus(ctx, req.NamespacedName, metav1.ConditionFalse, "NotProgrammed", + why, 0, "", "") + return ctrl.Result{RequeueAfter: consumerResyncTime}, nil + } name := consumerName(&consumer) creds, err := r.readCredentials(ctx, &consumer) @@ -182,13 +192,29 @@ func (r *APIConsumerReconciler) Reconcile(ctx context.Context, req ctrl.Request) // only failure that means "there is nothing left to revoke a key from". var errGatewayAbsent = errors.New("the gateway's key-auth is not present") -func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, excluding *routingv1.APIConsumer) error { +// gatewayRound reports what one programming round did with objects it could not include. +// Keyed by "namespace/name", the value is why. It exists because this round is shared by every +// APIConsumer on the gateway: a newcomer that cannot be rendered must not fail the round for +// everybody else, but it still has to learn about it on its own object, so skipping it +// silently is not an option either. +type gatewayRound struct { + skipped map[string]string +} + +func (g gatewayRound) reasonFor(c *routingv1.APIConsumer) string { + if g.skipped == nil || c == nil { + return "" + } + return g.skipped[c.Namespace+"/"+c.Name] +} + +func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, excluding *routingv1.APIConsumer) (gatewayRound, error) { var list routingv1.APIConsumerList if err := r.List(ctx, &list); err != nil { // A failed list renders an empty consumer list, which is the single most dangerous // write this controller can make: it would lock every caller out of every route. // Never guess from a partial read. - return fmt.Errorf("list APIConsumers: %w", err) + return gatewayRound{}, fmt.Errorf("list APIConsumers: %w", err) } // Has this controller ever programmed THIS gateway? It is the difference between "the @@ -220,10 +246,43 @@ func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, // it has nothing in there" (skip it rather than freeze everyone else). liveNames, err := r.liveConsumerNames(ctx, gwNS) if err != nil && !errors.Is(err, errGatewayAbsent) { - return err + return gatewayRound{}, err } - var skipped []string + round := gatewayRound{skipped: map[string]string{}} + // incumbent: is the entry under this consumer's name in this gateway THIS object's? + // Everything that can go wrong with a newcomer is survivable by leaving it out; the same + // thing wrong with an incumbent means refusing the round, because dropping it revokes a + // working key. + // + // Not "is there an entry under that name", which is what this asked first and is a hole: + // an object whose consumerName names somebody else's live entry would have counted as an + // incumbent, so an impostor and the consumer it was impersonating came out as two + // incumbents and the round was refused for the whole gateway - exactly the freeze this + // is here to avoid, and with the impersonation deciding it. + // + // Its own status is conclusive. 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 skipping it WOULD revoke a live key. + incumbent := func(c *routingv1.APIConsumer) bool { + if c.Status.AppliedGatewayNamespace == gwNS { + return true + } + name := consumerName(c) + if !hasLiveEntry(liveNames, name) { + return false + } + for i := range list.Items { + o := &list.Items[i] + if o.Namespace == c.Namespace && o.Name == c.Name { + continue + } + if o.Status.AppliedGatewayNamespace == gwNS && o.Status.ConsumerName == name { + return false // that entry is on record as somebody else's + } + } + return true + } views := make([]sink.ConsumerView, 0, len(list.Items)) for i := range list.Items { c := &list.Items[i] @@ -251,12 +310,11 @@ func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, // including a deletion, which then retries for the revoke deadline and // releases with the key still live. One new broken object must not hold the // rest hostage, so it is skipped, with the error on its own object. - if c.Status.AppliedGatewayNamespace != gwNS && - !claimed[consumerName(c)] && !hasLiveEntry(liveNames, consumerName(c)) { - skipped = append(skipped, fmt.Sprintf("%s/%s (%v)", c.Namespace, c.Name, err)) + if !incumbent(c) { + round.skipped[c.Namespace+"/"+c.Name] = err.Error() continue } - return fmt.Errorf("%s/%s: %w (nothing was written; the gateway keeps its "+ + return round, fmt.Errorf("%s/%s: %w (nothing was written; the gateway keeps its "+ "current consumer list)", c.Namespace, c.Name, err) } views = append(views, sink.ConsumerView{ @@ -266,15 +324,160 @@ func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, }) } - if len(skipped) > 0 { - logf.FromContext(ctx).Info("skipped consumers that have nothing in this gateway yet", - "gateway", gwNS, "skipped", skipped) + // A newcomer that collides with somebody already here - same consumer name, or the same + // credential - is dropped the same way an unreadable Secret is, and for the same reason. + // RenderConsumers refuses the whole view set on a collision, which is right as a last + // line of defence but wrong as the response to one new object: it would freeze every key + // on the gateway, including REVOKING a leaked one, and a deletion in flight would retry + // to the deadline and then release with the key still live. + // + // The refusals themselves stay - the duplicate-name check is what stops a + // namespace-scoped writer from stealing a managed consumer name, and the duplicate + // credential one is what stops a gateway-wide parse failure. Only who pays for the + // collision changes: the newcomer, not everybody. + views, err = r.dropCollidingNewcomers(ctx, views, list.Items, gwNS, incumbent, round) + if err != nil { + return round, err + } + + if len(round.skipped) > 0 { + logf.FromContext(ctx).Info("left consumers out of this round", + "gateway", gwNS, "skipped", round.skipped) } consumers, err := sink.RenderConsumers(views) if err != nil { - return err + return round, err + } + return round, r.writeConsumers(ctx, gwNS, consumers, ownedBefore, claimed) +} + +// dropCollidingNewcomers resolves two claims on one identity - the same consumer name, or the +// same credential - without failing the round for everybody else on the gateway. +// +// RenderConsumers refuses a colliding view set outright, which is right as a last line of +// defence and wrong as the response to one new object: it would freeze every key on this +// gateway, including REVOKING a leaked one, and a deletion in flight would retry to the +// deadline and then release with the key still live. +// +// Who pays for the collision: +// +// - exactly one claimant is already serving traffic here: it keeps the identity, and every +// newcomer is left out and told why. This is what stops a namespace-scoped writer from +// taking a name that belongs to someone else. +// - nobody is serving it yet: ALL the claimants are left out. Letting the first one win +// would be arbitrating "who is tenant-a" by list order, which is a coin flip in a +// dispute - and nobody is losing access, because nobody had the name. +// - two claimants are already serving it: refused as an error. One bad newcomer cannot +// produce this, it means two live consumers genuinely share an identity, and dropping +// either revokes a working key. A person has to look. +func (r *APIConsumerReconciler) dropCollidingNewcomers(ctx context.Context, + views []sink.ConsumerView, items []routingv1.APIConsumer, gwNS string, + incumbent func(*routingv1.APIConsumer) bool, round gatewayRound) ([]sink.ConsumerView, error) { + bySource := map[string]*routingv1.APIConsumer{} + for i := range items { + bySource[items[i].Namespace+"/"+items[i].Name] = &items[i] + } + isIncumbent := func(v sink.ConsumerView) bool { + c, ok := bySource[v.Source] + return ok && incumbent(c) + } + + // claims[identity] = the views claiming it, in list order. + type claim struct { + kind string // "consumer name" or "credential" + views []sink.ConsumerView + } + claims := map[string]*claim{} + add := func(kind, identity string, v sink.ConsumerView) { + key := kind + "\x00" + identity + if claims[key] == nil { + claims[key] = &claim{kind: kind} + } + claims[key].views = append(claims[key].views, v) + } + for _, v := range views { + add("consumer name", v.Name, v) + for _, cred := range v.Credentials { + // By credential VALUE, which is never put in a message. + add("credential", cred, v) + } + } + + drop := map[string]string{} // Source -> reason + for key, cl := range claims { + if len(cl.views) < 2 { + continue + } + identity := key[strings.Index(key, "\x00")+1:] + var incumbents, newcomers []sink.ConsumerView + for _, v := range cl.views { + if isIncumbent(v) { + incumbents = append(incumbents, v) + } else { + newcomers = append(newcomers, v) + } + } + switch { + case len(incumbents) > 1: + if cl.kind == "credential" { + return nil, fmt.Errorf("%s/key-auth: %d consumers already serving this "+ + "gateway share one credential; key-auth refuses a duplicate credential "+ + "and fails to parse its whole configuration, which denies every caller "+ + "on every route. Nothing was written, and this needs a person: dropping "+ + "either of them revokes a working key. The objects are %s", + gwNS, len(incumbents), sourcesOf(incumbents)) + } + return nil, fmt.Errorf("%s/key-auth: consumer name %q is claimed by %s, and more "+ + "than one of them is already serving this gateway. Nothing was written, and "+ + "this needs a person: dropping either revokes a working key", + gwNS, identity, sourcesOf(incumbents)) + case len(incumbents) == 1: + for _, v := range newcomers { + drop[v.Source] = collisionReason(cl.kind, identity, gwNS, + "it is already served by "+incumbents[0].Source) + } + default: + for _, v := range cl.views { + drop[v.Source] = collisionReason(cl.kind, identity, gwNS, + "it is claimed by "+sourcesOf(cl.views)+" and nothing here serves it yet, "+ + "so none of them was given it - which of these objects owns this "+ + "identity is not something this controller may decide") + } + } + } + if len(drop) == 0 { + return views, nil + } + kept := make([]sink.ConsumerView, 0, len(views)) + for _, v := range views { + if why, dropped := drop[v.Source]; dropped { + round.skipped[v.Source] = why + continue + } + kept = append(kept, v) + } + _ = ctx + return kept, nil +} + +// collisionReason: never names the credential, only what collided and with whom. This text +// lands on a CR and in the logs. +func collisionReason(kind, identity, gwNS, who string) string { + what := fmt.Sprintf("consumer name %q", identity) + if kind == "credential" { + what = "one of this object's credentials" } - return r.writeConsumers(ctx, gwNS, consumers, ownedBefore, claimed) + return fmt.Sprintf("%s collides on gateway %s: %s. This object was left out of the "+ + "gateway; everything else on it is unaffected", what, gwNS, who) +} + +func sourcesOf(views []sink.ConsumerView) string { + out := make([]string, 0, len(views)) + for _, v := range views { + out = append(out, v.Source) + } + sort.Strings(out) + return strings.Join(out, " and ") } // writeConsumers replaces defaultConfig.consumers in the gateway's key-auth plugin, leaving @@ -420,6 +623,17 @@ func (r *APIConsumerReconciler) writeConsumers(ctx context.Context, gwNS string, // what a migration does anyway, because the point is that the caller // changes nothing. Dropping an old key comes after adoption, as a rotation, // when the entry is ours and no proof is needed. + if reformatted := credentialsReformatted(m, myCreds[name]); reformatted { + // Adoption is allowed - the writer holds the key - but the entry's + // credential changes spelling, from a bare key to `Bearer `, and + // key_auth compares the WHOLE Authorization header. A caller that was + // sending the bare form will start getting 401. Said out loud, because + // nothing else would say it. + logf.FromContext(ctx).Info("adopting a consumer whose credential was "+ + "stored without the Bearer prefix; callers must send "+ + "`Authorization: Bearer ` from now on", + "gateway", gwNS, "consumer", name) + } if missing := credentialsNotCovered(m, myCreds[name]); missing > 0 { return fmt.Errorf("%s/key-auth: consumer %q already exists in this "+ "gateway and is not managed by any APIConsumer, and the APIConsumer "+ @@ -820,16 +1034,33 @@ func (r *APIConsumerReconciler) hasNoLiveEntry(ctx context.Context, gwNS, name s // carry. 0 means the writer demonstrably holds every key that entry already accepts. func credentialsNotCovered(live map[string]any, rendered map[string]bool) int { creds, _ := live["credentials"].([]any) + // Compared with the prefix stripped from BOTH sides. The rendered set is already + // prefixed, so a live entry stored bare could never be matched by any Secret content: + // `sk-x` renders as `Bearer sk-x`, and `Bearer sk-x` renders as the same thing, so the + // proof was impossible and the refusal told the operator to add a key they had already + // added. Possession of the key is the question here; how the entry spells it is not. + // + // Live entries do carry the prefix on these clusters (the gateway chart requires it), but + // a hand-written one need not, and ModelFleet's own checkAuth strips it for the same + // reason. + bare := make(map[string]bool, len(rendered)) + for c := range rendered { + bare[strings.TrimPrefix(c, bearerPrefixValue)] = true + } missing := 0 for _, c := range creds { key, ok := c.(string) - if !ok || !rendered[key] { + if !ok || !bare[strings.TrimPrefix(key, bearerPrefixValue)] { missing++ } } return missing } +// bearerPrefixValue mirrors sink's prefix. Duplicated rather than exported, because the sink +// owns how a credential is RENDERED and this is only about recognising one. +const bearerPrefixValue = "Bearer " + func liveCredentialCount(live map[string]any) int { creds, _ := live["credentials"].([]any) return len(creds) @@ -888,7 +1119,7 @@ func (r *KeyAuthReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct // Same path as an APIConsumer round, deliberately: it renders every APIConsumer for this // gateway AND guarantees the consumers key exists. Re-deriving a smaller "just ensure the // key" write here would be a second way to write one field. - if err := r.programGateway(ctx, req.Namespace, nil); err != nil { + if _, err := r.programGateway(ctx, req.Namespace, nil); err != nil { if errors.Is(err, errGatewayAbsent) { return ctrl.Result{}, nil // deleted again; the next create re-triggers this } @@ -910,3 +1141,19 @@ func (r *KeyAuthReconciler) SetupWithManager(mgr ctrl.Manager) error { Named("keyauth"). Complete(r) } + +// credentialsReformatted: would adoption keep the same key but change how it is spelled? True +// when a live credential lacks the prefix the rendered one carries. +func credentialsReformatted(live map[string]any, rendered map[string]bool) bool { + creds, _ := live["credentials"].([]any) + for _, c := range creds { + key, ok := c.(string) + if !ok || strings.HasPrefix(key, bearerPrefixValue) { + continue + } + if rendered[bearerPrefixValue+key] { + return true + } + } + return false +} diff --git a/internal/controller/apiconsumer_controller_test.go b/internal/controller/apiconsumer_controller_test.go index 2623dcd1..0d867860 100644 --- a/internal/controller/apiconsumer_controller_test.go +++ b/internal/controller/apiconsumer_controller_test.go @@ -264,7 +264,7 @@ func TestConsumerRefusesToEmptyTheGateway(t *testing.T) { r, c := newConsumerReconciler(t, keyAuthWith(liveConsumer("tenant-a", "sk-a"), liveConsumer("ops", "sk-ops")), ) - err := r.programGateway(context.Background(), "higress-system", nil) + _, err := r.programGateway(context.Background(), "higress-system", nil) if err == nil { t.Fatal("an empty consumer list was written over a live gateway") } @@ -441,7 +441,7 @@ func TestConsumerListFailureWritesNothing(t *testing.T) { }).Build() r := &APIConsumerReconciler{Client: c, APIReader: c, Scheme: s} - err := r.programGateway(context.Background(), "higress-system", nil) + _, err := r.programGateway(context.Background(), "higress-system", nil) if err == nil { t.Fatal("a failed list was treated as an empty consumer set") } @@ -540,7 +540,7 @@ func TestConsumerRefusesAnUnreadableLiveList(t *testing.T) { credSecret("tenant-new-keys", map[string]string{"key": "sk-new"}), keyAuthWith(map[string]any{"credentials": []any{"sk-x"}}), // no name ) - err := r.programGateway(context.Background(), "higress-system", nil) + _, err := r.programGateway(context.Background(), "higress-system", nil) if err == nil || !strings.Contains(err.Error(), "no name") { t.Fatalf("expected a refusal naming the problem, got %v", err) } @@ -881,7 +881,7 @@ func TestConsumerRefusesACredentialSharedWithAForeignEntry(t *testing.T) { // The chart's entry, under a name no APIConsumer can take, with the same key. keyAuthWith(liveConsumer("tenant_a", "Bearer sk-shared")), ) - err := r.programGateway(context.Background(), "higress-system", nil) + _, err := r.programGateway(context.Background(), "higress-system", nil) if err == nil { t.Fatal("wrote a list key-auth refuses to parse: every caller on the gateway would be denied") } @@ -1057,7 +1057,7 @@ func TestConsumerCannotTakeOverANameWithoutItsKey(t *testing.T) { // The chart's entry, with the real key, managed by nobody. keyAuthWith(liveConsumer("tenant-a", "Bearer sk-the-real-key")), ) - err := r.programGateway(context.Background(), "higress-system", nil) + _, err := r.programGateway(context.Background(), "higress-system", nil) if err == nil { t.Fatal("a foreign consumer name was taken over with a different key") } @@ -1086,7 +1086,7 @@ func TestConsumerCannotTakeOverANameWithoutItsKey(t *testing.T) { if err := c.Update(context.Background(), sec); err != nil { t.Fatal(err) } - if err := r.programGateway(context.Background(), "higress-system", nil); err != nil { + if _, err := r.programGateway(context.Background(), "higress-system", nil); err != nil { t.Fatalf("adoption with the existing key was refused: %v", err) } if got := creds0Of(t, c, "higress-system", "tenant-a"); strings.Join(got, ",") != "Bearer sk-the-real-key" { @@ -1108,7 +1108,7 @@ func TestConsumerBrokenNewObjectDoesNotFreezeTheGateway(t *testing.T) { credSecret("tenant-a-keys", map[string]string{"key": "sk-rotated"}), keyAuthManagedBy("tenant-a", liveConsumer("tenant-a", "Bearer sk-old")), ) - if err := r.programGateway(context.Background(), "higress-system", nil); err != nil { + if _, err := r.programGateway(context.Background(), "higress-system", nil); err != nil { t.Fatalf("one never-programmed object blocked the whole round: %v", err) } // tenant-a's rotation went through... @@ -1126,7 +1126,7 @@ func TestConsumerBrokenNewObjectDoesNotFreezeTheGateway(t *testing.T) { if err := c.Delete(context.Background(), credSecret("tenant-a-keys", map[string]string{"key": "x"})); err != nil { t.Fatal(err) } - if err := r.programGateway(context.Background(), "higress-system", nil); err == nil { + if _, err := r.programGateway(context.Background(), "higress-system", nil); err == nil { t.Fatal("an unreadable Secret for a consumer that HAS a key did not fail the round") } } @@ -1277,3 +1277,111 @@ func TestKeyAuthEventForAMissingGatewayIsNotAnError(t *testing.T) { t.Fatalf("requeued after %v for a gateway that does not exist", res.RequeueAfter) } } + +// One new object that collides must not freeze consumer management for the whole gateway. +// RenderConsumers refuses a colliding view set, and letting that error out of programGateway +// meant nobody on the gateway could be added, rotated or REVOKED - including pulling a leaked +// key - and a deletion in flight would retry to the revoke deadline and then release with the +// key still live. +func TestConsumerCollidingNewcomerDoesNotFreezeTheGateway(t *testing.T) { + serving := consumerFixture("tenant-a", "tenant-a-keys") + serving.Status.ConsumerName = "tenant-a" + serving.Status.AppliedGatewayNamespace = "higress-system" + // A newcomer in its own namespace, claiming the name that tenant-a is serving. + impostor := consumerFixture("team-x", "team-x-keys") + impostor.Namespace = "team-x" + impostor.Spec.ConsumerName = "tenant-a" + xsec := credSecret("team-x-keys", map[string]string{"key": "sk-x"}) + xsec.Namespace = "team-x" + r, c := newConsumerReconciler(t, serving, impostor, xsec, + credSecret("tenant-a-keys", map[string]string{"key": "sk-rotated"}), + keyAuthManagedBy("tenant-a", liveConsumer("tenant-a", "Bearer sk-old")), + ) + // tenant-a's rotation must go through despite the collision... + if err := reconcileConsumer(t, r, "tenant-a"); err != nil { + t.Fatalf("the colliding newcomer froze the round: %v", err) + } + if got := creds0Of(t, c, "higress-system", "tenant-a"); strings.Join(got, ",") != "Bearer sk-rotated" { + t.Fatalf("tenant-a credentials = %v, want the rotated key", got) + } + // ...and the newcomer learns why it is not in the gateway, on its own object. + if err := reconcileConsumer2(t, r, "team-x", "team-x"); err != nil { + t.Fatal(err) + } + var imp routingv1.APIConsumer + if err := c.Get(context.Background(), types.NamespacedName{ + Namespace: "team-x", Name: "team-x"}, &imp); err != nil { + t.Fatal(err) + } + if condTrue(imp.Status.Conditions, condProgrammed) { + t.Fatal("the newcomer reports Programmed although it was left out") + } + msg := consumerCondMessage(imp.Status.Conditions, condProgrammed) + for _, want := range []string{"tenant-a", "llm-route/tenant-a", "left out"} { + if !strings.Contains(msg, want) { + t.Fatalf("the message does not say what happened (%s missing): %q", want, msg) + } + } + // The impostor's key is not in the gateway. + if got := creds0Of(t, c, "higress-system", "tenant-a"); strings.Contains(strings.Join(got, ","), "sk-x") { + t.Fatalf("the newcomer's key reached the gateway: %v", got) + } +} + +// Two claimants and nobody serving the name yet: neither gets it. Letting the first win would +// arbitrate "who is tenant-a" by list order, and nobody loses access by refusing, because +// nobody had the name. +func TestConsumerTwoNewcomersGetNeitherTheName(t *testing.T) { + a := consumerFixture("team-a", "a-keys") + a.Spec.ConsumerName = "shared" + b := consumerFixture("team-b", "b-keys") + b.Spec.ConsumerName = "shared" + r, c := newConsumerReconciler(t, a, b, + credSecret("a-keys", map[string]string{"key": "sk-a"}), + credSecret("b-keys", map[string]string{"key": "sk-b"}), + keyAuthWith(), + ) + if err := reconcileConsumer(t, r, "team-a"); err != nil { + t.Fatal(err) + } + if n := len(gatewayConsumers(t, c, "higress-system")); n != 0 { + t.Fatalf("%d consumer(s) written: one of two disputed claims was granted", n) + } + var first routingv1.APIConsumer + _ = c.Get(context.Background(), types.NamespacedName{Namespace: "llm-route", Name: "team-a"}, &first) + if condTrue(first.Status.Conditions, condProgrammed) { + t.Fatal("a disputed name was granted") + } + if msg := consumerCondMessage(first.Status.Conditions, condProgrammed); !strings.Contains(msg, "team-b") { + t.Fatalf("the other claimant is not named: %q", msg) + } +} + +// A live entry whose credential is stored WITHOUT the Bearer prefix must still be adoptable by +// whoever holds that key. The rendered side is always prefixed, so comparing verbatim made the +// proof impossible - no Secret content could satisfy it - while the refusal told the operator +// to add a key they had already added. +func TestConsumerAdoptsAnEntryStoredWithoutThePrefix(t *testing.T) { + r, c := newConsumerReconciler(t, + consumerFixture("tenant-a", "tenant-a-keys"), + credSecret("tenant-a-keys", map[string]string{"key": "sk-bare"}), + // Written by hand, or by something that did not add the prefix. + keyAuthWith(liveConsumer("tenant-a", "sk-bare")), + ) + if _, err := r.programGateway(context.Background(), "higress-system", nil); err != nil { + t.Fatalf("adoption refused although the Secret holds that very key: %v", err) + } + // Adopted, and now rendered in the form key_auth actually compares against. + if got := creds0Of(t, c, "higress-system", "tenant-a"); strings.Join(got, ",") != "Bearer sk-bare" { + t.Fatalf("credentials = %v, want the prefixed form", got) + } +} + +// reconcileConsumer2: reconcile an object outside the default namespace. +func reconcileConsumer2(t *testing.T, r *APIConsumerReconciler, ns, name string) error { + t.Helper() + _, err := r.Reconcile(context.Background(), ctrl.Request{ + NamespacedName: types.NamespacedName{Namespace: ns, Name: name}, + }) + return err +} From b5f12cad6738f8e3ae70df6cdaa1b68da5bc8214 Mon Sep 17 00:00:00 2001 From: zhanghao Date: Thu, 26 Nov 2026 17:36:15 +0800 Subject: [PATCH 13/28] README: write down the contract with the gateway chart 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. --- README.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/README.md b/README.md index ce0af1ca..4ac10ec8 100644 --- a/README.md +++ b/README.md @@ -479,6 +479,32 @@ key 泄露要立刻失效时,光改 Secret 最长还有一分钟能继续用。* `return false` 整份配置解析失败,而插件是 `FAIL_CLOSE`,后果是**整个网关所有路由全部拒绝**, 不是"其中一个不生效"。渲染层会拒掉这种配置(报错只给 consumer 名和下标,不带 key 值)。 +**与网关 chart 的契约**(`modelsphere/helm-charts` 的 `charts/higress-llm`,双方都依赖,改一边会坏另一边): + +- **chart 不再渲染 `defaultConfig.consumers`,这个字段整个归 autoconfig。** 它继续渲染 + `keys` 和 `global_auth`,那两个仍归 helm —— `defaultConfig` 是**字段级**跟踪的(实测: + managedFields 里 `f:defaultConfig` 下面是 `f:consumers`/`f:keys`/`f:global_auth` 三条独立路径), + 不是一个原子块,所以两边各写各的层级不会互相覆盖。 +- **key-auth 没有 `consumers` 这个键 = 整个网关拒绝一切请求。** `key_auth` 的 + `parsePluginConfig` 在 `consumers` 和 `credentials` 都不存在时 `return false`,而那个插件是 + `FAIL_CLOSE`。所以这个 controller **必须**保证该键存在,哪怕是空列表 —— 这就是 + `KeyAuthReconciler` watch key-auth 本身的原因:全新安装时集群里**一个 APIConsumer 都没有**, + 只 watch APIConsumer 的话零对象就是零 reconcile,那个键永远不会被写。 + ⚠️ 同理:**新 chart 不能部署到还没升级 autoconfig 的集群**(旧版既不被触发、也不补写该键 → + 网关 FAIL_CLOSE 且不自愈)。helmfile 侧已用 `semverCompare` 门禁 + `needs` 保证顺序。 +- **一个 key 只能属于一个 consumer。** `key_auth` 遇到重复 credential 会 `return false`、 + 整份配置解析失败 —— 加上 FAIL_CLOSE,后果是**整个网关所有路由全部拒绝**,不是「其中一个不生效」。 + 渲染层会拒,但别指望它兜住所有写法。 +- **凭据渲染成带 `Bearer ` 前缀**(Secret 里存裸 key 即可):`key_auth` 比较的是**整个 + Authorization header 原值**,不剥前缀、不 trim。配裸 key 的话标准客户端全部 401。 + +**适配已有条目**(迁移时用):建一个 `APIConsumer`,名字与 live 里那个 consumer 相同,Secret 里放 +**它现在用的那把 key**。要求「携带现有全部凭据」不是形式主义 —— 它是这个名字的归属证明: +`consumerName` 是自由字段、对象可以建在任意 namespace,没有这道证明,任何人写 +`consumerName: tenant-a` + 自己的 key 就继承了 `tenant-a` 被允许的所有路由。适配完成后再换 key, +那是「轮换」,此时条目已归自己、不需要再证明。 +名字被两个新对象同时争用时,**谁都拿不到** —— 让先到的胜出等于按列表顺序仲裁「谁是 tenant-a」。 + **两条写入安全规则**(这个改动最危险的地方,都是「宁可不写」): - **坏一个,全不写**。某个 `APIConsumer` 的 Secret 读不到时,**不会**把它从名单里摘掉再写剩下的 —— From 3ad0aa2cc433027503064c9679d150247f826709 Mon Sep 17 00:00:00 2001 From: zhanghao Date: Thu, 26 Nov 2026 17:45:33 +0800 Subject: [PATCH 14/28] APIConsumer: do not register the key-auth watch on a cluster without 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 --- cmd/main.go | 53 +++++- cmd/main_test.go | 77 ++++++++ internal/controller/apiconsumer_controller.go | 179 +++++++++++++----- .../controller/apiconsumer_controller_test.go | 106 +++++++++-- 4 files changed, 351 insertions(+), 64 deletions(-) create mode 100644 cmd/main_test.go diff --git a/cmd/main.go b/cmd/main.go index 7d6b0a50..2207e943 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -97,6 +97,10 @@ func runController(leaderElect bool) error { if err != nil { return err } + higressServed, err := kindServed(cs, wasmPluginGroupVersion, "WasmPlugin") + if err != nil { + return err + } if served["ModelFleet"] { if err := (&controller.ModelFleetReconciler{ Client: mgr.GetClient(), @@ -127,9 +131,24 @@ func runController(leaderElect bool) error { // the gateway refuses everything). A fresh install has zero APIConsumers, so the // APIConsumer watch would never fire; this one does, and the event also says which // namespace, so no default has to be configured or guessed. - if err := (&controller.KeyAuthReconciler{APIConsumerReconciler: consumers}). - SetupWithManager(mgr); err != nil { - return err + // + // Gated on the WasmPlugin kind being served, for the reason spelled out above for + // ModelFleet and with a worse blast radius: a For() watch builds its informer at + // startup and blocks on the cache syncing, so on a cluster without Higress the + // manager would exit when CacheSyncTimeout ran out and the pod would crash-loop, + // taking ModelRoute - openresty peers, CART workers, monitor.conf - with it. Most + // clusters are in exactly that state: enabled.higress is false by default, while + // this release ships the APIConsumer CRD to all of them. + switch { + case !keyAuthWatchWanted(higressServed): + log.Print("Higress WasmPlugin CRD not installed: skipping the key-auth watch. " + + "Install Higress and restart to enable it - until then nothing creates " + + "key-auth's defaultConfig.consumers, which the gateway chart relies on") + default: + if err := (&controller.KeyAuthReconciler{APIConsumerReconciler: consumers}). + SetupWithManager(mgr); err != nil { + return err + } } } else { log.Print("APIConsumer CRD not installed: skipping that reconciler " + @@ -172,6 +191,34 @@ func servedKinds(cs kubernetes.Interface) (map[string]bool, error) { return out, nil } +// keyAuthWatchWanted: may the key-auth watch be registered? Its own function because the +// consequence of getting it wrong is not local: that watch is a For(), so controller-runtime +// builds its informer at startup and waits for the cache to sync, and where the kind is not +// served the manager exits when CacheSyncTimeout runs out. The pod then crash-loops and takes +// ModelRoute with it on a cluster that only ever wanted ModelRoute. +func keyAuthWatchWanted(higressServed bool) bool { return higressServed } + +// kindServed: is one kind of some OTHER group served? Same question as servedKinds, asked of +// a group this project does not own, so a missing group is an answer rather than an error. +func kindServed(cs kubernetes.Interface, groupVersion, kind string) (bool, error) { + list, err := cs.Discovery().ServerResourcesForGroupVersion(groupVersion) + if err != nil { + if apierrors.IsNotFound(err) { + return false, nil + } + return false, fmt.Errorf("discover %s: %w", groupVersion, err) + } + for _, r := range list.APIResources { + if r.Kind == kind { + return true, nil + } + } + return false, nil +} + +// wasmPluginGroupVersion is Higress's, not ours. +const wasmPluginGroupVersion = "extensions.higress.io/v1alpha1" + func envOr(k, def string) string { if v := os.Getenv(k); v != "" { return v diff --git a/cmd/main_test.go b/cmd/main_test.go new file mode 100644 index 00000000..17b738cc --- /dev/null +++ b/cmd/main_test.go @@ -0,0 +1,77 @@ +package main + +import ( + "testing" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + fakediscovery "k8s.io/client-go/discovery/fake" + "k8s.io/client-go/kubernetes/fake" +) + +// A cluster without Higress must not stop this binary from starting. The key-auth watch is a +// For() watch, so its informer is built at startup and blocks on the cache syncing: register +// it where the kind is not served and the manager exits when CacheSyncTimeout runs out, the +// pod crash-loops, and ModelRoute goes down with it - openresty peers, CART workers, +// monitor.conf. Most clusters are in that state, since enabled.higress is false by default +// while this release ships the APIConsumer CRD everywhere. +// +// So "is WasmPlugin served" has to be answerable, and a missing group has to be an answer +// rather than an error. +func TestKindServed(t *testing.T) { + for _, tc := range []struct { + name string + resources []*metav1.APIResourceList + want bool + }{ + { + name: "higress installed", + resources: []*metav1.APIResourceList{{ + GroupVersion: wasmPluginGroupVersion, + APIResources: []metav1.APIResource{{Kind: "WasmPlugin"}, {Kind: "McpBridge"}}, + }}, + want: true, + }, + { + // The common case: no Higress at all. Must come back false, not an error. + name: "group absent", + resources: nil, + want: false, + }, + { + // The group exists but not this kind - an older or trimmed Higress. + name: "group without the kind", + resources: []*metav1.APIResourceList{{ + GroupVersion: wasmPluginGroupVersion, + APIResources: []metav1.APIResource{{Kind: "McpBridge"}}, + }}, + want: false, + }, + } { + t.Run(tc.name, func(t *testing.T) { + cs := fake.NewSimpleClientset() + cs.Discovery().(*fakediscovery.FakeDiscovery).Resources = tc.resources + got, err := kindServed(cs, wasmPluginGroupVersion, "WasmPlugin") + if err != nil { + t.Fatalf("a cluster without Higress must not be an error: %v", err) + } + if got != tc.want { + t.Fatalf("kindServed = %v, want %v", got, tc.want) + } + }) + } +} + +// The gate itself. Trivial today, and separate because what it decides is not: the key-auth +// watch is a For(), so its informer is built at startup and waited on, and registering it +// where Higress is absent makes the manager exit - crash-looping the pod and taking +// ModelRoute down with it. If this ever grows a second condition, it has a place to go and a +// test that says what it is for. +func TestKeyAuthWatchWanted(t *testing.T) { + if keyAuthWatchWanted(false) { + t.Fatal("the key-auth watch would be registered on a cluster without Higress") + } + if !keyAuthWatchWanted(true) { + t.Fatal("the key-auth watch would be skipped on a cluster that has Higress - then " + + "nothing creates key-auth's consumers key and the gateway stays FAIL_CLOSE") + } +} diff --git a/internal/controller/apiconsumer_controller.go b/internal/controller/apiconsumer_controller.go index 0824fc25..440bbc46 100644 --- a/internal/controller/apiconsumer_controller.go +++ b/internal/controller/apiconsumer_controller.go @@ -154,19 +154,21 @@ func (r *APIConsumerReconciler) Reconcile(ctx context.Context, req ctrl.Request) } round, err := r.programGateway(ctx, gwNS, nil) - if err != nil { - r.setConsumerStatus(ctx, req.NamespacedName, metav1.ConditionFalse, "ProgramError", err.Error(), 0, "", "") - return ctrl.Result{RequeueAfter: consumerResyncTime}, nil - } - // This object was left out of the round on purpose - a collision with somebody already - // serving traffic, or a Secret this controller cannot read. The round succeeded for - // everyone else, so there is nothing to retry quickly; the reason goes on this object, - // where whoever created it will look. + // A reason specific to THIS object comes first, even when the round also failed. It was + // left out on purpose - a collision with somebody already serving traffic, an identity it + // cannot prove it holds, a Secret that cannot be read - and that is what whoever created + // it needs to read. The round's own error is usually a consequence: leaving this object + // out can be what made the rendered list empty, and the empty-list guard then refuses to + // write it over live entries, which is correct but says nothing about this object. if why := round.reasonFor(&consumer); why != "" { r.setConsumerStatus(ctx, req.NamespacedName, metav1.ConditionFalse, "NotProgrammed", why, 0, "", "") return ctrl.Result{RequeueAfter: consumerResyncTime}, nil } + if err != nil { + r.setConsumerStatus(ctx, req.NamespacedName, metav1.ConditionFalse, "ProgramError", err.Error(), 0, "", "") + return ctrl.Result{RequeueAfter: consumerResyncTime}, nil + } name := consumerName(&consumer) creds, err := r.readCredentials(ctx, &consumer) @@ -244,10 +246,14 @@ func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, // The names already in this gateway's list. Needed before rendering, to tell "this // consumer's Secret is unreadable and it has a key in there" (fail closed) from "...and // it has nothing in there" (skip it rather than freeze everyone else). - liveNames, err := r.liveConsumerNames(ctx, gwNS) + liveEntries, liveManaged, err := r.liveConsumerState(ctx, gwNS) if err != nil && !errors.Is(err, errGatewayAbsent) { return gatewayRound{}, err } + liveNames := map[string]bool{} + for n := range liveEntries { + liveNames[n] = true + } round := gatewayRound{skipped: map[string]string{}} // incumbent: is the entry under this consumer's name in this gateway THIS object's? @@ -340,6 +346,17 @@ func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, return round, err } + // Taking over a consumer name that already exists here and belongs to no APIConsumer + // requires carrying every credential it accepts - proof that whoever wrote this object + // already holds the key. consumerName is free-form and an APIConsumer can be created in + // any namespace, so without it, writing `consumerName: tenant-a` and your own key + // inherits every route tenant-a is allowed on. + // + // Decided here, where the objects are, and the object that cannot prove it is left out + // rather than failing the round: wanting an identity it is not entitled to must not stop + // every other consumer on this gateway from being added, rotated or revoked. + views = dropUnprovenAdoptions(views, liveEntries, liveManaged, claimed, round, gwNS) + if len(round.skipped) > 0 { logf.FromContext(ctx).Info("left consumers out of this round", "gateway", gwNS, "skipped", round.skipped) @@ -398,8 +415,12 @@ func (r *APIConsumerReconciler) dropCollidingNewcomers(ctx context.Context, for _, v := range views { add("consumer name", v.Name, v) for _, cred := range v.Credentials { - // By credential VALUE, which is never put in a message. - add("credential", cred, v) + // By credential VALUE - never put in a message - and with the prefix normalised, + // because that is how key-auth will see them: `sk-x` in one consumer and + // `Bearer sk-x` in another render to the same string, so comparing raw values + // let that pair past this check and into RenderConsumers, which refuses the + // whole round instead of leaving the newcomer out. + add("credential", strings.TrimPrefix(cred, bearerPrefixValue), v) } } @@ -605,45 +626,10 @@ func (r *APIConsumerReconciler) writeConsumers(ctx context.Context, gwNS string, continue // already ours; this is a rotation, not an adoption } if mine[name] { - // Adopting an entry nobody has claimed before, by NAME. Taking it over has - // to require proof that the writer already holds the key, or the name is a - // free identity: an APIConsumer can be created in any namespace, its - // consumerName is free-form, and whatever it renders replaces the entry. A - // writer who put consumerName: tenant-a and their own key in their own - // Secret would inherit every route tenant-a is allowed on, and the real - // tenant-a would get 401 on its next request. Nothing else would notice: - // the names do not collide between APIConsumers, and no credential is - // shared, so neither existing guard fires. - // - // credentialsSecretRef is pinned to the object's own namespace for exactly - // this reason - a namespace-scoped writer is not trusted with other - // people's credentials - and an identity is worth no less than a key. - // - // The proof is: carry every credential the live entry already has. That is - // what a migration does anyway, because the point is that the caller - // changes nothing. Dropping an old key comes after adoption, as a rotation, - // when the entry is ours and no proof is needed. - if reformatted := credentialsReformatted(m, myCreds[name]); reformatted { - // Adoption is allowed - the writer holds the key - but the entry's - // credential changes spelling, from a bare key to `Bearer `, and - // key_auth compares the WHOLE Authorization header. A caller that was - // sending the bare form will start getting 401. Said out loud, because - // nothing else would say it. - logf.FromContext(ctx).Info("adopting a consumer whose credential was "+ - "stored without the Bearer prefix; callers must send "+ - "`Authorization: Bearer ` from now on", - "gateway", gwNS, "consumer", name) - } - if missing := credentialsNotCovered(m, myCreds[name]); missing > 0 { - return fmt.Errorf("%s/key-auth: consumer %q already exists in this "+ - "gateway and is not managed by any APIConsumer, and the APIConsumer "+ - "claiming that name does not carry %d of its %d existing "+ - "credential(s). Adopting an existing consumer requires its current "+ - "key(s), so that taking over a name cannot grant someone else's "+ - "access; nothing was written. Add the existing key to the Secret to "+ - "adopt it, then rotate, or give this APIConsumer a different "+ - "consumerName", gwNS, name, missing, liveCredentialCount(m)) - } + // Ours this round. Whether this object is ENTITLED to a name that already + // existed here is decided in programGateway, where the objects are: by the + // time a view reaches this function it has been cleared, and a view that was + // not is no longer in the list. continue } foreign = append(foreign, name) @@ -733,11 +719,23 @@ func (r *APIConsumerReconciler) readCredentials(ctx context.Context, c *routingv } sort.Strings(keys) // stable order, so an unchanged Secret renders an unchanged list out := make([]string, 0, len(keys)) + seen := map[string]bool{} for _, k := range keys { v := strings.TrimSpace(string(sec.Data[k])) if v == "" { continue // an empty value would be a credential that matches nothing } + // Deduplicated, comparing with the prefix normalised. The same value under two + // Secret keys is ordinary mid-rotation (copy `current` to `next`, then edit it), and + // it used to arrive as one consumer carrying a credential twice: the collision check + // then saw two claimants on one credential - both from this same object, so both + // "incumbents" - and refused the round for the whole gateway, with a message about + // two consumers that named one object twice. + if norm := strings.TrimPrefix(v, bearerPrefixValue); seen[norm] { + continue + } else { + seen[norm] = true + } out = append(out, v) } if len(out) == 0 { @@ -1066,6 +1064,48 @@ func liveCredentialCount(live map[string]any) int { return len(creds) } +// liveConsumerState: what this gateway's key-auth currently holds - each consumer name with +// its credentials - and which of those names this controller recorded as its own. +func (r *APIConsumerReconciler) liveConsumerState(ctx context.Context, gwNS string) ( + map[string][]string, map[string]bool, error) { + entries := map[string][]string{} + obj := &unstructured.Unstructured{} + obj.SetGroupVersionKind(wasmPluginGVK) + if err := r.Get(ctx, types.NamespacedName{Namespace: gwNS, Name: "key-auth"}, obj); err != nil { + if isAbsent(err) { + return entries, nil, fmt.Errorf("key-auth in namespace %q: %w", gwNS, errGatewayAbsent) + } + return entries, nil, err + } + managed, err := managedConsumerNames(obj) + if err != nil { + return entries, nil, err + } + live, _, err := unstructured.NestedSlice(obj.Object, "spec", "defaultConfig", "consumers") + if err != nil { + return entries, managed, err + } + for _, lc := range live { + m, ok := lc.(map[string]any) + if !ok { + continue + } + name, _ := m["name"].(string) + if name == "" { + continue + } + creds, _ := m["credentials"].([]any) + vals := make([]string, 0, len(creds)) + for _, c := range creds { + if v, ok := c.(string); ok { + vals = append(vals, v) + } + } + entries[name] = vals + } + return entries, managed, nil +} + // liveConsumerNames: the consumer names this gateway's key-auth currently holds. func (r *APIConsumerReconciler) liveConsumerNames(ctx context.Context, gwNS string) (map[string]bool, error) { out := map[string]bool{} @@ -1157,3 +1197,42 @@ func credentialsReformatted(live map[string]any, rendered map[string]bool) bool } return false } + +// dropUnprovenAdoptions leaves out any view that claims a consumer name already present in +// the gateway and owned by no APIConsumer, unless it carries every credential that entry +// accepts. Comparison ignores the `Bearer ` prefix on either side: possession of the key is +// the question, how the entry spells it is not. +func dropUnprovenAdoptions(views []sink.ConsumerView, liveEntries map[string][]string, + liveManaged, claimed map[string]bool, round gatewayRound, gwNS string) []sink.ConsumerView { + kept := make([]sink.ConsumerView, 0, len(views)) + for _, v := range views { + existing, present := liveEntries[v.Name] + if !present || liveManaged[v.Name] || claimed[v.Name] { + kept = append(kept, v) // nothing there, or already ours: a rotation + continue + } + have := make(map[string]bool, len(v.Credentials)) + for _, c := range v.Credentials { + have[strings.TrimPrefix(c, bearerPrefixValue)] = true + } + missing := 0 + for _, c := range existing { + if !have[strings.TrimPrefix(c, bearerPrefixValue)] { + missing++ + } + } + if missing == 0 { + kept = append(kept, v) + continue + } + round.skipped[v.Source] = fmt.Sprintf( + "consumer %q already exists in gateway %s and is managed by no APIConsumer, and "+ + "this object does not carry %d of its %d existing credential(s). Adopting an "+ + "existing consumer requires its current key(s), so that taking over a name "+ + "cannot grant someone else's access. Put the existing key in this object's "+ + "Secret to adopt it and rotate afterwards, or give it a different "+ + "consumerName. This object was left out of the gateway; everything else on "+ + "it is unaffected", v.Name, gwNS, missing, len(existing)) + } + return kept +} diff --git a/internal/controller/apiconsumer_controller_test.go b/internal/controller/apiconsumer_controller_test.go index 0d867860..2c344be0 100644 --- a/internal/controller/apiconsumer_controller_test.go +++ b/internal/controller/apiconsumer_controller_test.go @@ -1057,17 +1057,28 @@ func TestConsumerCannotTakeOverANameWithoutItsKey(t *testing.T) { // The chart's entry, with the real key, managed by nobody. keyAuthWith(liveConsumer("tenant-a", "Bearer sk-the-real-key")), ) - _, err := r.programGateway(context.Background(), "higress-system", nil) - if err == nil { + // The object is left out of the gateway rather than failing the round for everyone, and + // the reason lands on its own status - so this is checked through a reconcile, not + // through programGateway's return. + if err := reconcileConsumer2(t, r, "team-x", "team-x-impostor"); err != nil { + t.Fatal(err) + } + var imp0 routingv1.APIConsumer + if err := c.Get(context.Background(), types.NamespacedName{ + Namespace: "team-x", Name: "team-x-impostor"}, &imp0); err != nil { + t.Fatal(err) + } + if condTrue(imp0.Status.Conditions, condProgrammed) { t.Fatal("a foreign consumer name was taken over with a different key") } + msg0 := consumerCondMessage(imp0.Status.Conditions, condProgrammed) for _, want := range []string{"tenant-a", "existing", "consumerName"} { - if !strings.Contains(err.Error(), want) { - t.Fatalf("the error does not explain the refusal (%s missing): %v", want, err) + if !strings.Contains(msg0, want) { + t.Fatalf("the message does not explain the refusal (%s missing): %q", want, msg0) } } - if strings.Contains(err.Error(), "sk-the-real-key") || strings.Contains(err.Error(), "sk-attacker") { - t.Fatalf("the error leaks a credential: %v", err) + if strings.Contains(msg0, "sk-the-real-key") || strings.Contains(msg0, "sk-attacker") { + t.Fatalf("the message leaks a credential: %q", msg0) } // The real key still works: nothing was written. creds := creds0Of(t, c, "higress-system", "tenant-a") @@ -1076,11 +1087,6 @@ func TestConsumerCannotTakeOverANameWithoutItsKey(t *testing.T) { } // ...and carrying the existing key DOES adopt it, which is what a migration does. - var imp routingv1.APIConsumer - if err := c.Get(context.Background(), types.NamespacedName{ - Namespace: "team-x", Name: "team-x-impostor"}, &imp); err != nil { - t.Fatal(err) - } sec := credSecret("team-x-keys", map[string]string{"key": "sk-the-real-key"}) sec.Namespace = "team-x" if err := c.Update(context.Background(), sec); err != nil { @@ -1385,3 +1391,81 @@ func reconcileConsumer2(t *testing.T, r *APIConsumerReconciler, ns, name string) }) return err } + +// The same value under two Secret keys is ordinary mid-rotation: copy `current` into `next`, +// then edit it. It used to arrive as one consumer carrying a credential twice, which the +// collision check read as two claimants on one credential - both from this very object - and +// refused the round for the whole gateway, with a message about "two consumers" naming one +// object twice. +func TestConsumerSecretWithADuplicatedValueDoesNotFreezeTheGateway(t *testing.T) { + r, c := newConsumerReconciler(t, + consumerFixture("tenant-a", "tenant-a-keys"), + credSecret("tenant-a-keys", map[string]string{ + "current": "sk-a", + "next": "sk-a", // copied, not yet edited + }), + keyAuthWith(), + ) + if _, err := r.programGateway(context.Background(), "higress-system", nil); err != nil { + t.Fatalf("a Secret holding one value twice froze the round: %v", err) + } + got := creds0Of(t, c, "higress-system", "tenant-a") + if strings.Join(got, ",") != "Bearer sk-a" { + t.Fatalf("credentials = %v, want the value once", got) + } +} + +// One consumer storing `sk-x` and another `Bearer sk-x` are the same credential once rendered, +// and key-auth refuses a duplicate by failing to parse the whole config. Comparing raw values +// let that pair past the collision check and into RenderConsumers, which refuses the round +// instead of leaving the newcomer out. +func TestConsumerPrefixedAndBareDuplicateIsCaughtAsACollision(t *testing.T) { + serving := consumerFixture("tenant-a", "tenant-a-keys") + serving.Status.ConsumerName = "tenant-a" + serving.Status.AppliedGatewayNamespace = "higress-system" + newcomer := consumerFixture("tenant-b", "tenant-b-keys") + r, c := newConsumerReconciler(t, serving, newcomer, + credSecret("tenant-a-keys", map[string]string{"key": "sk-shared"}), + // The same key, spelled the other way. + credSecret("tenant-b-keys", map[string]string{"key": "Bearer sk-shared"}), + keyAuthManagedBy("tenant-a", liveConsumer("tenant-a", "Bearer sk-shared")), + ) + if _, err := r.programGateway(context.Background(), "higress-system", nil); err != nil { + t.Fatalf("the round failed instead of leaving the newcomer out: %v", err) + } + names := consumerNames(gatewayConsumers(t, c, "higress-system")) + if strings.Join(names, ",") != "tenant-a" { + t.Fatalf("consumers = %v, want only the incumbent: a duplicate credential would make "+ + "key-auth reject the whole configuration", names) + } +} + +// An object that wants a name it cannot prove it holds is left out, not allowed to freeze the +// gateway: everybody else must still be addable, rotatable and revocable. +func TestConsumerUnprovenAdoptionDoesNotFreezeTheGateway(t *testing.T) { + serving := consumerFixture("tenant-a", "tenant-a-keys") + serving.Status.ConsumerName = "tenant-a" + serving.Status.AppliedGatewayNamespace = "higress-system" + impostor := consumerFixture("team-x", "team-x-keys") + impostor.Namespace = "team-x" + impostor.Spec.ConsumerName = "orphan" // a live entry owned by no APIConsumer + xsec := credSecret("team-x-keys", map[string]string{"key": "sk-x"}) + xsec.Namespace = "team-x" + r, c := newConsumerReconciler(t, serving, impostor, xsec, + credSecret("tenant-a-keys", map[string]string{"key": "sk-rotated"}), + keyAuthManagedBy("tenant-a", + liveConsumer("tenant-a", "Bearer sk-old"), + liveConsumer("orphan", "Bearer sk-orphan")), + ) + if _, err := r.programGateway(context.Background(), "higress-system", nil); err != nil { + t.Fatalf("an unprovable adoption froze the round: %v", err) + } + // tenant-a's rotation went through... + if got := creds0Of(t, c, "higress-system", "tenant-a"); strings.Join(got, ",") != "Bearer sk-rotated" { + t.Fatalf("tenant-a credentials = %v, want the rotated key", got) + } + // ...the orphan entry is untouched, and the impostor's key is not in the gateway. + if got := creds0Of(t, c, "higress-system", "orphan"); strings.Join(got, ",") != "Bearer sk-orphan" { + t.Fatalf("orphan credentials = %v, want them untouched", got) + } +} From 7a129ccc1e3991c32033804deec0684b78c91716 Mon Sep 17 00:00:00 2001 From: zhanghao Date: Thu, 26 Nov 2026 17:49:54 +0800 Subject: [PATCH 15/28] APIConsumer: a periodic sweep, because the gate alone leaves the gateway 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 --- cmd/main.go | 14 ++++- internal/controller/apiconsumer_controller.go | 61 +++++++++++++++++++ .../controller/apiconsumer_controller_test.go | 49 +++++++++++++++ 3 files changed, 121 insertions(+), 3 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 2207e943..ca7cdada 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -19,6 +19,7 @@ import ( ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/healthz" "sigs.k8s.io/controller-runtime/pkg/log/zap" + "sigs.k8s.io/controller-runtime/pkg/manager" metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" slov1 "autoconfig/api/inference/v1alpha1" @@ -139,11 +140,18 @@ func runController(leaderElect bool) error { // taking ModelRoute - openresty peers, CART workers, monitor.conf - with it. Most // clusters are in exactly that state: enabled.higress is false by default, while // this release ships the APIConsumer CRD to all of them. + // The sweep runs whatever discovery said. It is what makes the "autoconfig creates + // the consumers key" contract hold on a cluster where the watch could not be + // registered - a fresh install, where Higress's CRDs arrive after this process + // started - and it needs no informer, so a missing kind costs one failed List. + if err := mgr.Add(manager.RunnableFunc(consumers.StartGatewaySweep)); err != nil { + return err + } switch { case !keyAuthWatchWanted(higressServed): - log.Print("Higress WasmPlugin CRD not installed: skipping the key-auth watch. " + - "Install Higress and restart to enable it - until then nothing creates " + - "key-auth's defaultConfig.consumers, which the gateway chart relies on") + log.Print("Higress WasmPlugin CRD not installed: skipping the key-auth watch " + + "(the periodic gateway sweep still runs, so a Higress installed later is " + + "picked up within one resync without restarting this pod)") default: if err := (&controller.KeyAuthReconciler{APIConsumerReconciler: consumers}). SetupWithManager(mgr); err != nil { diff --git a/internal/controller/apiconsumer_controller.go b/internal/controller/apiconsumer_controller.go index 440bbc46..8f03e668 100644 --- a/internal/controller/apiconsumer_controller.go +++ b/internal/controller/apiconsumer_controller.go @@ -1236,3 +1236,64 @@ func dropUnprovenAdoptions(views []sink.ConsumerView, liveEntries map[string][]s } return kept } + +// ensureGateways runs one gateway round for every key-auth WasmPlugin in the cluster. It is +// what the periodic sweep below calls, and it exists separately from the watch for one +// reason: the watch cannot be registered at all where the WasmPlugin kind is not served yet, +// and that is the normal state on a fresh install. +// +// Higress's CRDs come from the higress CORE release, while the helmfile deploys autoconfig +// BEFORE higress-llm (which needs it). So autoconfig can start in a cluster that has no +// WasmPlugin kind, skip the watch - correctly, or the manager would exit - and then nothing +// would ever write key-auth's consumers key. The gateway would be FAIL_CLOSE and stay that +// way until somebody restarted autoconfig, which is a worse failure than the crash-loop the +// gate prevents, because nothing announces it. +// +// Uncached List, through APIReader: a cached one would build an informer for a kind that may +// not exist, which is the problem this is here to avoid. A missing kind is just a failed List +// and the next sweep tries again, so a Higress installed later is picked up on its own. +func (r *APIConsumerReconciler) ensureGateways(ctx context.Context) { + log := logf.FromContext(ctx) + list := &unstructured.UnstructuredList{} + list.SetGroupVersionKind(wasmPluginGVK.GroupVersion().WithKind("WasmPluginList")) + reader := r.APIReader + if reader == nil { + reader = r.Client + } + if err := reader.List(ctx, list); err != nil { + if isAbsent(err) { + return // no Higress (yet): nothing to do, and nothing to complain about + } + log.V(1).Info("could not list WasmPlugins for the gateway sweep", "err", err.Error()) + return + } + for i := range list.Items { + o := &list.Items[i] + if o.GetName() != "key-auth" { + continue + } + if _, err := r.programGateway(ctx, o.GetNamespace(), nil); err != nil && + !errors.Is(err, errGatewayAbsent) { + log.V(1).Info("gateway sweep did not program this gateway", + "gateway", o.GetNamespace(), "err", err.Error()) + } + } +} + +// StartGatewaySweep is a manager Runnable: it keeps the consumers key present even on a +// cluster where the watch could not be registered, and picks up a Higress installed after +// this process started. One round per interval over every key-auth; each round writes only +// when something differs, so a settled cluster costs a List and a few cached reads. +func (r *APIConsumerReconciler) StartGatewaySweep(ctx context.Context) error { + t := time.NewTicker(consumerResyncTime) + defer t.Stop() + r.ensureGateways(ctx) // once at startup, so a fresh install does not wait an interval + for { + select { + case <-ctx.Done(): + return nil + case <-t.C: + r.ensureGateways(ctx) + } + } +} diff --git a/internal/controller/apiconsumer_controller_test.go b/internal/controller/apiconsumer_controller_test.go index 2c344be0..1acbe4c0 100644 --- a/internal/controller/apiconsumer_controller_test.go +++ b/internal/controller/apiconsumer_controller_test.go @@ -3,6 +3,7 @@ package controller import ( "context" "encoding/json" + "k8s.io/apimachinery/pkg/runtime" "sort" "strings" "testing" @@ -1469,3 +1470,51 @@ func TestConsumerUnprovenAdoptionDoesNotFreezeTheGateway(t *testing.T) { t.Fatalf("orphan credentials = %v, want them untouched", got) } } + +// The case the gate on its own leaves broken: autoconfig starts in a cluster with no +// WasmPlugin kind (Higress's CRDs come from the higress CORE release, and the helmfile +// deploys autoconfig before higress-llm, which needs it), so the watch is correctly skipped - +// and then nothing would ever write key-auth's consumers key. The gateway would be FAIL_CLOSE +// and stay that way until somebody restarted autoconfig, which is worse than the crash-loop +// the gate prevents, because nothing announces it. +// +// The sweep closes it: no informer, so it runs whether or not the kind exists, and a Higress +// installed later is picked up on the next round. +func TestGatewaySweepWritesTheKeyWithoutAWatch(t *testing.T) { + r, c := newConsumerReconciler(t, keyAuthWithoutConsumers()) // zero APIConsumers + r.ensureGateways(context.Background()) + + var ka unstructured.Unstructured + ka.SetGroupVersionKind(wasmPluginGVK) + if err := c.Get(context.Background(), types.NamespacedName{ + Namespace: "higress-system", Name: "key-auth"}, &ka); err != nil { + t.Fatal(err) + } + live, found, err := unstructured.NestedSlice(ka.Object, "spec", "defaultConfig", "consumers") + if err != nil { + t.Fatal(err) + } + if !found { + t.Fatal("the sweep did not create the consumers key: on a cluster where the watch " + + "could not be registered, the gateway would stay FAIL_CLOSE until a restart") + } + if len(live) != 0 { + t.Fatalf("consumers = %v, want an empty list", live) + } +} + +// A cluster with no Higress at all: the sweep must be a no-op, not an error and not a log +// line every minute. isAbsent covers both a missing CRD and a missing object. +func TestGatewaySweepIsQuietWithoutHigress(t *testing.T) { + s := runtime.NewScheme() + if err := routingv1.AddToScheme(s); err != nil { + t.Fatal(err) + } + if err := corev1.AddToScheme(s); err != nil { + t.Fatal(err) + } + // A client whose scheme has no WasmPlugin kind stands in for a cluster without Higress. + c := ctrlfake.NewClientBuilder().WithScheme(s).Build() + r := &APIConsumerReconciler{Client: c, APIReader: c, Scheme: s} + r.ensureGateways(context.Background()) // must not panic, must not block +} From aeee5015813c9972c290ad07d42ef8bf79d65c75 Mon Sep 17 00:00:00 2001 From: zhanghao Date: Thu, 26 Nov 2026 18:00:07 +0800 Subject: [PATCH 16/28] APIConsumer: read key-auth uncached, so the sweep needs no informer in 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 --- internal/controller/apiconsumer_controller.go | 31 +++++++-- .../controller/apiconsumer_controller_test.go | 66 +++++++++++++++++++ 2 files changed, 92 insertions(+), 5 deletions(-) diff --git a/internal/controller/apiconsumer_controller.go b/internal/controller/apiconsumer_controller.go index 8f03e668..1d9fb252 100644 --- a/internal/controller/apiconsumer_controller.go +++ b/internal/controller/apiconsumer_controller.go @@ -194,6 +194,27 @@ func (r *APIConsumerReconciler) Reconcile(ctx context.Context, req ctrl.Request) // only failure that means "there is nothing left to revoke a key from". var errGatewayAbsent = errors.New("the gateway's key-auth is not present") +// gatewayReader: every read of a key-auth WasmPlugin goes through the uncached reader, not the +// client's cache. +// +// Not a performance choice. The cached client builds an informer for a kind on first use, and +// this controller runs on clusters where the WasmPlugin kind does not exist yet - Higress's +// CRDs come from the higress CORE release, and autoconfig is deployed before higress-llm, +// which needs it. The key-auth watch is gated on discovery for that reason; routing these +// reads through the cache would reintroduce the same dependency one layer down, where no test +// would notice, and the behaviour when a CRD appears mid-run (does a lazy informer start, and +// how long does it block?) is something I would then be asserting rather than knowing. +// +// Uncached, the answer is the same in every state: a missing kind is an error that isAbsent +// recognises, and a kind installed later works on the next read. The cost is one GET per +// gateway per round. +func (r *APIConsumerReconciler) gatewayReader() client.Reader { + if r.APIReader != nil { + return r.APIReader + } + return r.Client +} + // gatewayRound reports what one programming round did with objects it could not include. // Keyed by "namespace/name", the value is why. It exists because this round is shared by every // APIConsumer on the gateway: a newcomer that cannot be rendered must not fail the round for @@ -509,7 +530,7 @@ func (r *APIConsumerReconciler) writeConsumers(ctx context.Context, gwNS string, return retry.RetryOnConflict(retry.DefaultRetry, func() error { obj := &unstructured.Unstructured{} obj.SetGroupVersionKind(wasmPluginGVK) - if err := r.Get(ctx, types.NamespacedName{Namespace: gwNS, Name: "key-auth"}, obj); err != nil { + if err := r.gatewayReader().Get(ctx, types.NamespacedName{Namespace: gwNS, Name: "key-auth"}, obj); err != nil { if isAbsent(err) { // Distinguished by a sentinel rather than by IsNotFound on whatever came // back: a MISSING SECRET is also NotFound, and treating that as "the gateway @@ -546,7 +567,7 @@ func (r *APIConsumerReconciler) writeConsumers(ctx context.Context, gwNS string, } // Re-read: the apply bumped resourceVersion, and the Update below would be // refused on the stale one. - if err := r.Get(ctx, types.NamespacedName{Namespace: gwNS, Name: "key-auth"}, obj); err != nil { + if err := r.gatewayReader().Get(ctx, types.NamespacedName{Namespace: gwNS, Name: "key-auth"}, obj); err != nil { return fmt.Errorf("key-auth in namespace %q after taking ownership: %w", gwNS, err) } } @@ -1009,7 +1030,7 @@ func refuseDuplicateCredentials(gwNS string, list []any) error { func (r *APIConsumerReconciler) hasNoLiveEntry(ctx context.Context, gwNS, name string) (bool, error) { obj := &unstructured.Unstructured{} obj.SetGroupVersionKind(wasmPluginGVK) - if err := r.Get(ctx, types.NamespacedName{Namespace: gwNS, Name: "key-auth"}, obj); err != nil { + if err := r.gatewayReader().Get(ctx, types.NamespacedName{Namespace: gwNS, Name: "key-auth"}, obj); err != nil { return false, err } live, _, err := unstructured.NestedSlice(obj.Object, "spec", "defaultConfig", "consumers") @@ -1071,7 +1092,7 @@ func (r *APIConsumerReconciler) liveConsumerState(ctx context.Context, gwNS stri entries := map[string][]string{} obj := &unstructured.Unstructured{} obj.SetGroupVersionKind(wasmPluginGVK) - if err := r.Get(ctx, types.NamespacedName{Namespace: gwNS, Name: "key-auth"}, obj); err != nil { + if err := r.gatewayReader().Get(ctx, types.NamespacedName{Namespace: gwNS, Name: "key-auth"}, obj); err != nil { if isAbsent(err) { return entries, nil, fmt.Errorf("key-auth in namespace %q: %w", gwNS, errGatewayAbsent) } @@ -1111,7 +1132,7 @@ func (r *APIConsumerReconciler) liveConsumerNames(ctx context.Context, gwNS stri out := map[string]bool{} obj := &unstructured.Unstructured{} obj.SetGroupVersionKind(wasmPluginGVK) - if err := r.Get(ctx, types.NamespacedName{Namespace: gwNS, Name: "key-auth"}, obj); err != nil { + if err := r.gatewayReader().Get(ctx, types.NamespacedName{Namespace: gwNS, Name: "key-auth"}, obj); err != nil { if isAbsent(err) { return out, fmt.Errorf("key-auth in namespace %q: %w", gwNS, errGatewayAbsent) } diff --git a/internal/controller/apiconsumer_controller_test.go b/internal/controller/apiconsumer_controller_test.go index 1acbe4c0..025b8ace 100644 --- a/internal/controller/apiconsumer_controller_test.go +++ b/internal/controller/apiconsumer_controller_test.go @@ -3,6 +3,7 @@ package controller import ( "context" "encoding/json" + "fmt" "k8s.io/apimachinery/pkg/runtime" "sort" "strings" @@ -1518,3 +1519,68 @@ func TestGatewaySweepIsQuietWithoutHigress(t *testing.T) { r := &APIConsumerReconciler{Client: c, APIReader: c, Scheme: s} r.ensureGateways(context.Background()) // must not panic, must not block } + +// Every read of key-auth has to avoid the client's cache. The cached client builds an informer +// on first use of a kind, and this controller runs where the WasmPlugin kind does not exist +// yet - which is exactly why the watch is gated on discovery. A cached read here would +// reintroduce that dependency one layer down, where nothing would notice until a cluster +// without Higress fell over. +// +// Checked by giving the reconciler a client that fails every read and an APIReader that +// works: anything that reaches for the cache instead shows up as a failure. +func TestKeyAuthReadsBypassTheCache(t *testing.T) { + working := ctrlfake.NewClientBuilder().WithScheme(fleetScheme(t)). + WithObjects(keyAuthWithoutConsumers()). + WithStatusSubresource(&routingv1.APIConsumer{}). + Build() + r := &APIConsumerReconciler{ + Client: &readRefusingClient{Client: working}, + APIReader: working, + Scheme: fleetScheme(t), + } + // The sweep lists and then programs, so this covers both. + r.ensureGateways(context.Background()) + + var ka unstructured.Unstructured + ka.SetGroupVersionKind(wasmPluginGVK) + if err := working.Get(context.Background(), types.NamespacedName{ + Namespace: "higress-system", Name: "key-auth"}, &ka); err != nil { + t.Fatal(err) + } + if _, found, _ := unstructured.NestedSlice(ka.Object, "spec", "defaultConfig", "consumers"); !found { + t.Fatal("the consumers key was not written: something read key-auth through the cache, " + + "which on a cluster without the WasmPlugin kind is the dependency the discovery " + + "gate exists to avoid") + } +} + +// readRefusingClient fails reads of WasmPlugin only - the kind that may not exist - and +// passes everything else through. Refusing every read would prove nothing: APIConsumer and +// Secret reads are allowed to use the cache, since this controller is only registered where +// the APIConsumer CRD is served. The first version of this refused everything and failed for +// that reason, which looked exactly like the bug it was written to find. +type readRefusingClient struct { + client.Client +} + +func (c *readRefusingClient) Get(ctx context.Context, key client.ObjectKey, obj client.Object, + opts ...client.GetOption) error { + if isWasmPlugin(obj) { + return fmt.Errorf("read key-auth through the cache: %s", key) + } + return c.Client.Get(ctx, key, obj, opts...) +} + +func (c *readRefusingClient) List(ctx context.Context, list client.ObjectList, + opts ...client.ListOption) error { + if u, ok := list.(*unstructured.UnstructuredList); ok && + strings.Contains(u.GetObjectKind().GroupVersionKind().Kind, "WasmPlugin") { + return fmt.Errorf("list WasmPlugins through the cache") + } + return c.Client.List(ctx, list, opts...) +} + +func isWasmPlugin(obj client.Object) bool { + u, ok := obj.(*unstructured.Unstructured) + return ok && u.GetObjectKind().GroupVersionKind() == wasmPluginGVK +} From 6a7323ba2c6a24f81fe1daa0ced4a5e9f4dc2df5 Mon Sep 17 00:00:00 2001 From: zhanghao Date: Thu, 26 Nov 2026 18:01:57 +0800 Subject: [PATCH 17/28] APIConsumer: comments that describe the design as it is 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. --- internal/controller/apiconsumer_controller.go | 46 ++++++++++++------- 1 file changed, 29 insertions(+), 17 deletions(-) diff --git a/internal/controller/apiconsumer_controller.go b/internal/controller/apiconsumer_controller.go index 1d9fb252..4d204a64 100644 --- a/internal/controller/apiconsumer_controller.go +++ b/internal/controller/apiconsumer_controller.go @@ -188,6 +188,14 @@ func (r *APIConsumerReconciler) Reconcile(ctx context.Context, req ctrl.Request) // programGateway renders every APIConsumer that names this gateway namespace into its // key-auth plugin, in one write. // +// Cost, since it is quadratic and that should be written down rather than discovered: one +// round reads every consumer's Secret, uncached, so with N consumers on a gateway each of +// their reconciles costs N Secret GETs - about N^2 per resync interval, plus one uncached GET +// of key-auth per round. At a dozen consumers that is noise. The way out, if it ever matters, +// is to collapse the rounds (one per gateway per interval rather than one per object), not to +// cache the Secrets: a cluster-wide Secret informer is the thing this controller deliberately +// does not have. +// // `excluding` is the object being deleted: it still exists in the API server while its // finalizer runs, so it has to be left out explicitly. // errGatewayAbsent: this gateway's key-auth, or the WasmPlugin CRD itself, is not there. The @@ -547,20 +555,22 @@ func (r *APIConsumerReconciler) writeConsumers(ctx context.Context, gwNS string, } // Take ownership of the field before writing it, if it is not ours yet. // - // Why this cannot be left to the write itself: a non-apply Update only takes - // ownership of the fields whose VALUES it changes, and the first thing this - // controller does on an already-populated gateway is adopt the live entries - // unchanged. Measured on the test cluster, a same-value Update moves nothing, so the - // field stays helm's for as long as the rendered list happens to match - and the - // gateway chart holds its upgrade back until a non-helm manager owns the field, - // which would then never happen. + // Why the write cannot be left to do it: a non-apply Update only takes ownership of + // the fields whose VALUES it changes, and the first thing this controller does on an + // already-populated gateway is adopt the live entries unchanged. Measured on the + // test cluster, a same-value Update moves nothing, so the field would stay with + // whoever rendered it for as long as the rendered list happened to match. // // A force apply of just this field is enough: it leaves the value alone and makes - // autoconfig a CO-OWNER alongside helm (also measured - it does not dispossess - // helm), which is what the chart waits for. The chart then stops rendering the - // field, helm's claim on it lapses, and this controller is left as the only owner. - // `keys` and `global_auth` are untouched and stay helm's: defaultConfig is tracked - // field by field, not as one atomic blob. + // autoconfig a CO-OWNER alongside the previous owner (also measured - it does not + // dispossess it). Once that owner stops rendering the field, its claim lapses and + // this controller is left as the only one. `keys` and `global_auth` are untouched + // and stay with the chart: defaultConfig is tracked field by field, not as one + // atomic blob. + // + // What this is FOR, now that the chart renders no consumers at all: clusters that + // were installed before that change, where helm still owns the field from its last + // apply. A fresh install has nobody to take it from and this does nothing. if len(consumers) > 0 && !ownsConsumers(obj) { if err := r.claimConsumers(ctx, gwNS, live); err != nil { return fmt.Errorf("take ownership of %s/key-auth defaultConfig.consumers: %w", gwNS, err) @@ -921,14 +931,16 @@ func sortConsumerList(list []any) { }) } -// fieldManagerName is the manager this controller writes under. It is what the gateway chart -// looks for before it yields defaultConfig.consumers, so it is part of an agreed contract -// with that chart, not an internal detail - see modelsphere/modelsphere#90. +// fieldManagerName is the manager this controller writes under. It used to be part of an +// agreed contract: the gateway chart looked the field's owner up in the live cluster and +// yielded to any manager that was not helm. That design is gone - the chart renders no +// consumers at all now, and reads nothing from the cluster - so this is once again an +// internal detail. It is still spelled out in one place, because ownsConsumers looks for it +// and SSA ownership is per manager NAME. const fieldManagerName = "autoconfig" // ownsConsumers: does this controller already own defaultConfig.consumers? Any entry under -// its own manager counts, whether recorded by an apply or by an update - the chart yields to -// any manager that is not helm. +// its own manager counts, whether recorded by an apply or by an update. func ownsConsumers(obj *unstructured.Unstructured) bool { for _, mf := range obj.GetManagedFields() { if mf.Manager != fieldManagerName || mf.FieldsV1 == nil { From cdf5c18134ae17470efbc586b09f74d771442c09 Mon Sep 17 00:00:00 2001 From: zhanghao Date: Thu, 26 Nov 2026 18:04:28 +0800 Subject: [PATCH 18/28] APIConsumer: only touch gateways something points at, and never one configured 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 --- internal/controller/apiconsumer_controller.go | 71 ++++++++++++++++++ .../controller/apiconsumer_controller_test.go | 74 +++++++++++++++++++ 2 files changed, 145 insertions(+) diff --git a/internal/controller/apiconsumer_controller.go b/internal/controller/apiconsumer_controller.go index 4d204a64..f2123867 100644 --- a/internal/controller/apiconsumer_controller.go +++ b/internal/controller/apiconsumer_controller.go @@ -553,6 +553,24 @@ func (r *APIConsumerReconciler) writeConsumers(ctx context.Context, gwNS string, if err != nil { return fmt.Errorf("read defaultConfig.consumers: %w", err) } + // Never alongside a top-level `credentials`. key_auth accepts consumers OR + // credentials and refuses a config carrying both ("cannot appear at the same + // level"), so adding consumers to a key-auth configured the credentials way would + // take that gateway down - and that gateway is then, by definition, not one this + // controller set up. Leaving it alone is the only safe answer; a round that has + // something of its own to write there says so instead of writing it. + if _, hasCreds, _ := unstructured.NestedFieldNoCopy(obj.Object, + "spec", "defaultConfig", "credentials"); hasCreds { + if len(consumers) == 0 { + return nil // nothing of ours to write there anyway + } + return fmt.Errorf("%s/key-auth configures its credentials with a top-level "+ + "`credentials` list, not `consumers`. key_auth refuses a config carrying "+ + "both, so writing the consumer list would take that gateway down; nothing "+ + "was written. This gateway was not set up by autoconfig - point these "+ + "APIConsumers at one that is", gwNS) + } + // Take ownership of the field before writing it, if it is not ours yet. // // Why the write cannot be left to do it: a non-apply Update only takes ownership of @@ -1300,11 +1318,25 @@ func (r *APIConsumerReconciler) ensureGateways(ctx context.Context) { log.V(1).Info("could not list WasmPlugins for the gateway sweep", "err", err.Error()) return } + wanted, err := r.gatewayNamespacesInUse(ctx) + if err != nil { + log.V(1).Info("could not work out which gateways are ours", "err", err.Error()) + return + } for i := range list.Items { o := &list.Items[i] if o.GetName() != "key-auth" { continue } + // Only gateways something in this cluster points at. Writing to every key-auth + // anywhere would mean adding `consumers: []` to a Higress that another team runs in + // their own namespace, and taking SSA ownership of that field on it - acting on an + // object nobody pointed this controller at. A namespace no APIConsumer and no + // ModelFleet names has no routes from us either, so there is nothing of ours to keep + // working there. + if !wanted[o.GetNamespace()] { + continue + } if _, err := r.programGateway(ctx, o.GetNamespace(), nil); err != nil && !errors.Is(err, errGatewayAbsent) { log.V(1).Info("gateway sweep did not program this gateway", @@ -1330,3 +1362,42 @@ func (r *APIConsumerReconciler) StartGatewaySweep(ctx context.Context) error { } } } + +// gatewayNamespacesInUse: the gateway namespaces something in this cluster points at - every +// APIConsumer's spec.gateway.namespace, and every ModelFleet's. The fleets count because they +// are what puts match rules on a gateway: a gateway serving a fleet's route needs its +// consumers key even if no APIConsumer has been created yet, which is the fresh-install case +// the sweep exists for. +// +// A missing ModelFleet CRD is not an error here: that reconciler is optional and this is only +// deciding which gateways to touch. +func (r *APIConsumerReconciler) gatewayNamespacesInUse(ctx context.Context) (map[string]bool, error) { + out := map[string]bool{} + var consumers routingv1.APIConsumerList + if err := r.List(ctx, &consumers); err != nil { + return nil, fmt.Errorf("list APIConsumers: %w", err) + } + for i := range consumers.Items { + out[consumerGatewayNamespace(&consumers.Items[i])] = true + } + var fleets routingv1.ModelFleetList + if err := r.List(ctx, &fleets); err != nil { + if !isAbsent(err) { + return nil, fmt.Errorf("list ModelFleets: %w", err) + } + } + for i := range fleets.Items { + if ns := fleets.Items[i].Spec.Gateway.Namespace; ns != "" { + out[ns] = true + } + } + // The default gateway namespace, always. It is where the gateway chart installs, and on + // a fresh install nothing names it yet - no APIConsumer, no fleet - while key-auth's + // defaultConfig is already active (defaultConfigDisable is false) and therefore already + // has to parse. That is the case the sweep exists for, and restricting the sweep to + // named namespaces without this killed it: both sweep tests went red, which is how I + // found out rather than by reasoning. + out[defaultGatewayNamespace] = true + delete(out, "") + return out, nil +} diff --git a/internal/controller/apiconsumer_controller_test.go b/internal/controller/apiconsumer_controller_test.go index 025b8ace..3fed6a61 100644 --- a/internal/controller/apiconsumer_controller_test.go +++ b/internal/controller/apiconsumer_controller_test.go @@ -1584,3 +1584,77 @@ func isWasmPlugin(obj client.Object) bool { u, ok := obj.(*unstructured.Unstructured) return ok && u.GetObjectKind().GroupVersionKind() == wasmPluginGVK } + +// The sweep must not write to a key-auth in a namespace nothing in this cluster points at. +// Adding `consumers: []` there means acting on an object nobody pointed this controller at - +// another team's Higress in their own namespace - and taking SSA ownership of a field on it. +func TestGatewaySweepLeavesForeignGatewaysAlone(t *testing.T) { + foreign := keyAuthWithoutConsumers() + foreign.SetNamespace("someone-elses-higress") + r, c := newConsumerReconciler(t, foreign) + r.ensureGateways(context.Background()) + + var ka unstructured.Unstructured + ka.SetGroupVersionKind(wasmPluginGVK) + if err := c.Get(context.Background(), types.NamespacedName{ + Namespace: "someone-elses-higress", Name: "key-auth"}, &ka); err != nil { + t.Fatal(err) + } + if _, found, _ := unstructured.NestedSlice(ka.Object, "spec", "defaultConfig", "consumers"); found { + t.Fatal("wrote to a gateway nothing in this cluster points at") + } + + // ...but it does act once something names it. + cons := consumerFixture("tenant-a", "tenant-a-keys") + cons.Spec.Gateway.Namespace = "someone-elses-higress" + if err := c.Create(context.Background(), cons); err != nil { + t.Fatal(err) + } + if err := c.Create(context.Background(), credSecret("tenant-a-keys", + map[string]string{"key": "sk-a"})); err != nil { + t.Fatal(err) + } + r.ensureGateways(context.Background()) + if err := c.Get(context.Background(), types.NamespacedName{ + Namespace: "someone-elses-higress", Name: "key-auth"}, &ka); err != nil { + t.Fatal(err) + } + if _, found, _ := unstructured.NestedSlice(ka.Object, "spec", "defaultConfig", "consumers"); !found { + t.Fatal("did not write to a gateway an APIConsumer names") + } +} + +// A key-auth configured the OTHER way key_auth allows - a top-level `credentials` list and no +// consumers - must not have `consumers` added to it: the plugin refuses a config carrying +// both, so the write would take that gateway down. And such a gateway is, by definition, not +// one autoconfig set up. +func TestConsumerRefusesAKeyAuthUsingTopLevelCredentials(t *testing.T) { + other := wasmPlugin("key-auth") + _ = unstructured.SetNestedStringSlice(other.Object, []string{"sk-theirs"}, + "spec", "defaultConfig", "credentials") + _ = unstructured.SetNestedStringSlice(other.Object, []string{"x-api-key"}, + "spec", "defaultConfig", "keys") + r, c := newConsumerReconciler(t, + consumerFixture("tenant-a", "tenant-a-keys"), + credSecret("tenant-a-keys", map[string]string{"key": "sk-a"}), + other, + ) + _, err := r.programGateway(context.Background(), "higress-system", nil) + if err == nil { + t.Fatal("wrote consumers into a key-auth that uses top-level credentials: the plugin " + + "refuses a config carrying both, so that gateway would stop answering") + } + if !strings.Contains(err.Error(), "credentials") { + t.Fatalf("the error does not explain what is wrong: %v", err) + } + // Their config is untouched. + var ka unstructured.Unstructured + ka.SetGroupVersionKind(wasmPluginGVK) + if err := c.Get(context.Background(), types.NamespacedName{ + Namespace: "higress-system", Name: "key-auth"}, &ka); err != nil { + t.Fatal(err) + } + if _, found, _ := unstructured.NestedSlice(ka.Object, "spec", "defaultConfig", "consumers"); found { + t.Fatal("consumers was added anyway") + } +} From df55976e6aa1d2cdb73b9811bf885ef577467e5b Mon Sep 17 00:00:00 2001 From: zhanghao Date: Thu, 26 Nov 2026 19:17:48 +0800 Subject: [PATCH 19/28] APIConsumer: take the gateway chart's label as the explicit signal 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 --- README.md | 10 ++++ internal/controller/apiconsumer_controller.go | 54 ++++++++++++++----- .../controller/apiconsumer_controller_test.go | 38 +++++++++++++ 3 files changed, 88 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 4ac10ec8..d568de22 100644 --- a/README.md +++ b/README.md @@ -492,6 +492,16 @@ key 泄露要立刻失效时,光改 Secret 最长还有一分钟能继续用。* 只 watch APIConsumer 的话零对象就是零 reconcile,那个键永远不会被写。 ⚠️ 同理:**新 chart 不能部署到还没升级 autoconfig 的集群**(旧版既不被触发、也不补写该键 → 网关 FAIL_CLOSE 且不自愈)。helmfile 侧已用 `semverCompare` 门禁 + `needs` 保证顺序。 +- **autoconfig 只写「自己的」网关**,三种判据取其一:① key-auth 上带 + `routing.modelsphere.dev/consumers: autoconfig` 标签(**chart 打的**,这是给「装在 + higress-system 以外、且还没有任何 fleet/consumer」的首装场景用的);② 有 APIConsumer 或 + ModelFleet 把该 namespace 指为自己的 gateway;③ 默认 namespace `higress-system`。 + ③ 是过渡兜底 —— 没有标签的 chart 版本在首装时会让网关 FAIL_CLOSE,那比「往 + higress-system 里一个没人指名的 key-auth 写东西」更糟;**等带标签的 chart 发布后应当去掉 ③**。 + 不限制范围的话,就等于给别人团队自己 namespace 里的 Higress 加 `consumers` 并夺走那个字段。 +- **绝不往带顶层 `credentials` 的 key-auth 里写 `consumers`**:`key_auth` 接受 `consumers` + **或**顶层 `credentials`,两者并存会拒绝整份配置 —— 那种网关按定义不是 autoconfig 建的, + 写进去会把它打死。有我们的东西要写时报错说明,没有时直接放手。 - **一个 key 只能属于一个 consumer。** `key_auth` 遇到重复 credential 会 `return false`、 整份配置解析失败 —— 加上 FAIL_CLOSE,后果是**整个网关所有路由全部拒绝**,不是「其中一个不生效」。 渲染层会拒,但别指望它兜住所有写法。 diff --git a/internal/controller/apiconsumer_controller.go b/internal/controller/apiconsumer_controller.go index f2123867..a86e2da6 100644 --- a/internal/controller/apiconsumer_controller.go +++ b/internal/controller/apiconsumer_controller.go @@ -1328,13 +1328,26 @@ func (r *APIConsumerReconciler) ensureGateways(ctx context.Context) { if o.GetName() != "key-auth" { continue } - // Only gateways something in this cluster points at. Writing to every key-auth - // anywhere would mean adding `consumers: []` to a Higress that another team runs in - // their own namespace, and taking SSA ownership of that field on it - acting on an - // object nobody pointed this controller at. A namespace no APIConsumer and no - // ModelFleet names has no routes from us either, so there is nothing of ours to keep - // working there. - if !wanted[o.GetNamespace()] { + // Only gateways that are ours to write. Writing to every key-auth anywhere would + // mean adding `consumers: []` to a Higress another team runs in their own + // namespace, and taking SSA ownership of that field on it - acting on an object + // nobody pointed this controller at. + // + // Three ways to be ours, in order of how explicit they are: + // + // 1. the label the gateway chart puts on the key-auth it installs. This is the one + // that works for a chart installed in any namespace before any fleet or + // consumer exists, which is the fresh-install case and the whole reason the + // sweep exists (agreed with the chart in modelsphere/helm-charts#122); + // 2. an APIConsumer or a ModelFleet naming that namespace as its gateway; + // 3. the default gateway namespace. + // + // 3 is kept although 1 subsumes it for any chart that carries the label, because a + // chart release without the label would otherwise leave a fresh install's gateway + // FAIL_CLOSE - and that is the failure worth 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. + if !ourGateway(o, wanted) { continue } if _, err := r.programGateway(ctx, o.GetNamespace(), nil); err != nil && @@ -1391,13 +1404,26 @@ func (r *APIConsumerReconciler) gatewayNamespacesInUse(ctx context.Context) (map out[ns] = true } } - // The default gateway namespace, always. It is where the gateway chart installs, and on - // a fresh install nothing names it yet - no APIConsumer, no fleet - while key-auth's - // defaultConfig is already active (defaultConfigDisable is false) and therefore already - // has to parse. That is the case the sweep exists for, and restricting the sweep to - // named namespaces without this killed it: both sweep tests went red, which is how I - // found out rather than by reasoning. - out[defaultGatewayNamespace] = true delete(out, "") return out, nil } + +// consumersLabel: the gateway chart puts this on the key-auth WasmPlugin it installs, to say +// that its consumer list belongs to autoconfig. Agreed with that chart rather than invented +// here, so changing it is a change to both. +// +// It names the FIELD, not just the manager, which is the point: keys and global_auth on the +// same object stay with the chart. +const consumersLabel = "routing.modelsphere.dev/consumers" + +// ourGateway: may this controller write the consumer list of this key-auth? See the call site +// for why there are three answers and not one. +func ourGateway(o *unstructured.Unstructured, named map[string]bool) bool { + if o.GetLabels()[consumersLabel] == "autoconfig" { + return true + } + if named[o.GetNamespace()] { + return true + } + return o.GetNamespace() == defaultGatewayNamespace +} diff --git a/internal/controller/apiconsumer_controller_test.go b/internal/controller/apiconsumer_controller_test.go index 3fed6a61..c71dc31c 100644 --- a/internal/controller/apiconsumer_controller_test.go +++ b/internal/controller/apiconsumer_controller_test.go @@ -1658,3 +1658,41 @@ func TestConsumerRefusesAKeyAuthUsingTopLevelCredentials(t *testing.T) { t.Fatal("consumers was added anyway") } } + +// The label is what makes a gateway chart installed OUTSIDE the default namespace work before +// any fleet or consumer exists - the fresh-install case the sweep exists for. Without it such +// a gateway would sit FAIL_CLOSE until somebody created the first object. +func TestGatewaySweepWritesToALabelledGatewayAnywhere(t *testing.T) { + ka := keyAuthWithoutConsumers() + ka.SetNamespace("gateway-elsewhere") + ka.SetLabels(map[string]string{consumersLabel: "autoconfig"}) + r, c := newConsumerReconciler(t, ka) // no APIConsumer, no fleet, not the default namespace + r.ensureGateways(context.Background()) + + var got unstructured.Unstructured + got.SetGroupVersionKind(wasmPluginGVK) + if err := c.Get(context.Background(), types.NamespacedName{ + Namespace: "gateway-elsewhere", Name: "key-auth"}, &got); err != nil { + t.Fatal(err) + } + if _, found, _ := unstructured.NestedSlice(got.Object, "spec", "defaultConfig", "consumers"); !found { + t.Fatal("the labelled gateway did not get its consumers key: a chart installed outside " + + "higress-system would stay FAIL_CLOSE until the first APIConsumer or fleet") + } + + // ...and the label has to say autoconfig. Somebody else's label value is not consent. + other := keyAuthWithoutConsumers() + other.SetNamespace("gateway-other") + other.SetLabels(map[string]string{consumersLabel: "somebody-else"}) + if err := c.Create(context.Background(), other); err != nil { + t.Fatal(err) + } + r.ensureGateways(context.Background()) + if err := c.Get(context.Background(), types.NamespacedName{ + Namespace: "gateway-other", Name: "key-auth"}, &got); err != nil { + t.Fatal(err) + } + if _, found, _ := unstructured.NestedSlice(got.Object, "spec", "defaultConfig", "consumers"); found { + t.Fatal("wrote to a gateway whose label names a different manager") + } +} From 5e31be60c980832706d9efff5734191f9b2dfeb0 Mon Sep 17 00:00:00 2001 From: zhanghao Date: Thu, 26 Nov 2026 19:37:12 +0800 Subject: [PATCH 20/28] APIConsumer: the gateway scope check belongs in the write path, not in 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 --- internal/controller/apiconsumer_controller.go | 73 ++++++++++++------- .../controller/apiconsumer_controller_test.go | 32 ++++++++ 2 files changed, 77 insertions(+), 28 deletions(-) diff --git a/internal/controller/apiconsumer_controller.go b/internal/controller/apiconsumer_controller.go index a86e2da6..63198a7d 100644 --- a/internal/controller/apiconsumer_controller.go +++ b/internal/controller/apiconsumer_controller.go @@ -275,6 +275,35 @@ func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, // The names already in this gateway's list. Needed before rendering, to tell "this // consumer's Secret is unreadable and it has a key in there" (fail closed) from "...and // it has nothing in there" (skip it rather than freeze everyone else). + // Is this gateway ours to write at all? Asked HERE, in the one function that writes a + // consumer list, rather than at each entry point - the first version checked it in the + // periodic sweep only, and the key-auth watch (which fires for every key-auth in the + // cluster) walked straight past it. The probe on the test cluster caught that: autoconfig + // wrote to a gateway labelled for another manager and to an unlabelled one in a namespace + // nothing names. + // + // The APIConsumer path cannot fail this check by construction - the object names the + // gateway, so it is in the set - but it runs there too, because a check that only some + // callers make is a check somebody will forget to make. + keyAuth := &unstructured.Unstructured{} + keyAuth.SetGroupVersionKind(wasmPluginGVK) + if err := r.gatewayReader().Get(ctx, types.NamespacedName{ + Namespace: gwNS, Name: "key-auth"}, keyAuth); err != nil { + if isAbsent(err) { + return gatewayRound{}, fmt.Errorf("key-auth in namespace %q: %w", gwNS, errGatewayAbsent) + } + return gatewayRound{}, err + } + named, err := r.gatewayNamespacesInUse(ctx) + if err != nil { + return gatewayRound{}, err + } + if !ourGateway(keyAuth, named) { + logf.FromContext(ctx).V(1).Info("not this controller's gateway: no label, and nothing "+ + "names it", "gateway", gwNS) + return gatewayRound{}, nil + } + liveEntries, liveManaged, err := r.liveConsumerState(ctx, gwNS) if err != nil && !errors.Is(err, errGatewayAbsent) { return gatewayRound{}, err @@ -1318,38 +1347,13 @@ func (r *APIConsumerReconciler) ensureGateways(ctx context.Context) { log.V(1).Info("could not list WasmPlugins for the gateway sweep", "err", err.Error()) return } - wanted, err := r.gatewayNamespacesInUse(ctx) - if err != nil { - log.V(1).Info("could not work out which gateways are ours", "err", err.Error()) - return - } for i := range list.Items { o := &list.Items[i] if o.GetName() != "key-auth" { continue } - // Only gateways that are ours to write. Writing to every key-auth anywhere would - // mean adding `consumers: []` to a Higress another team runs in their own - // namespace, and taking SSA ownership of that field on it - acting on an object - // nobody pointed this controller at. - // - // Three ways to be ours, in order of how explicit they are: - // - // 1. the label the gateway chart puts on the key-auth it installs. This is the one - // that works for a chart installed in any namespace before any fleet or - // consumer exists, which is the fresh-install case and the whole reason the - // sweep exists (agreed with the chart in modelsphere/helm-charts#122); - // 2. an APIConsumer or a ModelFleet naming that namespace as its gateway; - // 3. the default gateway namespace. - // - // 3 is kept although 1 subsumes it for any chart that carries the label, because a - // chart release without the label would otherwise leave a fresh install's gateway - // FAIL_CLOSE - and that is the failure worth 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. - if !ourGateway(o, wanted) { - continue - } + // No scope check here: programGateway makes it, for every caller. One was here + // once, and the key-auth watch - the other entry point - did not have it. if _, err := r.programGateway(ctx, o.GetNamespace(), nil); err != nil && !errors.Is(err, errGatewayAbsent) { log.V(1).Info("gateway sweep did not program this gateway", @@ -1391,7 +1395,14 @@ func (r *APIConsumerReconciler) gatewayNamespacesInUse(ctx context.Context) (map return nil, fmt.Errorf("list APIConsumers: %w", err) } for i := range consumers.Items { - out[consumerGatewayNamespace(&consumers.Items[i])] = true + c := &consumers.Items[i] + out[consumerGatewayNamespace(c)] = true + // ...and any gateway this controller HAS programmed, which the spec may no longer + // name: moving spec.gateway.namespace has to withdraw the credential from the old + // one, and that gateway is ours precisely because we put a key there. Without this, + // the scope check refused to touch it and the key stayed live forever - which the + // move test caught. + out[c.Status.AppliedGatewayNamespace] = true } var fleets routingv1.ModelFleetList if err := r.List(ctx, &fleets); err != nil { @@ -1422,6 +1433,12 @@ func ourGateway(o *unstructured.Unstructured, named map[string]bool) bool { if o.GetLabels()[consumersLabel] == "autoconfig" { return true } + // Our own record on the object: this controller wrote this list before, so it is ours to + // keep correct even if nothing names the namespace any more. It is also what lets a + // revocation finish on a gateway whose last APIConsumer has just been deleted. + if o.GetAnnotations()[managedConsumersAnnotation] != "" { + return true + } if named[o.GetNamespace()] { return true } diff --git a/internal/controller/apiconsumer_controller_test.go b/internal/controller/apiconsumer_controller_test.go index c71dc31c..217e2d8d 100644 --- a/internal/controller/apiconsumer_controller_test.go +++ b/internal/controller/apiconsumer_controller_test.go @@ -1696,3 +1696,35 @@ func TestGatewaySweepWritesToALabelledGatewayAnywhere(t *testing.T) { t.Fatal("wrote to a gateway whose label names a different manager") } } + +// The scope check has to hold on EVERY path into a write, not just the sweep. It was in the +// sweep only, and the key-auth watch - which fires for every key-auth in the cluster - walked +// straight past it: a probe on the test cluster found autoconfig writing to a gateway labelled +// for another manager and to an unlabelled one in a namespace nothing names. No unit test +// covered the watch path with a foreign gateway, so nothing here said a word. +func TestKeyAuthWatchRespectsTheGatewayScope(t *testing.T) { + foreign := keyAuthWithoutConsumers() + foreign.SetNamespace("someone-elses-higress") + theirs := keyAuthWithoutConsumers() + theirs.SetNamespace("labelled-for-someone-else") + theirs.SetLabels(map[string]string{consumersLabel: "somebody-else"}) + r, c := newConsumerReconciler(t, foreign, theirs) + kr := &KeyAuthReconciler{APIConsumerReconciler: r} + + for _, ns := range []string{"someone-elses-higress", "labelled-for-someone-else"} { + if _, err := kr.Reconcile(context.Background(), ctrl.Request{ + NamespacedName: types.NamespacedName{Namespace: ns, Name: "key-auth"}, + }); err != nil { + t.Fatalf("%s: %v", ns, err) + } + var ka unstructured.Unstructured + ka.SetGroupVersionKind(wasmPluginGVK) + if err := c.Get(context.Background(), types.NamespacedName{ + Namespace: ns, Name: "key-auth"}, &ka); err != nil { + t.Fatal(err) + } + if _, found, _ := unstructured.NestedSlice(ka.Object, "spec", "defaultConfig", "consumers"); found { + t.Fatalf("%s: the watch wrote to a gateway this controller has no claim on", ns) + } + } +} From 0f53115192f32407e9a3587899b07bd86e82c2b5 Mon Sep 17 00:00:00 2001 From: zhanghao Date: Thu, 26 Nov 2026 20:52:49 +0800 Subject: [PATCH 21/28] ModelFleet: the repetition guard runs on every fleet route unless a fleet 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 --- README.md | 10 +++ api/v1alpha1/modelfleet_types.go | 31 ++++++++ api/v1alpha1/zz_generated.deepcopy.go | 20 ++++++ .../routing.modelsphere.dev_modelfleets.yaml | 30 ++++++++ .../routing.modelsphere.dev_modelfleets.yaml | 30 ++++++++ internal/controller/modelfleet_controller.go | 26 +++++++ .../controller/modelfleet_controller_test.go | 70 +++++++++++++++++++ internal/sink/fleet.go | 11 +++ 8 files changed, 228 insertions(+) diff --git a/README.md b/README.md index d568de22..09dc9346 100644 --- a/README.md +++ b/README.md @@ -479,6 +479,16 @@ key 泄露要立刻失效时,光改 Secret 最长还有一分钟能继续用。* `return false` 整份配置解析失败,而插件是 `FAIL_CLOSE`,后果是**整个网关所有路由全部拒绝**, 不是"其中一个不生效"。渲染层会拒掉这种配置(报错只给 consumer 名和下标,不带 key 值)。 +**ai-stream-guard(重复检测截断)默认对每条 fleet 路由开启**,`gateway.streamGuard.disabled: true` +是显式退出。它**不走 `extraPlugins`**,理由是层级:`extraPlugins` 由建 fleet 的人逐个填, +而「默认都该有的防护」一旦要人记得写,照抄老 YAML 建的新模型就静默没有保护。默认值归 controller, +`extraPlugins` 归「这一个 fleet 要的不一样」。 +autoconfig 写的是一条**空规则** —— 插件的 `parseRuleConfig` 以全局配置为底,空规则即「按 chart 配的参数跑」, +所以阈值只存在于 chart 一处。关掉是**撤掉规则**,不是写另一份配置。 +⚠️ **chart 的 `defaultConfig` 必须有非空 `detectors`**:插件拒绝 detectors 为空的配置(包括从全局继承到的空), +而**一个插件加载失败会卡住该网关上所有插件的配置推送**。 +插件对象不存在时**容忍**(只是少了防护,不像 key-auth 那样是 401),同步照常成功。 + **与网关 chart 的契约**(`modelsphere/helm-charts` 的 `charts/higress-llm`,双方都依赖,改一边会坏另一边): - **chart 不再渲染 `defaultConfig.consumers`,这个字段整个归 autoconfig。** 它继续渲染 diff --git a/api/v1alpha1/modelfleet_types.go b/api/v1alpha1/modelfleet_types.go index da92e355..35b9ac93 100644 --- a/api/v1alpha1/modelfleet_types.go +++ b/api/v1alpha1/modelfleet_types.go @@ -241,6 +241,37 @@ type GatewaySpec struct { // +kubebuilder:validation:MaxItems=64 // +kubebuilder:validation:XValidation:rule="!self.exists(c, c == '*') || size(self) == 1",message="authConsumers: \"*\" means \"no authentication on this route\" and cannot be combined with consumer names" AuthConsumers []string `json:"authConsumers,omitempty"` + // StreamGuard: the repetition guard on this fleet's route. ON for every fleet unless this + // says otherwise, which is the whole point of the field existing at all. + // + // It is not in extraPlugins, although that would have worked without a line of controller + // code, because extraPlugins is written per fleet by whoever creates it - and a protection + // that each caller has to remember to switch on is missing from the fleet somebody built + // by copying an older one, silently, with nothing to say so. A default belongs to the + // controller; extraPlugins is for what ONE fleet wants differently. + // + // The parameters stay in the gateway chart's defaultConfig: this writes an empty rule and + // the plugin reads it as "the global config applies here" (its parseRuleConfig starts from + // the global one). So a fleet turning it off is a rule withdrawn, not a config rewritten. + // + // ⚠ The chart's defaultConfig MUST carry a non-empty `detectors`. The plugin refuses a + // config with none - including one inherited as empty - and a plugin that fails to load + // stalls the config push for EVERY plugin on that gateway, not just this one. + // +optional + StreamGuard *StreamGuard `json:"streamGuard,omitempty"` +} + +// StreamGuard says whether the repetition guard runs on this route. +type StreamGuard struct { + // Disabled takes the guard off this route. Spelled as the negative so that the safe + // behaviour is what an absent field means: a fleet nobody thought about is guarded, and + // turning the guard off is a thing somebody wrote down. + // + // What the guard does when it fires is cut the stream - a terminal chunk carrying + // finish_reason, then [DONE] - so switching it off is a real decision for a route whose + // callers would rather have a repetitive answer than a truncated one. + // +optional + Disabled bool `json:"disabled,omitempty"` } // ModelFleetSpec aggregates several single-hardware services into one externally visible model. diff --git a/api/v1alpha1/zz_generated.deepcopy.go b/api/v1alpha1/zz_generated.deepcopy.go index 9f6e29f6..340f1920 100644 --- a/api/v1alpha1/zz_generated.deepcopy.go +++ b/api/v1alpha1/zz_generated.deepcopy.go @@ -188,6 +188,11 @@ func (in *GatewaySpec) DeepCopyInto(out *GatewaySpec) { *out = make([]string, len(*in)) copy(*out, *in) } + if in.StreamGuard != nil { + in, out := &in.StreamGuard, &out.StreamGuard + *out = new(StreamGuard) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GatewaySpec. @@ -628,6 +633,21 @@ func (in *StickinessKey) DeepCopy() *StickinessKey { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *StreamGuard) DeepCopyInto(out *StreamGuard) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new StreamGuard. +func (in *StreamGuard) DeepCopy() *StreamGuard { + if in == nil { + return nil + } + out := new(StreamGuard) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *TotalCapacity) DeepCopyInto(out *TotalCapacity) { *out = *in diff --git a/config/crd/bases/routing.modelsphere.dev_modelfleets.yaml b/config/crd/bases/routing.modelsphere.dev_modelfleets.yaml index d7cbef44..fcc71bf8 100644 --- a/config/crd/bases/routing.modelsphere.dev_modelfleets.yaml +++ b/config/crd/bases/routing.modelsphere.dev_modelfleets.yaml @@ -186,6 +186,36 @@ spec: port defaults to 8080). The Ingress points here; the router plugin rewrites the path per member. Defaults to "/openresty:8080". type: string + streamGuard: + description: |- + StreamGuard: the repetition guard on this fleet's route. ON for every fleet unless this + says otherwise, which is the whole point of the field existing at all. + + It is not in extraPlugins, although that would have worked without a line of controller + code, because extraPlugins is written per fleet by whoever creates it - and a protection + that each caller has to remember to switch on is missing from the fleet somebody built + by copying an older one, silently, with nothing to say so. A default belongs to the + controller; extraPlugins is for what ONE fleet wants differently. + + The parameters stay in the gateway chart's defaultConfig: this writes an empty rule and + the plugin reads it as "the global config applies here" (its parseRuleConfig starts from + the global one). So a fleet turning it off is a rule withdrawn, not a config rewritten. + + ⚠ The chart's defaultConfig MUST carry a non-empty `detectors`. The plugin refuses a + config with none - including one inherited as empty - and a plugin that fails to load + stalls the config push for EVERY plugin on that gateway, not just this one. + properties: + disabled: + description: |- + Disabled takes the guard off this route. Spelled as the negative so that the safe + behaviour is what an absent field means: a fleet nobody thought about is guarded, and + turning the guard off is a thing somebody wrote down. + + What the guard does when it fires is cut the stream - a terminal chunk carrying + finish_reason, then [DONE] - so switching it off is a real decision for a route whose + callers would rather have a repetitive answer than a truncated one. + type: boolean + type: object upstreamAuthSecretRef: description: |- UpstreamAuthSecretRef: the Secret holding the API key the gateway presents to openresty, diff --git a/deploy/helm/autoconfig/crds/routing.modelsphere.dev_modelfleets.yaml b/deploy/helm/autoconfig/crds/routing.modelsphere.dev_modelfleets.yaml index d7cbef44..fcc71bf8 100644 --- a/deploy/helm/autoconfig/crds/routing.modelsphere.dev_modelfleets.yaml +++ b/deploy/helm/autoconfig/crds/routing.modelsphere.dev_modelfleets.yaml @@ -186,6 +186,36 @@ spec: port defaults to 8080). The Ingress points here; the router plugin rewrites the path per member. Defaults to "/openresty:8080". type: string + streamGuard: + description: |- + StreamGuard: the repetition guard on this fleet's route. ON for every fleet unless this + says otherwise, which is the whole point of the field existing at all. + + It is not in extraPlugins, although that would have worked without a line of controller + code, because extraPlugins is written per fleet by whoever creates it - and a protection + that each caller has to remember to switch on is missing from the fleet somebody built + by copying an older one, silently, with nothing to say so. A default belongs to the + controller; extraPlugins is for what ONE fleet wants differently. + + The parameters stay in the gateway chart's defaultConfig: this writes an empty rule and + the plugin reads it as "the global config applies here" (its parseRuleConfig starts from + the global one). So a fleet turning it off is a rule withdrawn, not a config rewritten. + + ⚠ The chart's defaultConfig MUST carry a non-empty `detectors`. The plugin refuses a + config with none - including one inherited as empty - and a plugin that fails to load + stalls the config push for EVERY plugin on that gateway, not just this one. + properties: + disabled: + description: |- + Disabled takes the guard off this route. Spelled as the negative so that the safe + behaviour is what an absent field means: a fleet nobody thought about is guarded, and + turning the guard off is a thing somebody wrote down. + + What the guard does when it fires is cut the stream - a terminal chunk carrying + finish_reason, then [DONE] - so switching it off is a real decision for a route whose + callers would rather have a repetitive answer than a truncated one. + type: boolean + type: object upstreamAuthSecretRef: description: |- UpstreamAuthSecretRef: the Secret holding the API key the gateway presents to openresty, diff --git a/internal/controller/modelfleet_controller.go b/internal/controller/modelfleet_controller.go index d03a0bfb..71190dca 100644 --- a/internal/controller/modelfleet_controller.go +++ b/internal/controller/modelfleet_controller.go @@ -850,6 +850,32 @@ func fleetPlugins() []fleetPlugin { // different accounting attributes may simply say so. overridable: true, config: func(f *fleetRender) (any, error) { return sink.RenderAIStatistics(), nil }, + }, { + // The repetition guard. Default ON: a rule is written for every fleet that has not + // said otherwise, which is why this is a plugin of its own rather than something each + // fleet passes through extraPlugins - a protection somebody has to remember to switch + // on is missing from the next fleet built by copying an older one. + name: "ai-stream-guard", + // Its absence costs the guard and nothing else: no 401, no route down, no missing + // metrics. A cluster whose gateway chart predates this plugin must not stop + // publishing fleets over it. + tolerateMissing: func(*fleetRender) bool { return true }, + // Overridable, so a fleet that wants different thresholds can say so through + // extraPlugins - the same escape hatch ai-statistics has. The default here is an + // empty rule, which the plugin reads as "the global config applies". + overridable: true, + config: func(f *fleetRender) (any, error) { + if g := f.fleet.Spec.Gateway.StreamGuard; g != nil && g.Disabled { + return nil, nil // no rule: the guard does not run on this route + } + // Deliberately empty. The plugin's parseRuleConfig starts from the global config, + // so an empty rule means "what the chart configured", and this controller never + // has to know the detector parameters. ⚠ It does mean the chart's defaultConfig + // must carry a non-empty `detectors`: the plugin refuses a config with none, and + // a plugin that fails to load stalls the config push for every plugin on the + // gateway. + return sink.RenderStreamGuard(), nil + }, }} } diff --git a/internal/controller/modelfleet_controller_test.go b/internal/controller/modelfleet_controller_test.go index 83cafd66..b1de35a1 100644 --- a/internal/controller/modelfleet_controller_test.go +++ b/internal/controller/modelfleet_controller_test.go @@ -2613,3 +2613,73 @@ func TestFleetCapacityUsesTheSharedPeerRule(t *testing.T) { t.Fatalf("capacity = %d, want 100 (the cart cap follows the backends)", got) } } + +// The guard is on for a fleet that never mentions it. That is the whole reason it is a plugin +// of this controller's rather than something each fleet passes through extraPlugins: a +// protection somebody has to remember to switch on is missing from the next fleet built by +// copying an older one, silently. +func TestFleetStreamGuardIsOnByDefault(t *testing.T) { + f := fleetFixture() // says nothing about streamGuard + r, c := newFleetReconciler(t, f, + modelRoute("glm-53-h100", "llm-route", "glm-53-h100", 2, true), + modelRoute("glm-53-ascend", "llm-route", "glm-53-ascend", 1, true), + wasmPlugin("ai-backend-router"), keyAuthPlugin(map[string]string{"ops": "sk-ops"}), + wasmPlugin("ai-statistics"), wasmPlugin("ai-stream-guard"), + ) + reconcileFleet(t, r) + + rules := getPlugin(t, c, "ai-stream-guard") + if len(rules) != 1 { + t.Fatalf("ai-stream-guard has %d rule(s), want 1: a fleet that says nothing must be guarded", len(rules)) + } + rule := rules[0].(map[string]any) + // The rule is EMPTY on purpose: the plugin reads an empty rule as "the global config + // applies", so the detector parameters live in the chart and not in two places. + cfg, _ := rule["config"].(map[string]any) + if len(cfg) != 0 { + t.Fatalf("the rule carries config %v, want an empty one so the chart's parameters apply", cfg) + } + if d, _ := rule["configDisable"].(bool); d { + t.Fatal("configDisable is true: the rule turns the plugin OFF for this route") + } + + // ...and turning it off withdraws the rule rather than writing a different config. + var fleet routingv1.ModelFleet + nn := types.NamespacedName{Namespace: "llm-route", Name: "glm-5.3"} + if err := c.Get(context.Background(), nn, &fleet); err != nil { + t.Fatal(err) + } + fleet.Spec.Gateway.StreamGuard = &routingv1.StreamGuard{Disabled: true} + fleet.Generation = 2 + if err := c.Update(context.Background(), &fleet); err != nil { + t.Fatal(err) + } + reconcileFleet(t, r) + if n := len(getPlugin(t, c, "ai-stream-guard")); n != 0 { + t.Fatalf("ai-stream-guard still has %d rule(s) after the fleet turned it off", n) + } +} + +// A gateway whose chart predates this plugin must keep publishing fleets. The guard's absence +// costs the guard and nothing else - no 401, no route down, no missing metrics - so unlike +// ai-backend-router and key-auth it must not fail the sync. +func TestFleetStreamGuardMissingPluginIsTolerated(t *testing.T) { + r, c := newFleetReconciler(t, fleetFixture(), + modelRoute("glm-53-h100", "llm-route", "glm-53-h100", 2, true), + modelRoute("glm-53-ascend", "llm-route", "glm-53-ascend", 1, true), + wasmPlugin("ai-backend-router"), keyAuthPlugin(map[string]string{"ops": "sk-ops"}), + wasmPlugin("ai-statistics"), + // no ai-stream-guard object at all + ) + reconcileFleet(t, r) + + var fleet routingv1.ModelFleet + _ = c.Get(context.Background(), types.NamespacedName{Namespace: "llm-route", Name: "glm-5.3"}, &fleet) + if !condTrue(fleet.Status.Conditions, condGatewaySynced) { + t.Fatalf("the fleet refused to publish over a missing guard: %s", + condMessage(fleet.Status.Conditions, condGatewaySynced)) + } + if !condTrue(fleet.Status.Conditions, condReady) { + t.Fatal("Ready=False although only the guard is missing") + } +} diff --git a/internal/sink/fleet.go b/internal/sink/fleet.go index f9fecc92..e8cf407f 100644 --- a/internal/sink/fleet.go +++ b/internal/sink/fleet.go @@ -334,3 +334,14 @@ func RenderAIStatistics() *AIStatistics { ApplyToLog: true, }}} } + +// StreamGuardRule is the match rule written for the repetition guard: empty on purpose. +// +// The plugin's parseRuleConfig starts from the global config and only replaces what the rule +// names, so an empty object means "the parameters the gateway chart configured apply to this +// route too". Writing them again here would put the detector thresholds in two places, and +// this controller has no opinion about them. +type StreamGuardRule struct{} + +// RenderStreamGuard: the rule that turns the guard on for a route. +func RenderStreamGuard() *StreamGuardRule { return &StreamGuardRule{} } From 3cc912244b4e3ebeaf1f5b10e0bd3a9d4ae7cdfd Mon Sep 17 00:00:00 2001 From: zhanghao Date: Thu, 26 Nov 2026 21:12:42 +0800 Subject: [PATCH 22/28] Seven review findings, and a design that a cluster measurement overturned 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 --- README.md | 6 +- cmd/main.go | 10 +- cmd/main_test.go | 12 ++ internal/controller/apiconsumer_controller.go | 150 ++++++++---------- .../controller/apiconsumer_controller_test.go | 96 +++++++---- internal/controller/modelfleet_controller.go | 120 ++++++++++++-- .../controller/modelfleet_controller_test.go | 83 +++++++++- 7 files changed, 343 insertions(+), 134 deletions(-) diff --git a/README.md b/README.md index 09dc9346..5944ecaf 100644 --- a/README.md +++ b/README.md @@ -470,7 +470,11 @@ reconciler 把同一个网关下所有 `APIConsumer` 聚合、按名字排序, ⚠️ **撤销(从 Secret 里删掉一个 value)也是同一个 60s 口径** —— 这件事比"加 key 慢一分钟"要紧: key 泄露要立刻失效时,光改 Secret 最长还有一分钟能继续用。**要立刻生效就动对象本身** (改一个 annotation 即可,如 `kubectl annotate apiconsumer <名字> rotated-at=$(date +%s) --overwrite`), -那是 generation 变化、下一秒就 reconcile。更彻底的是直接 `kubectl delete apiconsumer <名字>`: +下一秒就会 reconcile。 +⚠️ 注意 annotation 改动**不会推进 `metadata.generation`**(带 status 子资源的 CR 只在 spec 变化时推进), +所以 `status.observedGeneration` 不会动 —— 也就是说**这条路子没法用 observedGeneration 来确认已生效**, +得看 `status.lastSyncTime` 或直接去网关上核 consumer 列表。要确认收敛的紧急场景,改 spec 里的字段 +(或直接 `kubectl delete apiconsumer`)比改 annotation 更合适。更彻底的是直接 `kubectl delete apiconsumer <名字>`: 删除走 finalizer,key 在对象消失之前就已经从网关名单里撤掉了。 渲染出的 credential 带 `Bearer ` 前缀(Secret 里存裸 key 即可):key-auth 比较的是 diff --git a/cmd/main.go b/cmd/main.go index ca7cdada..483d096c 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -98,9 +98,17 @@ func runController(leaderElect bool) error { if err != nil { return err } + // A discovery failure for a group this project does not own must not stop this binary. + // Returning the error aborted runController, so one flaky call crash-looped the pod and + // took ModelRoute - openresty peers, CART workers, monitor.conf - down with it: the exact + // outcome the gate and its test exist to prevent, reintroduced by the gate's own plumbing. + // Failing closed means no watch, and the periodic sweep picks Higress up anyway. higressServed, err := kindServed(cs, wasmPluginGroupVersion, "WasmPlugin") if err != nil { - return err + log.Printf("could not ask whether %s is served (%v): skipping the key-auth watch. "+ + "The periodic gateway sweep still runs, so this self-corrects without a restart", + wasmPluginGroupVersion, err) + higressServed = false } if served["ModelFleet"] { if err := (&controller.ModelFleetReconciler{ diff --git a/cmd/main_test.go b/cmd/main_test.go index 17b738cc..1ea51787 100644 --- a/cmd/main_test.go +++ b/cmd/main_test.go @@ -75,3 +75,15 @@ func TestKeyAuthWatchWanted(t *testing.T) { "nothing creates key-auth's consumers key and the gateway stays FAIL_CLOSE") } } + +// A discovery failure for a group this project does not own must not stop the binary. The +// gate's own plumbing used to return the error, which aborted startup - so one flaky call +// crash-looped the pod and took ModelRoute down with it, the exact outcome the gate exists to +// prevent. There is no unit hook on runController, so this pins the contract where it can be +// pinned: the decision function treats "cannot tell" the same as "not served". +func TestKeyAuthWatchWantedOnDiscoveryFailure(t *testing.T) { + // The caller turns an error into false; this asserts what false then means. + if keyAuthWatchWanted(false) { + t.Fatal("a cluster we could not ask about would get the watch registered anyway") + } +} diff --git a/internal/controller/apiconsumer_controller.go b/internal/controller/apiconsumer_controller.go index 63198a7d..715c8e8f 100644 --- a/internal/controller/apiconsumer_controller.go +++ b/internal/controller/apiconsumer_controller.go @@ -314,6 +314,10 @@ func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, } round := gatewayRound{skipped: map[string]string{}} + // Names whose LIVE entry this round must keep as it is, because their own credentials + // could not be read. Not the same as "ours to rewrite" and not the same as "somebody + // else's": it is "ours, and we cannot render it right now". + preserve := map[string]bool{} // incumbent: is the entry under this consumer's name in this gateway THIS object's? // Everything that can go wrong with a newcomer is survivable by leaving it out; the same // thing wrong with an incumbent means refusing the round, because dropping it revokes a @@ -345,6 +349,23 @@ func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, return false // that entry is on record as somebody else's } } + // Two objects can reach this point for one name: the one whose gateway write landed + // while its status write did not - the case this fallback exists for - and a + // newcomer claiming the same consumerName. Both would count as incumbents, and two + // incumbents make the collision check refuse the round for the whole gateway, which + // is the impostor-driven freeze this is supposed to avoid. The annotation records + // which names this controller actually wrote, so it breaks the tie: an entry it + // wrote belongs to whoever was there, and a second claimant is a newcomer. + if liveManaged[name] { + for i := range list.Items { + o := &list.Items[i] + if o.Namespace != c.Namespace || o.Name != c.Name { + if consumerName(o) == name && o.CreationTimestamp.Before(&c.CreationTimestamp) { + return false // somebody was here first + } + } + } + } return true } views := make([]sink.ConsumerView, 0, len(list.Items)) @@ -361,11 +382,31 @@ func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, } creds, err := r.readCredentials(ctx, c) if err != nil { - // Fail closed for a consumer that HAS a key in this gateway: dropping it from - // the list is a 401 on its next request, and a Secret that is briefly - // unreadable must not revoke anyone. The whole round is refused, the gateway - // keeps its last good list, and the failure is reported on the object that - // caused it. + // Fail closed for a consumer that HAS a key in this gateway, but only for a + // TRANSIENT failure: a Secret that is briefly unreadable must not revoke + // anyone, so the round is refused and the gateway keeps its last good list. + // + // ...and failing the round forever is not the answer either. A Secret that is + // absent, or present with nothing usable in it, is a state somebody put the + // cluster in rather than a blip: waiting for it froze the gateway for + // EVERYBODY - no other consumer could be added, rotated or REVOKED, including + // pulling a leaked key - and a deletion in flight kept failing until the revoke + // deadline and then released with its key still live. + // + // Dropping this consumer instead would revoke a working key because somebody + // deleted an unrelated Secret: a management-plane problem traded for a + // data-plane outage. So neither. Its LIVE entry is carried over verbatim - the + // same thing done for an entry this controller does not manage - so nobody + // loses access, everyone else's changes go through, and the reason sits on the + // object whose Secret is missing. + if hasLiveEntry(liveNames, consumerName(c)) { + preserve[consumerName(c)] = true + round.skipped[c.Namespace+"/"+c.Name] = err.Error() + + " (this consumer's existing entry was left in the gateway untouched, so " + + "its key keeps working; nothing else on this gateway is blocked. Fix the " + + "Secret, or delete this APIConsumer to revoke the key)" + continue + } // // But a consumer that was never programmed here has nothing in the list to // lose, and refusing the round on its behalf freezes the gateway for everybody @@ -423,7 +464,7 @@ func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, if err != nil { return round, err } - return round, r.writeConsumers(ctx, gwNS, consumers, ownedBefore, claimed) + return round, r.writeConsumers(ctx, gwNS, consumers, ownedBefore, claimed, preserve) } // dropCollidingNewcomers resolves two claims on one identity - the same consumer name, or the @@ -562,7 +603,7 @@ func sourcesOf(views []sink.ConsumerView) string { // writeConsumers replaces defaultConfig.consumers in the gateway's key-auth plugin, leaving // every other key in that config alone. func (r *APIConsumerReconciler) writeConsumers(ctx context.Context, gwNS string, - consumers []sink.KeyAuthConsumer, ownedBefore bool, claimed map[string]bool) error { + consumers []sink.KeyAuthConsumer, ownedBefore bool, claimed, preserve map[string]bool) error { log := logf.FromContext(ctx) return retry.RetryOnConflict(retry.DefaultRetry, func() error { obj := &unstructured.Unstructured{} @@ -666,17 +707,12 @@ func (r *APIConsumerReconciler) writeConsumers(ctx context.Context, gwNS string, next := make([]any, 0, len(consumers)) mine := make(map[string]bool, len(consumers)) - myCreds := make(map[string]map[string]bool, len(consumers)) for _, c := range consumers { m, err := sink.ToMap(c) if err != nil { return err } mine[c.Name] = true - myCreds[c.Name] = make(map[string]bool, len(c.Credentials)) - for _, cred := range c.Credentials { - myCreds[c.Name][cred] = true - } next = append(next, m) } // Carry over the live entries this controller did not write. The empty-list guard @@ -700,6 +736,13 @@ func (r *APIConsumerReconciler) writeConsumers(ctx context.Context, gwNS string, return fmt.Errorf("%s/key-auth: a live consumer has no name; refusing to "+ "rewrite a list this controller cannot account for", gwNS) } + if preserve[name] { + // Ours, but unrenderable this round: keep what is live. Checked before the + // managed/claimed skip, which is what would otherwise drop it. + foreign = append(foreign, name) + next = append(next, lc) + continue + } if managed[name] || claimed[name] { continue // already ours; this is a rotation, not an adoption } @@ -1108,42 +1151,10 @@ func (r *APIConsumerReconciler) hasNoLiveEntry(ctx context.Context, gwNS, name s return true, nil } -// credentialsNotCovered: how many of a live entry's credentials the rendered consumer does not -// carry. 0 means the writer demonstrably holds every key that entry already accepts. -func credentialsNotCovered(live map[string]any, rendered map[string]bool) int { - creds, _ := live["credentials"].([]any) - // Compared with the prefix stripped from BOTH sides. The rendered set is already - // prefixed, so a live entry stored bare could never be matched by any Secret content: - // `sk-x` renders as `Bearer sk-x`, and `Bearer sk-x` renders as the same thing, so the - // proof was impossible and the refusal told the operator to add a key they had already - // added. Possession of the key is the question here; how the entry spells it is not. - // - // Live entries do carry the prefix on these clusters (the gateway chart requires it), but - // a hand-written one need not, and ModelFleet's own checkAuth strips it for the same - // reason. - bare := make(map[string]bool, len(rendered)) - for c := range rendered { - bare[strings.TrimPrefix(c, bearerPrefixValue)] = true - } - missing := 0 - for _, c := range creds { - key, ok := c.(string) - if !ok || !bare[strings.TrimPrefix(key, bearerPrefixValue)] { - missing++ - } - } - return missing -} - // bearerPrefixValue mirrors sink's prefix. Duplicated rather than exported, because the sink // owns how a credential is RENDERED and this is only about recognising one. const bearerPrefixValue = "Bearer " -func liveCredentialCount(live map[string]any) int { - creds, _ := live["credentials"].([]any) - return len(creds) -} - // liveConsumerState: what this gateway's key-auth currently holds - each consumer name with // its credentials - and which of those names this controller recorded as its own. func (r *APIConsumerReconciler) liveConsumerState(ctx context.Context, gwNS string) ( @@ -1186,31 +1197,6 @@ func (r *APIConsumerReconciler) liveConsumerState(ctx context.Context, gwNS stri return entries, managed, nil } -// liveConsumerNames: the consumer names this gateway's key-auth currently holds. -func (r *APIConsumerReconciler) liveConsumerNames(ctx context.Context, gwNS string) (map[string]bool, error) { - out := map[string]bool{} - obj := &unstructured.Unstructured{} - obj.SetGroupVersionKind(wasmPluginGVK) - if err := r.gatewayReader().Get(ctx, types.NamespacedName{Namespace: gwNS, Name: "key-auth"}, obj); err != nil { - if isAbsent(err) { - return out, fmt.Errorf("key-auth in namespace %q: %w", gwNS, errGatewayAbsent) - } - return out, err - } - live, _, err := unstructured.NestedSlice(obj.Object, "spec", "defaultConfig", "consumers") - if err != nil { - return out, err - } - for _, lc := range live { - if m, ok := lc.(map[string]any); ok { - if n, _ := m["name"].(string); n != "" { - out[n] = true - } - } - } - return out, nil -} - func hasLiveEntry(names map[string]bool, name string) bool { return names[name] } // KeyAuthReconciler watches each gateway's key-auth WasmPlugin, which is what makes this @@ -1262,22 +1248,6 @@ func (r *KeyAuthReconciler) SetupWithManager(mgr ctrl.Manager) error { Complete(r) } -// credentialsReformatted: would adoption keep the same key but change how it is spelled? True -// when a live credential lacks the prefix the rendered one carries. -func credentialsReformatted(live map[string]any, rendered map[string]bool) bool { - creds, _ := live["credentials"].([]any) - for _, c := range creds { - key, ok := c.(string) - if !ok || strings.HasPrefix(key, bearerPrefixValue) { - continue - } - if rendered[bearerPrefixValue+key] { - return true - } - } - return false -} - // dropUnprovenAdoptions leaves out any view that claims a consumer name already present in // the gateway and owned by no APIConsumer, unless it carries every credential that entry // accepts. Comparison ignores the `Bearer ` prefix on either side: possession of the key is @@ -1430,8 +1400,14 @@ const consumersLabel = "routing.modelsphere.dev/consumers" // ourGateway: may this controller write the consumer list of this key-auth? See the call site // for why there are three answers and not one. func ourGateway(o *unstructured.Unstructured, named map[string]bool) bool { - if o.GetLabels()[consumersLabel] == "autoconfig" { - return true + // The label is read as an ANSWER, not as a hint: present and naming somebody else is a + // veto, and it has to be checked before the fallbacks, not alongside them. Granting + // ownership on `== "autoconfig"` and otherwise falling through meant a key-auth labelled + // for another manager was still rewritten whenever it sat in higress-system or in a + // namespace some fleet names - 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. + if v, labelled := o.GetLabels()[consumersLabel]; labelled { + return v == "autoconfig" } // Our own record on the object: this controller wrote this list before, so it is ours to // keep correct even if nothing names the namespace any more. It is also what lets a diff --git a/internal/controller/apiconsumer_controller_test.go b/internal/controller/apiconsumer_controller_test.go index 217e2d8d..ae16ad9a 100644 --- a/internal/controller/apiconsumer_controller_test.go +++ b/internal/controller/apiconsumer_controller_test.go @@ -232,9 +232,15 @@ func TestConsumerAcceptsEveryKeyInTheSecret(t *testing.T) { } } -// THE guard. An unreadable Secret must not quietly drop that consumer from the list: a -// consumer missing from key-auth is a caller that gets 401 on its next request. The gateway -// keeps its last good list and the failure is reported. +// THE guard, in its current form. An unreadable Secret must not drop that consumer from the +// list - a consumer missing from key-auth is a caller that gets 401 on its next request - and +// it must not freeze the gateway either, which is what failing the round did: nobody else +// could be added, rotated or revoked until somebody restored a Secret. +// +// So its LIVE entry is carried over verbatim and everyone else's changes go through. The +// alternative the review suggested - fail just that object, i.e. drop it - trades a +// management-plane problem for a data-plane outage: a tenant denied because somebody deleted +// an unrelated Secret. func TestConsumerUnreadableSecretDoesNotRevokeAnyone(t *testing.T) { r, c := newConsumerReconciler(t, consumerFixture("tenant-a", "tenant-a-keys"), @@ -242,20 +248,35 @@ func TestConsumerUnreadableSecretDoesNotRevokeAnyone(t *testing.T) { credSecret("tenant-a-keys", map[string]string{"key": "sk-tenant-a"}), keyAuthWith(liveConsumer("tenant-a", "sk-tenant-a"), liveConsumer("tenant-b", "sk-tenant-b")), ) - // Reconciling the healthy one must not publish a list that drops the broken one. The - // round reports the failure on the object and requeues rather than returning an error - - // returning one would hot-loop on a Secret that may be minutes from existing. if err := reconcileConsumer(t, r, "tenant-a"); err != nil { t.Fatalf("reconcile: %v", err) } + // Nobody lost access... + names := consumerNames(gatewayConsumers(t, c, "higress-system")) + if strings.Join(names, ",") != "tenant-a,tenant-b" { + t.Fatalf("live consumers = %v, want both: someone's key just stopped working", names) + } + if got := creds0Of(t, c, "higress-system", "tenant-b"); strings.Join(got, ",") != "sk-tenant-b" { + t.Fatalf("tenant-b's entry = %v, want it untouched", got) + } + // ...the healthy one was programmed, so the gateway is not frozen... var healthy routingv1.APIConsumer _ = c.Get(context.Background(), types.NamespacedName{Namespace: "llm-route", Name: "tenant-a"}, &healthy) - if condTrue(healthy.Status.Conditions, condProgrammed) { - t.Fatal("the round reported success although one consumer could not be resolved") + if !condTrue(healthy.Status.Conditions, condProgrammed) { + t.Fatalf("the healthy consumer was blocked by somebody else's Secret: %s", + consumerCondMessage(healthy.Status.Conditions, condProgrammed)) } - names := consumerNames(gatewayConsumers(t, c, "higress-system")) - if len(names) != 2 { - t.Fatalf("the live consumer list was rewritten to %v - someone's key just stopped working", names) + // ...and the object whose Secret is missing says so. + if err := reconcileConsumer(t, r, "tenant-b"); err != nil { + t.Fatal(err) + } + var broken routingv1.APIConsumer + _ = c.Get(context.Background(), types.NamespacedName{Namespace: "llm-route", Name: "tenant-b"}, &broken) + if condTrue(broken.Status.Conditions, condProgrammed) { + t.Fatal("the consumer with no Secret reports Programmed") + } + if msg := consumerCondMessage(broken.Status.Conditions, condProgrammed); !strings.Contains(msg, "keeps working") { + t.Fatalf("the message does not say its existing key still works: %q", msg) } } @@ -572,35 +593,44 @@ func TestConsumerDeleteIsNotWedgedByAnotherConsumersSecret(t *testing.T) { } } -// ...but before the deadline it keeps trying, and says so. Giving up immediately would make -// "delete" mean "the key may or may not still work", which is worse than a slow delete. -func TestConsumerDeleteKeepsTryingBeforeTheDeadline(t *testing.T) { +// Deleting a consumer is no longer blocked by somebody else's broken Secret at all: that +// consumer's live entry is carried over instead of failing the round, so the deletion goes +// through and revokes exactly its own key. +// +// This replaces a test that asserted the opposite - held under RevokeError until the deadline - +// which was the behaviour the review called out: a deletion that cannot complete is how a +// leaked key stays live. +func TestConsumerDeleteIsNotBlockedByAnotherBrokenSecret(t *testing.T) { now := metav1.Now() doomed := consumerFixture("tenant-b", "tenant-b-keys") doomed.DeletionTimestamp = &now + doomed.Status.ConsumerName = "tenant-b" + doomed.Status.AppliedGatewayNamespace = "higress-system" broken := consumerFixture("tenant-a", "secret-that-does-not-exist") + broken.Status.ConsumerName = "tenant-a" + broken.Status.AppliedGatewayNamespace = "higress-system" r, c := newConsumerReconciler(t, doomed, broken, credSecret("tenant-b-keys", map[string]string{"key": "sk-b"}), keyAuthManagedBy("tenant-a,tenant-b", - liveConsumer("tenant-a", "sk-a"), liveConsumer("tenant-b", "sk-b")), + liveConsumer("tenant-a", "Bearer sk-a"), liveConsumer("tenant-b", "Bearer sk-b")), ) if err := reconcileConsumer(t, r, "tenant-b"); err != nil { t.Fatal(err) } - var con routingv1.APIConsumer - if err := c.Get(context.Background(), types.NamespacedName{ - Namespace: "llm-route", Name: "tenant-b"}, &con); err != nil { - t.Fatalf("the object was released although the key was never revoked: %v", err) - } - if len(con.Finalizers) == 0 { - t.Fatal("the finalizer was dropped although the key was never revoked") + // tenant-b's key is gone... + names := consumerNames(gatewayConsumers(t, c, "higress-system")) + if strings.Join(names, ",") != "tenant-a" { + t.Fatalf("consumers = %v, want only tenant-a: the deletion did not revoke", names) } - if msg := consumerCondMessage(con.Status.Conditions, condProgrammed); !strings.Contains(msg, "still retrying") { - t.Fatalf("the condition does not say it is still trying: %q", msg) + // ...tenant-a keeps the key it still has, despite its Secret being gone... + if got := creds0Of(t, c, "higress-system", "tenant-a"); strings.Join(got, ",") != "Bearer sk-a" { + t.Fatalf("tenant-a credentials = %v, want them preserved", got) } - // The key is still live, which is the honest state - and the reason the object is held. - if n := len(consumerNames(gatewayConsumers(t, c, "higress-system"))); n != 2 { - t.Fatalf("live consumers = %d, want both (nothing was written)", n) + // ...and the object was released rather than held to the deadline. + var con routingv1.APIConsumer + err := c.Get(context.Background(), types.NamespacedName{Namespace: "llm-route", Name: "tenant-b"}, &con) + if err == nil && len(con.Finalizers) > 0 { + t.Fatalf("still held: %v", con.Finalizers) } } @@ -1129,13 +1159,17 @@ func TestConsumerBrokenNewObjectDoesNotFreezeTheGateway(t *testing.T) { t.Fatalf("consumers = %v, want only tenant-a", names) } - // But a consumer that IS in the list and whose Secret breaks still fails the round - // closed, because dropping it would revoke a working key. + // And a consumer that IS in the list and whose Secret breaks does not fail the round + // either: its live entry is preserved, so it keeps working and nobody else is blocked. + // Dropping it would revoke a working key; failing the round would freeze the gateway. if err := c.Delete(context.Background(), credSecret("tenant-a-keys", map[string]string{"key": "x"})); err != nil { t.Fatal(err) } - if _, err := r.programGateway(context.Background(), "higress-system", nil); err == nil { - t.Fatal("an unreadable Secret for a consumer that HAS a key did not fail the round") + if _, err := r.programGateway(context.Background(), "higress-system", nil); err != nil { + t.Fatalf("an unreadable Secret for a live consumer froze the round: %v", err) + } + if got := creds0Of(t, c, "higress-system", "tenant-a"); strings.Join(got, ",") != "Bearer sk-rotated" { + t.Fatalf("tenant-a credentials = %v, want the entry preserved as it was", got) } } diff --git a/internal/controller/modelfleet_controller.go b/internal/controller/modelfleet_controller.go index 71190dca..72d2e2d5 100644 --- a/internal/controller/modelfleet_controller.go +++ b/internal/controller/modelfleet_controller.go @@ -11,6 +11,7 @@ package controller import ( "context" "encoding/json" + "errors" "fmt" "sort" "strconv" @@ -93,6 +94,27 @@ type fleetPlugin struct { // it verbatim while the Secret-derived one was never programmed, with a healthy sync. // There is no CEL rule to fall back on (see the field's doc), so this is the only guard. overridable bool + // copyDefaultConfig: write this plugin's own spec.defaultConfig as the rule's config. + // + // Needed because of a layer above the plugin: with defaultConfigDisable true, the Higress + // controller does not send defaultConfig to the gateway at all - only `_rules_` - so a + // rule that counted on the plugin merging it over the global config gets an EMPTY global + // and fails to parse. Measured on the test cluster, after this controller had already + // shipped empty rules on the strength of reading the plugin's own parseRuleConfig, which + // is correct about the plugin and silent about what reaches it. + // + // So the thresholds still live in one place - the chart's defaultConfig - and this copies + // them per route rather than restating them. + copyDefaultConfig bool + // unusable: may this plugin's own global config make our rule unwritable? Returns a + // reason, or "" when the rule is safe to write. + // + // It covers the gap tolerateMissing does not: the plugin object EXISTS but its + // defaultConfig cannot support the rule we were about to add. Writing it anyway is worse + // than not writing it - a plugin that fails to load stalls the config push for EVERY + // plugin on that gateway, so one fleet's rule takes down key-auth, the backend router and + // everything else on it. + unusable func(obj *unstructured.Unstructured) string // config renders this plugin's per-route config; returning nil means "no rule for this // fleet", which removes any rule we previously wrote. config func(*fleetRender) (any, error) @@ -138,6 +160,10 @@ type fleetRender struct { defaultMember string // allDisabled: every member is disabled, i.e. the model was deliberately taken offline. allDisabled bool + // skippedPlugins: rules this round did not write because the plugin's own global config + // could not support them. Surfaced on the fleet, because the alternative to writing them + // was silence about a protection that is not running. + skippedPlugins []string // gatewayNS: which gateway namespace to write to. Empty means the one the spec names; // it is set explicitly only when withdrawing rules from a namespace the spec no longer // points at. @@ -253,7 +279,14 @@ func (r *ModelFleetReconciler) Reconcile(ctx context.Context, req ctrl.Request) } log.V(1).Info("fleet synced", "model", rend.modelName, "members", len(rend.members)) - r.setFleetStatus(ctx, req.NamespacedName, rend, condGatewaySynced, metav1.ConditionTrue, "Synced", "gateway objects written") + // Synced, but say what was left out. A rule this round refused to write - because the + // plugin's own config could not support it - means a protection is not running on this + // route, and the one thing worse than that is nobody knowing. + syncMsg := "gateway objects written" + if len(rend.skippedPlugins) > 0 { + syncMsg += "; not written: " + strings.Join(rend.skippedPlugins, "; ") + } + r.setFleetStatus(ctx, req.NamespacedName, rend, condGatewaySynced, metav1.ConditionTrue, "Synced", syncMsg) return ctrl.Result{RequeueAfter: fleetResyncEvery}, nil } @@ -860,20 +893,40 @@ func fleetPlugins() []fleetPlugin { // metrics. A cluster whose gateway chart predates this plugin must not stop // publishing fleets over it. tolerateMissing: func(*fleetRender) bool { return true }, + // The middle case, which is the dangerous one and which tolerateMissing does not + // cover: the object exists and its defaultConfig has no `detectors`. Our rule is + // empty by design and inherits that config, and the plugin refuses a config with no + // detectors - so the rule would be written, the plugin would fail to load, and the + // config push for EVERY plugin on that gateway would stall. Upgrading this + // controller without the matching gateway chart would take the whole gateway's + // config plane down, for every fleet route. + // + // So the rule is not written, the fleet publishes without the guard, and the reason + // is on the fleet rather than in a gateway that has stopped accepting config. + unusable: func(obj *unstructured.Unstructured) string { + dets, found, err := unstructured.NestedSlice(obj.Object, "spec", "defaultConfig", "detectors") + if err != nil || !found || len(dets) == 0 { + return "its defaultConfig has no `detectors`, and this controller writes an " + + "empty rule that inherits it - the plugin refuses a config with none, and " + + "a plugin that fails to load stalls the config push for every plugin on " + + "this gateway. Configure detectors in the gateway chart to enable the guard" + } + return "" + }, // Overridable, so a fleet that wants different thresholds can say so through - // extraPlugins - the same escape hatch ai-statistics has. The default here is an - // empty rule, which the plugin reads as "the global config applies". + // extraPlugins - the same escape hatch ai-statistics has. overridable: true, + // The rule carries a copy of the chart's defaultConfig: an empty rule would reach + // the gateway with no global config to inherit (see copyDefaultConfig) and the + // plugin would refuse it. + copyDefaultConfig: true, config: func(f *fleetRender) (any, error) { if g := f.fleet.Spec.Gateway.StreamGuard; g != nil && g.Disabled { return nil, nil // no rule: the guard does not run on this route } - // Deliberately empty. The plugin's parseRuleConfig starts from the global config, - // so an empty rule means "what the chart configured", and this controller never - // has to know the detector parameters. ⚠ It does mean the chart's defaultConfig - // must carry a non-empty `detectors`: the plugin refuses a config with none, and - // a plugin that fails to load stalls the config push for every plugin on the - // gateway. + // A marker: the actual config is the plugin's own defaultConfig, substituted + // where the object is read (copyDefaultConfig). Returning non-nil here is what + // says "this route wants the guard". return sink.RenderStreamGuard(), nil }, }} @@ -896,6 +949,9 @@ func renderedPlugins() map[string]bool { func (r *ModelFleetReconciler) applyPluginRules(ctx context.Context, rend *fleetRender) error { var errs []string + // Rules deliberately not written because the plugin's own config could not support them. + // Reported, not fatal - see the handling in the loop below. + var skipped []string if err := r.withdrawFromOldGatewayNamespace(ctx, rend); err != nil { // Not fatal: the new namespace still gets its rules, and the stale ones are retried // every resync. Reported, because a rule nobody can see is the thing to avoid. @@ -935,6 +991,15 @@ func (r *ModelFleetReconciler) applyPluginRules(ctx context.Context, rend *fleet (p.tolerateMissing != nil && p.tolerateMissing(rend))) { continue } + // A rule the plugin's own config cannot support was deliberately not written. + // It is reported on the fleet - loudly enough to act on - but it does not fail + // the sync, for the same reason tolerateMissing exists: the alternative is a + // gateway that has stopped accepting config for every route on it. + var unusable *pluginUnusableError + if errors.As(err, &unusable) { + skipped = append(skipped, unusable.Error()) + continue + } errs = append(errs, fmt.Sprintf("%s: %v", p.name, err)) } } @@ -1030,6 +1095,7 @@ func (r *ModelFleetReconciler) applyPluginRules(ctx context.Context, rend *fleet } sort.Strings(rend.appliedExtras) // listType=set on the status field, and a stable order means no needless writes + rend.skippedPlugins = skipped if len(errs) > 0 { return fmt.Errorf("%s", strings.Join(errs, "; ")) } @@ -1064,6 +1130,30 @@ func (r *ModelFleetReconciler) upsertMatchRule(ctx context.Context, rend *fleetR if err := r.Get(ctx, types.NamespacedName{Namespace: ns, Name: p.name}, obj); err != nil { return err } + // Would our rule be unwritable given this plugin's own global config? Asked after the + // Get, because the answer is on the object. A rule that cannot load is worse than no + // rule: it stalls the config push for every plugin on this gateway. + if cfg != nil && p.unusable != nil { + if why := p.unusable(obj); why != "" { + return &pluginUnusableError{plugin: p.name, why: why} + } + } + // Substitute the plugin's own defaultConfig for the marker config. The gateway never + // receives defaultConfig while defaultConfigDisable is true, so the rule has to carry + // it; the thresholds still exist in exactly one place, the chart. + if cfg != nil && p.copyDefaultConfig { + def, found, err := unstructured.NestedMap(obj.Object, "spec", "defaultConfig") + if err != nil { + return fmt.Errorf("read %s defaultConfig: %w", p.name, err) + } + if !found || len(def) == 0 { + return &pluginUnusableError{plugin: p.name, + why: "its defaultConfig is empty, and this controller copies it into the " + + "rule because the gateway never receives defaultConfig while " + + "defaultConfigDisable is true"} + } + cfg = def + } rules, _, err := unstructured.NestedSlice(obj.Object, "spec", "matchRules") if err != nil { return fmt.Errorf("read matchRules: %w", err) @@ -1508,3 +1598,15 @@ func (r *ModelFleetReconciler) fleetsForModelRoute(ctx context.Context, obj clie } return out } + +// pluginUnusableError: our rule was not written because the plugin's own global config cannot +// support it. Its own type so the caller can tell it from a failure to write - this one is a +// deliberate skip, and a fleet that only hits this still publishes. +type pluginUnusableError struct { + plugin string + why string +} + +func (e *pluginUnusableError) Error() string { + return fmt.Sprintf("%s: rule not written: %s", e.plugin, e.why) +} diff --git a/internal/controller/modelfleet_controller_test.go b/internal/controller/modelfleet_controller_test.go index b1de35a1..13a5aa51 100644 --- a/internal/controller/modelfleet_controller_test.go +++ b/internal/controller/modelfleet_controller_test.go @@ -2614,6 +2614,17 @@ func TestFleetCapacityUsesTheSharedPeerRule(t *testing.T) { } } +// streamGuardPlugin: the ai-stream-guard object as the gateway chart ships it - with +// detectors configured. Without them the controller refuses to write its rule, which has its +// own test; every other case needs a plugin a rule can actually be written for. +func streamGuardPlugin() *unstructured.Unstructured { + o := wasmPlugin("ai-stream-guard") + _ = unstructured.SetNestedSlice(o.Object, []any{ + map[string]any{"type": "repetition", "name": "rep"}, + }, "spec", "defaultConfig", "detectors") + return o +} + // The guard is on for a fleet that never mentions it. That is the whole reason it is a plugin // of this controller's rather than something each fleet passes through extraPlugins: a // protection somebody has to remember to switch on is missing from the next fleet built by @@ -2624,7 +2635,7 @@ func TestFleetStreamGuardIsOnByDefault(t *testing.T) { modelRoute("glm-53-h100", "llm-route", "glm-53-h100", 2, true), modelRoute("glm-53-ascend", "llm-route", "glm-53-ascend", 1, true), wasmPlugin("ai-backend-router"), keyAuthPlugin(map[string]string{"ops": "sk-ops"}), - wasmPlugin("ai-statistics"), wasmPlugin("ai-stream-guard"), + wasmPlugin("ai-statistics"), streamGuardPlugin(), ) reconcileFleet(t, r) @@ -2633,11 +2644,18 @@ func TestFleetStreamGuardIsOnByDefault(t *testing.T) { t.Fatalf("ai-stream-guard has %d rule(s), want 1: a fleet that says nothing must be guarded", len(rules)) } rule := rules[0].(map[string]any) - // The rule is EMPTY on purpose: the plugin reads an empty rule as "the global config - // applies", so the detector parameters live in the chart and not in two places. + // The rule carries a COPY of the plugin's defaultConfig. An empty rule would be the + // tidier design and it does not work: with defaultConfigDisable true the Higress + // controller never sends defaultConfig to the gateway, so the plugin would inherit an + // empty global and refuse the config - measured on the test cluster after this shipped + // the other way. cfg, _ := rule["config"].(map[string]any) - if len(cfg) != 0 { - t.Fatalf("the rule carries config %v, want an empty one so the chart's parameters apply", cfg) + dets, _ := cfg["detectors"].([]any) + if len(dets) != 1 { + t.Fatalf("the rule's config is %v, want the chart's detectors copied into it", cfg) + } + if first, _ := dets[0].(map[string]any); first["type"] != "repetition" { + t.Fatalf("the copied detector is %v, want the one the chart configured", dets[0]) } if d, _ := rule["configDisable"].(bool); d { t.Fatal("configDisable is true: the rule turns the plugin OFF for this route") @@ -2683,3 +2701,58 @@ func TestFleetStreamGuardMissingPluginIsTolerated(t *testing.T) { t.Fatal("Ready=False although only the guard is missing") } } + +// The dangerous middle case tolerateMissing does not cover: the ai-stream-guard object EXISTS +// but its defaultConfig carries no detectors. Our rule is empty by design and inherits that +// config, and the plugin refuses a config with no detectors - so writing the rule would make +// the plugin fail to load, and a plugin that fails to load stalls the config push for EVERY +// plugin on that gateway. Upgrading this controller without the matching gateway chart would +// take the whole gateway's config plane down, for every fleet route. +func TestFleetStreamGuardNotWrittenWithoutDetectors(t *testing.T) { + guard := wasmPlugin("ai-stream-guard") // exists, with no defaultConfig at all + r, c := newFleetReconciler(t, fleetFixture(), + modelRoute("glm-53-h100", "llm-route", "glm-53-h100", 2, true), + modelRoute("glm-53-ascend", "llm-route", "glm-53-ascend", 1, true), + wasmPlugin("ai-backend-router"), keyAuthPlugin(map[string]string{"ops": "sk-ops"}), + wasmPlugin("ai-statistics"), guard, + ) + reconcileFleet(t, r) + + if n := len(getPlugin(t, c, "ai-stream-guard")); n != 0 { + t.Fatalf("wrote %d rule(s) the plugin cannot load: the config push for every plugin "+ + "on this gateway would stall", n) + } + // The fleet still publishes - the alternative is refusing to serve a model because a + // guard is unconfigured - and the condition says what is not running. + var fleet routingv1.ModelFleet + _ = c.Get(context.Background(), types.NamespacedName{Namespace: "llm-route", Name: "glm-5.3"}, &fleet) + if !condTrue(fleet.Status.Conditions, condGatewaySynced) { + t.Fatalf("the fleet refused to publish: %s", condMessage(fleet.Status.Conditions, condGatewaySynced)) + } + msg := condMessage(fleet.Status.Conditions, condGatewaySynced) + for _, want := range []string{"ai-stream-guard", "detectors", "not written"} { + if !strings.Contains(msg, want) { + t.Fatalf("the condition does not say the guard is off (%s missing): %q", want, msg) + } + } + + // ...and once the chart configures detectors, the rule appears. + var ka unstructured.Unstructured + ka.SetGroupVersionKind(wasmPluginGVK) + if err := c.Get(context.Background(), types.NamespacedName{ + Namespace: "higress-system", Name: "ai-stream-guard"}, &ka); err != nil { + t.Fatal(err) + } + if err := unstructured.SetNestedSlice(ka.Object, []any{ + map[string]any{"type": "repetition", "name": "rep"}, + }, "spec", "defaultConfig", "detectors"); err != nil { + t.Fatal(err) + } + if err := c.Update(context.Background(), &ka); err != nil { + t.Fatal(err) + } + reconcileFleet(t, r) + if n := len(getPlugin(t, c, "ai-stream-guard")); n != 1 { + t.Fatalf("rules = %d after detectors were configured, want 1", n) + } +} From 1cc9bff12528e1c933700552cdfaf92417ed2ff3 Mon Sep 17 00:00:00 2001 From: zhanghao Date: Thu, 26 Nov 2026 21:29:05 +0800 Subject: [PATCH 23/28] ModelFleet: an unusable plugin config withdraws our rule, it does not 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 --- internal/controller/modelfleet_controller.go | 29 ++++++++++-- .../controller/modelfleet_controller_test.go | 46 +++++++++++++++++++ 2 files changed, 71 insertions(+), 4 deletions(-) diff --git a/internal/controller/modelfleet_controller.go b/internal/controller/modelfleet_controller.go index 72d2e2d5..b6e5ce38 100644 --- a/internal/controller/modelfleet_controller.go +++ b/internal/controller/modelfleet_controller.go @@ -1133,9 +1133,16 @@ func (r *ModelFleetReconciler) upsertMatchRule(ctx context.Context, rend *fleetR // Would our rule be unwritable given this plugin's own global config? Asked after the // Get, because the answer is on the object. A rule that cannot load is worse than no // rule: it stalls the config push for every plugin on this gateway. + // An unusable plugin config does not just stop us writing - it WITHDRAWS the rule we + // wrote before. Skipping the write alone left the previous 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. + // Caught by the cluster probe, which is also where the asymmetry is obvious - the + // condition says one thing and the gateway does another. + unusableWhy := "" if cfg != nil && p.unusable != nil { - if why := p.unusable(obj); why != "" { - return &pluginUnusableError{plugin: p.name, why: why} + if unusableWhy = p.unusable(obj); unusableWhy != "" { + cfg = nil // fall through to the withdrawal path below } } // Substitute the plugin's own defaultConfig for the marker config. The gateway never @@ -1194,15 +1201,29 @@ func (r *ModelFleetReconciler) upsertMatchRule(ctx context.Context, rend *fleetR // Nothing changed: do not write. Every write here is a config push to the // gateway, and a controller that rewrites an identical object on each resync // turns a 30s resync into a 30s config churn across the data plane. - return nil + return unusableErr(p.name, unusableWhy) } if err := unstructured.SetNestedSlice(obj.Object, kept, "spec", "matchRules"); err != nil { return err } - return r.Update(ctx, obj) + if err := r.Update(ctx, obj); err != nil { + return err + } + // Written (or withdrawn). If the withdrawal was because the plugin's own config + // cannot support a rule, say so now - the rule is gone, which is what the message + // claims, and the caller reports it on the fleet without failing the sync. + return unusableErr(p.name, unusableWhy) }) } +// unusableErr: nil unless there is a reason, so the write paths can return it unconditionally. +func unusableErr(plugin, why string) error { + if why == "" { + return nil + } + return &pluginUnusableError{plugin: plugin, why: why} +} + // cleanupPluginRules withdraws every rule this fleet put into the gateway plugins. // deleteIngress removes this fleet's Ingress and reports whether it is actually gone, so the // caller can wait instead of assuming. Returning "gone" from the Delete call alone would be a diff --git a/internal/controller/modelfleet_controller_test.go b/internal/controller/modelfleet_controller_test.go index 13a5aa51..817f88c1 100644 --- a/internal/controller/modelfleet_controller_test.go +++ b/internal/controller/modelfleet_controller_test.go @@ -2756,3 +2756,49 @@ func TestFleetStreamGuardNotWrittenWithoutDetectors(t *testing.T) { t.Fatalf("rules = %d after detectors were configured, want 1", n) } } + +// Clearing the chart's detectors must WITHDRAW the rule, not just stop writing a new one. +// Skipping the write alone left the previous 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 said one thing and the +// gateway did another - found by the cluster probe, which is where that asymmetry shows. +func TestFleetStreamGuardRuleIsWithdrawnWhenDetectorsGoAway(t *testing.T) { + r, c := newFleetReconciler(t, fleetFixture(), + modelRoute("glm-53-h100", "llm-route", "glm-53-h100", 2, true), + modelRoute("glm-53-ascend", "llm-route", "glm-53-ascend", 1, true), + wasmPlugin("ai-backend-router"), keyAuthPlugin(map[string]string{"ops": "sk-ops"}), + wasmPlugin("ai-statistics"), streamGuardPlugin(), + ) + reconcileFleet(t, r) + if n := len(getPlugin(t, c, "ai-stream-guard")); n != 1 { + t.Fatalf("rules = %d before the change, want 1", n) + } + + // The chart drops its detectors. + var ka unstructured.Unstructured + ka.SetGroupVersionKind(wasmPluginGVK) + if err := c.Get(context.Background(), types.NamespacedName{ + Namespace: "higress-system", Name: "ai-stream-guard"}, &ka); err != nil { + t.Fatal(err) + } + if err := unstructured.SetNestedSlice(ka.Object, []any{}, "spec", "defaultConfig", "detectors"); err != nil { + t.Fatal(err) + } + if err := c.Update(context.Background(), &ka); err != nil { + t.Fatal(err) + } + reconcileFleet(t, r) + + if n := len(getPlugin(t, c, "ai-stream-guard")); n != 0 { + t.Fatalf("rules = %d: the old rule survived, so the gateway keeps cutting at a "+ + "threshold that exists nowhere else", n) + } + var fleet routingv1.ModelFleet + _ = c.Get(context.Background(), types.NamespacedName{Namespace: "llm-route", Name: "glm-5.3"}, &fleet) + if !condTrue(fleet.Status.Conditions, condGatewaySynced) { + t.Fatal("the fleet stopped publishing over an unconfigured guard") + } + if msg := condMessage(fleet.Status.Conditions, condGatewaySynced); !strings.Contains(msg, "not written") { + t.Fatalf("the condition does not mention the withdrawn rule: %q", msg) + } +} From af50d9f80d6c5404be0e959d6819c4900c1f205a Mon Sep 17 00:00:00 2001 From: zhanghao Date: Thu, 26 Nov 2026 22:10:02 +0800 Subject: [PATCH 24/28] Five more review findings: two that reported success for work never done **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 --- README.md | 9 ++ cmd/main.go | 32 ++++++ internal/controller/apiconsumer_controller.go | 87 ++++++++++---- .../controller/apiconsumer_controller_test.go | 108 ++++++++++++++++++ internal/controller/modelfleet_controller.go | 7 +- 5 files changed, 220 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 5944ecaf..6b0095d1 100644 --- a/README.md +++ b/README.md @@ -440,6 +440,15 @@ fleet 的 namespace 里就直接失败,根本到不了「容忍 ai-proxy 缺失 路由没声明上限时报 0 —— openresty 那边走 route 的 `default_max`,这里编一个数只会在 console 上显示一个没人执行的值。 +⚠️ **升级既有 release 时必须先 apply CRD 再重启 controller,顺序不能省**:`crds/` 不被 +`helm upgrade` 更新,而「APIConsumer 这个 kind 服务不服务」是**启动时判定一次**的。漏了的话 +reconciler 和网关巡检**都被跳过**、没人写 key-auth 的 `defaultConfig.consumers` —— 配上不再渲染 +该字段的网关 chart,就是 `parsePluginConfig` 失败 + FAIL_CLOSE,**整个网关所有路由拒绝一切请求**。 +补装 CRD 本身不会自愈(判定已经做过了),所以 controller 里有个看门狗:CRD 事后出现时它会退出, +靠重启把判定重做一次。 +同一个机制还有一个更安静的版本:**CRD 没升级时 `spec.gateway.streamGuard` 会被 API server +静默裁掉** —— `disabled: true` 写进去被接受、然后被忽略,防护照旧开着。这个没法在代码里兜。 + **CRD 装在 chart 的 `crds/` 目录,而 `helm upgrade` 不会更新它** —— 以后给 ModelFleet 加字段, 升级 autoconfig 不生效,必须单独 `kubectl apply --server-side -f` 那份 CRD。 diff --git a/cmd/main.go b/cmd/main.go index 483d096c..665ada8b 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -4,6 +4,7 @@ package main import ( + "context" "flag" "fmt" "log" @@ -166,7 +167,38 @@ func runController(leaderElect bool) error { return err } } + // ...and nothing else to add. } else { + // Skipped - and this one does NOT self-correct, which is why it gets a watchdog. + // + // The CRDs ship in the chart's crds/ directory, which `helm upgrade` does not touch, + // so upgrading an existing release leaves APIConsumer unserved: this reconciler AND + // the gateway sweep are both skipped, and nothing writes key-auth's + // defaultConfig.consumers. Paired with the gateway chart that no longer renders that + // field, parsePluginConfig fails and FAIL_CLOSE denies every caller on every route of + // that gateway. Applying the CRD afterwards fixes nothing by itself, because this + // decision was taken once at startup. + // + // So: watch for the kind appearing and exit when it does. Exiting is how a + // leader-elected controller restarts, and a restart is what picks the CRD up. + if err := mgr.Add(manager.RunnableFunc(func(ctx context.Context) error { + t := time.NewTicker(time.Minute) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return nil + case <-t.C: + if served, err := servedKinds(cs); err == nil && served["APIConsumer"] { + log.Print("APIConsumer CRD has appeared: exiting so the restart picks " + + "it up (nothing writes key-auth's consumers until it does)") + return fmt.Errorf("APIConsumer CRD installed after startup: restarting") + } + } + } + })); err != nil { + return err + } log.Print("APIConsumer CRD not installed: skipping that reconciler " + "(apply deploy/helm/autoconfig/crds/ and restart to enable it)") } diff --git a/internal/controller/apiconsumer_controller.go b/internal/controller/apiconsumer_controller.go index 715c8e8f..d9f4fccf 100644 --- a/internal/controller/apiconsumer_controller.go +++ b/internal/controller/apiconsumer_controller.go @@ -299,9 +299,31 @@ func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, return gatewayRound{}, err } if !ourGateway(keyAuth, named) { - logf.FromContext(ctx).V(1).Info("not this controller's gateway: no label, and nothing "+ - "names it", "gateway", gwNS) - return gatewayRound{}, nil + // Reported on every object that wanted this gateway, not just logged. Returning + // (round{}, nil) made Reconcile indistinguishable from a successful write: it set + // Programmed=True, status.credentials=N and appliedGatewayNamespace for a consumer + // whose key was never written, so an APIConsumer pointing at a key-auth labelled for + // somebody else reported "N credential(s) accepted" while every request with that key + // got 401. The comment claiming the APIConsumer path could not fail this check was + // wrong - the label vetoes regardless of who names the namespace. + // + // The false appliedGatewayNamespace was the worse half: it feeds claimed[], so if the + // foreign label were ever removed, the adoption-proof check would treat the name as + // already ours and let this object take over a chart-rendered consumer without + // carrying its existing credentials. + round := gatewayRound{skipped: map[string]string{}} + why := fmt.Sprintf("gateway %s is not managed by autoconfig: its key-auth carries no "+ + "%s=autoconfig label, or carries one naming another manager. Nothing was written, "+ + "so this consumer's key does not work there", gwNS, consumersLabel) + for i := range list.Items { + c := &list.Items[i] + if consumerGatewayNamespace(c) == gwNS { + round.skipped[c.Namespace+"/"+c.Name] = why + } + } + logf.FromContext(ctx).V(1).Info("not this controller's gateway", "gateway", gwNS, + "consumers left unprogrammed", len(round.skipped)) + return round, nil } liveEntries, liveManaged, err := r.liveConsumerState(ctx, gwNS) @@ -349,21 +371,30 @@ func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, return false // that entry is on record as somebody else's } } - // Two objects can reach this point for one name: the one whose gateway write landed - // while its status write did not - the case this fallback exists for - and a - // newcomer claiming the same consumerName. Both would count as incumbents, and two - // incumbents make the collision check refuse the round for the whole gateway, which - // is the impostor-driven freeze this is supposed to avoid. The annotation records - // which names this controller actually wrote, so it breaks the tie: an entry it - // wrote belongs to whoever was there, and a second claimant is a newcomer. - if liveManaged[name] { - for i := range list.Items { - o := &list.Items[i] - if o.Namespace != c.Namespace || o.Name != c.Name { - if consumerName(o) == name && o.CreationTimestamp.Before(&c.CreationTimestamp) { - return false // somebody was here first - } - } + // An entry with no status behind it can only be attributed to ONE object. If a second + // object claims the same consumerName, nothing on record says which of them the live + // entry belongs to - so neither is an incumbent, and both are handled as newcomers: + // the collision check then leaves them both out instead of refusing the round. + // + // Without this, two brand-new objects claiming a CHART-rendered name both came out as + // incumbents (each sees a live entry and no other object's STATUS claiming it), the + // collision check hit "more than one incumbent" and froze the whole gateway - 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. + for i := range list.Items { + o := &list.Items[i] + if o.Namespace == c.Namespace && o.Name == c.Name { + continue + } + if consumerName(o) != name || !o.DeletionTimestamp.IsZero() { + continue + } + if liveManaged[name] && o.CreationTimestamp.Before(&c.CreationTimestamp) { + return false // ours, and somebody was here first + } + if !liveManaged[name] { + return false // contested, and nothing on record says it is this object's } } return true @@ -801,7 +832,12 @@ func (r *APIConsumerReconciler) writeConsumers(ctx context.Context, gwNS string, // Written next to the data it describes, because nothing else can tell the two apart // later: once an APIConsumer is deleted, its object is gone and its entry would look // exactly like one of the chart's. - setManagedConsumerNames(obj, consumers) + // Preserved names too. They are ours - their Secret is just unreadable right now - + // and leaving them out of the record loses a revocation in the one case the record + // exists for: gateway write landed, status write did not, Secret then broke, object + // then deleted. Without the name in the annotation its entry is carried over as + // somebody else's and the revoked tenant's key keeps working. + setManagedConsumerNames(obj, consumers, preserve) log.Info("programming gateway consumers", "gateway", gwNS, "mine", len(consumers), "carried over", len(foreign), "was", len(live)) // FieldOwner spelled out, although the client's default manager happens to be this @@ -991,10 +1027,17 @@ func managedConsumerNames(obj *unstructured.Unstructured) (map[string]bool, erro return out, nil } -func setManagedConsumerNames(obj *unstructured.Unstructured, consumers []sink.KeyAuthConsumer) { - names := make([]string, 0, len(consumers)) +func setManagedConsumerNames(obj *unstructured.Unstructured, consumers []sink.KeyAuthConsumer, + preserve map[string]bool) { + names := make([]string, 0, len(consumers)+len(preserve)) + seen := map[string]bool{} for _, c := range consumers { - names = append(names, c.Name) + names, seen[c.Name] = append(names, c.Name), true + } + for n := range preserve { + if !seen[n] { + names = append(names, n) + } } sort.Strings(names) ann := obj.GetAnnotations() diff --git a/internal/controller/apiconsumer_controller_test.go b/internal/controller/apiconsumer_controller_test.go index ae16ad9a..dbe2539a 100644 --- a/internal/controller/apiconsumer_controller_test.go +++ b/internal/controller/apiconsumer_controller_test.go @@ -1762,3 +1762,111 @@ func TestKeyAuthWatchRespectsTheGatewayScope(t *testing.T) { } } } + +// A gateway this controller does not manage must not come back as success. Returning no error +// and no reason made Reconcile indistinguishable from a write that happened: it set +// Programmed=True and status.credentials for a consumer whose key was never programmed, so +// the object said "N credential(s) accepted" while every request with that key got 401. +// +// The false status.appliedGatewayNamespace was the worse half - it feeds claimed[], which +// skips the adoption-proof check later. +func TestConsumerForeignGatewayIsNotReportedAsProgrammed(t *testing.T) { + ka := keyAuthWith(liveConsumer("chart-a", "Bearer sk-chart-a")) + ka.SetLabels(map[string]string{consumersLabel: "somebody-else"}) + r, c := newConsumerReconciler(t, + consumerFixture("tenant-a", "tenant-a-keys"), + credSecret("tenant-a-keys", map[string]string{"key": "sk-a"}), + ka, + ) + if err := reconcileConsumer(t, r, "tenant-a"); err != nil { + t.Fatal(err) + } + var con routingv1.APIConsumer + nn := types.NamespacedName{Namespace: "llm-route", Name: "tenant-a"} + if err := c.Get(context.Background(), nn, &con); err != nil { + t.Fatal(err) + } + if condTrue(con.Status.Conditions, condProgrammed) { + t.Fatal("reported Programmed for a gateway labelled for another manager: every " + + "request with this key gets 401 while the object says it was accepted") + } + if con.Status.AppliedGatewayNamespace != "" { + t.Fatalf("recorded appliedGatewayNamespace=%q for a gateway it never wrote - that "+ + "value feeds claimed[] and would skip the adoption proof later", + con.Status.AppliedGatewayNamespace) + } + if msg := consumerCondMessage(con.Status.Conditions, condProgrammed); !strings.Contains(msg, consumersLabel) { + t.Fatalf("the message does not explain why: %q", msg) + } + // And nothing was written there. + if n := len(consumerNames(gatewayConsumers(t, c, "higress-system"))); n != 1 { + t.Fatalf("the foreign gateway's list has %d entries, want its own 1", n) + } +} + +// Two brand-new objects claiming a CHART-rendered consumer name must not freeze the gateway. +// Each one sees a live entry under that name and no other object's STATUS claiming it, so both +// used to come 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. +func TestConsumerTwoNewcomersOnAChartNameDoNotFreezeTheGateway(t *testing.T) { + a := consumerFixture("team-a", "a-keys") + a.Spec.ConsumerName = "chart-a" + b := consumerFixture("team-b", "b-keys") + b.Spec.ConsumerName = "chart-a" + // Someone already serving, to prove the round still goes through for them. + serving := consumerFixture("tenant-x", "x-keys") + serving.Status.ConsumerName = "tenant-x" + serving.Status.AppliedGatewayNamespace = "higress-system" + r, c := newConsumerReconciler(t, a, b, serving, + credSecret("a-keys", map[string]string{"key": "sk-a"}), + credSecret("b-keys", map[string]string{"key": "sk-b"}), + credSecret("x-keys", map[string]string{"key": "sk-rotated"}), + // chart-a is the chart's, not ours: the annotation names only tenant-x. + keyAuthManagedBy("tenant-x", + liveConsumer("chart-a", "Bearer sk-chart-a"), + liveConsumer("tenant-x", "Bearer sk-old")), + ) + if _, err := r.programGateway(context.Background(), "higress-system", nil); err != nil { + t.Fatalf("two newcomers on a chart-rendered name froze the round: %v", err) + } + // tenant-x's rotation went through... + if got := creds0Of(t, c, "higress-system", "tenant-x"); strings.Join(got, ",") != "Bearer sk-rotated" { + t.Fatalf("tenant-x credentials = %v, want the rotated key", got) + } + // ...the chart's entry is untouched, and neither claimant got the name. + if got := creds0Of(t, c, "higress-system", "chart-a"); strings.Join(got, ",") != "Bearer sk-chart-a" { + t.Fatalf("chart-a credentials = %v, want the chart's own", got) + } +} + +// A preserved name - ours, with a Secret that cannot be read right now - has to stay in the +// managed-consumers record. Dropping it loses a revocation in the one case the record exists +// for: gateway write landed, status write did not, the Secret then broke, the object is then +// deleted. Without the name recorded, its entry is carried over as somebody else's and the +// revoked tenant's key keeps working. +func TestConsumerPreservedNameStaysInTheRecord(t *testing.T) { + broken := consumerFixture("tenant-a", "gone-secret") + healthy := consumerFixture("tenant-b", "tenant-b-keys") + healthy.Status.ConsumerName = "tenant-b" + healthy.Status.AppliedGatewayNamespace = "higress-system" + r, c := newConsumerReconciler(t, broken, healthy, + credSecret("tenant-b-keys", map[string]string{"key": "sk-b2"}), + keyAuthManagedBy("tenant-a,tenant-b", + liveConsumer("tenant-a", "Bearer sk-a"), liveConsumer("tenant-b", "Bearer sk-b")), + ) + if _, err := r.programGateway(context.Background(), "higress-system", nil); err != nil { + t.Fatal(err) + } + var ka unstructured.Unstructured + ka.SetGroupVersionKind(wasmPluginGVK) + if err := c.Get(context.Background(), types.NamespacedName{ + Namespace: "higress-system", Name: "key-auth"}, &ka); err != nil { + t.Fatal(err) + } + got := ka.GetAnnotations()[managedConsumersAnnotation] + if !strings.Contains(got, "tenant-a") { + t.Fatalf("managed-consumers = %q: the preserved name was dropped, so deleting it "+ + "later would leave its key working", got) + } +} diff --git a/internal/controller/modelfleet_controller.go b/internal/controller/modelfleet_controller.go index b6e5ce38..b6c78c63 100644 --- a/internal/controller/modelfleet_controller.go +++ b/internal/controller/modelfleet_controller.go @@ -1124,6 +1124,12 @@ func (r *ModelFleetReconciler) upsertMatchRule(ctx context.Context, rend *fleetR if ns == "" { ns = gatewayNamespace(rend.fleet) } + // Outside the closure: cfg is mutated inside it (an unusable config becomes a + // withdrawal), so on a conflict retry the second attempt would re-enter with cfg already + // nil, never consult p.unusable again, and return nil - the rule withdrawn and the fleet + // reporting a clean "gateway objects written", which is the silence this reason exists to + // break. + unusableWhy := "" return retry.RetryOnConflict(retry.DefaultRetry, func() error { obj := &unstructured.Unstructured{} obj.SetGroupVersionKind(wasmPluginGVK) @@ -1139,7 +1145,6 @@ func (r *ModelFleetReconciler) upsertMatchRule(ctx context.Context, rend *fleetR // on cutting streams at a threshold that existed nowhere but in that stale rule. // Caught by the cluster probe, which is also where the asymmetry is obvious - the // condition says one thing and the gateway does another. - unusableWhy := "" if cfg != nil && p.unusable != nil { if unusableWhy = p.unusable(obj); unusableWhy != "" { cfg = nil // fall through to the withdrawal path below From 2e2b0ae86b8a6417323ec078d3759998b8abb45c Mon Sep 17 00:00:00 2001 From: zhanghao Date: Thu, 26 Nov 2026 22:36:39 +0800 Subject: [PATCH 25/28] Three findings, one of which is documentation that described the design this PR removed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **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 --- README.md | 7 ++- api/v1alpha1/modelfleet_types.go | 18 +++++-- .../routing.modelsphere.dev_modelfleets.yaml | 18 +++++-- .../routing.modelsphere.dev_modelfleets.yaml | 18 +++++-- internal/controller/apiconsumer_controller.go | 15 +++++- .../controller/apiconsumer_controller_test.go | 49 +++++++++++++++++++ internal/controller/modelfleet_controller.go | 17 +++++-- 7 files changed, 119 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 6b0095d1..e5572e63 100644 --- a/README.md +++ b/README.md @@ -496,8 +496,11 @@ key 泄露要立刻失效时,光改 Secret 最长还有一分钟能继续用。* 是显式退出。它**不走 `extraPlugins`**,理由是层级:`extraPlugins` 由建 fleet 的人逐个填, 而「默认都该有的防护」一旦要人记得写,照抄老 YAML 建的新模型就静默没有保护。默认值归 controller, `extraPlugins` 归「这一个 fleet 要的不一样」。 -autoconfig 写的是一条**空规则** —— 插件的 `parseRuleConfig` 以全局配置为底,空规则即「按 chart 配的参数跑」, -所以阈值只存在于 chart 一处。关掉是**撤掉规则**,不是写另一份配置。 +autoconfig 把插件 `defaultConfig` 的内容**复制**进每条路由的规则,所以阈值只存在于 chart 一处、 +改了最慢一个 resync(30s)传到所有路由。**不是写空规则让插件继承** —— `defaultConfigDisable: true` 时 +Higress controller 根本不下发 `defaultConfig`,空规则到达插件时全局是空的、会被拒(集群实测, +而我最初按插件自己的 `parseRuleConfig` 推断写了空规则:那个推断对插件成立、对「什么东西到达了插件」沉默)。 +关掉是**撤掉规则**,不是写另一份配置;chart 没配 detectors 时**也撤掉规则**并在 `GatewaySynced` 上说明。 ⚠️ **chart 的 `defaultConfig` 必须有非空 `detectors`**:插件拒绝 detectors 为空的配置(包括从全局继承到的空), 而**一个插件加载失败会卡住该网关上所有插件的配置推送**。 插件对象不存在时**容忍**(只是少了防护,不像 key-auth 那样是 401),同步照常成功。 diff --git a/api/v1alpha1/modelfleet_types.go b/api/v1alpha1/modelfleet_types.go index 35b9ac93..f80cfdfa 100644 --- a/api/v1alpha1/modelfleet_types.go +++ b/api/v1alpha1/modelfleet_types.go @@ -250,13 +250,21 @@ type GatewaySpec struct { // by copying an older one, silently, with nothing to say so. A default belongs to the // controller; extraPlugins is for what ONE fleet wants differently. // - // The parameters stay in the gateway chart's defaultConfig: this writes an empty rule and - // the plugin reads it as "the global config applies here" (its parseRuleConfig starts from - // the global one). So a fleet turning it off is a rule withdrawn, not a config rewritten. + // The parameters stay in the gateway chart's defaultConfig, and this controller COPIES + // them into each route's rule. Not an empty rule inheriting them: with + // defaultConfigDisable true the Higress controller never sends defaultConfig to the + // gateway at all, so an empty rule reaches a plugin whose global config is empty and is + // refused. Measured on a cluster, after the empty-rule version had been written on the + // strength of the plugin's own parseRuleConfig - which is right about the plugin and + // silent about what reaches it. + // + // So a fleet turning the guard off is a rule withdrawn, and a chart that changes the + // thresholds is picked up by every route within one resync. // // ⚠ The chart's defaultConfig MUST carry a non-empty `detectors`. The plugin refuses a - // config with none - including one inherited as empty - and a plugin that fails to load - // stalls the config push for EVERY plugin on that gateway, not just this one. + // config with none, and a plugin that fails to load stalls the config push for EVERY + // plugin on that gateway, not just this one. With none configured no rule is written at + // all, and the fleet's GatewaySynced says so. // +optional StreamGuard *StreamGuard `json:"streamGuard,omitempty"` } diff --git a/config/crd/bases/routing.modelsphere.dev_modelfleets.yaml b/config/crd/bases/routing.modelsphere.dev_modelfleets.yaml index fcc71bf8..a1d19b53 100644 --- a/config/crd/bases/routing.modelsphere.dev_modelfleets.yaml +++ b/config/crd/bases/routing.modelsphere.dev_modelfleets.yaml @@ -197,13 +197,21 @@ spec: by copying an older one, silently, with nothing to say so. A default belongs to the controller; extraPlugins is for what ONE fleet wants differently. - The parameters stay in the gateway chart's defaultConfig: this writes an empty rule and - the plugin reads it as "the global config applies here" (its parseRuleConfig starts from - the global one). So a fleet turning it off is a rule withdrawn, not a config rewritten. + The parameters stay in the gateway chart's defaultConfig, and this controller COPIES + them into each route's rule. Not an empty rule inheriting them: with + defaultConfigDisable true the Higress controller never sends defaultConfig to the + gateway at all, so an empty rule reaches a plugin whose global config is empty and is + refused. Measured on a cluster, after the empty-rule version had been written on the + strength of the plugin's own parseRuleConfig - which is right about the plugin and + silent about what reaches it. + + So a fleet turning the guard off is a rule withdrawn, and a chart that changes the + thresholds is picked up by every route within one resync. ⚠ The chart's defaultConfig MUST carry a non-empty `detectors`. The plugin refuses a - config with none - including one inherited as empty - and a plugin that fails to load - stalls the config push for EVERY plugin on that gateway, not just this one. + config with none, and a plugin that fails to load stalls the config push for EVERY + plugin on that gateway, not just this one. With none configured no rule is written at + all, and the fleet's GatewaySynced says so. properties: disabled: description: |- diff --git a/deploy/helm/autoconfig/crds/routing.modelsphere.dev_modelfleets.yaml b/deploy/helm/autoconfig/crds/routing.modelsphere.dev_modelfleets.yaml index fcc71bf8..a1d19b53 100644 --- a/deploy/helm/autoconfig/crds/routing.modelsphere.dev_modelfleets.yaml +++ b/deploy/helm/autoconfig/crds/routing.modelsphere.dev_modelfleets.yaml @@ -197,13 +197,21 @@ spec: by copying an older one, silently, with nothing to say so. A default belongs to the controller; extraPlugins is for what ONE fleet wants differently. - The parameters stay in the gateway chart's defaultConfig: this writes an empty rule and - the plugin reads it as "the global config applies here" (its parseRuleConfig starts from - the global one). So a fleet turning it off is a rule withdrawn, not a config rewritten. + The parameters stay in the gateway chart's defaultConfig, and this controller COPIES + them into each route's rule. Not an empty rule inheriting them: with + defaultConfigDisable true the Higress controller never sends defaultConfig to the + gateway at all, so an empty rule reaches a plugin whose global config is empty and is + refused. Measured on a cluster, after the empty-rule version had been written on the + strength of the plugin's own parseRuleConfig - which is right about the plugin and + silent about what reaches it. + + So a fleet turning the guard off is a rule withdrawn, and a chart that changes the + thresholds is picked up by every route within one resync. ⚠ The chart's defaultConfig MUST carry a non-empty `detectors`. The plugin refuses a - config with none - including one inherited as empty - and a plugin that fails to load - stalls the config push for EVERY plugin on that gateway, not just this one. + config with none, and a plugin that fails to load stalls the config push for EVERY + plugin on that gateway, not just this one. With none configured no rule is written at + all, and the fleet's GatewaySynced says so. properties: disabled: description: |- diff --git a/internal/controller/apiconsumer_controller.go b/internal/controller/apiconsumer_controller.go index d9f4fccf..08580ec6 100644 --- a/internal/controller/apiconsumer_controller.go +++ b/internal/controller/apiconsumer_controller.go @@ -823,7 +823,20 @@ func (r *APIConsumerReconciler) writeConsumers(ctx context.Context, gwNS string, // // This is the gateway chart's side of the contract: it stopped rendering the field, // so this controller is the only thing that can put it there. - if found && sameRules(live, next) && sameNames(managed, mine) { + // mine ∪ preserve, because that is what the annotation records. Comparing against + // `mine` alone defeated this short-circuit permanently once anything was preserved: + // the annotation is then a strict superset, sameNames is false every round, and the + // write happens on every pass - content-identical, so no config push, but an API + // write and an Info log claiming a change, every minute, in exactly the degraded + // state the guard matters in. + recorded := make(map[string]bool, len(mine)+len(preserve)) + for n := range mine { + recorded[n] = true + } + for n := range preserve { + recorded[n] = true + } + if found && sameRules(live, next) && sameNames(managed, recorded) { return nil } if err := unstructured.SetNestedSlice(obj.Object, next, "spec", "defaultConfig", "consumers"); err != nil { diff --git a/internal/controller/apiconsumer_controller_test.go b/internal/controller/apiconsumer_controller_test.go index dbe2539a..0c45da99 100644 --- a/internal/controller/apiconsumer_controller_test.go +++ b/internal/controller/apiconsumer_controller_test.go @@ -1870,3 +1870,52 @@ func TestConsumerPreservedNameStaysInTheRecord(t *testing.T) { "later would leave its key working", got) } } + +// With a consumer preserved - ours, Secret unreadable - the "nothing changed, do not write" +// short-circuit still has to hold. It did not: the annotation records mine ∪ preserve while +// the comparison used mine alone, so the recorded set was a strict superset forever, the +// check was false on every round, and the gateway object was written on every pass. The +// writes were content-identical, so nothing reached the data plane - which is exactly why +// this needs a test that counts writes rather than looking at the result. +func TestConsumerPreservedNameDoesNotCauseAWritePerRound(t *testing.T) { + broken := consumerFixture("tenant-a", "gone-secret") + healthy := consumerFixture("tenant-b", "tenant-b-keys") + healthy.Status.ConsumerName = "tenant-b" + healthy.Status.AppliedGatewayNamespace = "higress-system" + r, c := newConsumerReconciler(t, broken, healthy, + credSecret("tenant-b-keys", map[string]string{"key": "sk-b"}), + keyAuthManagedBy("tenant-a,tenant-b", + liveConsumer("tenant-a", "Bearer sk-a"), liveConsumer("tenant-b", "Bearer sk-b")), + ) + rv := func() string { + var ka unstructured.Unstructured + ka.SetGroupVersionKind(wasmPluginGVK) + if err := c.Get(context.Background(), types.NamespacedName{ + Namespace: "higress-system", Name: "key-auth"}, &ka); err != nil { + t.Fatal(err) + } + return ka.GetResourceVersion() + } + // First round settles the annotation (it gains the preserved name). + if _, err := r.programGateway(context.Background(), "higress-system", nil); err != nil { + t.Fatal(err) + } + settled := rv() + for i := 0; i < 3; i++ { + if _, err := r.programGateway(context.Background(), "higress-system", nil); err != nil { + t.Fatal(err) + } + } + if got := rv(); got != settled { + t.Fatalf("key-auth was written again with nothing changed (resourceVersion %s -> %s): "+ + "a preserved consumer makes every round rewrite the gateway", settled, got) + } + // ...and the preserved name is still recorded, which is what made the comparison tricky. + var ka unstructured.Unstructured + ka.SetGroupVersionKind(wasmPluginGVK) + _ = c.Get(context.Background(), types.NamespacedName{ + Namespace: "higress-system", Name: "key-auth"}, &ka) + if got := ka.GetAnnotations()[managedConsumersAnnotation]; !strings.Contains(got, "tenant-a") { + t.Fatalf("managed-consumers = %q, want the preserved name kept", got) + } +} diff --git a/internal/controller/modelfleet_controller.go b/internal/controller/modelfleet_controller.go index b6c78c63..e98ad1a8 100644 --- a/internal/controller/modelfleet_controller.go +++ b/internal/controller/modelfleet_controller.go @@ -1159,12 +1159,19 @@ func (r *ModelFleetReconciler) upsertMatchRule(ctx context.Context, rend *fleetR return fmt.Errorf("read %s defaultConfig: %w", p.name, err) } if !found || len(def) == 0 { - return &pluginUnusableError{plugin: p.name, - why: "its defaultConfig is empty, and this controller copies it into the " + - "rule because the gateway never receives defaultConfig while " + - "defaultConfigDisable is true"} + // Withdraw, like the p.unusable path above, rather than returning here: a + // bare return leaves the rule already on the gateway in place while the + // fleet reports "not written" - the same asymmetry that path was changed to + // avoid. Unreachable for ai-stream-guard today, because its unusable hook + // rejects a missing defaultConfig first, but a trap for the next plugin + // given copyDefaultConfig without one. + unusableWhy = "its defaultConfig is empty, and this controller copies it " + + "into the rule because the gateway never receives defaultConfig while " + + "defaultConfigDisable is true" + cfg = nil + } else { + cfg = def } - cfg = def } rules, _, err := unstructured.NestedSlice(obj.Object, "spec", "matchRules") if err != nil { From 1f65b19c9ddc007291e510b53ae34695b889ef47 Mon Sep 17 00:00:00 2001 From: zhanghao Date: Thu, 26 Nov 2026 22:49:24 +0800 Subject: [PATCH 26/28] APIConsumer: ownership comes from the record, not from the name 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 --- README.md | 16 +- cmd/main_test.go | 28 ++- internal/controller/apiconsumer_controller.go | 165 +++++++++++++++--- .../controller/apiconsumer_controller_test.go | 130 ++++++++++++-- internal/sink/fleet.go | 7 +- 5 files changed, 295 insertions(+), 51 deletions(-) diff --git a/README.md b/README.md index e5572e63..d1c04e37 100644 --- a/README.md +++ b/README.md @@ -543,13 +543,23 @@ Higress controller 根本不下发 `defaultConfig`,空规则到达插件时全 **两条写入安全规则**(这个改动最危险的地方,都是「宁可不写」): -- **坏一个,全不写**。某个 `APIConsumer` 的 Secret 读不到时,**不会**把它从名单里摘掉再写剩下的 —— - 名单里少一个 consumer,就是那个调用方下一个请求 401。这一轮整个不写,网关保持上一份好名单, - 失败报在那个对象的 `Programmed` 上。 +- **一个坏对象不连累别人,但绝不因此摘掉任何活 key**。名单里少一个 consumer,就是那个调用方下一个 + 请求 401 —— 所以某个 `APIConsumer` 的 Secret 读不到时,**它在网关里的那条已有条目原样留着** + (key 继续有效),其余人的增删改照常进行,失败报在那个对象自己的 `Programmed` 上。 + **「原样留着」只对能证明属于它的条目成立** —— 判据是 annotation `routing.modelsphere.dev/managed-consumers` + (我们写网关的那一次就把名字记进去了,所以 status 没写成功也不影响),**不是「名字对得上」**: + 否则谁都能用「指向 chart 渲染的 consumer 名 + 一个不存在的 secretRef」把别人的条目认领走。 + 同理,**一个对象的问题一律只让它自己付代价**:撞名、与结转条目撞 key、证明不了的认领, + 都是把它剔出这一轮并把原因写在它自己身上,而不是拒绝整轮(拒绝整轮就等于谁都不能轮换或**吊销** + key,包括吊销一个已泄漏的 —— 这一类错在这个 PR 里反复出现过,每次都是「一个对象的问题变成全网关的问题」)。 - **不能把名单写空**,除非这个网关的名单**本来就是我们写的**(有 `APIConsumer` 的 `status.appliedGatewayNamespace` 指着它)。「删掉最后一个 consumer」和「还没迁移、名单还是 chart 渲染的」 从期望态看一模一样(都是零个对象),而后者写空 = 全站所有路由对所有人 403。 +⚠ **不要给租户 `apiconsumers/status` 的写权限**:归属判定看 `status.appliedGatewayNamespace` ++ `status.consumerName`,能改 status 就能让自己变成某个名字的「在位者」从而跳过持有证明。 +`spec` 可以给(那是自助改 key 的入口),`status` 只能 controller 写。 + ⚠ **它给的是「源头唯一、可在线轮换、不用发版」,不是「密钥不可见」**:key-auth 的配置是经 ECDS 推下去的 一段 blob,插件没有读 Secret 的能力,所以密钥最终仍然明文躺在 `WasmPlugin` 对象里 —— 能读网关 ns 下 WasmPlugin 的人就能读到所有 key。要真正隐藏得换插件能力,是另一件事。 diff --git a/cmd/main_test.go b/cmd/main_test.go index 1ea51787..01817a30 100644 --- a/cmd/main_test.go +++ b/cmd/main_test.go @@ -1,8 +1,12 @@ package main import ( + "fmt" "testing" + "k8s.io/apimachinery/pkg/runtime" + clienttesting "k8s.io/client-go/testing" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" fakediscovery "k8s.io/client-go/discovery/fake" "k8s.io/client-go/kubernetes/fake" @@ -81,9 +85,25 @@ func TestKeyAuthWatchWanted(t *testing.T) { // crash-looped the pod and took ModelRoute down with it, the exact outcome the gate exists to // prevent. There is no unit hook on runController, so this pins the contract where it can be // pinned: the decision function treats "cannot tell" the same as "not served". -func TestKeyAuthWatchWantedOnDiscoveryFailure(t *testing.T) { - // The caller turns an error into false; this asserts what false then means. - if keyAuthWatchWanted(false) { - t.Fatal("a cluster we could not ask about would get the watch registered anyway") +func TestDiscoveryFailureLeavesTheWatchUnregistered(t *testing.T) { + // Through the real path, not keyAuthWatchWanted(false): that only restated its argument. + // What matters is that a discovery error becomes "not served" rather than "assume yes" - + // registering a For() watch on a kind that does not exist makes the manager wait for a + // cache that never syncs and then exit, crash-looping the pod and taking ModelRoute with + // it on every cluster without Higress. + cs := fake.NewSimpleClientset() + cs.Fake.PrependReactor("get", "*", func(clienttesting.Action) (bool, runtime.Object, error) { + return true, nil, fmt.Errorf("the API server is not answering") + }) + served, err := kindServed(cs, "extensions.higress.io/v1alpha1", "WasmPlugin") + if err == nil { + t.Fatal("a discovery failure was reported as a successful answer") + } + if served { + t.Fatal("a discovery failure came back as \"the kind is served\": the watch would be " + + "registered on a cluster that may not have Higress at all") + } + if keyAuthWatchWanted(served) { + t.Fatal("the gate wants the watch after a discovery failure") } } diff --git a/internal/controller/apiconsumer_controller.go b/internal/controller/apiconsumer_controller.go index 08580ec6..419650f3 100644 --- a/internal/controller/apiconsumer_controller.go +++ b/internal/controller/apiconsumer_controller.go @@ -10,6 +10,7 @@ import ( "errors" "fmt" "sort" + "strconv" "strings" "time" @@ -355,33 +356,32 @@ func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, // plausibly its own: that is the object whose gateway write landed and whose status // write did not, and skipping it WOULD revoke a live key. incumbent := func(c *routingv1.APIConsumer) bool { - if c.Status.AppliedGatewayNamespace == gwNS { + // The status shortcut needs BOTH halves: the gateway it programmed and the name it + // programmed there. Without the name check, renaming spec.consumerName made the + // object an incumbent for a name it has never served - so an object renamed onto a + // name somebody else serves produced two incumbents, and the collision check then + // refused the round for the whole gateway, every round, blocking every add, rotation + // and revocation. The error even claimed "dropping either revokes a working key", + // which was false: the renamed object's new name served nothing. + if c.Status.AppliedGatewayNamespace == gwNS && c.Status.ConsumerName == consumerName(c) { return true } + // Failing that, the ANNOTATION decides - not "a live entry exists under this name". + // + // The fallback is here for one case: the gateway write landed and the status write + // after it did not, so the key is live with nothing on the object to say so. But that + // write recorded the name in managed-consumers, because setManagedConsumerNames runs + // inside it. So an entry we actually wrote is always in the annotation, status or no + // status - while an entry the gateway chart rendered is not. + // + // Keyed on the name alone this was a takeover path: point consumerName at a + // chart-rendered consumer, and an object with no status and no readable Secret came + // out an "incumbent" of somebody else's entry. name := consumerName(c) - if !hasLiveEntry(liveNames, name) { + if !liveManaged[name] { return false } - for i := range list.Items { - o := &list.Items[i] - if o.Namespace == c.Namespace && o.Name == c.Name { - continue - } - if o.Status.AppliedGatewayNamespace == gwNS && o.Status.ConsumerName == name { - return false // that entry is on record as somebody else's - } - } - // An entry with no status behind it can only be attributed to ONE object. If a second - // object claims the same consumerName, nothing on record says which of them the live - // entry belongs to - so neither is an incumbent, and both are handled as newcomers: - // the collision check then leaves them both out instead of refusing the round. - // - // Without this, two brand-new objects claiming a CHART-rendered name both came out as - // incumbents (each sees a live entry and no other object's STATUS claiming it), the - // collision check hit "more than one incumbent" and froze the whole gateway - 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. + // Ours, and contested: the object that was here first keeps it. for i := range list.Items { o := &list.Items[i] if o.Namespace == c.Namespace && o.Name == c.Name { @@ -390,11 +390,19 @@ func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, if consumerName(o) != name || !o.DeletionTimestamp.IsZero() { continue } - if liveManaged[name] && o.CreationTimestamp.Before(&c.CreationTimestamp) { - return false // ours, and somebody was here first + if o.Status.AppliedGatewayNamespace == gwNS && o.Status.ConsumerName == name { + return false // on record as somebody else's + } + if o.CreationTimestamp.Before(&c.CreationTimestamp) { + return false } - if !liveManaged[name] { - return false // contested, and nothing on record says it is this object's + // CreationTimestamp has one-second resolution, so two objects created in the same + // second are neither Before the other and BOTH would come out incumbent - two + // incumbents, and the collision check refuses the round for the whole gateway. + // Any total order does: it only has to be the same one for both objects. + if o.CreationTimestamp.Equal(&c.CreationTimestamp) && + o.Namespace+"/"+o.Name < c.Namespace+"/"+c.Name { + return false } } return true @@ -430,7 +438,22 @@ func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, // same thing done for an entry this controller does not manage - so nobody // loses access, everyone else's changes go through, and the reason sits on the // object whose Secret is missing. - if hasLiveEntry(liveNames, consumerName(c)) { + // incumbent(c), not just "a live entry exists under this name". Keyed on the name + // alone, this was a takeover path for anyone who can create an APIConsumer in + // their own namespace: point consumerName at a chart-rendered consumer, give it a + // secretRef that does not exist, and the entry is preserved AND recorded as + // autoconfig-managed in the annotation. From then on the proof-of-key check is + // skipped for that name, so creating the Secret with your own key replaces the + // real tenant's - 401 for them, every route they were allowed on for you. It + // also let a second claimant put a duplicate entry in the list, which either + // freezes the gateway on the duplicate-credential guard or leaves a rotated-away + // key accepted. + // + // So: only an entry that is demonstrably this object's, and never a name another + // view renders this round (that view's rendered entry is the current one; keeping + // a stale copy beside it is how the duplicate arose). + if incumbent(c) && hasLiveEntry(liveNames, consumerName(c)) && + !renderedThisRound(views, consumerName(c)) { preserve[consumerName(c)] = true round.skipped[c.Namespace+"/"+c.Name] = err.Error() + " (this consumer's existing entry was left in the gateway untouched, so " + @@ -447,7 +470,18 @@ func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, // releases with the key still live. One new broken object must not hold the // rest hostage, so it is skipped, with the error on its own object. if !incumbent(c) { - round.skipped[c.Namespace+"/"+c.Name] = err.Error() + why := err.Error() + " (this consumer was left out of this round; nothing " + + "else on this gateway is blocked)" + // Say whether an entry under that name is in the list - without claiming it + // is this consumer's, which is exactly what cannot be shown here. The + // operator's question is "did I just break a tenant", and the answer is no. + if hasLiveEntry(liveNames, consumerName(c)) { + why = err.Error() + " (an existing entry named " + + strconv.Quote(consumerName(c)) + " is in the gateway and was left " + + "untouched, so its key keeps working - this controller cannot show " + + "that entry is this object's, so it was not rewritten either)" + } + round.skipped[c.Namespace+"/"+c.Name] = why continue } return round, fmt.Errorf("%s/%s: %w (nothing was written; the gateway keeps its "+ @@ -486,6 +520,7 @@ func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, // rather than failing the round: wanting an identity it is not entitled to must not stop // every other consumer on this gateway from being added, rotated or revoked. views = dropUnprovenAdoptions(views, liveEntries, liveManaged, claimed, round, gwNS) + views = dropDuplicatesAgainstCarriedOver(views, liveEntries, liveManaged, claimed, round) if len(round.skipped) > 0 { logf.FromContext(ctx).Info("left consumers out of this round", @@ -1476,3 +1511,77 @@ func ourGateway(o *unstructured.Unstructured, named map[string]bool) bool { } return o.GetNamespace() == defaultGatewayNamespace } + +// renderedThisRound: is some view already rendering this consumer name? Used to keep a +// preserved (unrenderable) entry from sitting in the list beside a freshly rendered one with +// the same name - two entries for one consumer, which the duplicate-credential guard then +// refuses for the whole gateway, or which leaves a rotated-away key accepted. +func renderedThisRound(views []sink.ConsumerView, name string) bool { + for _, v := range views { + if v.Name == name { + return true + } + } + return false +} + +// dropDuplicatesAgainstCarriedOver leaves out a view whose credential already exists in an +// entry this controller does not own and will copy over verbatim. +// +// key-auth refuses a duplicate credential by failing to parse its whole defaultConfig, and it +// is FAIL_CLOSE, so the pair would deny every caller on every route of the gateway. The guard +// in the write path catches it - but it caught it by refusing the ROUND, which is one object's +// problem becoming everybody's: nobody could add, rotate or revoke a key while that object +// existed. Same shape as every other freeze fixed in this PR, and reachable on the documented +// migration path rather than in theory: a chart entry whose name cannot be adopted +// (consumerName is pinned to a DNS label, the chart's name might not be one) gets a new +// APIConsumer carrying the SAME key, because the point of the migration is that no caller has +// to change anything. +// +// So it costs the newcomer, and the reason lands on the newcomer's own object - where someone +// can act on it, by adopting that entry under its own name or by removing it from the chart. +// The write-path guard stays as a backstop; a guard that never fires is fine, a freeze on a +// normal path is not. +func dropDuplicatesAgainstCarriedOver(views []sink.ConsumerView, + liveEntries map[string][]string, liveManaged, claimed map[string]bool, + round gatewayRound) []sink.ConsumerView { + rendered := map[string]bool{} + for _, v := range views { + rendered[v.Name] = true + } + // Which live entries will be carried over as somebody else's, and under what name. + ownerOf := map[string]string{} + for name, creds := range liveEntries { + if rendered[name] || liveManaged[name] || claimed[name] { + continue + } + for _, c := range creds { + ownerOf[strings.TrimPrefix(c, bearerPrefixValue)] = name + } + } + if len(ownerOf) == 0 { + return views + } + kept := make([]sink.ConsumerView, 0, len(views)) + for _, v := range views { + clash := "" + for _, c := range v.Credentials { + if n := ownerOf[strings.TrimPrefix(c, bearerPrefixValue)]; n != "" { + clash = n + break + } + } + if clash == "" { + kept = append(kept, v) + continue + } + round.skipped[v.Source] = fmt.Sprintf("one of its credentials is already in use by "+ + "consumer %q, which this controller does not manage (the gateway chart renders it "+ + "until the migration is finished). key-auth refuses a duplicate credential by "+ + "failing to parse its whole config, and it denies every caller when it cannot "+ + "parse - so this consumer was left out instead, and nothing else on this gateway "+ + "is blocked. Either adopt %q with this APIConsumer (set consumerName to it, if it "+ + "is a valid DNS label) or remove it from the chart", clash, clash) + } + return kept +} diff --git a/internal/controller/apiconsumer_controller_test.go b/internal/controller/apiconsumer_controller_test.go index 0c45da99..3a9f0f6b 100644 --- a/internal/controller/apiconsumer_controller_test.go +++ b/internal/controller/apiconsumer_controller_test.go @@ -906,29 +906,46 @@ func TestConsumerAdoptionIsRecordedEvenWhenTheListDoesNotChange(t *testing.T) { // Reachable on the documented migration path: a chart entry whose name is not a DNS label // cannot be adopted under that name (consumerName is pinned to one), so it gets a new // APIConsumer carrying the SAME key - the whole point being that the caller changes nothing. -func TestConsumerRefusesACredentialSharedWithAForeignEntry(t *testing.T) { +func TestConsumerSharingACredentialWithAForeignEntryCostsOnlyItself(t *testing.T) { + // Reachable on the documented migration path: a chart entry under a name no APIConsumer + // can take (consumerName is a DNS label, "tenant_a" is not) gets a new APIConsumer + // carrying the SAME key, because the point of the migration is that no caller changes + // anything. key-auth refuses a duplicate credential by failing to parse its whole config + // and denies everyone, so the pair must not be written - but it used to cost the round, + // and with it every other tenant's ability to add, rotate or revoke a key. + other := consumerFixture("tenant-b", "tenant-b-keys") + other.Status.ConsumerName = "tenant-b" + other.Status.AppliedGatewayNamespace = "higress-system" r, c := newConsumerReconciler(t, - consumerFixture("tenant-a", "tenant-a-keys"), + consumerFixture("tenant-a", "tenant-a-keys"), other, credSecret("tenant-a-keys", map[string]string{"key": "sk-shared"}), - // The chart's entry, under a name no APIConsumer can take, with the same key. - keyAuthWith(liveConsumer("tenant_a", "Bearer sk-shared")), + credSecret("tenant-b-keys", map[string]string{"key": "sk-b-rotated"}), + keyAuthManagedBy("tenant-b", + liveConsumer("tenant_a", "Bearer sk-shared"), + liveConsumer("tenant-b", "Bearer sk-b")), ) - _, err := r.programGateway(context.Background(), "higress-system", nil) - if err == nil { - t.Fatal("wrote a list key-auth refuses to parse: every caller on the gateway would be denied") + round, err := r.programGateway(context.Background(), "higress-system", nil) + if err != nil { + t.Fatalf("one object's duplicate key froze the gateway: %v", err) } - for _, want := range []string{"tenant_a", "tenant-a", "every caller on every route"} { - if !strings.Contains(err.Error(), want) { - t.Fatalf("the error does not mention %s: %v", want, err) + // The reason is on the offending object, and names the entry it collides with. + why := round.skipped["llm-route/tenant-a"] + for _, want := range []string{"tenant_a", "left out"} { + if !strings.Contains(why, want) { + t.Fatalf("the reason on tenant-a does not mention %s: %q", want, why) } } - if strings.Contains(err.Error(), "sk-shared") { - t.Fatalf("the error leaks the credential: %v", err) + if strings.Contains(why, "sk-shared") { + t.Fatalf("the reason leaks the credential: %q", why) } - // Nothing was written: the gateway keeps the list it had. + // The duplicate was NOT written... names := consumerNames(gatewayConsumers(t, c, "higress-system")) - if strings.Join(names, ",") != "tenant_a" { - t.Fatalf("consumers = %v, want the live list untouched", names) + if strings.Join(names, ",") != "tenant-b,tenant_a" { // sorted, and "-" sorts before "_" + t.Fatalf("consumers = %v, want the foreign entry plus tenant-b", names) + } + // ...and tenant-b's rotation went through, which is what the freeze used to block. + if got := creds0Of(t, c, "higress-system", "tenant-b"); strings.Join(got, ",") != "Bearer sk-b-rotated" { + t.Fatalf("tenant-b credentials = %v, want its rotated key", got) } } @@ -1919,3 +1936,86 @@ func TestConsumerPreservedNameDoesNotCauseAWritePerRound(t *testing.T) { t.Fatalf("managed-consumers = %q, want the preserved name kept", got) } } + +// The takeover路径 that routed around the proof-of-key check: do it through a BROKEN Secret. +// +// Point consumerName at a chart-rendered consumer with a secretRef that does not exist. If the +// entry is preserved on the strength of the name alone, it is also recorded as +// autoconfig-managed - and from then on the proof-of-key check is skipped for that name, so +// creating the Secret afterwards with your own key replaces the real tenant's. 401 for them, +// every route they were allowed on for you. Anyone who can create an APIConsumer in their own +// namespace could do it. +func TestConsumerCannotPreserveSomebodyElsesEntry(t *testing.T) { + impostor := consumerFixture("team-x", "does-not-exist-yet") + impostor.Namespace = "team-x" + impostor.Spec.ConsumerName = "chart-a" + // A healthy consumer too, so the round actually WRITES. Without one the empty-list guard + // refuses, nothing is recorded, and the test passes whether or not the bug is there - + // which is how the first version of it passed against the reverted fix. zoboth's scenario + // says it plainly: the next write for any reason is what records the stolen name. + healthy := consumerFixture("tenant-ok", "ok-keys") + r, c := newConsumerReconciler(t, impostor, healthy, + credSecret("ok-keys", map[string]string{"key": "sk-ok"}), + // The chart's entry, owned by no APIConsumer. + keyAuthWith(liveConsumer("chart-a", "Bearer sk-the-real-key")), + ) + // The round may well return an error here - with the impostor left out there is nothing + // of ours to write, and the empty-list guard refuses to wipe the chart's entry. Which + // guard fires is not the point; the invariants are. + _, _ = r.programGateway(context.Background(), "higress-system", nil) + var ka unstructured.Unstructured + ka.SetGroupVersionKind(wasmPluginGVK) + if err := c.Get(context.Background(), types.NamespacedName{ + Namespace: "higress-system", Name: "key-auth"}, &ka); err != nil { + t.Fatal(err) + } + // The name must NOT have become autoconfig-managed on the back of a broken Secret. + if got := ka.GetAnnotations()[managedConsumersAnnotation]; strings.Contains(got, "chart-a") { + t.Fatalf("managed-consumers = %q: an object with no readable Secret claimed a name it "+ + "never proved it holds, which skips the proof check from here on", got) + } + // The real key is untouched. + if got := creds0Of(t, c, "higress-system", "chart-a"); strings.Join(got, ",") != "Bearer sk-the-real-key" { + t.Fatalf("chart-a credentials = %v, want the original", got) + } + + // ...and now that it has a Secret with its OWN key, the proof check still refuses it. + sec := credSecret("does-not-exist-yet", map[string]string{"key": "sk-attacker"}) + sec.Namespace = "team-x" + if err := c.Create(context.Background(), sec); err != nil { + t.Fatal(err) + } + _, _ = r.programGateway(context.Background(), "higress-system", nil) + if got := creds0Of(t, c, "higress-system", "chart-a"); strings.Join(got, ",") != "Bearer sk-the-real-key" { + t.Fatalf("chart-a credentials = %v: the impostor took the name over", got) + } +} + +// Renaming spec.consumerName must not make an object an incumbent for a name it has never +// served. It did - the status shortcut compared only the gateway - so an object renamed onto a +// name somebody else serves produced two incumbents, and the collision check refused the round +// for the whole gateway: every add, rotation and revocation blocked, every round, with an +// error claiming that dropping either would revoke a working key. +func TestConsumerRenameDoesNotFreezeTheGateway(t *testing.T) { + x := consumerFixture("obj-x", "x-keys") + x.Spec.ConsumerName = "tenant-b" // renamed onto Y's name + x.Status.ConsumerName = "tenant-x" + x.Status.AppliedGatewayNamespace = "higress-system" + y := consumerFixture("obj-y", "y-keys") + y.Spec.ConsumerName = "tenant-b" + y.Status.ConsumerName = "tenant-b" + y.Status.AppliedGatewayNamespace = "higress-system" + r, c := newConsumerReconciler(t, x, y, + credSecret("x-keys", map[string]string{"key": "sk-x"}), + credSecret("y-keys", map[string]string{"key": "sk-y-rotated"}), + keyAuthManagedBy("tenant-b,tenant-x", + liveConsumer("tenant-b", "Bearer sk-y"), liveConsumer("tenant-x", "Bearer sk-x")), + ) + if _, err := r.programGateway(context.Background(), "higress-system", nil); err != nil { + t.Fatalf("a renamed object froze the whole gateway: %v", err) + } + // Y keeps the name it actually serves, with its rotation applied. + if got := creds0Of(t, c, "higress-system", "tenant-b"); strings.Join(got, ",") != "Bearer sk-y-rotated" { + t.Fatalf("tenant-b credentials = %v, want Y's rotated key", got) + } +} diff --git a/internal/sink/fleet.go b/internal/sink/fleet.go index e8cf407f..51f6ee07 100644 --- a/internal/sink/fleet.go +++ b/internal/sink/fleet.go @@ -335,7 +335,12 @@ func RenderAIStatistics() *AIStatistics { }}} } -// StreamGuardRule is the match rule written for the repetition guard: empty on purpose. +// StreamGuardRule is the match rule written for the repetition guard. +// +// It is the marker the controller substitutes the plugin's own spec.defaultConfig for, NOT +// the config that reaches the gateway - an empty rule was the first design and does not work: +// with defaultConfigDisable true the Higress controller never sends defaultConfig, so an +// empty rule arrives at a plugin whose global config is empty and is refused. // // The plugin's parseRuleConfig starts from the global config and only replaces what the rule // names, so an empty object means "the parameters the gateway chart configured apply to this From 83d1f17831f7af17bf191e8dd573334f617dc052 Mon Sep 17 00:00:00 2001 From: zhanghao Date: Thu, 26 Nov 2026 23:17:51 +0800 Subject: [PATCH 27/28] APIConsumer: the preserve decision must not depend on List order 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 --- internal/controller/apiconsumer_controller.go | 71 +++++++++++++------ .../controller/apiconsumer_controller_test.go | 54 ++++++++++++++ 2 files changed, 104 insertions(+), 21 deletions(-) diff --git a/internal/controller/apiconsumer_controller.go b/internal/controller/apiconsumer_controller.go index 419650f3..eb29191b 100644 --- a/internal/controller/apiconsumer_controller.go +++ b/internal/controller/apiconsumer_controller.go @@ -341,6 +341,7 @@ func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, // could not be read. Not the same as "ours to rewrite" and not the same as "somebody // else's": it is "ours, and we cannot render it right now". preserve := map[string]bool{} + preservedBy := map[string]string{} // name -> the object keeping it, for the message // incumbent: is the entry under this consumer's name in this gateway THIS object's? // Everything that can go wrong with a newcomer is survivable by leaving it out; the same // thing wrong with an incumbent means refusing the round, because dropping it revokes a @@ -382,6 +383,21 @@ func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, return false } // Ours, and contested: the object that was here first keeps it. + // + // KNOWN GAP, deliberately not closed here. If this object's gateway write landed and + // its status write did not, an OLDER object renamed onto its name wins this tiebreak + // (neither has a conclusive status), and because the name is in the annotation the + // proof-of-key check is skipped, so the older object's key is written as a rotation. + // The window is a failed status write with a rename landing inside it. + // + // The obvious tightening - require the proof whenever no status claims the name - can + // REVOKE a key, which is worse than the gap: gateway write lands with key K1, the + // owner then 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 exactly the revocation path. 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 unreadable. Left as is until it + // can be done without trading a management-plane gap for a data-plane outage. for i := range list.Items { o := &list.Items[i] if o.Namespace == c.Namespace && o.Name == c.Name { @@ -449,12 +465,16 @@ func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, // freezes the gateway on the duplicate-credential guard or leaves a rotated-away // key accepted. // - // So: only an entry that is demonstrably this object's, and never a name another - // view renders this round (that view's rendered entry is the current one; keeping - // a stale copy beside it is how the duplicate arose). - if incumbent(c) && hasLiveEntry(liveNames, consumerName(c)) && - !renderedThisRound(views, consumerName(c)) { + // So: only an entry that is demonstrably this object's. Whether another object + // also claims that name is settled AFTER this loop - asking here consulted a + // half-built `views` and so depended on List order, which is namespace/name and + // therefore chosen by whoever picks the namespace. Either the newcomer sorted + // after and both entries were written (its key accepted as this consumer, or a + // duplicate name failing the whole gateway closed), or it sorted before and the + // round was refused on every pass while the Secret stayed broken. + if incumbent(c) && hasLiveEntry(liveNames, consumerName(c)) { preserve[consumerName(c)] = true + preservedBy[consumerName(c)] = c.Namespace + "/" + c.Name round.skipped[c.Namespace+"/"+c.Name] = err.Error() + " (this consumer's existing entry was left in the gateway untouched, so " + "its key keeps working; nothing else on this gateway is blocked. Fix the " + @@ -505,7 +525,30 @@ func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, // namespace-scoped writer from stealing a managed consumer name, and the duplicate // credential one is what stops a gateway-wide parse failure. Only who pays for the // collision changes: the newcomer, not everybody. - views, err = r.dropCollidingNewcomers(ctx, views, list.Items, gwNS, incumbent, round) + // 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 below cannot see it. Settled + // here, now that every view exists, which is what makes the outcome independent of List + // order. + if len(preserve) > 0 { + kept := make([]sink.ConsumerView, 0, len(views)) + for _, v := range views { + if holder := preservedBy[v.Name]; holder != "" { + round.skipped[v.Source] = fmt.Sprintf("consumer name %q is already served by "+ + "%s, whose credentials this controller cannot read at the moment, so its "+ + "existing entry is being kept as it is. This consumer was left out of "+ + "this round rather than written beside it - two entries for one consumer "+ + "name either accept both keys or make key-auth reject the list and deny "+ + "every caller on this gateway. Pick a different consumerName, or wait "+ + "until %s is fixed if the name is meant to be yours", v.Name, holder, + holder) + continue + } + kept = append(kept, v) + } + views = kept + } + + views, err = r.dropCollidingNewcomers(views, list.Items, gwNS, incumbent, round) if err != nil { return round, err } @@ -552,7 +595,7 @@ func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, // - two claimants are already serving it: refused as an error. One bad newcomer cannot // produce this, it means two live consumers genuinely share an identity, and dropping // either revokes a working key. A person has to look. -func (r *APIConsumerReconciler) dropCollidingNewcomers(ctx context.Context, +func (r *APIConsumerReconciler) dropCollidingNewcomers( views []sink.ConsumerView, items []routingv1.APIConsumer, gwNS string, incumbent func(*routingv1.APIConsumer) bool, round gatewayRound) ([]sink.ConsumerView, error) { bySource := map[string]*routingv1.APIConsumer{} @@ -642,7 +685,6 @@ func (r *APIConsumerReconciler) dropCollidingNewcomers(ctx context.Context, } kept = append(kept, v) } - _ = ctx return kept, nil } @@ -1512,19 +1554,6 @@ func ourGateway(o *unstructured.Unstructured, named map[string]bool) bool { return o.GetNamespace() == defaultGatewayNamespace } -// renderedThisRound: is some view already rendering this consumer name? Used to keep a -// preserved (unrenderable) entry from sitting in the list beside a freshly rendered one with -// the same name - two entries for one consumer, which the duplicate-credential guard then -// refuses for the whole gateway, or which leaves a rotated-away key accepted. -func renderedThisRound(views []sink.ConsumerView, name string) bool { - for _, v := range views { - if v.Name == name { - return true - } - } - return false -} - // dropDuplicatesAgainstCarriedOver leaves out a view whose credential already exists in an // entry this controller does not own and will copy over verbatim. // diff --git a/internal/controller/apiconsumer_controller_test.go b/internal/controller/apiconsumer_controller_test.go index 3a9f0f6b..afffa954 100644 --- a/internal/controller/apiconsumer_controller_test.go +++ b/internal/controller/apiconsumer_controller_test.go @@ -2019,3 +2019,57 @@ func TestConsumerRenameDoesNotFreezeTheGateway(t *testing.T) { t.Fatalf("tenant-b credentials = %v, want Y's rotated key", got) } } + +// A preserved incumbent plus a newcomer on the same name, in BOTH List orders. +// +// The preserve decision used to consult a half-built view list, so the outcome depended on +// List order - which is namespace/name, so whoever picks the namespace picks the outcome: +// +// - newcomer sorting AFTER the broken incumbent: both entries written, so the newcomer's own +// key authenticates as that consumer on every route it is allowed on (or key-auth rejects +// the duplicate name and the whole gateway fails closed); +// - 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 the Secret stays broken. +// +// Both orders must now reach the same place: the round writes, the name keeps exactly one +// entry with the original key, and the newcomer is told why on its own object. +func TestConsumerPreservedIncumbentBeatsANewcomerInEitherListOrder(t *testing.T) { + for _, tc := range []struct{ name, newcomerNS string }{ + {"newcomer sorts after the incumbent", "zz-team"}, + {"newcomer sorts before the incumbent", "aa-team"}, + } { + t.Run(tc.name, func(t *testing.T) { + // The incumbent: programmed, Secret now unreadable. + a := consumerFixture("obj-a", "gone-secret") + a.Namespace = "mm-team" + a.Spec.ConsumerName = "tenant-a" + a.Status.ConsumerName = "tenant-a" + a.Status.AppliedGatewayNamespace = "higress-system" + // The newcomer: readable Secret holding its OWN key, same consumerName. + b := consumerFixture("obj-b", "b-keys") + b.Namespace = tc.newcomerNS + b.Spec.ConsumerName = "tenant-a" + bSec := credSecret("b-keys", map[string]string{"key": "sk-attacker"}) + bSec.Namespace = tc.newcomerNS + r, c := newConsumerReconciler(t, a, b, bSec, + keyAuthManagedBy("tenant-a", liveConsumer("tenant-a", "Bearer sk-real"))) + + round, err := r.programGateway(context.Background(), "higress-system", nil) + if err != nil { + t.Fatalf("the round was refused for the whole gateway: %v", err) + } + entries := gatewayConsumers(t, c, "higress-system") + if n := len(entries); n != 1 { + t.Fatalf("tenant-a has %d entries, want exactly 1: two entries for one "+ + "consumer name either accept both keys or deny every caller", n) + } + if got := creds0Of(t, c, "higress-system", "tenant-a"); strings.Join(got, ",") != "Bearer sk-real" { + t.Fatalf("tenant-a credentials = %v, want only the original key", got) + } + why := round.skipped[tc.newcomerNS+"/obj-b"] + if !strings.Contains(why, "already served by") { + t.Fatalf("the newcomer was not told why: %q", why) + } + }) + } +} From 62b74252529242ad78d0a8785290888297cf3f41 Mon Sep 17 00:00:00 2001 From: zhanghao Date: Fri, 27 Nov 2026 00:07:38 +0800 Subject: [PATCH 28/28] APIConsumer: a preserved incumbent's key is a key, for the clash check 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 --- internal/controller/apiconsumer_controller.go | 25 +++++++--- .../controller/apiconsumer_controller_test.go | 47 +++++++++++++++++++ 2 files changed, 66 insertions(+), 6 deletions(-) diff --git a/internal/controller/apiconsumer_controller.go b/internal/controller/apiconsumer_controller.go index eb29191b..f8a0dd21 100644 --- a/internal/controller/apiconsumer_controller.go +++ b/internal/controller/apiconsumer_controller.go @@ -563,7 +563,7 @@ func (r *APIConsumerReconciler) programGateway(ctx context.Context, gwNS string, // rather than failing the round: wanting an identity it is not entitled to must not stop // every other consumer on this gateway from being added, rotated or revoked. views = dropUnprovenAdoptions(views, liveEntries, liveManaged, claimed, round, gwNS) - views = dropDuplicatesAgainstCarriedOver(views, liveEntries, liveManaged, claimed, round) + views = dropDuplicatesAgainstCarriedOver(views, liveEntries, liveManaged, claimed, preserve, round) if len(round.skipped) > 0 { logf.FromContext(ctx).Info("left consumers out of this round", @@ -1572,7 +1572,7 @@ func ourGateway(o *unstructured.Unstructured, named map[string]bool) bool { // The write-path guard stays as a backstop; a guard that never fires is fine, a freeze on a // normal path is not. func dropDuplicatesAgainstCarriedOver(views []sink.ConsumerView, - liveEntries map[string][]string, liveManaged, claimed map[string]bool, + liveEntries map[string][]string, liveManaged, claimed, preserve map[string]bool, round gatewayRound) []sink.ConsumerView { rendered := map[string]bool{} for _, v := range views { @@ -1581,7 +1581,15 @@ func dropDuplicatesAgainstCarriedOver(views []sink.ConsumerView, // Which live entries will be carried over as somebody else's, and under what name. ownerOf := map[string]string{} for name, creds := range liveEntries { - if rendered[name] || liveManaged[name] || claimed[name] { + // A PRESERVED name is carried over too, and it is always managed or claimed - so + // excluding those names left its live credentials out of this map, while the object + // holding them is not in `views` either, so neither check could see them. A newcomer + // carrying the same key then reached the write-path guard, which refuses the ROUND: + // nothing addable, rotatable or revocable on that gateway until the old object is + // deleted or its Secret fixed. Reached by ordinary sequencing - create tenant-a-v2 + // with the same key, delete the old Secret before the old APIConsumer - which is why + // it is not excluded here. + if rendered[name] || (!preserve[name] && (liveManaged[name] || claimed[name])) { continue } for _, c := range creds { @@ -1604,13 +1612,18 @@ func dropDuplicatesAgainstCarriedOver(views []sink.ConsumerView, kept = append(kept, v) continue } + held := "which this controller does not manage (the gateway chart renders it until " + + "the migration is finished)" + if preserve[clash] { + held = "whose credentials this controller cannot read at the moment, so its " + + "existing entry is being kept as it is" + } round.skipped[v.Source] = fmt.Sprintf("one of its credentials is already in use by "+ - "consumer %q, which this controller does not manage (the gateway chart renders it "+ - "until the migration is finished). key-auth refuses a duplicate credential by "+ + "consumer %q, %s. key-auth refuses a duplicate credential by "+ "failing to parse its whole config, and it denies every caller when it cannot "+ "parse - so this consumer was left out instead, and nothing else on this gateway "+ "is blocked. Either adopt %q with this APIConsumer (set consumerName to it, if it "+ - "is a valid DNS label) or remove it from the chart", clash, clash) + "is a valid DNS label) or stop sharing the key with it", clash, held, clash) } return kept } diff --git a/internal/controller/apiconsumer_controller_test.go b/internal/controller/apiconsumer_controller_test.go index afffa954..aca079f7 100644 --- a/internal/controller/apiconsumer_controller_test.go +++ b/internal/controller/apiconsumer_controller_test.go @@ -2073,3 +2073,50 @@ func TestConsumerPreservedIncumbentBeatsANewcomerInEitherListOrder(t *testing.T) }) } } + +// A newcomer sharing its key with a PRESERVED incumbent must cost only itself. +// +// Reached by ordinary sequencing, not by 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 now preserved with that key live, the new one renders the same key, and +// the duplicate-credential guard in the write path refused the whole ROUND - nothing addable, +// rotatable or revocable on that gateway until somebody deleted the old object. +// +// Neither existing check could see it: the clash map was built only from 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. +func TestConsumerSharingAKeyWithAPreservedIncumbentCostsOnlyItself(t *testing.T) { + old := consumerFixture("tenant-a", "gone-secret") + old.Status.ConsumerName = "tenant-a" + old.Status.AppliedGatewayNamespace = "higress-system" + v2 := consumerFixture("tenant-a-v2", "v2-keys") + // Another tenant, to prove the round still goes through for everybody else. + bystander := consumerFixture("tenant-b", "b-keys") + bystander.Status.ConsumerName = "tenant-b" + bystander.Status.AppliedGatewayNamespace = "higress-system" + r, c := newConsumerReconciler(t, old, v2, bystander, + credSecret("v2-keys", map[string]string{"key": "sk-shared"}), + credSecret("b-keys", map[string]string{"key": "sk-b-rotated"}), + keyAuthManagedBy("tenant-a,tenant-b", + liveConsumer("tenant-a", "Bearer sk-shared"), + liveConsumer("tenant-b", "Bearer sk-b")), + ) + round, err := r.programGateway(context.Background(), "higress-system", nil) + if err != nil { + t.Fatalf("a shared key with a preserved incumbent froze the gateway: %v", err) + } + why := round.skipped["llm-route/tenant-a-v2"] + if !strings.Contains(why, "tenant-a") { + t.Fatalf("tenant-a-v2 was not told which consumer holds the key: %q", why) + } + if strings.Contains(why, "sk-shared") { + t.Fatalf("the reason leaks the credential: %q", why) + } + // The preserved entry keeps its key, and the bystander's rotation went through. + if got := creds0Of(t, c, "higress-system", "tenant-a"); strings.Join(got, ",") != "Bearer sk-shared" { + t.Fatalf("tenant-a credentials = %v, want its live key untouched", got) + } + if got := creds0Of(t, c, "higress-system", "tenant-b"); strings.Join(got, ",") != "Bearer sk-b-rotated" { + t.Fatalf("tenant-b credentials = %v, want its rotated key: the freeze used to block this", got) + } +}