unitysvc-core 0.3.6__tar.gz → 0.3.8__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {unitysvc_core-0.3.6/src/unitysvc_core.egg-info → unitysvc_core-0.3.8}/PKG-INFO +20 -1
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/README.md +19 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/pyproject.toml +1 -1
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/src/unitysvc_core/models/__init__.py +4 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/src/unitysvc_core/models/channel.py +149 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/src/unitysvc_core/schema/offering_v1.json +143 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8/src/unitysvc_core.egg-info}/PKG-INFO +20 -1
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/src/unitysvc_core.egg-info/SOURCES.txt +1 -0
- unitysvc_core-0.3.8/tests/test_request_rules.py +220 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/tests/test_validate_service.py +39 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/LICENSE +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/setup.cfg +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/src/unitysvc_core/__init__.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/src/unitysvc_core/grants.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/src/unitysvc_core/models/base.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/src/unitysvc_core/models/documents.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/src/unitysvc_core/models/listing_data.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/src/unitysvc_core/models/listing_v1.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/src/unitysvc_core/models/offering_data.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/src/unitysvc_core/models/offering_v1.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/src/unitysvc_core/models/pricing.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/src/unitysvc_core/models/promotion_data.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/src/unitysvc_core/models/provider_data.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/src/unitysvc_core/models/provider_v1.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/src/unitysvc_core/models/service.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/src/unitysvc_core/models/service_group_data.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/src/unitysvc_core/models/validators.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/src/unitysvc_core/parameter_usage.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/src/unitysvc_core/py.typed +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/src/unitysvc_core/schema/base.json +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/src/unitysvc_core/schema/listing_v1.json +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/src/unitysvc_core/schema/promotion_v1.json +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/src/unitysvc_core/schema/provider_v1.json +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/src/unitysvc_core/schema/service_group_v1.json +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/src/unitysvc_core/utils.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/src/unitysvc_core/validator.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/src/unitysvc_core.egg-info/dependency_links.txt +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/src/unitysvc_core.egg-info/requires.txt +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/src/unitysvc_core.egg-info/top_level.txt +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/tests/test_access_interface_routing.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/tests/test_canonical_interfaces.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/tests/test_channel.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/tests/test_effective_price.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/tests/test_external_apps.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/tests/test_grants.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/tests/test_hidden_path_skip.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/tests/test_listing_audience.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/tests/test_offering_data.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/tests/test_parameter_usage.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/tests/test_pricing.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/tests/test_provider_account_rate_limits.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/tests/test_service_group.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/tests/test_service_status.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/tests/test_utils.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/tests/test_validator.py +0 -0
- {unitysvc_core-0.3.6 → unitysvc_core-0.3.8}/tests/test_validators.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: unitysvc-core
|
|
3
|
-
Version: 0.3.
|
|
3
|
+
Version: 0.3.8
|
|
4
4
|
Summary: Shared data models and validation helpers for UnitySVC packages
|
|
5
5
|
Author-email: Bo Peng <bo.peng@unitysvc.com>
|
|
6
6
|
Maintainer-email: Bo Peng <bo.peng@unitysvc.com>
|
|
@@ -266,12 +266,31 @@ A policy has three kinds of entry (unitysvc/unitysvc#2770):
|
|
|
266
266
|
| `rate_limit_refs` | the provider rate limits it consumes |
|
|
267
267
|
| `customer_access_requests` | what the enrolling customer is asked to approve (see above) |
|
|
268
268
|
| `params` | the enrollment parameters (below) |
|
|
269
|
+
| `request_rules` | `http` channels only: rules the gateway answers itself before dispatch (below) |
|
|
269
270
|
| `servers` | the connection: `HttpServer`, `SmtpServer`, `S3Server` or `McpServer` |
|
|
270
271
|
|
|
271
272
|
The common one-server case writes the connection fields directly on the channel; they are read as `servers[0]`. When a channel has both, each server inherits the direct fields it does not set. Any string may be a template (`{{ params.X }}`, `${ secrets.X }`, `${ customer_secrets.X ?? default }`), so numeric and boolean connection fields also accept strings.
|
|
272
273
|
|
|
273
274
|
Unknown keys are refused. Retired keys are refused with what to do instead (`RETIRED_CHANNEL_KEYS`): `raw`, `is_primary`, the listing-style parameter trio, `grants`, `rate_limits` (nothing reads it; use `rate_limit_refs`), `storage_type` (use `access_method: s3`), `response_rules`, `timeout_ms`, `transport`, and the platform-derived `customer_secrets_required` / `customer_secrets_optional`.
|
|
274
275
|
|
|
276
|
+
### Request rules
|
|
277
|
+
|
|
278
|
+
An `http` channel may list up to 32 `request_rules` (unitysvc/unitysvc#2947, unitysvc/apisix-gateways#94). The gateway checks them in order after authentication, channel selection and rate limiting and before anything is dispatched. The first rule whose `when` holds answers with its static `respond`, and the request goes no further; when none holds, the request continues unchanged. A rule without `when` answers every request.
|
|
279
|
+
|
|
280
|
+
```json
|
|
281
|
+
"request_rules": [
|
|
282
|
+
{"name": "github-ping", "when": "header[\"x-github-event\"] == \"ping\"", "respond": {"status": 200}},
|
|
283
|
+
{"name": "own-echo", "when": "secret_equals(\"DISCORD_WEBHOOK_ID\", body.user_id)",
|
|
284
|
+
"customer_secrets": ["DISCORD_WEBHOOK_ID"], "respond": {"status": 204}}
|
|
285
|
+
]
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
`when` is a Lua expression that the gateway compiles and evaluates against the request; its environment (the request's `body`, `header`, `query`, `method`, the enrollment's `params`, the approved helpers) and its limits are the gateway's, documented there. Core does not parse it. It checks only that it is non-empty, at most 1024 bytes, and free of template references (`${ … }`, `{{ … }}`): values reach a condition as arguments, never by substitution into its source. A condition reads a customer secret only through `secret_equals(NAME, value)`, and only a secret the rule declares in `customer_secrets` (1–8 `UPPER_SNAKE_CASE` names); a rule's secret is always optional for the customer. A Lua syntax error is reported by the gateway (the channel answers 503) and by a gateway-run test (`services run-tests`), not by `specs validate`.
|
|
289
|
+
|
|
290
|
+
`respond` takes a `status` (200–599), an optional `body` (an object or array is sent as JSON; a string needs `content_type`), and optional `headers` (not the gateway-managed or hop-by-hop ones).
|
|
291
|
+
|
|
292
|
+
0.3.7 accepted a different, two-operator condition grammar; 0.3.8 replaces it. No published service used it.
|
|
293
|
+
|
|
275
294
|
### External apps and product links
|
|
276
295
|
|
|
277
296
|
An offering that declares no channel (`upstream_access_config` omitted or `{}`) is an **external app**: customers reach it at its own site, not through the gateway (unitysvc/unitysvc#2873). `external` is not a channel type. An external app:
|
|
@@ -231,12 +231,31 @@ A policy has three kinds of entry (unitysvc/unitysvc#2770):
|
|
|
231
231
|
| `rate_limit_refs` | the provider rate limits it consumes |
|
|
232
232
|
| `customer_access_requests` | what the enrolling customer is asked to approve (see above) |
|
|
233
233
|
| `params` | the enrollment parameters (below) |
|
|
234
|
+
| `request_rules` | `http` channels only: rules the gateway answers itself before dispatch (below) |
|
|
234
235
|
| `servers` | the connection: `HttpServer`, `SmtpServer`, `S3Server` or `McpServer` |
|
|
235
236
|
|
|
236
237
|
The common one-server case writes the connection fields directly on the channel; they are read as `servers[0]`. When a channel has both, each server inherits the direct fields it does not set. Any string may be a template (`{{ params.X }}`, `${ secrets.X }`, `${ customer_secrets.X ?? default }`), so numeric and boolean connection fields also accept strings.
|
|
237
238
|
|
|
238
239
|
Unknown keys are refused. Retired keys are refused with what to do instead (`RETIRED_CHANNEL_KEYS`): `raw`, `is_primary`, the listing-style parameter trio, `grants`, `rate_limits` (nothing reads it; use `rate_limit_refs`), `storage_type` (use `access_method: s3`), `response_rules`, `timeout_ms`, `transport`, and the platform-derived `customer_secrets_required` / `customer_secrets_optional`.
|
|
239
240
|
|
|
241
|
+
### Request rules
|
|
242
|
+
|
|
243
|
+
An `http` channel may list up to 32 `request_rules` (unitysvc/unitysvc#2947, unitysvc/apisix-gateways#94). The gateway checks them in order after authentication, channel selection and rate limiting and before anything is dispatched. The first rule whose `when` holds answers with its static `respond`, and the request goes no further; when none holds, the request continues unchanged. A rule without `when` answers every request.
|
|
244
|
+
|
|
245
|
+
```json
|
|
246
|
+
"request_rules": [
|
|
247
|
+
{"name": "github-ping", "when": "header[\"x-github-event\"] == \"ping\"", "respond": {"status": 200}},
|
|
248
|
+
{"name": "own-echo", "when": "secret_equals(\"DISCORD_WEBHOOK_ID\", body.user_id)",
|
|
249
|
+
"customer_secrets": ["DISCORD_WEBHOOK_ID"], "respond": {"status": 204}}
|
|
250
|
+
]
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
`when` is a Lua expression that the gateway compiles and evaluates against the request; its environment (the request's `body`, `header`, `query`, `method`, the enrollment's `params`, the approved helpers) and its limits are the gateway's, documented there. Core does not parse it. It checks only that it is non-empty, at most 1024 bytes, and free of template references (`${ … }`, `{{ … }}`): values reach a condition as arguments, never by substitution into its source. A condition reads a customer secret only through `secret_equals(NAME, value)`, and only a secret the rule declares in `customer_secrets` (1–8 `UPPER_SNAKE_CASE` names); a rule's secret is always optional for the customer. A Lua syntax error is reported by the gateway (the channel answers 503) and by a gateway-run test (`services run-tests`), not by `specs validate`.
|
|
254
|
+
|
|
255
|
+
`respond` takes a `status` (200–599), an optional `body` (an object or array is sent as JSON; a string needs `content_type`), and optional `headers` (not the gateway-managed or hop-by-hop ones).
|
|
256
|
+
|
|
257
|
+
0.3.7 accepted a different, two-operator condition grammar; 0.3.8 replaces it. No published service used it.
|
|
258
|
+
|
|
240
259
|
### External apps and product links
|
|
241
260
|
|
|
242
261
|
An offering that declares no channel (`upstream_access_config` omitted or `{}`) is an **external app**: customers reach it at its own site, not through the gateway (unitysvc/unitysvc#2873). `external` is not a channel type. An external app:
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "unitysvc-core"
|
|
7
|
-
version = "0.3.
|
|
7
|
+
version = "0.3.8"
|
|
8
8
|
description = "Shared data models and validation helpers for UnitySVC packages"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
authors = [{ name = "Bo Peng", email = "bo.peng@unitysvc.com" }]
|
|
@@ -34,7 +34,9 @@ from .channel import (
|
|
|
34
34
|
HttpServer,
|
|
35
35
|
McpChannel,
|
|
36
36
|
McpServer,
|
|
37
|
+
RequestRule,
|
|
37
38
|
RequestTransformer,
|
|
39
|
+
RuleResponse,
|
|
38
40
|
S3Channel,
|
|
39
41
|
S3Server,
|
|
40
42
|
SmtpChannel,
|
|
@@ -131,7 +133,9 @@ __all__ = [
|
|
|
131
133
|
"SmtpServer",
|
|
132
134
|
"S3Server",
|
|
133
135
|
"McpServer",
|
|
136
|
+
"RequestRule",
|
|
134
137
|
"RequestTransformer",
|
|
138
|
+
"RuleResponse",
|
|
135
139
|
"RETIRED_CHANNEL_KEYS",
|
|
136
140
|
# Data models (for API/backend use)
|
|
137
141
|
"ProviderAccountRateLimit",
|
|
@@ -28,6 +28,8 @@ field also accepts a string.
|
|
|
28
28
|
"""
|
|
29
29
|
|
|
30
30
|
import builtins
|
|
31
|
+
import json
|
|
32
|
+
import re
|
|
31
33
|
from typing import Annotated, Any, ClassVar, Literal
|
|
32
34
|
|
|
33
35
|
from pydantic import (
|
|
@@ -83,6 +85,139 @@ class RequestTransformer(BaseModel):
|
|
|
83
85
|
set_body: str | None = Field(default=None, description="Replace the request body with this template")
|
|
84
86
|
|
|
85
87
|
|
|
88
|
+
# Response headers a request rule may not set: the gateway manages them, they
|
|
89
|
+
# are hop-by-hop, or the response's content type has its own field.
|
|
90
|
+
_REFUSED_RULE_HEADERS = frozenset(
|
|
91
|
+
{
|
|
92
|
+
"connection",
|
|
93
|
+
"content-length",
|
|
94
|
+
"content-type",
|
|
95
|
+
"date",
|
|
96
|
+
"keep-alive",
|
|
97
|
+
"server",
|
|
98
|
+
"set-cookie",
|
|
99
|
+
"te",
|
|
100
|
+
"trailer",
|
|
101
|
+
"transfer-encoding",
|
|
102
|
+
"upgrade",
|
|
103
|
+
}
|
|
104
|
+
)
|
|
105
|
+
_HEADER_NAME_RE = re.compile(r"^[!#$%&'*+.^_`|~0-9A-Za-z-]+$")
|
|
106
|
+
_CONTENT_TYPE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*([ \t]*;[ -~]*)?$")
|
|
107
|
+
_MAX_RULE_BODY_BYTES = 8192
|
|
108
|
+
MAX_RULES = 32
|
|
109
|
+
MAX_CONDITION_BYTES = 1024
|
|
110
|
+
_MAX_RULE_SECRETS = 8
|
|
111
|
+
_SECRET_NAME_RE = re.compile(r"[A-Z_][A-Z0-9_]*")
|
|
112
|
+
_MAX_RULE_HEADERS = 16
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class RuleResponse(BaseModel):
|
|
116
|
+
"""The static response a request rule answers with (unitysvc/unitysvc#2947)."""
|
|
117
|
+
|
|
118
|
+
model_config = ConfigDict(extra="forbid")
|
|
119
|
+
|
|
120
|
+
status: int = Field(ge=200, le=599, description="HTTP status, 200-599")
|
|
121
|
+
body: dict[str, Any] | list[Any] | str | None = Field(
|
|
122
|
+
default=None,
|
|
123
|
+
description="An object or array is sent as JSON; a string is sent as is, with content_type",
|
|
124
|
+
)
|
|
125
|
+
content_type: str | None = Field(default=None, description="Content type of a string body, e.g. text/plain")
|
|
126
|
+
headers: dict[str, str] | None = Field(default=None, description="Extra response headers")
|
|
127
|
+
|
|
128
|
+
@model_validator(mode="after")
|
|
129
|
+
def _check_response(self) -> "RuleResponse":
|
|
130
|
+
if self.body is not None and self.status in (204, 205, 304):
|
|
131
|
+
raise ValueError(f"a {self.status} response has no body")
|
|
132
|
+
if isinstance(self.body, str):
|
|
133
|
+
if self.content_type is None:
|
|
134
|
+
raise ValueError("a string body needs content_type")
|
|
135
|
+
size = len(self.body.encode())
|
|
136
|
+
else:
|
|
137
|
+
if self.content_type is not None:
|
|
138
|
+
raise ValueError("content_type is only for a string body; an object or array is sent as JSON")
|
|
139
|
+
size = len(json.dumps(self.body, ensure_ascii=False).encode()) if self.body is not None else 0
|
|
140
|
+
if size > _MAX_RULE_BODY_BYTES:
|
|
141
|
+
raise ValueError(f"the body is larger than {_MAX_RULE_BODY_BYTES} bytes")
|
|
142
|
+
if self.content_type is not None and not _CONTENT_TYPE_RE.fullmatch(self.content_type):
|
|
143
|
+
raise ValueError(f"content_type {self.content_type!r} is not a media type")
|
|
144
|
+
headers = self.headers or {}
|
|
145
|
+
if len(headers) > _MAX_RULE_HEADERS:
|
|
146
|
+
raise ValueError(f"at most {_MAX_RULE_HEADERS} headers")
|
|
147
|
+
for name, value in headers.items():
|
|
148
|
+
lower = name.lower()
|
|
149
|
+
if not _HEADER_NAME_RE.fullmatch(name):
|
|
150
|
+
raise ValueError(f"header name {name!r} is not valid")
|
|
151
|
+
if lower in _REFUSED_RULE_HEADERS or lower.startswith(("proxy-", "x-unitysvc-")):
|
|
152
|
+
raise ValueError(f"header {name!r} is managed by the gateway and cannot be set by a rule")
|
|
153
|
+
if "\r" in value or "\n" in value or len(value) > 1024:
|
|
154
|
+
raise ValueError(f"header {name!r} must be one line of at most 1024 characters")
|
|
155
|
+
return self
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class RequestRule(BaseModel):
|
|
159
|
+
"""A condition the gateway checks before dispatch, and the response it answers with when it holds.
|
|
160
|
+
|
|
161
|
+
``when`` is a Lua expression the gateway compiles and evaluates against the
|
|
162
|
+
request (unitysvc/apisix-gateways#94); its language, the values it can read
|
|
163
|
+
and its limits are the gateway's. Core does not parse it: it checks only
|
|
164
|
+
that it is a bounded string carrying no template syntax, since values
|
|
165
|
+
reach a condition as arguments, never by substitution into its source.
|
|
166
|
+
|
|
167
|
+
A condition reads a customer secret only through the gateway's
|
|
168
|
+
``secret_equals(NAME, value)`` helper, and only a secret it declares in
|
|
169
|
+
``customer_secrets``; the platform resolves exactly those names for the rule.
|
|
170
|
+
"""
|
|
171
|
+
|
|
172
|
+
model_config = ConfigDict(extra="forbid")
|
|
173
|
+
|
|
174
|
+
name: str | None = Field(
|
|
175
|
+
default=None,
|
|
176
|
+
pattern=r"^[a-z0-9][a-z0-9-]{0,47}$",
|
|
177
|
+
description="Shown in logs and the X-UnitySVC-Rule response header",
|
|
178
|
+
)
|
|
179
|
+
when: str | None = Field(
|
|
180
|
+
default=None,
|
|
181
|
+
description='A Lua expression evaluated by the gateway, e.g. header["x-github-event"] == "ping"; '
|
|
182
|
+
"absent means every request",
|
|
183
|
+
)
|
|
184
|
+
customer_secrets: list[str] | None = Field(
|
|
185
|
+
default=None,
|
|
186
|
+
description="Customer secrets the condition compares with secret_equals(NAME, value); "
|
|
187
|
+
"a rule's secret is always optional for the customer",
|
|
188
|
+
)
|
|
189
|
+
respond: RuleResponse
|
|
190
|
+
|
|
191
|
+
@field_validator("when")
|
|
192
|
+
@classmethod
|
|
193
|
+
def _check_condition(cls, value: str | None) -> str | None:
|
|
194
|
+
if value is None:
|
|
195
|
+
return value
|
|
196
|
+
if not value.strip():
|
|
197
|
+
raise ValueError("a condition must not be empty; omit `when` to answer every request")
|
|
198
|
+
if len(value.encode()) > MAX_CONDITION_BYTES:
|
|
199
|
+
raise ValueError(f"a condition is longer than {MAX_CONDITION_BYTES} bytes (UTF-8)")
|
|
200
|
+
if "${" in value or "{{" in value:
|
|
201
|
+
raise ValueError(
|
|
202
|
+
"a condition takes no template references: read params as params.NAME, and compare a "
|
|
203
|
+
'customer secret with secret_equals("NAME", value) after declaring it in customer_secrets'
|
|
204
|
+
)
|
|
205
|
+
return value
|
|
206
|
+
|
|
207
|
+
@field_validator("customer_secrets")
|
|
208
|
+
@classmethod
|
|
209
|
+
def _check_secret_names(cls, names: list[str] | None) -> list[str] | None:
|
|
210
|
+
if names is None:
|
|
211
|
+
return names
|
|
212
|
+
if not names or len(names) > _MAX_RULE_SECRETS:
|
|
213
|
+
raise ValueError(f"customer_secrets lists 1 to {_MAX_RULE_SECRETS} names; omit it when there are none")
|
|
214
|
+
if bad := [name for name in names if not _SECRET_NAME_RE.fullmatch(name)]:
|
|
215
|
+
raise ValueError(f"customer secret names are UPPER_SNAKE_CASE: {', '.join(bad)}")
|
|
216
|
+
if len(set(names)) != len(names):
|
|
217
|
+
raise ValueError("customer_secrets lists a name twice")
|
|
218
|
+
return names
|
|
219
|
+
|
|
220
|
+
|
|
86
221
|
class _Server(BaseModel):
|
|
87
222
|
"""Fields every server has, whatever its protocol."""
|
|
88
223
|
|
|
@@ -252,6 +387,20 @@ class HttpChannel(_ChannelBase):
|
|
|
252
387
|
server_model: ClassVar[builtins.type[_Server]] = HttpServer
|
|
253
388
|
access_method: Literal["http"] = "http"
|
|
254
389
|
servers: list[HttpServer] = Field(default_factory=list)
|
|
390
|
+
request_rules: list[RequestRule] | None = Field(
|
|
391
|
+
default=None,
|
|
392
|
+
min_length=1,
|
|
393
|
+
max_length=MAX_RULES,
|
|
394
|
+
description="Rules the gateway checks in order before dispatch; the first that holds answers the request",
|
|
395
|
+
)
|
|
396
|
+
|
|
397
|
+
@field_validator("request_rules")
|
|
398
|
+
@classmethod
|
|
399
|
+
def _unique_rule_names(cls, rules: list[RequestRule] | None) -> list[RequestRule] | None:
|
|
400
|
+
names = [rule.name for rule in rules or [] if rule.name is not None]
|
|
401
|
+
if duplicates := sorted({name for name in names if names.count(name) > 1}):
|
|
402
|
+
raise ValueError(f"rule names must be unique: {', '.join(duplicates)}")
|
|
403
|
+
return rules
|
|
255
404
|
|
|
256
405
|
|
|
257
406
|
class SmtpChannel(_ChannelBase):
|
|
@@ -1061,6 +1061,24 @@
|
|
|
1061
1061
|
"description": "Request formats the channel serves",
|
|
1062
1062
|
"title": "Request Formats"
|
|
1063
1063
|
},
|
|
1064
|
+
"request_rules": {
|
|
1065
|
+
"anyOf": [
|
|
1066
|
+
{
|
|
1067
|
+
"items": {
|
|
1068
|
+
"$ref": "#/$defs/RequestRule"
|
|
1069
|
+
},
|
|
1070
|
+
"maxItems": 32,
|
|
1071
|
+
"minItems": 1,
|
|
1072
|
+
"type": "array"
|
|
1073
|
+
},
|
|
1074
|
+
{
|
|
1075
|
+
"type": "null"
|
|
1076
|
+
}
|
|
1077
|
+
],
|
|
1078
|
+
"default": null,
|
|
1079
|
+
"description": "Rules the gateway checks in order before dispatch; the first that holds answers the request",
|
|
1080
|
+
"title": "Request Rules"
|
|
1081
|
+
},
|
|
1064
1082
|
"request_transformer": {
|
|
1065
1083
|
"anyOf": [
|
|
1066
1084
|
{
|
|
@@ -2341,6 +2359,63 @@
|
|
|
2341
2359
|
"title": "PriceTier",
|
|
2342
2360
|
"type": "object"
|
|
2343
2361
|
},
|
|
2362
|
+
"RequestRule": {
|
|
2363
|
+
"additionalProperties": false,
|
|
2364
|
+
"description": "A condition the gateway checks before dispatch, and the response it answers with when it holds.\n\n``when`` is a Lua expression the gateway compiles and evaluates against the\nrequest (unitysvc/apisix-gateways#94); its language, the values it can read\nand its limits are the gateway's. Core does not parse it: it checks only\nthat it is a bounded string carrying no template syntax, since values\nreach a condition as arguments, never by substitution into its source.\n\nA condition reads a customer secret only through the gateway's\n``secret_equals(NAME, value)`` helper, and only a secret it declares in\n``customer_secrets``; the platform resolves exactly those names for the rule.",
|
|
2365
|
+
"properties": {
|
|
2366
|
+
"customer_secrets": {
|
|
2367
|
+
"anyOf": [
|
|
2368
|
+
{
|
|
2369
|
+
"items": {
|
|
2370
|
+
"type": "string"
|
|
2371
|
+
},
|
|
2372
|
+
"type": "array"
|
|
2373
|
+
},
|
|
2374
|
+
{
|
|
2375
|
+
"type": "null"
|
|
2376
|
+
}
|
|
2377
|
+
],
|
|
2378
|
+
"default": null,
|
|
2379
|
+
"description": "Customer secrets the condition compares with secret_equals(NAME, value); a rule's secret is always optional for the customer",
|
|
2380
|
+
"title": "Customer Secrets"
|
|
2381
|
+
},
|
|
2382
|
+
"name": {
|
|
2383
|
+
"anyOf": [
|
|
2384
|
+
{
|
|
2385
|
+
"pattern": "^[a-z0-9][a-z0-9-]{0,47}$",
|
|
2386
|
+
"type": "string"
|
|
2387
|
+
},
|
|
2388
|
+
{
|
|
2389
|
+
"type": "null"
|
|
2390
|
+
}
|
|
2391
|
+
],
|
|
2392
|
+
"default": null,
|
|
2393
|
+
"description": "Shown in logs and the X-UnitySVC-Rule response header",
|
|
2394
|
+
"title": "Name"
|
|
2395
|
+
},
|
|
2396
|
+
"respond": {
|
|
2397
|
+
"$ref": "#/$defs/RuleResponse"
|
|
2398
|
+
},
|
|
2399
|
+
"when": {
|
|
2400
|
+
"anyOf": [
|
|
2401
|
+
{
|
|
2402
|
+
"type": "string"
|
|
2403
|
+
},
|
|
2404
|
+
{
|
|
2405
|
+
"type": "null"
|
|
2406
|
+
}
|
|
2407
|
+
],
|
|
2408
|
+
"default": null,
|
|
2409
|
+
"description": "A Lua expression evaluated by the gateway, e.g. header[\"x-github-event\"] == \"ping\"; absent means every request",
|
|
2410
|
+
"title": "When"
|
|
2411
|
+
}
|
|
2412
|
+
},
|
|
2413
|
+
"required": [
|
|
2414
|
+
"respond"
|
|
2415
|
+
],
|
|
2416
|
+
"title": "RequestRule",
|
|
2417
|
+
"type": "object"
|
|
2418
|
+
},
|
|
2344
2419
|
"RequestTransformer": {
|
|
2345
2420
|
"additionalProperties": false,
|
|
2346
2421
|
"description": "How the gateway rewrites a request before sending it upstream.",
|
|
@@ -2482,6 +2557,74 @@
|
|
|
2482
2557
|
"title": "RevenueSharePriceData",
|
|
2483
2558
|
"type": "object"
|
|
2484
2559
|
},
|
|
2560
|
+
"RuleResponse": {
|
|
2561
|
+
"additionalProperties": false,
|
|
2562
|
+
"description": "The static response a request rule answers with (unitysvc/unitysvc#2947).",
|
|
2563
|
+
"properties": {
|
|
2564
|
+
"body": {
|
|
2565
|
+
"anyOf": [
|
|
2566
|
+
{
|
|
2567
|
+
"additionalProperties": true,
|
|
2568
|
+
"type": "object"
|
|
2569
|
+
},
|
|
2570
|
+
{
|
|
2571
|
+
"items": {},
|
|
2572
|
+
"type": "array"
|
|
2573
|
+
},
|
|
2574
|
+
{
|
|
2575
|
+
"type": "string"
|
|
2576
|
+
},
|
|
2577
|
+
{
|
|
2578
|
+
"type": "null"
|
|
2579
|
+
}
|
|
2580
|
+
],
|
|
2581
|
+
"default": null,
|
|
2582
|
+
"description": "An object or array is sent as JSON; a string is sent as is, with content_type",
|
|
2583
|
+
"title": "Body"
|
|
2584
|
+
},
|
|
2585
|
+
"content_type": {
|
|
2586
|
+
"anyOf": [
|
|
2587
|
+
{
|
|
2588
|
+
"type": "string"
|
|
2589
|
+
},
|
|
2590
|
+
{
|
|
2591
|
+
"type": "null"
|
|
2592
|
+
}
|
|
2593
|
+
],
|
|
2594
|
+
"default": null,
|
|
2595
|
+
"description": "Content type of a string body, e.g. text/plain",
|
|
2596
|
+
"title": "Content Type"
|
|
2597
|
+
},
|
|
2598
|
+
"headers": {
|
|
2599
|
+
"anyOf": [
|
|
2600
|
+
{
|
|
2601
|
+
"additionalProperties": {
|
|
2602
|
+
"type": "string"
|
|
2603
|
+
},
|
|
2604
|
+
"type": "object"
|
|
2605
|
+
},
|
|
2606
|
+
{
|
|
2607
|
+
"type": "null"
|
|
2608
|
+
}
|
|
2609
|
+
],
|
|
2610
|
+
"default": null,
|
|
2611
|
+
"description": "Extra response headers",
|
|
2612
|
+
"title": "Headers"
|
|
2613
|
+
},
|
|
2614
|
+
"status": {
|
|
2615
|
+
"description": "HTTP status, 200-599",
|
|
2616
|
+
"maximum": 599,
|
|
2617
|
+
"minimum": 200,
|
|
2618
|
+
"title": "Status",
|
|
2619
|
+
"type": "integer"
|
|
2620
|
+
}
|
|
2621
|
+
},
|
|
2622
|
+
"required": [
|
|
2623
|
+
"status"
|
|
2624
|
+
],
|
|
2625
|
+
"title": "RuleResponse",
|
|
2626
|
+
"type": "object"
|
|
2627
|
+
},
|
|
2485
2628
|
"S3Channel": {
|
|
2486
2629
|
"additionalProperties": false,
|
|
2487
2630
|
"properties": {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: unitysvc-core
|
|
3
|
-
Version: 0.3.
|
|
3
|
+
Version: 0.3.8
|
|
4
4
|
Summary: Shared data models and validation helpers for UnitySVC packages
|
|
5
5
|
Author-email: Bo Peng <bo.peng@unitysvc.com>
|
|
6
6
|
Maintainer-email: Bo Peng <bo.peng@unitysvc.com>
|
|
@@ -266,12 +266,31 @@ A policy has three kinds of entry (unitysvc/unitysvc#2770):
|
|
|
266
266
|
| `rate_limit_refs` | the provider rate limits it consumes |
|
|
267
267
|
| `customer_access_requests` | what the enrolling customer is asked to approve (see above) |
|
|
268
268
|
| `params` | the enrollment parameters (below) |
|
|
269
|
+
| `request_rules` | `http` channels only: rules the gateway answers itself before dispatch (below) |
|
|
269
270
|
| `servers` | the connection: `HttpServer`, `SmtpServer`, `S3Server` or `McpServer` |
|
|
270
271
|
|
|
271
272
|
The common one-server case writes the connection fields directly on the channel; they are read as `servers[0]`. When a channel has both, each server inherits the direct fields it does not set. Any string may be a template (`{{ params.X }}`, `${ secrets.X }`, `${ customer_secrets.X ?? default }`), so numeric and boolean connection fields also accept strings.
|
|
272
273
|
|
|
273
274
|
Unknown keys are refused. Retired keys are refused with what to do instead (`RETIRED_CHANNEL_KEYS`): `raw`, `is_primary`, the listing-style parameter trio, `grants`, `rate_limits` (nothing reads it; use `rate_limit_refs`), `storage_type` (use `access_method: s3`), `response_rules`, `timeout_ms`, `transport`, and the platform-derived `customer_secrets_required` / `customer_secrets_optional`.
|
|
274
275
|
|
|
276
|
+
### Request rules
|
|
277
|
+
|
|
278
|
+
An `http` channel may list up to 32 `request_rules` (unitysvc/unitysvc#2947, unitysvc/apisix-gateways#94). The gateway checks them in order after authentication, channel selection and rate limiting and before anything is dispatched. The first rule whose `when` holds answers with its static `respond`, and the request goes no further; when none holds, the request continues unchanged. A rule without `when` answers every request.
|
|
279
|
+
|
|
280
|
+
```json
|
|
281
|
+
"request_rules": [
|
|
282
|
+
{"name": "github-ping", "when": "header[\"x-github-event\"] == \"ping\"", "respond": {"status": 200}},
|
|
283
|
+
{"name": "own-echo", "when": "secret_equals(\"DISCORD_WEBHOOK_ID\", body.user_id)",
|
|
284
|
+
"customer_secrets": ["DISCORD_WEBHOOK_ID"], "respond": {"status": 204}}
|
|
285
|
+
]
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
`when` is a Lua expression that the gateway compiles and evaluates against the request; its environment (the request's `body`, `header`, `query`, `method`, the enrollment's `params`, the approved helpers) and its limits are the gateway's, documented there. Core does not parse it. It checks only that it is non-empty, at most 1024 bytes, and free of template references (`${ … }`, `{{ … }}`): values reach a condition as arguments, never by substitution into its source. A condition reads a customer secret only through `secret_equals(NAME, value)`, and only a secret the rule declares in `customer_secrets` (1–8 `UPPER_SNAKE_CASE` names); a rule's secret is always optional for the customer. A Lua syntax error is reported by the gateway (the channel answers 503) and by a gateway-run test (`services run-tests`), not by `specs validate`.
|
|
289
|
+
|
|
290
|
+
`respond` takes a `status` (200–599), an optional `body` (an object or array is sent as JSON; a string needs `content_type`), and optional `headers` (not the gateway-managed or hop-by-hop ones).
|
|
291
|
+
|
|
292
|
+
0.3.7 accepted a different, two-operator condition grammar; 0.3.8 replaces it. No published service used it.
|
|
293
|
+
|
|
275
294
|
### External apps and product links
|
|
276
295
|
|
|
277
296
|
An offering that declares no channel (`upstream_access_config` omitted or `{}`) is an **external app**: customers reach it at its own site, not through the gateway (unitysvc/unitysvc#2873). `external` is not a channel type. An external app:
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
"""Request rules: the channel field and what core checks of it (unitysvc/unitysvc#2947).
|
|
2
|
+
|
|
3
|
+
Conditions are Lua expressions compiled by the gateway (apisix-gateways#94);
|
|
4
|
+
core does not parse them.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
from pydantic import ValidationError
|
|
9
|
+
|
|
10
|
+
from unitysvc_core.models import HttpChannel, RequestRule, UpstreamAccessConfig
|
|
11
|
+
from unitysvc_core.models.channel import MAX_CONDITION_BYTES, MAX_RULES
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _channel(config: dict):
|
|
15
|
+
return UpstreamAccessConfig.model_validate({"default": config}).root["default"]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _rules_channel(*rules: dict) -> HttpChannel:
|
|
19
|
+
channel = _channel({"base_url": "https://api.example.com", "request_rules": list(rules)})
|
|
20
|
+
assert isinstance(channel, HttpChannel)
|
|
21
|
+
return channel
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class TestCondition:
|
|
25
|
+
@staticmethod
|
|
26
|
+
def _rule(**fields: object) -> RequestRule:
|
|
27
|
+
return RequestRule.model_validate({"respond": {"status": 204}, **fields})
|
|
28
|
+
|
|
29
|
+
@pytest.mark.parametrize(
|
|
30
|
+
"when",
|
|
31
|
+
[
|
|
32
|
+
'header["x-github-event"] == "ping"',
|
|
33
|
+
'body.type == "ping" or string.find(body.text or "", params.MARKER, 1, true) ~= nil',
|
|
34
|
+
"not body.author or body.author.bot == true",
|
|
35
|
+
"(body.n or 0) > 3 and method == 'POST'",
|
|
36
|
+
"this is not even Lua", # the gateway reports syntax, core does not
|
|
37
|
+
],
|
|
38
|
+
)
|
|
39
|
+
def test_any_lua_text_is_accepted_unparsed(self, when: str) -> None:
|
|
40
|
+
assert self._rule(when=when).when == when
|
|
41
|
+
|
|
42
|
+
@pytest.mark.parametrize("when", ["", " ", "\n\t"])
|
|
43
|
+
def test_an_empty_condition_is_refused(self, when: str) -> None:
|
|
44
|
+
with pytest.raises(ValidationError, match="must not be empty"):
|
|
45
|
+
self._rule(when=when)
|
|
46
|
+
|
|
47
|
+
def test_length_is_measured_in_utf8_bytes(self) -> None:
|
|
48
|
+
assert self._rule(when="x" * MAX_CONDITION_BYTES).when
|
|
49
|
+
with pytest.raises(ValidationError, match="longer than"):
|
|
50
|
+
self._rule(when="测" * (MAX_CONDITION_BYTES // 3 + 1))
|
|
51
|
+
|
|
52
|
+
@pytest.mark.parametrize(
|
|
53
|
+
"when",
|
|
54
|
+
[
|
|
55
|
+
"body.id == '${ customer_secrets.HOOK ?? }'",
|
|
56
|
+
"body.id == '${ secrets.TOKEN }'",
|
|
57
|
+
"body.name == '{{ params.marker }}'",
|
|
58
|
+
],
|
|
59
|
+
)
|
|
60
|
+
def test_template_references_are_refused(self, when: str) -> None:
|
|
61
|
+
with pytest.raises(ValidationError, match="takes no template references"):
|
|
62
|
+
self._rule(when=when)
|
|
63
|
+
|
|
64
|
+
def test_declared_customer_secrets(self) -> None:
|
|
65
|
+
rule = self._rule(when='secret_equals("HOOK_ID", body.user_id)', customer_secrets=["HOOK_ID"])
|
|
66
|
+
assert rule.customer_secrets == ["HOOK_ID"]
|
|
67
|
+
|
|
68
|
+
@pytest.mark.parametrize(
|
|
69
|
+
("names", "message"),
|
|
70
|
+
[
|
|
71
|
+
([], "1 to 8 names"),
|
|
72
|
+
([f"S{i}" for i in range(9)], "1 to 8 names"),
|
|
73
|
+
(["hook_id"], "UPPER_SNAKE_CASE"),
|
|
74
|
+
(["HOOK-ID"], "UPPER_SNAKE_CASE"),
|
|
75
|
+
(["HOOK_ID\n"], "UPPER_SNAKE_CASE"),
|
|
76
|
+
(["A", "A"], "twice"),
|
|
77
|
+
],
|
|
78
|
+
)
|
|
79
|
+
def test_bad_customer_secret_lists(self, names: list[str], message: str) -> None:
|
|
80
|
+
with pytest.raises(ValidationError, match=message):
|
|
81
|
+
self._rule(when="true", customer_secrets=names)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class TestChannelField:
|
|
85
|
+
def test_rules_are_a_channel_field(self) -> None:
|
|
86
|
+
channel = _rules_channel(
|
|
87
|
+
{"name": "github-ping", "when": 'header["x-github-event"] == "ping"', "respond": {"status": 200}},
|
|
88
|
+
{"respond": {"status": 503, "body": {"error": "paused"}}},
|
|
89
|
+
)
|
|
90
|
+
assert channel.request_rules is not None
|
|
91
|
+
assert [rule.name for rule in channel.request_rules] == ["github-ping", None]
|
|
92
|
+
assert channel.request_rules[1].when is None
|
|
93
|
+
# Not lifted into the server like base_url or request_transformer.
|
|
94
|
+
assert "request_rules" not in channel.servers[0].model_dump(exclude_none=True)
|
|
95
|
+
|
|
96
|
+
def test_round_trip(self) -> None:
|
|
97
|
+
rule = {
|
|
98
|
+
"name": "echo",
|
|
99
|
+
"when": 'secret_equals("DISCORD_WEBHOOK_ID", body.user_id)',
|
|
100
|
+
"customer_secrets": ["DISCORD_WEBHOOK_ID"],
|
|
101
|
+
"respond": {"status": 204},
|
|
102
|
+
}
|
|
103
|
+
dumped = _rules_channel(rule).model_dump(exclude_none=True)
|
|
104
|
+
assert dumped["request_rules"] == [rule]
|
|
105
|
+
|
|
106
|
+
def test_bad_condition_names_its_rule(self) -> None:
|
|
107
|
+
with pytest.raises(ValidationError, match=r"request_rules\.0\.when"):
|
|
108
|
+
_rules_channel({"when": "body.a == '{{ params.a }}'", "respond": {"status": 204}})
|
|
109
|
+
|
|
110
|
+
@pytest.mark.parametrize(
|
|
111
|
+
"config",
|
|
112
|
+
[
|
|
113
|
+
{"access_method": "smtp", "host": "smtp.example.com"},
|
|
114
|
+
{"access_method": "s3", "bucket": "b"},
|
|
115
|
+
{"access_method": "mcp", "base_url": "https://mcp.example.com/mcp"},
|
|
116
|
+
],
|
|
117
|
+
)
|
|
118
|
+
def test_only_http_channels_take_rules(self, config: dict) -> None:
|
|
119
|
+
with pytest.raises(ValidationError, match="request_rules"):
|
|
120
|
+
_channel({**config, "request_rules": [{"respond": {"status": 204}}]})
|
|
121
|
+
|
|
122
|
+
def test_rule_count_limits(self) -> None:
|
|
123
|
+
with pytest.raises(ValidationError, match="at least 1"):
|
|
124
|
+
_channel({"base_url": "https://x", "request_rules": []})
|
|
125
|
+
with pytest.raises(ValidationError, match=f"at most {MAX_RULES}"):
|
|
126
|
+
_rules_channel(*[{"respond": {"status": 204}}] * (MAX_RULES + 1))
|
|
127
|
+
|
|
128
|
+
def test_rule_names_are_unique(self) -> None:
|
|
129
|
+
with pytest.raises(ValidationError, match="unique: a"):
|
|
130
|
+
_rules_channel({"name": "a", "respond": {"status": 204}}, {"name": "a", "respond": {"status": 200}})
|
|
131
|
+
|
|
132
|
+
def test_rule_name_pattern(self) -> None:
|
|
133
|
+
with pytest.raises(ValidationError, match="name"):
|
|
134
|
+
RequestRule.model_validate({"name": "Bad Name", "respond": {"status": 204}})
|
|
135
|
+
|
|
136
|
+
def test_unknown_rule_key(self) -> None:
|
|
137
|
+
with pytest.raises(ValidationError, match="if"):
|
|
138
|
+
RequestRule.model_validate({"if": "method == 'GET'", "respond": {"status": 204}})
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class TestResponse:
|
|
142
|
+
@staticmethod
|
|
143
|
+
def _respond(respond: dict) -> RequestRule:
|
|
144
|
+
return RequestRule.model_validate({"respond": respond})
|
|
145
|
+
|
|
146
|
+
def test_json_and_string_bodies(self) -> None:
|
|
147
|
+
assert self._respond({"status": 400, "body": {"error": "x"}}).respond.body == {"error": "x"}
|
|
148
|
+
rule = self._respond({"status": 200, "body": "<Response/>", "content_type": "application/xml"})
|
|
149
|
+
assert rule.respond.content_type == "application/xml"
|
|
150
|
+
|
|
151
|
+
@pytest.mark.parametrize("status", [100, 101, 199, 600])
|
|
152
|
+
def test_status_range(self, status: int) -> None:
|
|
153
|
+
with pytest.raises(ValidationError, match="status"):
|
|
154
|
+
self._respond({"status": status})
|
|
155
|
+
|
|
156
|
+
def test_status_is_required(self) -> None:
|
|
157
|
+
with pytest.raises(ValidationError, match="status"):
|
|
158
|
+
self._respond({})
|
|
159
|
+
|
|
160
|
+
@pytest.mark.parametrize("status", [204, 205, 304])
|
|
161
|
+
def test_no_body_statuses(self, status: int) -> None:
|
|
162
|
+
with pytest.raises(ValidationError, match="has no body"):
|
|
163
|
+
self._respond({"status": status, "body": {"a": 1}})
|
|
164
|
+
|
|
165
|
+
def test_string_body_needs_content_type(self) -> None:
|
|
166
|
+
with pytest.raises(ValidationError, match="needs content_type"):
|
|
167
|
+
self._respond({"status": 200, "body": "ok"})
|
|
168
|
+
|
|
169
|
+
def test_content_type_only_with_string_body(self) -> None:
|
|
170
|
+
with pytest.raises(ValidationError, match="only for a string body"):
|
|
171
|
+
self._respond({"status": 200, "body": {"a": 1}, "content_type": "application/json"})
|
|
172
|
+
|
|
173
|
+
@pytest.mark.parametrize(
|
|
174
|
+
"content_type",
|
|
175
|
+
[
|
|
176
|
+
"text/plain\r\nx-a: b",
|
|
177
|
+
"text/plain\n",
|
|
178
|
+
"text/plain\r\n; charset=utf-8",
|
|
179
|
+
"text/plain\v; charset=utf-8",
|
|
180
|
+
"text/plain\u00a0; charset=utf-8",
|
|
181
|
+
],
|
|
182
|
+
)
|
|
183
|
+
def test_bad_content_type(self, content_type: str) -> None:
|
|
184
|
+
with pytest.raises(ValidationError, match="not a media type"):
|
|
185
|
+
self._respond({"status": 200, "body": "ok", "content_type": content_type})
|
|
186
|
+
|
|
187
|
+
@pytest.mark.parametrize("content_type", ["text/plain; charset=utf-8", "text/plain\t; charset=utf-8"])
|
|
188
|
+
def test_content_type_horizontal_whitespace(self, content_type: str) -> None:
|
|
189
|
+
rule = self._respond({"status": 200, "body": "ok", "content_type": content_type})
|
|
190
|
+
assert rule.respond.content_type == content_type
|
|
191
|
+
|
|
192
|
+
@pytest.mark.parametrize("body", [1, True])
|
|
193
|
+
def test_scalar_body_is_refused(self, body: object) -> None:
|
|
194
|
+
with pytest.raises(ValidationError):
|
|
195
|
+
self._respond({"status": 200, "body": body})
|
|
196
|
+
|
|
197
|
+
def test_body_size_limit(self) -> None:
|
|
198
|
+
with pytest.raises(ValidationError, match="larger than"):
|
|
199
|
+
self._respond({"status": 400, "body": {"error": "x" * 9000}})
|
|
200
|
+
|
|
201
|
+
@pytest.mark.parametrize(
|
|
202
|
+
"name", ["Content-Length", "transfer-encoding", "Connection", "Set-Cookie", "Content-Type", "X-UnitySVC-Rule"]
|
|
203
|
+
)
|
|
204
|
+
def test_refused_headers(self, name: str) -> None:
|
|
205
|
+
with pytest.raises(ValidationError, match="managed by the gateway"):
|
|
206
|
+
self._respond({"status": 200, "headers": {name: "x"}})
|
|
207
|
+
|
|
208
|
+
def test_header_value_must_be_one_line(self) -> None:
|
|
209
|
+
with pytest.raises(ValidationError, match="one line"):
|
|
210
|
+
self._respond({"status": 200, "headers": {"X-Note": "a\r\nSet-Cookie: b"}})
|
|
211
|
+
|
|
212
|
+
@pytest.mark.parametrize("name", ["X Note", "X-Note\n", "Content-Length\n"])
|
|
213
|
+
def test_header_name_must_be_a_token(self, name: str) -> None:
|
|
214
|
+
with pytest.raises(ValidationError, match="not valid"):
|
|
215
|
+
self._respond({"status": 200, "headers": {name: "a"}})
|
|
216
|
+
|
|
217
|
+
def test_allowed_header(self) -> None:
|
|
218
|
+
assert self._respond({"status": 200, "headers": {"Cache-Control": "no-store"}}).respond.headers == {
|
|
219
|
+
"Cache-Control": "no-store"
|
|
220
|
+
}
|
|
@@ -113,3 +113,42 @@ def test_services_validate_in_parallel_with_one_validator(validator: DataValidat
|
|
|
113
113
|
results = list(pool.map(lambda job: validator.validate_service(**job[1], service_dir=job[0]), jobs))
|
|
114
114
|
|
|
115
115
|
assert results == expected
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def test_a_request_rule_condition_is_checked(validator: DataValidator) -> None:
|
|
119
|
+
"""``specs validate`` accepts a Lua condition unparsed and reports a template
|
|
120
|
+
reference with the rule it is in (unitysvc/unitysvc#2947, apisix-gateways#94)."""
|
|
121
|
+
files = _files(SERVICES[0])
|
|
122
|
+
offering = files["offering"]
|
|
123
|
+
channel = next(iter(offering["upstream_access_config"].values()))
|
|
124
|
+
channel["request_rules"] = [
|
|
125
|
+
{"when": 'header["x-github-event"] == "ping" or (body.n or 0) > 3', "respond": {"status": 200}},
|
|
126
|
+
{
|
|
127
|
+
"when": 'secret_equals("HOOK_ID", body.user_id)',
|
|
128
|
+
"customer_secrets": ["HOOK_ID"],
|
|
129
|
+
"respond": {"status": 204},
|
|
130
|
+
},
|
|
131
|
+
]
|
|
132
|
+
assert validator.validate_service(offering=offering)["offering"] == []
|
|
133
|
+
|
|
134
|
+
channel["request_rules"] = [{"when": "body.id == '${ customer_secrets.HOOK ?? }'", "respond": {"status": 204}}]
|
|
135
|
+
errors = validator.validate_service(offering=offering)["offering"]
|
|
136
|
+
assert any("request_rules" in e and "takes no template references" in e for e in errors)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
@pytest.mark.parametrize(
|
|
140
|
+
"rule",
|
|
141
|
+
[
|
|
142
|
+
{"respond": {"status": 200, "headers": {"Content-Length\n": "100"}}},
|
|
143
|
+
{"respond": {"status": 200, "body": "ok", "content_type": "text/plain\r\n; charset=utf-8"}},
|
|
144
|
+
{"when": "body.id == '{{ params.HOOK }}'", "respond": {"status": 204}},
|
|
145
|
+
{"when": " ", "respond": {"status": 204}},
|
|
146
|
+
{"when": "x", "customer_secrets": ["lower_case"], "respond": {"status": 204}},
|
|
147
|
+
],
|
|
148
|
+
)
|
|
149
|
+
def test_request_rule_boundary_errors_reach_service_validation(validator: DataValidator, rule: dict) -> None:
|
|
150
|
+
offering = _files(SERVICES[0])["offering"]
|
|
151
|
+
channel = next(iter(offering["upstream_access_config"].values()))
|
|
152
|
+
channel["request_rules"] = [rule]
|
|
153
|
+
errors = validator.validate_service(offering=offering)["offering"]
|
|
154
|
+
assert any("request_rules" in error for error in errors)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|