unitysvc-core 0.3.1__tar.gz → 0.3.3__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.1/src/unitysvc_core.egg-info → unitysvc_core-0.3.3}/PKG-INFO +14 -10
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/README.md +13 -9
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/pyproject.toml +1 -1
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/src/unitysvc_core/grants.py +170 -57
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/src/unitysvc_core/parameter_usage.py +21 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3/src/unitysvc_core.egg-info}/PKG-INFO +14 -10
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/tests/test_grants.py +236 -17
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/tests/test_parameter_usage.py +84 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/tests/test_validator.py +1 -1
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/LICENSE +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/setup.cfg +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/src/unitysvc_core/__init__.py +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/src/unitysvc_core/models/__init__.py +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/src/unitysvc_core/models/base.py +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/src/unitysvc_core/models/channel.py +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/src/unitysvc_core/models/documents.py +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/src/unitysvc_core/models/listing_data.py +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/src/unitysvc_core/models/listing_v1.py +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/src/unitysvc_core/models/offering_data.py +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/src/unitysvc_core/models/offering_v1.py +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/src/unitysvc_core/models/pricing.py +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/src/unitysvc_core/models/promotion_data.py +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/src/unitysvc_core/models/provider_data.py +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/src/unitysvc_core/models/provider_v1.py +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/src/unitysvc_core/models/service.py +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/src/unitysvc_core/models/service_group_data.py +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/src/unitysvc_core/models/validators.py +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/src/unitysvc_core/py.typed +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/src/unitysvc_core/schema/base.json +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/src/unitysvc_core/schema/listing_v1.json +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/src/unitysvc_core/schema/offering_v1.json +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/src/unitysvc_core/schema/promotion_v1.json +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/src/unitysvc_core/schema/provider_v1.json +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/src/unitysvc_core/schema/service_group_v1.json +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/src/unitysvc_core/utils.py +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/src/unitysvc_core/validator.py +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/src/unitysvc_core.egg-info/SOURCES.txt +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/src/unitysvc_core.egg-info/dependency_links.txt +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/src/unitysvc_core.egg-info/requires.txt +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/src/unitysvc_core.egg-info/top_level.txt +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/tests/test_access_interface_routing.py +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/tests/test_canonical_interfaces.py +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/tests/test_channel.py +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/tests/test_effective_price.py +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/tests/test_hidden_path_skip.py +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/tests/test_listing_audience.py +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/tests/test_offering_data.py +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/tests/test_pricing.py +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/tests/test_provider_account_rate_limits.py +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/tests/test_service_group.py +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/tests/test_service_status.py +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/tests/test_utils.py +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/tests/test_validate_service.py +0 -0
- {unitysvc_core-0.3.1 → unitysvc_core-0.3.3}/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.3
|
|
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>
|
|
@@ -199,7 +199,7 @@ Three stages (unitysvc/unitysvc#2720): a target service's **`exports`** (what it
|
|
|
199
199
|
- `permissions`: a name (lowercase letters, digits and `_`) → the routes it covers, each `"<METHOD> /<path>"` (`*` for any method, `*` globs in the path). Permissions are never inferred from HTTP methods.
|
|
200
200
|
- `options`: a JSON Schema (draft 7) object of the customizations a grant may set on the service, like a channel's `params.schema`, with an optional react-jsonschema-form `options_ui_schema`; the frontend renders it with the same form component. It covers limits only the service can apply (a message size). Restrictions so a grant can write every value in query-string syntax: property names are lowercase letters, digits and `_`; each property is a `string`, `integer`, `number`, `boolean` or an `array` of strings, serialized as an OpenAPI form-style query parameter with arrays comma-joined (`style: form, explode: false`); options are optional (no `required`) and only declared properties are accepted; the schema is self-contained (no `$ref`), so validating against it never fetches anything. A property's `default` is what the service does when the policy does not set the option.
|
|
201
201
|
|
|
202
|
-
**2. A customer access request (`upstream_access_config.<channel>.customer_access_requests`), and the policy entry it becomes.** Any channel may declare its own list
|
|
202
|
+
**2. A customer access request (`upstream_access_config.<channel>.customer_access_requests`), and the policy entry it becomes.** Any channel may declare its own list: a fixed list of items the customer works on, and nothing else (unitysvc/unitysvc#2831). Each approved request becomes an entry (a grant) in the issued key's policy, in the same shape:
|
|
203
203
|
|
|
204
204
|
```json
|
|
205
205
|
"customer_access_requests": [{"object": "service:log", "permissions": ["invoke"], "required": true,
|
|
@@ -208,11 +208,13 @@ Three stages (unitysvc/unitysvc#2720): a target service's **`exports`** (what it
|
|
|
208
208
|
"limits": {"count_per_day": 1000}}]
|
|
209
209
|
```
|
|
210
210
|
|
|
211
|
-
- `object` names one service (`service:<name>`, no wildcards), or `apikey` for the leased key's lifespan (below).
|
|
211
|
+
- `object` names one service (`service:<name>`, no wildcards), or `apikey` for the leased key's lifespan (below). `permissions` are plain names (lowercase letters, digits and `_`; no wildcards), checked against the target's exports with a catalog.
|
|
212
|
+
- `required` (`true` or `false`, on every entry, `apikey` included) says whether the customer may decline the request. A stored declaration from before this rule reads as optional when a policy is built.
|
|
212
213
|
- `options` is written in query-string syntax (`parse_options`; a notation, not how options are delivered): each name once, each value non-empty; with a catalog, each value is converted to its declared type and validated against the target's `options` schema.
|
|
213
|
-
- **
|
|
214
|
-
-
|
|
215
|
-
-
|
|
214
|
+
- **A request's `options` are fixed.** Every option it declares is in the policy of an approved request, with the declared value; the customer may repeat it but not change or drop it. An option the request does not declare is the customer's to set at enrollment (a form rendered from the target's `options` schema). So `{"object": "service:ai", ...}` lets the customer pick the AI service, and `"options": "service=labs/llm-balanced"` pins it.
|
|
215
|
+
- Several requests may name one object (two kinds of room) only if each fixes some option to a different value (`kind=chat`, `kind=feed`), so an approval says which one it is.
|
|
216
|
+
- `limits` (`validate_limits`): `count_per_hour` / `count_per_day` / `count_per_month` / `count_total` (positive integer) and the same for `amount_` (finite positive decimal, as a number or a string). Limits are universal: the platform meters every call, so any service can be limited without exporting anything. The seller's limits only pre-fill the form; the customer sets them at enrollment, and an enrollment's own limits (unitysvc/unitysvc#2687) use the same shape. They are counted per policy entry (the enrollment's calls to that service) from the usage stream (counters keyed by scope, metric and window bucket), and the gateway refuses calls once one is exceeded.
|
|
217
|
+
- **A longer-lived leased key** is asked for with one `apikey` entry: `{"object": "apikey", "required": false, "limits": {"api_key_lifespan": 14400}, "justification": "Batch runs take up to four hours"}`. It names the key itself, so it takes only `limits` (exactly `api_key_lifespan`, whole seconds from 1 to 86400), `required` and a `justification`, needs no catalog lookup, and grants nothing. Without it, a key the seller leases for the enrollment lives `DEFAULT_API_KEY_LIFESPAN` (3600 s). `api_key_lifespan` is valid only on this entry.
|
|
216
218
|
|
|
217
219
|
**3. How options reach the service.** Not through the upstream URL: the gateway never changes a target's `base_url` or query to carry policy. How an option is applied is up to the service's implementation:
|
|
218
220
|
|
|
@@ -236,10 +238,11 @@ Three stages (unitysvc/unitysvc#2720): a target service's **`exports`** (what it
|
|
|
236
238
|
{"object": "apikey", "limits": {"api_key_lifespan": 7200}}]
|
|
237
239
|
```
|
|
238
240
|
|
|
239
|
-
- Each approval
|
|
240
|
-
-
|
|
241
|
+
- Each approval matches one request (`match_request`): the request of its object whose fixed options it does not contradict. One that fits none is refused, as is one that fits several (it names the option that tells them apart). A request is approved at most once; every `required` one must be; optional ones may be left out. Nothing else may be added, apart from the `enrollment` entry below.
|
|
242
|
+
- An approved request keeps exactly its permissions (in any order) and its fixed options; the approval may leave the options out. Values compare as the target's schema types them (`max_size=02000` repeats `2000`).
|
|
243
|
+
- The options the request leaves open, and the limits, are the customer's, checked against the target's `exports` (with `resolve`) and `validate_limits`.
|
|
241
244
|
- The `apikey` lifespan may be shortened, never lengthened beyond the request.
|
|
242
|
-
- The result drops `required` / `justification` and empty `options` / `limits
|
|
245
|
+
- The result drops `required` / `justification` and empty `options` / `limits`, and writes options as one canonical query string (`options_text`: names sorted, only what must be escaped escaped), so equal policies are equal. `match_request` finds a stored entry's request again, for a readout or a diff. `api_key_lifespan(policy)` reads the lifespan back (the default when there is none).
|
|
243
246
|
|
|
244
247
|
A policy has three kinds of entry (unitysvc/unitysvc#2770):
|
|
245
248
|
|
|
@@ -247,7 +250,7 @@ A policy has three kinds of entry (unitysvc/unitysvc#2770):
|
|
|
247
250
|
| --- | --- |
|
|
248
251
|
| `{"object": "enrollment", "limits": {"amount_per_day": "1.00"}}` | This enrollment's own limits (total spending, say). The customer adds it without a request; it takes only `limits`, at least one, at most one entry. It grants nothing. |
|
|
249
252
|
| `{"object": "service:ai", ...}` | A service the app calls for the customer. A seller may name a specific one (`service:labs/llm-premium` instead of `service:ai` with `options="service=labs/llm-premium"`), at the cost of the customer's choice of provider, which a customer may decline. |
|
|
250
|
-
| `{"object": "service:<name>", "enrollment": "<CODE>", ...}` | One of the customer's enrollments of a service that requires enrolling (a chain enrollment), called through `/e/<CODE>`. The customer picks the enrollment when approving the request for `service:<name>`, so a request never carries a code. A canonical code, no `options` (the enrollment's params are fixed), permissions and limits as for any service entry. Core checks the code's form; the caller checks the enrollment is the customer's. |
|
|
253
|
+
| `{"object": "service:<name>", "enrollment": "<CODE>", ...}` | One of the customer's enrollments of a service that requires enrolling (a chain enrollment), called through `/e/<CODE>`. The customer picks the enrollment when approving the request for `service:<name>`, so a request never carries a code; a request with fixed options can't be approved with one, since an enrollment carries no options. A canonical code, no `options` (the enrollment's params are fixed), permissions and limits as for any service entry. Core checks the code's form; the caller checks the enrollment is the customer's. |
|
|
251
254
|
|
|
252
255
|
### Upstream access channels
|
|
253
256
|
|
|
@@ -288,5 +291,6 @@ A channel declares the enrollment parameters it reads, so each plan of a service
|
|
|
288
291
|
`params.schema` is a JSON Schema of the parameters (a property's own `default` pre-fills the customer's form), `params.ui_schema` holds form hints, and `params.testing_defaults` holds the values the platform tests the channel with. Rules:
|
|
289
292
|
|
|
290
293
|
- a channel reads only the parameters its `params.schema` declares, and a channel that reads `{{ params.* }}` must declare `params` (`validate_channel_parameters`, on every `offering_v1`);
|
|
294
|
+
- `params.schema` is a valid, self-contained JSON Schema (draft 7, no `$ref`), and `params.testing_defaults` validates against it with format checking (an `email` property needs an email address), so a malformed schema is refused at ingest rather than when a customer enrolls;
|
|
291
295
|
- each required parameter has a value in that channel's `params.testing_defaults`, which is also what `${ customer_secrets.{{ params.X }} }` renders with when secret references are checked;
|
|
292
296
|
- each required parameter is read by its own channel or by document content (`validate_required_parameter_usage`, which backend ingest also calls).
|
|
@@ -164,7 +164,7 @@ Three stages (unitysvc/unitysvc#2720): a target service's **`exports`** (what it
|
|
|
164
164
|
- `permissions`: a name (lowercase letters, digits and `_`) → the routes it covers, each `"<METHOD> /<path>"` (`*` for any method, `*` globs in the path). Permissions are never inferred from HTTP methods.
|
|
165
165
|
- `options`: a JSON Schema (draft 7) object of the customizations a grant may set on the service, like a channel's `params.schema`, with an optional react-jsonschema-form `options_ui_schema`; the frontend renders it with the same form component. It covers limits only the service can apply (a message size). Restrictions so a grant can write every value in query-string syntax: property names are lowercase letters, digits and `_`; each property is a `string`, `integer`, `number`, `boolean` or an `array` of strings, serialized as an OpenAPI form-style query parameter with arrays comma-joined (`style: form, explode: false`); options are optional (no `required`) and only declared properties are accepted; the schema is self-contained (no `$ref`), so validating against it never fetches anything. A property's `default` is what the service does when the policy does not set the option.
|
|
166
166
|
|
|
167
|
-
**2. A customer access request (`upstream_access_config.<channel>.customer_access_requests`), and the policy entry it becomes.** Any channel may declare its own list
|
|
167
|
+
**2. A customer access request (`upstream_access_config.<channel>.customer_access_requests`), and the policy entry it becomes.** Any channel may declare its own list: a fixed list of items the customer works on, and nothing else (unitysvc/unitysvc#2831). Each approved request becomes an entry (a grant) in the issued key's policy, in the same shape:
|
|
168
168
|
|
|
169
169
|
```json
|
|
170
170
|
"customer_access_requests": [{"object": "service:log", "permissions": ["invoke"], "required": true,
|
|
@@ -173,11 +173,13 @@ Three stages (unitysvc/unitysvc#2720): a target service's **`exports`** (what it
|
|
|
173
173
|
"limits": {"count_per_day": 1000}}]
|
|
174
174
|
```
|
|
175
175
|
|
|
176
|
-
- `object` names one service (`service:<name>`, no wildcards), or `apikey` for the leased key's lifespan (below).
|
|
176
|
+
- `object` names one service (`service:<name>`, no wildcards), or `apikey` for the leased key's lifespan (below). `permissions` are plain names (lowercase letters, digits and `_`; no wildcards), checked against the target's exports with a catalog.
|
|
177
|
+
- `required` (`true` or `false`, on every entry, `apikey` included) says whether the customer may decline the request. A stored declaration from before this rule reads as optional when a policy is built.
|
|
177
178
|
- `options` is written in query-string syntax (`parse_options`; a notation, not how options are delivered): each name once, each value non-empty; with a catalog, each value is converted to its declared type and validated against the target's `options` schema.
|
|
178
|
-
- **
|
|
179
|
-
-
|
|
180
|
-
-
|
|
179
|
+
- **A request's `options` are fixed.** Every option it declares is in the policy of an approved request, with the declared value; the customer may repeat it but not change or drop it. An option the request does not declare is the customer's to set at enrollment (a form rendered from the target's `options` schema). So `{"object": "service:ai", ...}` lets the customer pick the AI service, and `"options": "service=labs/llm-balanced"` pins it.
|
|
180
|
+
- Several requests may name one object (two kinds of room) only if each fixes some option to a different value (`kind=chat`, `kind=feed`), so an approval says which one it is.
|
|
181
|
+
- `limits` (`validate_limits`): `count_per_hour` / `count_per_day` / `count_per_month` / `count_total` (positive integer) and the same for `amount_` (finite positive decimal, as a number or a string). Limits are universal: the platform meters every call, so any service can be limited without exporting anything. The seller's limits only pre-fill the form; the customer sets them at enrollment, and an enrollment's own limits (unitysvc/unitysvc#2687) use the same shape. They are counted per policy entry (the enrollment's calls to that service) from the usage stream (counters keyed by scope, metric and window bucket), and the gateway refuses calls once one is exceeded.
|
|
182
|
+
- **A longer-lived leased key** is asked for with one `apikey` entry: `{"object": "apikey", "required": false, "limits": {"api_key_lifespan": 14400}, "justification": "Batch runs take up to four hours"}`. It names the key itself, so it takes only `limits` (exactly `api_key_lifespan`, whole seconds from 1 to 86400), `required` and a `justification`, needs no catalog lookup, and grants nothing. Without it, a key the seller leases for the enrollment lives `DEFAULT_API_KEY_LIFESPAN` (3600 s). `api_key_lifespan` is valid only on this entry.
|
|
181
183
|
|
|
182
184
|
**3. How options reach the service.** Not through the upstream URL: the gateway never changes a target's `base_url` or query to carry policy. How an option is applied is up to the service's implementation:
|
|
183
185
|
|
|
@@ -201,10 +203,11 @@ Three stages (unitysvc/unitysvc#2720): a target service's **`exports`** (what it
|
|
|
201
203
|
{"object": "apikey", "limits": {"api_key_lifespan": 7200}}]
|
|
202
204
|
```
|
|
203
205
|
|
|
204
|
-
- Each approval
|
|
205
|
-
-
|
|
206
|
+
- Each approval matches one request (`match_request`): the request of its object whose fixed options it does not contradict. One that fits none is refused, as is one that fits several (it names the option that tells them apart). A request is approved at most once; every `required` one must be; optional ones may be left out. Nothing else may be added, apart from the `enrollment` entry below.
|
|
207
|
+
- An approved request keeps exactly its permissions (in any order) and its fixed options; the approval may leave the options out. Values compare as the target's schema types them (`max_size=02000` repeats `2000`).
|
|
208
|
+
- The options the request leaves open, and the limits, are the customer's, checked against the target's `exports` (with `resolve`) and `validate_limits`.
|
|
206
209
|
- The `apikey` lifespan may be shortened, never lengthened beyond the request.
|
|
207
|
-
- The result drops `required` / `justification` and empty `options` / `limits
|
|
210
|
+
- The result drops `required` / `justification` and empty `options` / `limits`, and writes options as one canonical query string (`options_text`: names sorted, only what must be escaped escaped), so equal policies are equal. `match_request` finds a stored entry's request again, for a readout or a diff. `api_key_lifespan(policy)` reads the lifespan back (the default when there is none).
|
|
208
211
|
|
|
209
212
|
A policy has three kinds of entry (unitysvc/unitysvc#2770):
|
|
210
213
|
|
|
@@ -212,7 +215,7 @@ A policy has three kinds of entry (unitysvc/unitysvc#2770):
|
|
|
212
215
|
| --- | --- |
|
|
213
216
|
| `{"object": "enrollment", "limits": {"amount_per_day": "1.00"}}` | This enrollment's own limits (total spending, say). The customer adds it without a request; it takes only `limits`, at least one, at most one entry. It grants nothing. |
|
|
214
217
|
| `{"object": "service:ai", ...}` | A service the app calls for the customer. A seller may name a specific one (`service:labs/llm-premium` instead of `service:ai` with `options="service=labs/llm-premium"`), at the cost of the customer's choice of provider, which a customer may decline. |
|
|
215
|
-
| `{"object": "service:<name>", "enrollment": "<CODE>", ...}` | One of the customer's enrollments of a service that requires enrolling (a chain enrollment), called through `/e/<CODE>`. The customer picks the enrollment when approving the request for `service:<name>`, so a request never carries a code. A canonical code, no `options` (the enrollment's params are fixed), permissions and limits as for any service entry. Core checks the code's form; the caller checks the enrollment is the customer's. |
|
|
218
|
+
| `{"object": "service:<name>", "enrollment": "<CODE>", ...}` | One of the customer's enrollments of a service that requires enrolling (a chain enrollment), called through `/e/<CODE>`. The customer picks the enrollment when approving the request for `service:<name>`, so a request never carries a code; a request with fixed options can't be approved with one, since an enrollment carries no options. A canonical code, no `options` (the enrollment's params are fixed), permissions and limits as for any service entry. Core checks the code's form; the caller checks the enrollment is the customer's. |
|
|
216
219
|
|
|
217
220
|
### Upstream access channels
|
|
218
221
|
|
|
@@ -253,5 +256,6 @@ A channel declares the enrollment parameters it reads, so each plan of a service
|
|
|
253
256
|
`params.schema` is a JSON Schema of the parameters (a property's own `default` pre-fills the customer's form), `params.ui_schema` holds form hints, and `params.testing_defaults` holds the values the platform tests the channel with. Rules:
|
|
254
257
|
|
|
255
258
|
- a channel reads only the parameters its `params.schema` declares, and a channel that reads `{{ params.* }}` must declare `params` (`validate_channel_parameters`, on every `offering_v1`);
|
|
259
|
+
- `params.schema` is a valid, self-contained JSON Schema (draft 7, no `$ref`), and `params.testing_defaults` validates against it with format checking (an `email` property needs an email address), so a malformed schema is refused at ingest rather than when a customer enrolls;
|
|
256
260
|
- each required parameter has a value in that channel's `params.testing_defaults`, which is also what `${ customer_secrets.{{ params.X }} }` renders with when secret references are checked;
|
|
257
261
|
- each required parameter is read by its own channel or by document content (`validate_required_parameter_usage`, which backend ingest also calls).
|
|
@@ -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.3"
|
|
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" }]
|
|
@@ -42,13 +42,19 @@ Three stages (unitysvc/unitysvc#2720):
|
|
|
42
42
|
"options": "log_level=warn",
|
|
43
43
|
"limits": {"count_per_day": 1000}}
|
|
44
44
|
|
|
45
|
-
A request grants nothing by itself.
|
|
46
|
-
|
|
45
|
+
A request grants nothing by itself. ``required`` says whether the customer
|
|
46
|
+
may decline it. Its ``object`` and ``permissions`` are fixed, and so are
|
|
47
|
+
its ``options``: the values the seller declares are the values the policy
|
|
48
|
+
holds (unitysvc/unitysvc#2831). An option it does not declare is the
|
|
49
|
+
customer's to set. Its ``limits`` only pre-fill the enrollment form.
|
|
50
|
+
Several requests may name one object (two kinds of room) if each fixes an
|
|
51
|
+
option to a different value, so an approval says which one it is.
|
|
47
52
|
|
|
48
53
|
* **The key's policy** — what the customer actually approves when enrolling:
|
|
49
|
-
they
|
|
50
|
-
|
|
51
|
-
|
|
54
|
+
they keep every required request, keep or decline each optional one, add
|
|
55
|
+
options the request leaves open, and set limits, their own included. Each
|
|
56
|
+
approved request becomes an entry (a grant) in the policy of the key issued
|
|
57
|
+
for that enrollment, in the same shape, with the request's fixed options.
|
|
52
58
|
|
|
53
59
|
**Invariant.** Calls made under an approved request run under the enrolling
|
|
54
60
|
customer's delegated identity, within the approved permissions, options and
|
|
@@ -110,7 +116,7 @@ from collections.abc import Callable
|
|
|
110
116
|
from dataclasses import dataclass
|
|
111
117
|
from decimal import Decimal, InvalidOperation
|
|
112
118
|
from typing import Any
|
|
113
|
-
from urllib.parse import parse_qsl
|
|
119
|
+
from urllib.parse import parse_qsl, urlencode
|
|
114
120
|
|
|
115
121
|
from jsonschema import Draft7Validator
|
|
116
122
|
from jsonschema.exceptions import SchemaError
|
|
@@ -123,6 +129,10 @@ INVOKE = "invoke"
|
|
|
123
129
|
# The key itself: a request for a longer-lived leased key, and the approved
|
|
124
130
|
# lifespan in a policy. It grants nothing.
|
|
125
131
|
APIKEY_OBJECT = "apikey"
|
|
132
|
+
# Every service at once. It belongs to keys a customer creates by hand: a
|
|
133
|
+
# policy derived from an enrollment names each service it calls
|
|
134
|
+
# (unitysvc/unitysvc#2783), so no request or approval may hold it.
|
|
135
|
+
SERVICE_WILDCARD = "service:*"
|
|
126
136
|
API_KEY_LIFESPAN = "api_key_lifespan"
|
|
127
137
|
# Seconds a leased key lives unless the policy says otherwise, and at most.
|
|
128
138
|
DEFAULT_API_KEY_LIFESPAN = 3600
|
|
@@ -170,7 +180,7 @@ DEFAULT_PERMISSIONS: dict[str, tuple[str, ...]] = {INVOKE: (ALL_ROUTES,)}
|
|
|
170
180
|
DEFAULT_EXPORTS = Exports(DEFAULT_PERMISSIONS, {})
|
|
171
181
|
|
|
172
182
|
_REQUEST_KEYS = frozenset({"object", "permissions", "required", "justification", "options", "limits"})
|
|
173
|
-
_APIKEY_REQUEST_KEYS = frozenset({"object", "justification", "limits"})
|
|
183
|
+
_APIKEY_REQUEST_KEYS = frozenset({"object", "required", "justification", "limits"})
|
|
174
184
|
# What a policy entry (an approved request) holds.
|
|
175
185
|
_POLICY_KEYS = frozenset({"object", "permissions", "options", "limits"})
|
|
176
186
|
# This enrollment itself: an entry capping what it may cost. It grants nothing.
|
|
@@ -380,7 +390,9 @@ def validate_limits(where: str, limits: Any, *, apikey: bool = False) -> None:
|
|
|
380
390
|
raise ValueError(f"{at} must be a positive amount")
|
|
381
391
|
|
|
382
392
|
|
|
383
|
-
def validate_access_requests(
|
|
393
|
+
def validate_access_requests(
|
|
394
|
+
where: str, requests: Any, resolve: ExportsResolver | None = None, *, explicit_required: bool = True
|
|
395
|
+
) -> None:
|
|
384
396
|
"""Refuse a channel's ``customer_access_requests`` unless every entry is a
|
|
385
397
|
valid request.
|
|
386
398
|
|
|
@@ -391,21 +403,28 @@ def validate_access_requests(where: str, requests: Any, resolve: ExportsResolver
|
|
|
391
403
|
declares permissions may not export it), and an unknown target is
|
|
392
404
|
refused. Limits need no lookup. Without ``resolve``, only the shape is
|
|
393
405
|
checked.
|
|
406
|
+
|
|
407
|
+
Every entry says whether it is ``required``. :func:`build_policy` passes
|
|
408
|
+
``explicit_required=False``: a declaration stored before that rule reads
|
|
409
|
+
as optional, as it always did.
|
|
394
410
|
"""
|
|
395
411
|
if not isinstance(requests, list):
|
|
396
412
|
raise ValueError(f"{where} must be a list of access request objects")
|
|
397
|
-
seen:
|
|
413
|
+
seen: list[tuple[str, dict[str, str], Exports | None]] = []
|
|
398
414
|
for index, entry in enumerate(requests):
|
|
399
415
|
at = f"{where}[{index}]"
|
|
400
416
|
if not isinstance(entry, dict) or not isinstance(entry.get("object"), str):
|
|
401
417
|
raise ValueError(f'{at} must be {{"object": "service:<name>", ...}}')
|
|
402
418
|
obj = entry["object"]
|
|
403
419
|
if obj == APIKEY_OBJECT:
|
|
404
|
-
if obj in seen:
|
|
420
|
+
if any(other == obj for other, _, _ in seen):
|
|
405
421
|
raise ValueError(f"{at}: {obj} is listed twice")
|
|
406
|
-
seen.
|
|
422
|
+
seen.append((obj, {}, None))
|
|
407
423
|
_check_apikey_request(at, entry)
|
|
424
|
+
_check_required(at, entry, explicit_required)
|
|
408
425
|
continue
|
|
426
|
+
if obj == SERVICE_WILDCARD:
|
|
427
|
+
raise ValueError(_service_wildcard_refusal(at, "requested"))
|
|
409
428
|
if not obj.startswith(SERVICE_PREFIX):
|
|
410
429
|
raise ValueError(f"{at}: {obj!r} cannot be requested; name one service as 'service:<name>'")
|
|
411
430
|
name = obj.removeprefix(SERVICE_PREFIX)
|
|
@@ -413,9 +432,6 @@ def validate_access_requests(where: str, requests: Any, resolve: ExportsResolver
|
|
|
413
432
|
validate_service_identifier(name, "requested service")
|
|
414
433
|
except ValueError as exc:
|
|
415
434
|
raise ValueError(f"{at}: {obj!r} cannot be requested: {exc}") from None
|
|
416
|
-
if obj in seen:
|
|
417
|
-
raise ValueError(f"{at}: {obj} is listed twice")
|
|
418
|
-
seen.add(obj)
|
|
419
435
|
if extra := set(entry) - _REQUEST_KEYS:
|
|
420
436
|
raise ValueError(f"{at}: unknown keys {sorted(extra)}")
|
|
421
437
|
justification = entry.get("justification")
|
|
@@ -423,19 +439,96 @@ def validate_access_requests(where: str, requests: Any, resolve: ExportsResolver
|
|
|
423
439
|
raise ValueError(
|
|
424
440
|
f"{at}.justification must say why the service needs {obj}; the customer reads it before approving"
|
|
425
441
|
)
|
|
426
|
-
|
|
427
|
-
raise ValueError(f"{at}.required must be true or false")
|
|
442
|
+
_check_required(at, entry, explicit_required)
|
|
428
443
|
permissions: list[str] = entry.get("permissions") or []
|
|
429
|
-
if not _strings(permissions):
|
|
430
|
-
raise ValueError(
|
|
444
|
+
if not _strings(permissions) or not all(_PERMISSION_NAME.match(p) for p in permissions):
|
|
445
|
+
raise ValueError(
|
|
446
|
+
f"{at}.permissions must be a non-empty list of distinct permission names "
|
|
447
|
+
"(lowercase letters, digits and '_'; no wildcards)"
|
|
448
|
+
)
|
|
431
449
|
options = parse_options(f"{at}.options", entry.get("options", ""))
|
|
432
450
|
validate_limits(f"{at}.limits", entry.get("limits", {}))
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
451
|
+
exports = None
|
|
452
|
+
if resolve is not None:
|
|
453
|
+
declared = resolve(name)
|
|
454
|
+
if declared is None:
|
|
455
|
+
raise ValueError(f"{at}: {obj} is not a published service")
|
|
456
|
+
exports = parse_exports(f"{obj} exports", declared)
|
|
457
|
+
check_claim(at, obj, permissions, options, exports)
|
|
458
|
+
for other_index, (other, other_options, _) in enumerate(seen):
|
|
459
|
+
if other == obj and _conflict(exports, options, other_options) is None:
|
|
460
|
+
raise ValueError(
|
|
461
|
+
f"{at}: {obj} is listed twice; requests of one object must each fix an option "
|
|
462
|
+
f"to a different value (kind=chat, kind=feed), or the customer can't say which "
|
|
463
|
+
f"one they approve (see [{other_index}])"
|
|
464
|
+
)
|
|
465
|
+
seen.append((obj, options, exports))
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def _check_required(at: str, entry: dict[str, Any], explicit: bool) -> None:
|
|
469
|
+
if "required" in entry:
|
|
470
|
+
if not isinstance(entry["required"], bool):
|
|
471
|
+
raise ValueError(f"{at}.required must be true or false")
|
|
472
|
+
elif explicit:
|
|
473
|
+
raise ValueError(f"{at}.required must be true or false: say whether the customer may decline it")
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def _conflict(exports: Exports | None, a: dict[str, str], b: dict[str, str]) -> str | None:
|
|
477
|
+
"""The first option ``a`` and ``b`` both set, to different values, or
|
|
478
|
+
``None``. Values are compared as the target's ``exports`` type them
|
|
479
|
+
(``100`` and ``0100`` are one integer); without exports, as written."""
|
|
480
|
+
properties = exports.options.get("properties", {}) if exports else {}
|
|
481
|
+
for name in sorted(set(a) & set(b)):
|
|
482
|
+
prop = properties.get(name, {})
|
|
483
|
+
if _typed(prop, a[name]) != _typed(prop, b[name]):
|
|
484
|
+
return name
|
|
485
|
+
return None
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def _label(request: dict[str, Any]) -> str:
|
|
489
|
+
"""A request as the customer tells it apart: its object, and its fixed options."""
|
|
490
|
+
return f"{request['object']} ({request['options']})" if request.get("options") else str(request["object"])
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
def match_request(
|
|
494
|
+
where: str, requests: list[dict[str, Any]], entry: dict[str, Any], exports: Exports | None = None
|
|
495
|
+
) -> int:
|
|
496
|
+
"""The index of the request in ``requests`` (already valid) that ``entry``,
|
|
497
|
+
an approval or a stored policy entry, approves.
|
|
498
|
+
|
|
499
|
+
It is the request of the same object whose fixed options the entry does
|
|
500
|
+
not contradict: one the entry repeats, or leaves out. Requests of one
|
|
501
|
+
object each fix an option to a different value, so only an entry that
|
|
502
|
+
leaves all of those out can fit more than one; it is refused, naming the
|
|
503
|
+
option that tells them apart. Raises ``ValueError``.
|
|
504
|
+
"""
|
|
505
|
+
obj = entry.get("object")
|
|
506
|
+
options = parse_options(f"{where}.options", entry.get("options", ""))
|
|
507
|
+
same = [i for i, request in enumerate(requests) if request["object"] == obj]
|
|
508
|
+
if not same:
|
|
509
|
+
raise ValueError(f"{where}: {obj} is not requested")
|
|
510
|
+
fixed = {i: parse_options("options", requests[i].get("options", "")) for i in same}
|
|
511
|
+
fitting = [i for i in same if _conflict(exports, fixed[i], options) is None]
|
|
512
|
+
if not fitting:
|
|
513
|
+
if len(same) == 1:
|
|
514
|
+
name = _conflict(exports, fixed[same[0]], options)
|
|
515
|
+
assert name is not None
|
|
516
|
+
raise ValueError(f"{where}.options.{name}: the service fixes it to {fixed[same[0]][name]!r}")
|
|
517
|
+
raise ValueError(
|
|
518
|
+
f"{where}: no request of {obj} has these options; the service requests "
|
|
519
|
+
+ ", ".join(_label(requests[i]) for i in same)
|
|
520
|
+
)
|
|
521
|
+
if len(fitting) > 1:
|
|
522
|
+
name = _conflict(exports, fixed[fitting[0]], fixed[fitting[1]])
|
|
523
|
+
raise ValueError(f"{where}.options: {obj} is requested {len(fitting)} times; set {name} to say which")
|
|
524
|
+
return fitting[0]
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def _service_wildcard_refusal(at: str, verb: str) -> str:
|
|
528
|
+
return (
|
|
529
|
+
f"{at}: {SERVICE_WILDCARD!r} cannot be {verb}: every service at once is only for keys "
|
|
530
|
+
"a customer creates by hand; name each service as 'service:<name>'"
|
|
531
|
+
)
|
|
439
532
|
|
|
440
533
|
|
|
441
534
|
def _check_apikey_request(at: str, entry: dict[str, Any]) -> None:
|
|
@@ -479,91 +572,111 @@ def validate_channel_access_requests(config: Any, resolve: ExportsResolver | Non
|
|
|
479
572
|
|
|
480
573
|
def build_policy(requests: Any, approvals: Any, resolve: ExportsResolver | None = None) -> list[dict[str, Any]]:
|
|
481
574
|
"""The key policy a customer's ``approvals`` of a channel's ``requests``
|
|
482
|
-
make (unitysvc/unitysvc#2766).
|
|
575
|
+
make (unitysvc/unitysvc#2766, #2831).
|
|
483
576
|
|
|
484
577
|
``requests`` is the channel's ``customer_access_requests``; ``approvals``
|
|
485
578
|
lists the requests the customer approves, each ``{"object", "permissions",
|
|
486
579
|
"options", "limits"}`` (the ``apikey`` entry only ``{"object", "limits"}``).
|
|
487
|
-
Each approval
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
580
|
+
Each approval matches one request (:func:`match_request`), at most once,
|
|
581
|
+
and every ``required`` request is approved. An approved request keeps
|
|
582
|
+
exactly its permissions and its fixed options: the approval may repeat
|
|
583
|
+
them, or leave the options out, but not change them. Beside them the
|
|
584
|
+
customer sets the options the request leaves open and the limits, checked
|
|
585
|
+
against the target's ``exports`` (with ``resolve``) and
|
|
586
|
+
:func:`validate_limits`; a request's limits only pre-fill the form. A key
|
|
587
|
+
lifespan may only be shortened. Returns the approvals as policy entries,
|
|
588
|
+
their options in one canonical query string (names sorted), without empty
|
|
493
589
|
``options`` / ``limits``. Raises ``ValueError``.
|
|
494
590
|
|
|
495
591
|
The customer may also add, at most once and without a request, this
|
|
496
592
|
enrollment's own limits: ``{"object": "enrollment", "limits": {...}}``,
|
|
497
593
|
with at least one limit and nothing else (unitysvc/unitysvc#2770). And an
|
|
498
|
-
approval of a
|
|
499
|
-
(``"enrollment": "<CODE>"``, a chain
|
|
500
|
-
``options``. The caller checks the
|
|
594
|
+
approval of a request that fixes no options may select one of the
|
|
595
|
+
customer's enrollments of its service (``"enrollment": "<CODE>"``, a chain
|
|
596
|
+
enrollment): a canonical code, and no ``options``. The caller checks the
|
|
597
|
+
enrollment is the customer's.
|
|
501
598
|
"""
|
|
502
|
-
validate_access_requests("requests", requests)
|
|
503
|
-
requested = {entry["object"]: entry for entry in requests}
|
|
599
|
+
validate_access_requests("requests", requests, explicit_required=False)
|
|
504
600
|
if not isinstance(approvals, list):
|
|
505
601
|
raise ValueError("approvals must be a list of approved requests")
|
|
506
602
|
policy: list[dict[str, Any]] = []
|
|
603
|
+
approved: set[int] = set()
|
|
507
604
|
for index, approval in enumerate(approvals):
|
|
508
605
|
at = f"approvals[{index}]"
|
|
509
606
|
if not isinstance(approval, dict) or not isinstance(approval.get("object"), str):
|
|
510
607
|
raise ValueError(f'{at} must be {{"object": ..., "permissions": [...]}}')
|
|
511
608
|
obj = approval["object"]
|
|
609
|
+
if obj == SERVICE_WILDCARD:
|
|
610
|
+
raise ValueError(_service_wildcard_refusal(at, "approved"))
|
|
512
611
|
if obj == ENROLLMENT_OBJECT:
|
|
513
612
|
if any(entry["object"] == obj for entry in policy):
|
|
514
613
|
raise ValueError(f"{at}: {obj} is listed twice")
|
|
515
614
|
policy.append(_enrollment_entry(at, approval))
|
|
516
615
|
continue
|
|
517
|
-
request = requested.get(obj)
|
|
518
|
-
if request is None:
|
|
519
|
-
raise ValueError(f"{at}: {obj} is not requested")
|
|
520
|
-
if any(entry["object"] == obj for entry in policy):
|
|
521
|
-
raise ValueError(f"{at}: {obj} is approved twice")
|
|
522
616
|
if obj == APIKEY_OBJECT:
|
|
523
617
|
if extra := set(approval) - {"object", "limits"}:
|
|
524
618
|
raise ValueError(f"{at}: unknown keys {sorted(extra)} (the {APIKEY_OBJECT} entry takes only limits)")
|
|
619
|
+
elif extra := set(approval) - _POLICY_KEYS - {ENROLLMENT_KEY}:
|
|
620
|
+
raise ValueError(f"{at}: unknown keys {sorted(extra)}")
|
|
621
|
+
exports = None
|
|
622
|
+
if resolve is not None and obj.startswith(SERVICE_PREFIX) and any(r["object"] == obj for r in requests):
|
|
623
|
+
declared = resolve(obj.removeprefix(SERVICE_PREFIX))
|
|
624
|
+
if declared is None:
|
|
625
|
+
raise ValueError(f"{at}: {obj} is not a published service")
|
|
626
|
+
exports = parse_exports(f"{obj} exports", declared)
|
|
627
|
+
matched = match_request(at, requests, approval, exports)
|
|
628
|
+
if matched in approved:
|
|
629
|
+
raise ValueError(f"{at}: {_label(requests[matched])} is approved twice")
|
|
630
|
+
approved.add(matched)
|
|
631
|
+
request = requests[matched]
|
|
632
|
+
if obj == APIKEY_OBJECT:
|
|
525
633
|
validate_limits(f"{at}.limits", approval.get("limits"), apikey=True)
|
|
526
634
|
asked = request["limits"][API_KEY_LIFESPAN]
|
|
527
635
|
if approval["limits"][API_KEY_LIFESPAN] > asked:
|
|
528
636
|
raise ValueError(f"{at}.limits.{API_KEY_LIFESPAN}: the service asks for at most {asked} seconds")
|
|
529
637
|
policy.append({"object": obj, "limits": dict(approval["limits"])})
|
|
530
638
|
continue
|
|
531
|
-
|
|
532
|
-
raise ValueError(f"{at}: unknown keys {sorted(extra)}")
|
|
639
|
+
fixed = parse_options("options", request.get("options", ""))
|
|
533
640
|
code = approval.get(ENROLLMENT_KEY)
|
|
534
641
|
if ENROLLMENT_KEY in approval:
|
|
535
642
|
if not isinstance(code, str) or not _ENROLLMENT_CODE.match(code):
|
|
536
643
|
raise ValueError(f"{at}.{ENROLLMENT_KEY} must be an enrollment code, like JYY87Y")
|
|
537
644
|
if approval.get("options"):
|
|
538
645
|
raise ValueError(f"{at}.options: an enrollment's params are fixed; it takes no options")
|
|
646
|
+
if fixed:
|
|
647
|
+
raise ValueError(
|
|
648
|
+
f"{at}.{ENROLLMENT_KEY}: the service fixes options of {obj} ({request['options']}), "
|
|
649
|
+
"which an enrollment cannot carry; approve it without one"
|
|
650
|
+
)
|
|
539
651
|
permissions: list[str] = approval.get("permissions") or []
|
|
540
|
-
if not _strings(permissions):
|
|
541
|
-
raise ValueError(f"{at}.permissions
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
options_text = approval.get("options", "")
|
|
545
|
-
options = parse_options(f"{at}.options", options_text)
|
|
652
|
+
if not _strings(permissions) or set(permissions) != set(request["permissions"]):
|
|
653
|
+
raise ValueError(f"{at}.permissions: the service requests exactly {request['permissions']}")
|
|
654
|
+
# The request's values win over an equal value written another way.
|
|
655
|
+
options = {**parse_options(f"{at}.options", approval.get("options", "")), **fixed}
|
|
546
656
|
limits = approval.get("limits", {})
|
|
547
657
|
validate_limits(f"{at}.limits", limits)
|
|
548
|
-
if
|
|
549
|
-
|
|
550
|
-
if declared is None:
|
|
551
|
-
raise ValueError(f"{at}: {obj} is not a published service")
|
|
552
|
-
check_claim(at, obj, permissions, options, parse_exports(f"{obj} exports", declared))
|
|
658
|
+
if exports is not None:
|
|
659
|
+
check_claim(at, obj, permissions, options, exports)
|
|
553
660
|
entry: dict[str, Any] = {"object": obj, "permissions": list(permissions)}
|
|
554
661
|
if code is not None:
|
|
555
662
|
entry[ENROLLMENT_KEY] = code
|
|
556
663
|
if options:
|
|
557
|
-
entry["options"] = options_text
|
|
664
|
+
entry["options"] = options_text(options)
|
|
558
665
|
if limits:
|
|
559
666
|
entry["limits"] = dict(limits)
|
|
560
667
|
policy.append(entry)
|
|
561
|
-
|
|
562
|
-
if missing := sorted(obj for obj, request in requested.items() if request.get("required") and obj not in approved):
|
|
668
|
+
if missing := [_label(r) for i, r in enumerate(requests) if r.get("required") and i not in approved]:
|
|
563
669
|
raise ValueError(f"approvals: the service requires {', '.join(missing)}")
|
|
564
670
|
return policy
|
|
565
671
|
|
|
566
672
|
|
|
673
|
+
def options_text(options: dict[str, str]) -> str:
|
|
674
|
+
"""``options`` as the one query string a policy stores: names sorted, and
|
|
675
|
+
only what must be escaped escaped (``service=labs/llm-fast``,
|
|
676
|
+
``profile=a,b``), so equal options are equal text."""
|
|
677
|
+
return urlencode(sorted(options.items()), safe=",/")
|
|
678
|
+
|
|
679
|
+
|
|
567
680
|
def _enrollment_entry(at: str, approval: dict[str, Any]) -> dict[str, Any]:
|
|
568
681
|
"""This enrollment's own entry: limits only, and at least one."""
|
|
569
682
|
if extra := set(approval) - {"object", "limits"}:
|
|
@@ -5,6 +5,8 @@ declares none. Checks shared by seller validation and backend ingest:
|
|
|
5
5
|
|
|
6
6
|
- a channel reads only parameters it declares, and declares ``params`` if it
|
|
7
7
|
reads any;
|
|
8
|
+
- ``params.schema`` is a self-contained JSON Schema (draft 7), and
|
|
9
|
+
``params.testing_defaults`` validates against it;
|
|
8
10
|
- every required parameter has a value in ``params.testing_defaults``;
|
|
9
11
|
- every required parameter is read by its channel or by document content.
|
|
10
12
|
|
|
@@ -17,6 +19,10 @@ reference there does not count (unitysvc/unitysvc#2649).
|
|
|
17
19
|
from typing import Any
|
|
18
20
|
|
|
19
21
|
from jinja2 import Environment, TemplateSyntaxError, nodes
|
|
22
|
+
from jsonschema import Draft7Validator
|
|
23
|
+
from jsonschema.exceptions import SchemaError
|
|
24
|
+
|
|
25
|
+
from .grants import _find_reference
|
|
20
26
|
|
|
21
27
|
_ENV = Environment()
|
|
22
28
|
|
|
@@ -156,6 +162,16 @@ def validate_channel_parameters(offering: dict[str, Any]) -> list[str]:
|
|
|
156
162
|
if not isinstance(schema, dict):
|
|
157
163
|
errors.append(f"{at}.schema must be a JSON Schema object")
|
|
158
164
|
continue
|
|
165
|
+
schema_ok = True
|
|
166
|
+
if ref := _find_reference(schema):
|
|
167
|
+
errors.append(f"{at}.schema: {ref!r} is not allowed; a params schema is self-contained")
|
|
168
|
+
schema_ok = False
|
|
169
|
+
else:
|
|
170
|
+
try:
|
|
171
|
+
Draft7Validator.check_schema(schema)
|
|
172
|
+
except SchemaError as exc:
|
|
173
|
+
errors.append(f"{at}.schema is not a valid JSON Schema: {exc.message}")
|
|
174
|
+
schema_ok = False
|
|
159
175
|
ui_schema = params.get("ui_schema")
|
|
160
176
|
if ui_schema is not None and not isinstance(ui_schema, dict):
|
|
161
177
|
errors.append(f"{at}.ui_schema must be an object")
|
|
@@ -173,6 +189,11 @@ def validate_channel_parameters(offering: dict[str, Any]) -> list[str]:
|
|
|
173
189
|
f"{where}: required parameter(s) {', '.join(missing)} need a value in "
|
|
174
190
|
f"{at}.testing_defaults, used to test the channel"
|
|
175
191
|
)
|
|
192
|
+
elif schema_ok:
|
|
193
|
+
validator = Draft7Validator(schema, format_checker=Draft7Validator.FORMAT_CHECKER)
|
|
194
|
+
for error in sorted(validator.iter_errors(defaults or {}), key=lambda e: [str(p) for p in e.path]):
|
|
195
|
+
path = "".join(f".{p}" for p in error.path)
|
|
196
|
+
errors.append(f"{at}.testing_defaults{path}: {error.message}")
|
|
176
197
|
return errors
|
|
177
198
|
|
|
178
199
|
|