diff --git a/README.md b/README.md index 819b2217..d1c04e37 100644 --- a/README.md +++ b/README.md @@ -440,11 +440,134 @@ 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。 端到端验证脚本(测试集群 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`、且不走缓存读)。 + +⚠️ **撤销(从 Secret 里删掉一个 value)也是同一个 60s 口径** —— 这件事比"加 key 慢一分钟"要紧: +key 泄露要立刻失效时,光改 Secret 最长还有一分钟能继续用。**要立刻生效就动对象本身** +(改一个 annotation 即可,如 `kubectl annotate apiconsumer <名字> rotated-at=$(date +%s) --overwrite`), +下一秒就会 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 比较的是 +**整个 Authorization header 原值**,不剥前缀、不 trim,配裸 key 的话标准客户端全部 401。 +⚠️ **同一个 key 不能给两个 consumer 用** —— key-auth 遇到重复 credential 会 +`return false` 整份配置解析失败,而插件是 `FAIL_CLOSE`,后果是**整个网关所有路由全部拒绝**, +不是"其中一个不生效"。渲染层会拒掉这种配置(报错只给 consumer 名和下标,不带 key 值)。 + +**ai-stream-guard(重复检测截断)默认对每条 fleet 路由开启**,`gateway.streamGuard.disabled: true` +是显式退出。它**不走 `extraPlugins`**,理由是层级:`extraPlugins` 由建 fleet 的人逐个填, +而「默认都该有的防护」一旦要人记得写,照抄老 YAML 建的新模型就静默没有保护。默认值归 controller, +`extraPlugins` 归「这一个 fleet 要的不一样」。 +autoconfig 把插件 `defaultConfig` 的内容**复制**进每条路由的规则,所以阈值只存在于 chart 一处、 +改了最慢一个 resync(30s)传到所有路由。**不是写空规则让插件继承** —— `defaultConfigDisable: true` 时 +Higress controller 根本不下发 `defaultConfig`,空规则到达插件时全局是空的、会被拒(集群实测, +而我最初按插件自己的 `parseRuleConfig` 推断写了空规则:那个推断对插件成立、对「什么东西到达了插件」沉默)。 +关掉是**撤掉规则**,不是写另一份配置;chart 没配 detectors 时**也撤掉规则**并在 `GatewaySynced` 上说明。 +⚠️ **chart 的 `defaultConfig` 必须有非空 `detectors`**:插件拒绝 detectors 为空的配置(包括从全局继承到的空), +而**一个插件加载失败会卡住该网关上所有插件的配置推送**。 +插件对象不存在时**容忍**(只是少了防护,不像 key-auth 那样是 401),同步照常成功。 + +**与网关 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` 保证顺序。 +- **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,后果是**整个网关所有路由全部拒绝**,不是「其中一个不生效」。 + 渲染层会拒,但别指望它兜住所有写法。 +- **凭据渲染成带 `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」。 + +**两条写入安全规则**(这个改动最危险的地方,都是「宁可不写」): + +- **一个坏对象不连累别人,但绝不因此摘掉任何活 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。要真正隐藏得换插件能力,是另一件事。 + +**迁移要和网关 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..13fd5f9f --- /dev/null +++ b/api/v1alpha1/apiconsumer_types.go @@ -0,0 +1,134 @@ +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. + // + // 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 + 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 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 + // +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'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). + // +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/modelfleet_types.go b/api/v1alpha1/modelfleet_types.go index da92e355..f80cfdfa 100644 --- a/api/v1alpha1/modelfleet_types.go +++ b/api/v1alpha1/modelfleet_types.go @@ -241,6 +241,45 @@ 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, 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, 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"` +} + +// 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 d11b541d..340f1920 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 *CartSpec) DeepCopyInto(out *CartSpec) { *out = *in @@ -25,6 +126,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 @@ -62,7 +178,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() } @@ -72,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. @@ -245,7 +366,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]) } @@ -367,7 +488,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]) } @@ -512,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/cmd/main.go b/cmd/main.go index 821b62b1..665ada8b 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -4,6 +4,7 @@ package main import ( + "context" "flag" "fmt" "log" @@ -19,6 +20,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" @@ -93,11 +95,23 @@ 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 { + // 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 { + 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{ Client: mgr.GetClient(), APIReader: mgr.GetAPIReader(), @@ -109,6 +123,85 @@ 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"] { + consumers := &controller.APIConsumerReconciler{ + Client: mgr.GetClient(), + APIReader: mgr.GetAPIReader(), + Scheme: mgr.GetScheme(), + } + 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. + // + // 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. + // 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 " + + "(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 { + 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)") + } // controller-runtime 自带的 ping 检查:进程存活即通过。 // 注意它【不能】发现 reconcile 卡死 —— 要那个得看 metrics 的 workqueue_depth。 if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil { @@ -118,30 +211,62 @@ 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 nil, fmt.Errorf("discover %s: %w", routingv1.GroupVersion, err) + } + for _, r := range list.APIResources { + out[r.Kind] = true + } + 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", routingv1.GroupVersion, err) + return false, fmt.Errorf("discover %s: %w", groupVersion, err) } for _, r := range list.APIResources { - if r.Kind == "ModelFleet" { + 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..01817a30 --- /dev/null +++ b/cmd/main_test.go @@ -0,0 +1,109 @@ +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" +) + +// 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") + } +} + +// 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 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/config/crd/bases/routing.modelsphere.dev_apiconsumers.yaml b/config/crd/bases/routing.modelsphere.dev_apiconsumers.yaml new file mode 100644 index 00000000..d5512fb4 --- /dev/null +++ b/config/crd/bases/routing.modelsphere.dev_apiconsumers.yaml @@ -0,0 +1,231 @@ +--- +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. + + 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: |- + 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 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 + 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'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: + 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/crd/bases/routing.modelsphere.dev_modelfleets.yaml b/config/crd/bases/routing.modelsphere.dev_modelfleets.yaml index d7cbef44..a1d19b53 100644 --- a/config/crd/bases/routing.modelsphere.dev_modelfleets.yaml +++ b/config/crd/bases/routing.modelsphere.dev_modelfleets.yaml @@ -186,6 +186,44 @@ 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, 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, 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: |- + 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/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..d5512fb4 --- /dev/null +++ b/deploy/helm/autoconfig/crds/routing.modelsphere.dev_apiconsumers.yaml @@ -0,0 +1,231 @@ +--- +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. + + 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: |- + 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 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 + 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'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: + 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/crds/routing.modelsphere.dev_modelfleets.yaml b/deploy/helm/autoconfig/crds/routing.modelsphere.dev_modelfleets.yaml index d7cbef44..a1d19b53 100644 --- a/deploy/helm/autoconfig/crds/routing.modelsphere.dev_modelfleets.yaml +++ b/deploy/helm/autoconfig/crds/routing.modelsphere.dev_modelfleets.yaml @@ -186,6 +186,44 @@ 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, 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, 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: |- + 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/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..f8a0dd21 --- /dev/null +++ b/internal/controller/apiconsumer_controller.go @@ -0,0 +1,1629 @@ +// 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" + "encoding/json" + "errors" + "fmt" + "sort" + "strconv" + "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/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" +) + +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, 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 + // 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. + // 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 + // 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 + } + } + 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 { + // 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 + } + } + + round, err := r.programGateway(ctx, gwNS, nil) + // 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) + 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, gwNS) + return ctrl.Result{RequeueAfter: consumerResyncTime}, nil +} + +// 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 +// 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 +// 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 gatewayRound{}, 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 + // 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 { + c := &list.Items[i] + if c.Status.AppliedGatewayNamespace == gwNS { + ownedBefore = true + if c.Status.ConsumerName != "" { + claimed[c.Status.ConsumerName] = true + } + } + } + + // 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) { + // 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) + 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{}} + // 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{} + 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 + // 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 { + // 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 !liveManaged[name] { + 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 { + continue + } + if consumerName(o) != name || !o.DeletionTimestamp.IsZero() { + continue + } + 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 + } + // 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 + } + 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 { + // 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. + // 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. 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 " + + "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 + // 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 !incumbent(c) { + 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 "+ + "current consumer list)", c.Namespace, c.Name, err) + } + views = append(views, sink.ConsumerView{ + Name: consumerName(c), + Credentials: creds, + Source: c.Namespace + "/" + c.Name, + }) + } + + // 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. + // 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 + } + + // 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) + views = dropDuplicatesAgainstCarriedOver(views, liveEntries, liveManaged, claimed, preserve, round) + + 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 round, err + } + return round, r.writeConsumers(ctx, gwNS, consumers, ownedBefore, claimed, preserve) +} + +// 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( + 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 - 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) + } + } + + 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) + } + 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 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 +// every other key in that config alone. +func (r *APIConsumerReconciler) writeConsumers(ctx context.Context, gwNS string, + 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{} + obj.SetGroupVersionKind(wasmPluginGVK) + 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 + // 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, found, err := unstructured.NestedSlice(obj.Object, "spec", "defaultConfig", "consumers") + 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 + // 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 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) + } + // Re-read: the apply bumped resourceVersion, and the Update below would be + // refused on the stale one. + 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) + } + } + + // 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. + // 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 "+ + "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)) + 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. + 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 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 + } + if mine[name] { + // 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) + 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. + // + // 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. + // `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. + // 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 { + return err + } + // 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. + // 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 + // 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)) + }) +} + +// 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)) + 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 { + 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)) +} + +// 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, appliedGateway 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 + 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 + // carries the old list. + st.ObservedGeneration = c.Generation + if appliedGateway != "" { + st.AppliedGatewayNamespace = appliedGateway + } + 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 + 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) +} + +// 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, + preserve map[string]bool) { + names := make([]string, 0, len(consumers)+len(preserve)) + seen := map[string]bool{} + for _, c := range consumers { + 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() + 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 + }) +} + +// 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. +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)) +} + +// 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 +} + +// 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.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") + 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 +} + +// 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 " + +// 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.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) + } + 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 +} + +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) +} + +// 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 +} + +// 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 + } + // 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", + "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) + } + } +} + +// 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 { + 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 { + 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 + } + } + 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 { + // 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 + // revocation finish on a gateway whose last APIConsumer has just been deleted. + if o.GetAnnotations()[managedConsumersAnnotation] != "" { + return true + } + if named[o.GetNamespace()] { + return true + } + return o.GetNamespace() == defaultGatewayNamespace +} + +// 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, preserve 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 { + // 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 { + 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 + } + 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, %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 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 new file mode 100644 index 00000000..aca079f7 --- /dev/null +++ b/internal/controller/apiconsumer_controller_test.go @@ -0,0 +1,2122 @@ +package controller + +import ( + "context" + "encoding/json" + "fmt" + "k8s.io/apimachinery/pkg/runtime" + "sort" + "strings" + "testing" + "time" + + 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 +} + +// ...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 { + cs = append(cs, c) + } + return map[string]any{ + "name": name, "credentials": cs, "keys": []any{"Authorization"}, + "in_header": true, "in_query": false, + } +} + +// 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, applies +} + +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) + } + // 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] != "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") + 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] != "Bearer sk-new" || creds[1] != "Bearer sk-old" { + t.Fatalf("credentials = %v, want both keys with the Bearer prefix, sorted", creds) + } +} + +// 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"), + 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")), + ) + 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.Fatalf("the healthy consumer was blocked by somebody else's Secret: %s", + consumerCondMessage(healthy.Status.Conditions, condProgrammed)) + } + // ...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) + } +} + +// 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"}), + 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) + } + 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(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) + } +} + +// 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) + // 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 +} + +// 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 + } + } + 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) + } +} + +// 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", "Bearer sk-a"), liveConsumer("tenant-b", "Bearer sk-b")), + ) + if err := reconcileConsumer(t, r, "tenant-b"); err != nil { + t.Fatal(err) + } + // 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) + } + // ...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) + } + // ...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) + } +} + +// 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) + } +} + +// 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") + } +} + +// 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) + } +} + +// 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) + } +} + +// 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 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"), other, + credSecret("tenant-a-keys", map[string]string{"key": "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")), + ) + round, err := r.programGateway(context.Background(), "higress-system", nil) + if err != nil { + t.Fatalf("one object's duplicate key froze the gateway: %v", 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(why, "sk-shared") { + t.Fatalf("the reason leaks the credential: %q", why) + } + // The duplicate was NOT written... + names := consumerNames(gatewayConsumers(t, c, "higress-system")) + 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) + } +} + +// 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) + } +} + +// 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")), + ) + // 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(msg0, want) { + t.Fatalf("the message does not explain the refusal (%s missing): %q", want, msg0) + } + } + 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") + 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. + 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) + } + + // 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.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) + } +} + +// 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) + } +} + +// 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) + } +} + +// 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 +} + +// 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) + } +} + +// 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 +} + +// 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 +} + +// 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") + } +} + +// 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") + } +} + +// 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) + } + } +} + +// 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) + } +} + +// 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) + } +} + +// 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) + } +} + +// 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) + } + }) + } +} + +// 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) + } +} diff --git a/internal/controller/modelfleet_controller.go b/internal/controller/modelfleet_controller.go index d03a0bfb..e98ad1a8 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 } @@ -850,6 +883,52 @@ 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 }, + // 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. + 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 + } + // 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 + }, }} } @@ -870,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. @@ -909,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)) } } @@ -1004,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, "; ")) } @@ -1032,12 +1124,55 @@ 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) 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. + // 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. + if cfg != nil && p.unusable != nil { + 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 + // 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 { + // 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 + } + } rules, _, err := unstructured.NestedSlice(obj.Object, "spec", "matchRules") if err != nil { return fmt.Errorf("read matchRules: %w", err) @@ -1078,15 +1213,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 @@ -1482,3 +1631,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 83cafd66..817f88c1 100644 --- a/internal/controller/modelfleet_controller_test.go +++ b/internal/controller/modelfleet_controller_test.go @@ -2613,3 +2613,192 @@ func TestFleetCapacityUsesTheSharedPeerRule(t *testing.T) { t.Fatalf("capacity = %d, want 100 (the cart cap follows the backends)", got) } } + +// 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 +// 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"), streamGuardPlugin(), + ) + 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 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) + 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") + } + + // ...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") + } +} + +// 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) + } +} + +// 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) + } +} diff --git a/internal/sink/consumer.go b/internal/sink/consumer.go new file mode 100644 index 00000000..afcfb6b9 --- /dev/null +++ b/internal/sink/consumer.go @@ -0,0 +1,117 @@ +package sink + +import ( + "fmt" + "sort" + "strings" +) + +// 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" + // 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. +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{} + // 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) + } + 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 := 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, + 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..b146e5d6 --- /dev/null +++ b/internal/sink/consumer_test.go @@ -0,0 +1,140 @@ +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) + // 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) + } +} + +// 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] != "Bearer sk-1" || got[0].Credentials[1] != "Bearer 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) + } +} + +// 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") + } +} diff --git a/internal/sink/fleet.go b/internal/sink/fleet.go index f9fecc92..51f6ee07 100644 --- a/internal/sink/fleet.go +++ b/internal/sink/fleet.go @@ -334,3 +334,19 @@ func RenderAIStatistics() *AIStatistics { ApplyToLog: true, }}} } + +// 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 +// 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{} }