Skip to content

Commit d87cd98

Browse files
authored
feature(kubernetes-controller): support namespace selector route attachment. (#8406)
1 parent 7536955 commit d87cd98

15 files changed

Lines changed: 1652 additions & 67 deletions

File tree

‎docs/kubernetes-gateway-api-support-matrix.md‎

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -88,8 +88,11 @@ Consequences that the rest of this document depends on:
8888
therefore only as strong as the hostname/path conditions themselves.
8989
- **Multiple replicas need no leader election**, but readiness must be gated on the
9090
`k8sCacheReadiness` health indicator, otherwise a cold pod serves traffic with empty config.
91-
- Informers resync every 60s; ReferenceGrant changes additionally re-queue the affected routes
92-
immediately.
91+
- Informers resync every 60s; ReferenceGrant changes and Namespace create, label update or delete
92+
events additionally re-queue affected routes. Namespace events include previously rejected routes.
93+
- Gateway API mode requires cluster-scoped `get`, `list` and `watch` access to core `namespaces`,
94+
in addition to Services/Endpoints and Gateway API resources. Namespace informer sync participates
95+
in `k8sCacheReadiness`; its lifecycle is owned by the HTTPRoute informer factory.
9396

9497
## 3. Resource support
9598

@@ -111,7 +114,7 @@ Consequences that the rest of this document depends on:
111114
| `spec.listeners[].protocol` | `HTTP` only. Everything else → listener `Accepted=False`, `UnsupportedProtocol`. |
112115
| `spec.listeners[].port` | Must equal the data-plane port. Otherwise → listener `Accepted=False`, `PortUnavailable`. |
113116
| `spec.listeners[].hostname` | Honoured; intersected with `HTTPRoute.spec.hostnames`. Exact names and `*.` suffix wildcards, which match one or more leading labels (`*.example.com` matches `a.example.com` and `a.b.example.com`). |
114-
| `spec.listeners[].allowedRoutes.namespaces.from` | `Same` (default) and `All`. `Selector` → route `Accepted=False`, `UnsupportedValue`. |
117+
| `spec.listeners[].allowedRoutes.namespaces.from` | `Same` (default), `All` and `Selector`. Selector evaluates the **route Namespace's labels**, with conjunctive `matchLabels` and `matchExpressions` (`In`, `NotIn`, `Exists`, `DoesNotExist`). An empty selector matches any present Namespace; a missing Namespace or malformed/missing selector denies attachment with `Accepted=False`, `NotAllowedByListeners`. |
115118
| `spec.listeners[].allowedRoutes.kinds` | Honoured; absent means "all protocol-matching kinds", i.e. HTTPRoute. |
116119
| `spec.listeners[].tls` | Not supported (no TLS listener). Ignored for HTTP listeners. |
117120
| `spec.addresses` | **Ignored** — the controller does not bind the requested address (see §5.2). |
@@ -212,7 +215,8 @@ Unsupported input falls into three classes. The classification is deliberate and
212215
| --- | --- |
213216
| Route-level `filters` | Route config removed entirely, `Accepted=False` / `UnsupportedValue`. |
214217
| Non-Service `backendRef`, missing Service/Endpoints, denied cross-namespace reference | Only that backend is dropped; its declared weight becomes a fail-target (`127.0.0.1:1`, connection refused) so the invalid share fails instead of silently re-flowing onto healthy backends. `ResolvedRefs=False` with `InvalidKind` / `BackendNotFound` / `RefNotPermitted`. |
215-
| Listener with unsupported protocol or port, `allowedRoutes.from=Selector`, unmatched `sectionName`/port | Route not attached, `Accepted=False` with `UnsupportedProtocol` / `PortUnavailable` / `UnsupportedValue`. |
218+
| Namespace selector mismatch, missing Namespace or malformed selector; disallowed route kind | Route not attached to that listener, `Accepted=False` with `NotAllowedByListeners` if no other listener accepts. |
219+
| Listener with unsupported protocol or port, unmatched `sectionName`/port | Route not attached, `Accepted=False` with `UnsupportedProtocol` / `PortUnavailable` / `UnsupportedValue`. |
216220

217221
In all three cases the request either fails or reaches nothing: routing is never broadened, and
218222
never silently redirected to a backend the author did not ask for.
@@ -343,10 +347,11 @@ The v1.5.1 API reference is explicit:
343347
- `NoMatchingParent` — "a Route ParentRef specifies a Port and/or SectionName that does not match
344348
any Listeners in the Gateway".
345349

346-
ShenYu reports `RefNotPermitted` for the first case and `UnsupportedValue` for the second
347-
(`HTTPRouteReconciler#evaluateListeners`), and the suite asserts these reason strings exactly in
348-
four core tests. `RefNotPermitted` is reserved for `ResolvedRefs`, where ShenYu already uses it
349-
correctly. This is the cheapest conformance fix in the list.
350+
ShenYu reports `NotAllowedByListeners` for `allowedRoutes` policy denials, including Namespace
351+
selectors and route kinds. Unmatched parent sections/ports still report `UnsupportedValue`
352+
(`HTTPRouteReconciler#evaluateListeners`) instead of `NoMatchingParent`; the remaining listener
353+
status alignment is tracked separately in #8163 / PR #8239. `RefNotPermitted` remains reserved
354+
for denied backend references in `ResolvedRefs`. No official conformance result is claimed.
350355

351356
### 7.5 Backends are resolved only from `Endpoints` *(blocks conformance)*
352357

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
<!--
2+
Licensed to the Apache Software Foundation (ASF) under one or more
3+
contributor license agreements. See the NOTICE file distributed with
4+
this work for additional information regarding copyright ownership.
5+
The ASF licenses this file to You under the Apache License, Version 2.0
6+
(the "License"); you may not use this file except in compliance with
7+
the License. You may obtain a copy of the License at
8+
9+
http://www.apache.org/licenses/LICENSE-2.0
10+
11+
Unless required by applicable law or agreed to in writing, software
12+
distributed under the License is distributed on an "AS IS" BASIS,
13+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
See the License for the specific language governing permissions and
15+
limitations under the License.
16+
-->
17+
18+
# Gateway API Namespace selectors
19+
20+
Source: [SPEC-8403001](https://github.com/apache/shenyu/issues/8403#issuecomment-6760387073)
21+
22+
## Requirement: Namespace selector route attachment
23+
24+
The Gateway API controller MUST authorize from=Selector against the route Namespace's current labels with Kubernetes matchLabels and matchExpressions semantics (In, NotIn, Exists, DoesNotExist), combining requirements with AND. An empty selector MUST match a present Namespace; missing Namespace or malformed/missing selector MUST fail closed. Namespace add, label change and delete MUST trigger affected routes to grant, revoke or restore runtime config and listener bindings without editing routes or waiting for resync. Parent policy denials MUST report Accepted=False/NotAllowedByListeners, and affected Gateway listener attachedRoutes MUST be refreshed after binding cache updates. Same/All, other listener gates, independently accepted parents, backend ReferenceGrant authorization and legacy Ingress MUST retain existing semantics.
25+
26+
### Scenario: matching namespace
27+
28+
- **WHEN** a route Namespace satisfies all selector requirements and other listener gates
29+
- **THEN** the route attaches and is programmed, including match-all empty selectors
30+
31+
### Scenario: revocation and recovery
32+
33+
- **WHEN** Namespace labels change, Namespace is deleted, or missing Namespace is created
34+
- **THEN** affected routes reconcile against current cache, remove or restore config and bindings, report parent status and queue Gateway counts after cache mutation
35+
36+
### Scenario: fail closed
37+
38+
- **WHEN** Namespace data is missing or selector syntax, operators, keys, values or cardinalities are invalid
39+
- **THEN** that listener cannot authorize attachment or broaden access
40+
41+
### Scenario: independent acceptance
42+
43+
- **WHEN** one listener or parent rejects but another accepts
44+
- **THEN** remaining authorized config and bindings survive with appropriate per-parent status
45+
46+
### Scenario: preserved behavior
47+
48+
- **WHEN** Same, All, backend ReferenceGrant or legacy Ingress behavior is exercised
49+
- **THEN** existing semantics remain and Namespace data is not required for Same or All

‎shenyu-integrated-test/shenyu-integrated-test-k8s-gateway-api-http/deploy/deploy-shenyu.yaml‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ rules:
101101
resources:
102102
- services
103103
- endpoints
104+
- namespaces
104105
verbs:
105106
- get
106107
- list
@@ -131,7 +132,7 @@ rules:
131132
verbs:
132133
- get
133134
- patch
134-
# Required for cross-namespace parentRef validation via ReferenceGrant
135+
# Required for cross-namespace backendRef validation via ReferenceGrant
135136
- apiGroups:
136137
- gateway.networking.k8s.io
137138
resources:

‎shenyu-kubernetes-controller/src/main/java/org/apache/shenyu/k8s/common/GatewayApiConstants.java‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,12 @@ public final class GatewayApiConstants {
4242
/** ResolvedRefs=False reason: a backendRef's Service has no ready endpoints. */
4343
public static final String REASON_BACKEND_NOT_FOUND = "BackendNotFound";
4444

45-
/** ResolvedRefs=False / Accepted=False reason: a cross-namespace reference (parentRef or backendRef) is not permitted by a ReferenceGrant or listener policy. */
45+
/** ResolvedRefs=False reason: a cross-namespace backendRef is not permitted by a ReferenceGrant. */
4646
public static final String REASON_REF_NOT_PERMITTED = "RefNotPermitted";
4747

48+
/** Accepted=False reason: listener allowedRoutes policy denies attachment. */
49+
public static final String REASON_NOT_ALLOWED_BY_LISTENERS = "NotAllowedByListeners";
50+
4851
/** ResolvedRefs=False reason: a backendRef's kind is not Service, the only supported kind. */
4952
public static final String REASON_INVALID_KIND = "InvalidKind";
5053

‎shenyu-kubernetes-controller/src/main/java/org/apache/shenyu/k8s/common/ListenerSupport.java‎

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
import java.util.ArrayList;
2525
import java.util.LinkedHashSet;
2626
import java.util.List;
27+
import java.util.Map;
2728
import java.util.Objects;
2829
import java.util.Set;
2930

@@ -130,29 +131,38 @@ public static boolean isSupportedProtocol(final JsonObject listener) {
130131
}
131132

132133
/**
133-
* Spec default is Same, from=All allows all; from=Selector is unimplemented and denies (widening would break isolation).
134+
* Evaluate Same/All without Namespace data; Selector fails closed without labels.
134135
*
135136
* @param listener the listener object
136137
* @param routeNamespace namespace of the attaching HTTPRoute
137138
* @param gatewayNamespace namespace of the Gateway
138139
* @return true if the namespace policy permits the attachment
139140
*/
140141
public static boolean allowsNamespace(final JsonObject listener, final String routeNamespace, final String gatewayNamespace) {
141-
String from = fromOf(listener);
142-
if (Objects.isNull(from) || "Same".equals(from)) {
143-
return Objects.equals(routeNamespace, gatewayNamespace);
144-
}
145-
return "All".equals(from);
142+
return allowsNamespace(listener, routeNamespace, gatewayNamespace, null);
146143
}
147144

148145
/**
149-
* from=Selector is unsupported; distinguishable so status reports UnsupportedValue, not a permission denial.
146+
* Evaluate namespace attachment using labels from the route Namespace, never route labels.
150147
*
151-
* @param listener the listener json object
152-
* @return true when allowedRoutes.from is the unsupported Selector value
148+
* @param listener the listener object
149+
* @param routeNamespace namespace of the HTTPRoute
150+
* @param gatewayNamespace namespace of the Gateway
151+
* @param namespaceLabels current Namespace labels; null means Namespace unavailable
152+
* @return whether the namespace policy permits attachment
153153
*/
154-
public static boolean usesUnsupportedFrom(final JsonObject listener) {
155-
return "Selector".equals(fromOf(listener));
154+
public static boolean allowsNamespace(final JsonObject listener, final String routeNamespace,
155+
final String gatewayNamespace, final Map<String, String> namespaceLabels) {
156+
String from = fromOf(listener);
157+
if (Objects.isNull(from) || "Same".equals(from)) {
158+
return Objects.equals(routeNamespace, gatewayNamespace);
159+
}
160+
if ("All".equals(from)) {
161+
return true;
162+
}
163+
JsonObject namespaces = JsonFields.getJsonObject(JsonFields.getJsonObject(listener, "allowedRoutes"), "namespaces");
164+
return "Selector".equals(from)
165+
&& NamespaceSelector.matches(JsonFields.getJsonObject(namespaces, "selector"), namespaceLabels);
156166
}
157167

158168
private static String fromOf(final JsonObject listener) {
Lines changed: 187 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,187 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to You under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
package org.apache.shenyu.k8s.common;
19+
20+
import com.google.gson.JsonArray;
21+
import com.google.gson.JsonElement;
22+
import com.google.gson.JsonObject;
23+
24+
import java.util.Map;
25+
import java.util.Objects;
26+
import java.util.Set;
27+
import java.util.regex.Pattern;
28+
29+
/**
30+
* Strict, read-only Kubernetes label selector matching for Namespace labels.
31+
*/
32+
public final class NamespaceSelector {
33+
34+
private static final Set<String> SELECTOR_FIELDS = Set.of("matchLabels", "matchExpressions");
35+
36+
private static final Set<String> EXPRESSION_FIELDS = Set.of("key", "operator", "values");
37+
38+
private static final Pattern LABEL_NAME = Pattern.compile("[A-Za-z0-9]([A-Za-z0-9_.-]*[A-Za-z0-9])?");
39+
40+
private static final Pattern DNS_PREFIX = Pattern.compile("[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*");
41+
42+
private NamespaceSelector() {
43+
}
44+
45+
/**
46+
* Match all requirements after validating the entire selector.
47+
* Omitted optional fields and empty collections impose no requirements, so an empty
48+
* selector matches any present Namespace, including one with no labels. Explicit JSON
49+
* nulls, unknown fields and malformed requirements fail closed without JSON coercion.
50+
* In and NotIn require nonempty values; Exists and DoesNotExist allow omitted or empty
51+
* values. NotIn also matches an absent key, as required by Kubernetes.
52+
*
53+
* @param selector raw label selector, null when missing
54+
* @param labels Namespace labels; use an empty map for a present, unlabeled Namespace and null for a missing Namespace
55+
* @return true only when the selector is valid, the Namespace is present and all requirements match
56+
*/
57+
public static boolean matches(final JsonObject selector, final Map<String, String> labels) {
58+
if (Objects.isNull(selector) || Objects.isNull(labels) || !isValidSelector(selector)) {
59+
return false;
60+
}
61+
if (selector.has("matchLabels")) {
62+
for (Map.Entry<String, JsonElement> entry : selector.getAsJsonObject("matchLabels").entrySet()) {
63+
if (!entry.getValue().getAsString().equals(labels.get(entry.getKey()))) {
64+
return false;
65+
}
66+
}
67+
}
68+
if (selector.has("matchExpressions")) {
69+
for (JsonElement expression : selector.getAsJsonArray("matchExpressions")) {
70+
if (!matchesExpression(expression.getAsJsonObject(), labels)) {
71+
return false;
72+
}
73+
}
74+
}
75+
return true;
76+
}
77+
78+
private static boolean isValidSelector(final JsonObject selector) {
79+
if (!SELECTOR_FIELDS.containsAll(selector.keySet())) {
80+
return false;
81+
}
82+
if (selector.has("matchLabels")) {
83+
JsonElement matchLabels = selector.get("matchLabels");
84+
if (!matchLabels.isJsonObject()) {
85+
return false;
86+
}
87+
for (Map.Entry<String, JsonElement> entry : matchLabels.getAsJsonObject().entrySet()) {
88+
if (!isValidKey(entry.getKey()) || !isValidValue(entry.getValue())) {
89+
return false;
90+
}
91+
}
92+
}
93+
if (selector.has("matchExpressions")) {
94+
JsonElement expressions = selector.get("matchExpressions");
95+
if (!expressions.isJsonArray()) {
96+
return false;
97+
}
98+
for (JsonElement expression : expressions.getAsJsonArray()) {
99+
if (!expression.isJsonObject() || !isValidExpression(expression.getAsJsonObject())) {
100+
return false;
101+
}
102+
}
103+
}
104+
return true;
105+
}
106+
107+
private static boolean isValidExpression(final JsonObject expression) {
108+
if (!EXPRESSION_FIELDS.containsAll(expression.keySet())
109+
|| !isString(expression.get("key")) || !isValidKey(expression.get("key").getAsString())
110+
|| !isString(expression.get("operator"))) {
111+
return false;
112+
}
113+
JsonElement values = expression.get("values");
114+
if (expression.has("values") && !values.isJsonArray()) {
115+
return false;
116+
}
117+
if (Objects.nonNull(values)) {
118+
for (JsonElement value : values.getAsJsonArray()) {
119+
if (!isValidValue(value)) {
120+
return false;
121+
}
122+
}
123+
}
124+
String operator = expression.get("operator").getAsString();
125+
switch (operator) {
126+
case "In":
127+
case "NotIn":
128+
return Objects.nonNull(values) && !values.getAsJsonArray().isEmpty();
129+
case "Exists":
130+
case "DoesNotExist":
131+
return Objects.isNull(values) || values.getAsJsonArray().isEmpty();
132+
default:
133+
return false;
134+
}
135+
}
136+
137+
private static boolean matchesExpression(final JsonObject expression, final Map<String, String> labels) {
138+
String key = expression.get("key").getAsString();
139+
String operator = expression.get("operator").getAsString();
140+
switch (operator) {
141+
case "In":
142+
return labels.containsKey(key) && containsValue(expression.getAsJsonArray("values"), labels.get(key));
143+
case "NotIn":
144+
return !labels.containsKey(key) || !containsValue(expression.getAsJsonArray("values"), labels.get(key));
145+
case "Exists":
146+
return labels.containsKey(key);
147+
case "DoesNotExist":
148+
return !labels.containsKey(key);
149+
default:
150+
return false;
151+
}
152+
}
153+
154+
private static boolean containsValue(final JsonArray values, final String label) {
155+
for (JsonElement value : values) {
156+
if (value.getAsString().equals(label)) {
157+
return true;
158+
}
159+
}
160+
return false;
161+
}
162+
163+
private static boolean isString(final JsonElement value) {
164+
return Objects.nonNull(value) && value.isJsonPrimitive() && value.getAsJsonPrimitive().isString();
165+
}
166+
167+
private static boolean isValidValue(final JsonElement value) {
168+
if (!isString(value)) {
169+
return false;
170+
}
171+
String text = value.getAsString();
172+
return text.length() <= 63 && (text.isEmpty() || LABEL_NAME.matcher(text).matches());
173+
}
174+
175+
private static boolean isValidKey(final String key) {
176+
int slash = key.indexOf('/');
177+
String name = slash < 0 ? key : key.substring(slash + 1);
178+
if (name.isEmpty() || name.length() > 63 || !LABEL_NAME.matcher(name).matches()) {
179+
return false;
180+
}
181+
if (slash < 0) {
182+
return true;
183+
}
184+
String prefix = key.substring(0, slash);
185+
return !prefix.isEmpty() && prefix.length() <= 253 && DNS_PREFIX.matcher(prefix).matches();
186+
}
187+
}

0 commit comments

Comments
 (0)