unitysvc-core 0.3.2__tar.gz → 0.3.4__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.
Files changed (55) hide show
  1. {unitysvc_core-0.3.2/src/unitysvc_core.egg-info → unitysvc_core-0.3.4}/PKG-INFO +14 -10
  2. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/README.md +13 -9
  3. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/pyproject.toml +1 -1
  4. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/src/unitysvc_core/grants.py +246 -68
  5. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/src/unitysvc_core/models/base.py +9 -0
  6. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/src/unitysvc_core/models/offering_data.py +6 -3
  7. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/src/unitysvc_core/schema/offering_v1.json +14 -5
  8. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4/src/unitysvc_core.egg-info}/PKG-INFO +14 -10
  9. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/tests/test_grants.py +354 -17
  10. unitysvc_core-0.3.4/tests/test_offering_data.py +26 -0
  11. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/tests/test_validator.py +1 -1
  12. unitysvc_core-0.3.2/tests/test_offering_data.py +0 -14
  13. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/LICENSE +0 -0
  14. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/setup.cfg +0 -0
  15. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/src/unitysvc_core/__init__.py +0 -0
  16. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/src/unitysvc_core/models/__init__.py +0 -0
  17. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/src/unitysvc_core/models/channel.py +0 -0
  18. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/src/unitysvc_core/models/documents.py +0 -0
  19. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/src/unitysvc_core/models/listing_data.py +0 -0
  20. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/src/unitysvc_core/models/listing_v1.py +0 -0
  21. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/src/unitysvc_core/models/offering_v1.py +0 -0
  22. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/src/unitysvc_core/models/pricing.py +0 -0
  23. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/src/unitysvc_core/models/promotion_data.py +0 -0
  24. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/src/unitysvc_core/models/provider_data.py +0 -0
  25. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/src/unitysvc_core/models/provider_v1.py +0 -0
  26. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/src/unitysvc_core/models/service.py +0 -0
  27. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/src/unitysvc_core/models/service_group_data.py +0 -0
  28. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/src/unitysvc_core/models/validators.py +0 -0
  29. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/src/unitysvc_core/parameter_usage.py +0 -0
  30. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/src/unitysvc_core/py.typed +0 -0
  31. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/src/unitysvc_core/schema/base.json +0 -0
  32. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/src/unitysvc_core/schema/listing_v1.json +0 -0
  33. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/src/unitysvc_core/schema/promotion_v1.json +0 -0
  34. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/src/unitysvc_core/schema/provider_v1.json +0 -0
  35. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/src/unitysvc_core/schema/service_group_v1.json +0 -0
  36. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/src/unitysvc_core/utils.py +0 -0
  37. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/src/unitysvc_core/validator.py +0 -0
  38. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/src/unitysvc_core.egg-info/SOURCES.txt +0 -0
  39. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/src/unitysvc_core.egg-info/dependency_links.txt +0 -0
  40. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/src/unitysvc_core.egg-info/requires.txt +0 -0
  41. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/src/unitysvc_core.egg-info/top_level.txt +0 -0
  42. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/tests/test_access_interface_routing.py +0 -0
  43. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/tests/test_canonical_interfaces.py +0 -0
  44. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/tests/test_channel.py +0 -0
  45. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/tests/test_effective_price.py +0 -0
  46. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/tests/test_hidden_path_skip.py +0 -0
  47. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/tests/test_listing_audience.py +0 -0
  48. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/tests/test_parameter_usage.py +0 -0
  49. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/tests/test_pricing.py +0 -0
  50. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/tests/test_provider_account_rate_limits.py +0 -0
  51. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/tests/test_service_group.py +0 -0
  52. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/tests/test_service_status.py +0 -0
  53. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/tests/test_utils.py +0 -0
  54. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/tests/test_validate_service.py +0 -0
  55. {unitysvc_core-0.3.2 → unitysvc_core-0.3.4}/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.2
3
+ Version: 0.3.4
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; each approved request becomes an entry (a grant) in the issued key's policy, in the same shape:
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,14 @@ 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), a resource the platform provisions for the enrollment (`resource:room`, below), 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
- - **Enrollment is where options and limits are set.** In a request, `options` and `limits` only pre-fill the enrollment form for convenience. When enrolling, the customer confirms and sets the options (a form rendered from the target's `options` schema) and the limits, and adds their own limits; the result is the issued key's policy.
214
- - `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 are a pre-fill; 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.
215
- - **A longer-lived leased key** is asked for with one `apikey` entry: `{"object": "apikey", "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) 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.
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 room the platform provisions** (unitysvc/unitysvc#2830) is asked for with `resource:room`: `{"object": "resource:room", "permissions": ["create"], "required": true, "justification": "Creates your chat room", "options": "kind=chat&max_members=100"}`. Core knows the resource, so no catalog is consulted. The request must fix `kind`, the room's identity; each kind bounds the permissions (`chat`: `create`, a room the customer owns; `support`: `join`, `read`, `post`, the seller's private room with the customer; `announcement`: `join`, `read`; `discussion`: `join`, `read`, `post`). `max_members` (a positive integer) caps only a room the customer creates. A channel requests each kind at most once, and a resource takes no limits.
218
+ - **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
219
 
217
220
  **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
221
 
@@ -236,10 +239,11 @@ Three stages (unitysvc/unitysvc#2720): a target service's **`exports`** (what it
236
239
  {"object": "apikey", "limits": {"api_key_lifespan": 7200}}]
237
240
  ```
238
241
 
239
- - Each approval names a requested object, at most once, with some of the permissions requested. Every `required` request must be approved; optional ones may be left out.
240
- - Options and limits are the customer's. They are checked against the target's `exports` (with `resolve`) and `validate_limits`, not against the request, whose values only pre-fill the form.
242
+ - 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.
243
+ - 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`).
244
+ - 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
245
  - The `apikey` lifespan may be shortened, never lengthened beyond the request.
242
- - The result drops `required` / `justification` and empty `options` / `limits`. `api_key_lifespan(policy)` reads the lifespan back (the default when there is none).
246
+ - 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
247
 
244
248
  A policy has three kinds of entry (unitysvc/unitysvc#2770):
245
249
 
@@ -247,7 +251,7 @@ A policy has three kinds of entry (unitysvc/unitysvc#2770):
247
251
  | --- | --- |
248
252
  | `{"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
253
  | `{"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. |
254
+ | `{"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
255
 
252
256
  ### Upstream access channels
253
257
 
@@ -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; each approved request becomes an entry (a grant) in the issued key's policy, in the same shape:
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,14 @@ 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), a resource the platform provisions for the enrollment (`resource:room`, below), 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
- - **Enrollment is where options and limits are set.** In a request, `options` and `limits` only pre-fill the enrollment form for convenience. When enrolling, the customer confirms and sets the options (a form rendered from the target's `options` schema) and the limits, and adds their own limits; the result is the issued key's policy.
179
- - `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 are a pre-fill; 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.
180
- - **A longer-lived leased key** is asked for with one `apikey` entry: `{"object": "apikey", "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) 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.
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 room the platform provisions** (unitysvc/unitysvc#2830) is asked for with `resource:room`: `{"object": "resource:room", "permissions": ["create"], "required": true, "justification": "Creates your chat room", "options": "kind=chat&max_members=100"}`. Core knows the resource, so no catalog is consulted. The request must fix `kind`, the room's identity; each kind bounds the permissions (`chat`: `create`, a room the customer owns; `support`: `join`, `read`, `post`, the seller's private room with the customer; `announcement`: `join`, `read`; `discussion`: `join`, `read`, `post`). `max_members` (a positive integer) caps only a room the customer creates. A channel requests each kind at most once, and a resource takes no limits.
183
+ - **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
184
 
182
185
  **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
186
 
@@ -201,10 +204,11 @@ Three stages (unitysvc/unitysvc#2720): a target service's **`exports`** (what it
201
204
  {"object": "apikey", "limits": {"api_key_lifespan": 7200}}]
202
205
  ```
203
206
 
204
- - Each approval names a requested object, at most once, with some of the permissions requested. Every `required` request must be approved; optional ones may be left out.
205
- - Options and limits are the customer's. They are checked against the target's `exports` (with `resolve`) and `validate_limits`, not against the request, whose values only pre-fill the form.
207
+ - 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.
208
+ - 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`).
209
+ - 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
210
  - The `apikey` lifespan may be shortened, never lengthened beyond the request.
207
- - The result drops `required` / `justification` and empty `options` / `limits`. `api_key_lifespan(policy)` reads the lifespan back (the default when there is none).
211
+ - 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
212
 
209
213
  A policy has three kinds of entry (unitysvc/unitysvc#2770):
210
214
 
@@ -212,7 +216,7 @@ A policy has three kinds of entry (unitysvc/unitysvc#2770):
212
216
  | --- | --- |
213
217
  | `{"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
218
  | `{"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. |
219
+ | `{"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
220
 
217
221
  ### Upstream access channels
218
222
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "unitysvc-core"
7
- version = "0.3.2"
7
+ version = "0.3.4"
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. Its ``options`` and ``limits`` only
46
- pre-fill the enrollment form.
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 confirm or decline each request, set its options and limits, and may
50
- add limits of their own. Each approved request becomes an entry (a grant) in
51
- the policy of the key issued for that enrollment, in the same shape.
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
@@ -72,10 +78,14 @@ customer consent and key issuance establish its *authority*.
72
78
  be limited by ``count`` or ``amount`` per hour, day or month, or in total,
73
79
  without exporting anything (``{"count_per_day": 2, "amount_per_month": "2.00"}``).
74
80
 
75
- Today a request's ``object`` is ``service:<name>``, or ``apikey``: how long a
76
- key leased for the enrollment lives (``limits.api_key_lifespan``, up to a day,
77
- with a justification), which grants nothing. :func:`build_policy` turns a
78
- customer's approvals into the policy an enrollment keeps.
81
+ A request's ``object`` is ``service:<name>``; or ``resource:room``, a room the
82
+ platform provisions for the enrollment (unitysvc/unitysvc#2830), whose
83
+ ``kind`` (``chat``, ``support``, ``announcement``, ``discussion``) the
84
+ request fixes and whose permissions the kind bounds (:data:`ROOM_KINDS`); or
85
+ ``apikey``: how long a key leased for the enrollment lives
86
+ (``limits.api_key_lifespan``, up to a day, with a justification), which grants
87
+ nothing. :func:`build_policy` turns a customer's approvals into the policy an
88
+ enrollment keeps.
79
89
 
80
90
  A policy has three kinds of entry (unitysvc/unitysvc#2770):
81
91
 
@@ -110,7 +120,7 @@ from collections.abc import Callable
110
120
  from dataclasses import dataclass
111
121
  from decimal import Decimal, InvalidOperation
112
122
  from typing import Any
113
- from urllib.parse import parse_qsl
123
+ from urllib.parse import parse_qsl, urlencode
114
124
 
115
125
  from jsonschema import Draft7Validator
116
126
  from jsonschema.exceptions import SchemaError
@@ -173,8 +183,38 @@ ALL_ROUTES = "* /*"
173
183
  DEFAULT_PERMISSIONS: dict[str, tuple[str, ...]] = {INVOKE: (ALL_ROUTES,)}
174
184
  DEFAULT_EXPORTS = Exports(DEFAULT_PERMISSIONS, {})
175
185
 
186
+ # What a request may ask the platform to provision for the enrolling customer,
187
+ # rather than a service to call (unitysvc/unitysvc#2830): ``resource:<name>``.
188
+ # Core knows each resource, so its claims need no catalog lookup.
189
+ RESOURCE_PREFIX = "resource:"
190
+ # A room's kind is its identity: a request fixes it, and each kind allows the
191
+ # permissions its provisioning grants. The customer creates and owns a chat
192
+ # room; the others are the seller's rooms the customer is admitted to (a
193
+ # private support room, a read-only announcement room, a discussion room).
194
+ ROOM_KINDS: dict[str, frozenset[str]] = {
195
+ "chat": frozenset({"create"}),
196
+ "support": frozenset({"join", "read", "post"}),
197
+ "announcement": frozenset({"join", "read"}),
198
+ "discussion": frozenset({"join", "read", "post"}),
199
+ }
200
+ ROOM_KIND = "kind"
201
+ ROOM_MAX_MEMBERS = "max_members"
202
+ RESOURCES: dict[str, Exports] = {
203
+ "room": Exports(
204
+ {name: () for name in ("create", "join", "read", "post")},
205
+ {
206
+ "type": "object",
207
+ "additionalProperties": False,
208
+ "properties": {
209
+ ROOM_KIND: {"type": "string", "enum": list(ROOM_KINDS)},
210
+ ROOM_MAX_MEMBERS: {"type": "integer", "minimum": 1},
211
+ },
212
+ },
213
+ ),
214
+ }
215
+
176
216
  _REQUEST_KEYS = frozenset({"object", "permissions", "required", "justification", "options", "limits"})
177
- _APIKEY_REQUEST_KEYS = frozenset({"object", "justification", "limits"})
217
+ _APIKEY_REQUEST_KEYS = frozenset({"object", "required", "justification", "limits"})
178
218
  # What a policy entry (an approved request) holds.
179
219
  _POLICY_KEYS = frozenset({"object", "permissions", "options", "limits"})
180
220
  # This enrollment itself: an entry capping what it may cost. It grants nothing.
@@ -384,7 +424,9 @@ def validate_limits(where: str, limits: Any, *, apikey: bool = False) -> None:
384
424
  raise ValueError(f"{at} must be a positive amount")
385
425
 
386
426
 
387
- def validate_access_requests(where: str, requests: Any, resolve: ExportsResolver | None = None) -> None:
427
+ def validate_access_requests(
428
+ where: str, requests: Any, resolve: ExportsResolver | None = None, *, explicit_required: bool = True
429
+ ) -> None:
388
430
  """Refuse a channel's ``customer_access_requests`` unless every entry is a
389
431
  valid request.
390
432
 
@@ -395,33 +437,46 @@ def validate_access_requests(where: str, requests: Any, resolve: ExportsResolver
395
437
  declares permissions may not export it), and an unknown target is
396
438
  refused. Limits need no lookup. Without ``resolve``, only the shape is
397
439
  checked.
440
+
441
+ Every entry says whether it is ``required``. :func:`build_policy` passes
442
+ ``explicit_required=False``: a declaration stored before that rule reads
443
+ as optional, as it always did.
398
444
  """
399
445
  if not isinstance(requests, list):
400
446
  raise ValueError(f"{where} must be a list of access request objects")
401
- seen: set[str] = set()
447
+ seen: list[tuple[str, dict[str, str], Exports | None]] = []
402
448
  for index, entry in enumerate(requests):
403
449
  at = f"{where}[{index}]"
404
450
  if not isinstance(entry, dict) or not isinstance(entry.get("object"), str):
405
451
  raise ValueError(f'{at} must be {{"object": "service:<name>", ...}}')
406
452
  obj = entry["object"]
407
453
  if obj == APIKEY_OBJECT:
408
- if obj in seen:
454
+ if any(other == obj for other, _, _ in seen):
409
455
  raise ValueError(f"{at}: {obj} is listed twice")
410
- seen.add(obj)
456
+ seen.append((obj, {}, None))
411
457
  _check_apikey_request(at, entry)
458
+ _check_required(at, entry, explicit_required)
412
459
  continue
413
460
  if obj == SERVICE_WILDCARD:
414
461
  raise ValueError(_service_wildcard_refusal(at, "requested"))
415
- if not obj.startswith(SERVICE_PREFIX):
416
- raise ValueError(f"{at}: {obj!r} cannot be requested; name one service as 'service:<name>'")
417
- name = obj.removeprefix(SERVICE_PREFIX)
418
- try:
419
- validate_service_identifier(name, "requested service")
420
- except ValueError as exc:
421
- raise ValueError(f"{at}: {obj!r} cannot be requested: {exc}") from None
422
- if obj in seen:
423
- raise ValueError(f"{at}: {obj} is listed twice")
424
- seen.add(obj)
462
+ resource = obj.startswith(RESOURCE_PREFIX)
463
+ name = obj.removeprefix(RESOURCE_PREFIX if resource else SERVICE_PREFIX)
464
+ if resource:
465
+ if name not in RESOURCES:
466
+ raise ValueError(
467
+ f"{at}: {obj!r} cannot be requested; the resources are "
468
+ + ", ".join(f"'{RESOURCE_PREFIX}{r}'" for r in RESOURCES)
469
+ )
470
+ elif not obj.startswith(SERVICE_PREFIX):
471
+ raise ValueError(
472
+ f"{at}: {obj!r} cannot be requested; name one service as 'service:<name>' "
473
+ f"or a resource as '{RESOURCE_PREFIX}<name>'"
474
+ )
475
+ else:
476
+ try:
477
+ validate_service_identifier(name, "requested service")
478
+ except ValueError as exc:
479
+ raise ValueError(f"{at}: {obj!r} cannot be requested: {exc}") from None
425
480
  if extra := set(entry) - _REQUEST_KEYS:
426
481
  raise ValueError(f"{at}: unknown keys {sorted(extra)}")
427
482
  justification = entry.get("justification")
@@ -429,19 +484,96 @@ def validate_access_requests(where: str, requests: Any, resolve: ExportsResolver
429
484
  raise ValueError(
430
485
  f"{at}.justification must say why the service needs {obj}; the customer reads it before approving"
431
486
  )
432
- if not isinstance(entry.get("required", False), bool):
433
- raise ValueError(f"{at}.required must be true or false")
487
+ _check_required(at, entry, explicit_required)
434
488
  permissions: list[str] = entry.get("permissions") or []
435
- if not _strings(permissions):
436
- raise ValueError(f"{at}.permissions must be a non-empty list of distinct names")
489
+ if not _strings(permissions) or not all(_PERMISSION_NAME.match(p) for p in permissions):
490
+ raise ValueError(
491
+ f"{at}.permissions must be a non-empty list of distinct permission names "
492
+ "(lowercase letters, digits and '_'; no wildcards)"
493
+ )
437
494
  options = parse_options(f"{at}.options", entry.get("options", ""))
438
495
  validate_limits(f"{at}.limits", entry.get("limits", {}))
439
- if resolve is None:
440
- continue
441
- declared = resolve(name)
442
- if declared is None:
443
- raise ValueError(f"{at}: {obj} is not a published service")
444
- check_claim(at, obj, permissions, options, parse_exports(f"{obj} exports", declared))
496
+ exports = None
497
+ if resource:
498
+ exports = RESOURCES[name]
499
+ check_resource(at, obj, permissions, options, entry.get("limits"))
500
+ if kind := next(
501
+ (o[ROOM_KIND] for other, o, _ in seen if other == obj and o[ROOM_KIND] == options[ROOM_KIND]), None
502
+ ):
503
+ raise ValueError(f"{at}: {obj} with {ROOM_KIND}={kind} is listed twice; a kind is requested once")
504
+ elif resolve is not None:
505
+ declared = resolve(name)
506
+ if declared is None:
507
+ raise ValueError(f"{at}: {obj} is not a published service")
508
+ exports = parse_exports(f"{obj} exports", declared)
509
+ check_claim(at, obj, permissions, options, exports)
510
+ for other_index, (other, other_options, _) in enumerate(seen):
511
+ if other == obj and _conflict(exports, options, other_options) is None:
512
+ raise ValueError(
513
+ f"{at}: {obj} is listed twice; requests of one object must each fix an option "
514
+ f"to a different value (kind=chat, kind=feed), or the customer can't say which "
515
+ f"one they approve (see [{other_index}])"
516
+ )
517
+ seen.append((obj, options, exports))
518
+
519
+
520
+ def _check_required(at: str, entry: dict[str, Any], explicit: bool) -> None:
521
+ if "required" in entry:
522
+ if not isinstance(entry["required"], bool):
523
+ raise ValueError(f"{at}.required must be true or false")
524
+ elif explicit:
525
+ raise ValueError(f"{at}.required must be true or false: say whether the customer may decline it")
526
+
527
+
528
+ def _conflict(exports: Exports | None, a: dict[str, str], b: dict[str, str]) -> str | None:
529
+ """The first option ``a`` and ``b`` both set, to different values, or
530
+ ``None``. Values are compared as the target's ``exports`` type them
531
+ (``100`` and ``0100`` are one integer); without exports, as written."""
532
+ properties = exports.options.get("properties", {}) if exports else {}
533
+ for name in sorted(set(a) & set(b)):
534
+ prop = properties.get(name, {})
535
+ if _typed(prop, a[name]) != _typed(prop, b[name]):
536
+ return name
537
+ return None
538
+
539
+
540
+ def _label(request: dict[str, Any]) -> str:
541
+ """A request as the customer tells it apart: its object, and its fixed options."""
542
+ return f"{request['object']} ({request['options']})" if request.get("options") else str(request["object"])
543
+
544
+
545
+ def match_request(
546
+ where: str, requests: list[dict[str, Any]], entry: dict[str, Any], exports: Exports | None = None
547
+ ) -> int:
548
+ """The index of the request in ``requests`` (already valid) that ``entry``,
549
+ an approval or a stored policy entry, approves.
550
+
551
+ It is the request of the same object whose fixed options the entry does
552
+ not contradict: one the entry repeats, or leaves out. Requests of one
553
+ object each fix an option to a different value, so only an entry that
554
+ leaves all of those out can fit more than one; it is refused, naming the
555
+ option that tells them apart. Raises ``ValueError``.
556
+ """
557
+ obj = entry.get("object")
558
+ options = parse_options(f"{where}.options", entry.get("options", ""))
559
+ same = [i for i, request in enumerate(requests) if request["object"] == obj]
560
+ if not same:
561
+ raise ValueError(f"{where}: {obj} is not requested")
562
+ fixed = {i: parse_options("options", requests[i].get("options", "")) for i in same}
563
+ fitting = [i for i in same if _conflict(exports, fixed[i], options) is None]
564
+ if not fitting:
565
+ if len(same) == 1:
566
+ name = _conflict(exports, fixed[same[0]], options)
567
+ assert name is not None
568
+ raise ValueError(f"{where}.options.{name}: the service fixes it to {fixed[same[0]][name]!r}")
569
+ raise ValueError(
570
+ f"{where}: no request of {obj} has these options; the service requests "
571
+ + ", ".join(_label(requests[i]) for i in same)
572
+ )
573
+ if len(fitting) > 1:
574
+ name = _conflict(exports, fixed[fitting[0]], fixed[fitting[1]])
575
+ raise ValueError(f"{where}.options: {obj} is requested {len(fitting)} times; set {name} to say which")
576
+ return fitting[0]
445
577
 
446
578
 
447
579
  def _service_wildcard_refusal(at: str, verb: str) -> str:
@@ -480,6 +612,29 @@ def check_claim(where: str, obj: str, permissions: list[str], options: dict[str,
480
612
  raise ValueError(f"{where}.options: {error}")
481
613
 
482
614
 
615
+ def check_resource(where: str, obj: str, permissions: list[str], options: dict[str, str], limits: Any = None) -> None:
616
+ """Refuse a claim on ``obj`` (``resource:<name>``) that the resource does
617
+ not allow, for a request and for a policy entry alike.
618
+
619
+ A room claim names its ``kind`` in its options; its permissions are some
620
+ of those the kind allows, and ``max_members`` (a positive integer) only
621
+ caps a room the customer creates. A resource is provisioned, not called,
622
+ so it takes no limits.
623
+ """
624
+ check_claim(where, obj, permissions, options, RESOURCES[obj.removeprefix(RESOURCE_PREFIX)])
625
+ if limits:
626
+ raise ValueError(f"{where}.limits: {obj} is provisioned, not called; it takes no limits")
627
+ kind = options.get(ROOM_KIND)
628
+ if kind is None:
629
+ raise ValueError(
630
+ f"{where}.options must set {ROOM_KIND} (one of {list(ROOM_KINDS)}): a room's kind is its identity"
631
+ )
632
+ if not set(permissions) <= ROOM_KINDS[kind]:
633
+ raise ValueError(f"{where}.permissions: a {kind} room allows only {sorted(ROOM_KINDS[kind])}")
634
+ if ROOM_MAX_MEMBERS in options and "create" not in ROOM_KINDS[kind]:
635
+ raise ValueError(f"{where}.options.{ROOM_MAX_MEMBERS}: only a room the customer creates takes a member cap")
636
+
637
+
483
638
  def validate_channel_access_requests(config: Any, resolve: ExportsResolver | None = None) -> None:
484
639
  """Refuse the ``customer_access_requests`` of any channel of an ``upstream_access_config``
485
640
  unless valid. Each channel declares its own (unitysvc/unitysvc#2726)."""
@@ -492,31 +647,35 @@ def validate_channel_access_requests(config: Any, resolve: ExportsResolver | Non
492
647
 
493
648
  def build_policy(requests: Any, approvals: Any, resolve: ExportsResolver | None = None) -> list[dict[str, Any]]:
494
649
  """The key policy a customer's ``approvals`` of a channel's ``requests``
495
- make (unitysvc/unitysvc#2766).
650
+ make (unitysvc/unitysvc#2766, #2831).
496
651
 
497
652
  ``requests`` is the channel's ``customer_access_requests``; ``approvals``
498
653
  lists the requests the customer approves, each ``{"object", "permissions",
499
654
  "options", "limits"}`` (the ``apikey`` entry only ``{"object", "limits"}``).
500
- Each approval names a requested object, at most once; its permissions are
501
- some of those requested; every ``required`` request is approved. The
502
- customer sets options and limits: a request's own only pre-fill them, so
503
- they are checked against the target's ``exports`` (with ``resolve``) and
504
- :func:`validate_limits`, not against the request. A key lifespan may only
505
- be shortened. Returns the approvals as policy entries, without empty
655
+ Each approval matches one request (:func:`match_request`), at most once,
656
+ and every ``required`` request is approved. An approved request keeps
657
+ exactly its permissions and its fixed options: the approval may repeat
658
+ them, or leave the options out, but not change them. Beside them the
659
+ customer sets the options the request leaves open and the limits, checked
660
+ against the target's ``exports`` (with ``resolve``) and
661
+ :func:`validate_limits`; a request's limits only pre-fill the form. A key
662
+ lifespan may only be shortened. Returns the approvals as policy entries,
663
+ their options in one canonical query string (names sorted), without empty
506
664
  ``options`` / ``limits``. Raises ``ValueError``.
507
665
 
508
666
  The customer may also add, at most once and without a request, this
509
667
  enrollment's own limits: ``{"object": "enrollment", "limits": {...}}``,
510
668
  with at least one limit and nothing else (unitysvc/unitysvc#2770). And an
511
- approval of a service may select one of the customer's enrollments of it
512
- (``"enrollment": "<CODE>"``, a chain enrollment): a canonical code, and no
513
- ``options``. The caller checks the enrollment is the customer's.
669
+ approval of a request that fixes no options may select one of the
670
+ customer's enrollments of its service (``"enrollment": "<CODE>"``, a chain
671
+ enrollment): a canonical code, and no ``options``. The caller checks the
672
+ enrollment is the customer's.
514
673
  """
515
- validate_access_requests("requests", requests)
516
- requested = {entry["object"]: entry for entry in requests}
674
+ validate_access_requests("requests", requests, explicit_required=False)
517
675
  if not isinstance(approvals, list):
518
676
  raise ValueError("approvals must be a list of approved requests")
519
677
  policy: list[dict[str, Any]] = []
678
+ approved: set[int] = set()
520
679
  for index, approval in enumerate(approvals):
521
680
  at = f"approvals[{index}]"
522
681
  if not isinstance(approval, dict) or not isinstance(approval.get("object"), str):
@@ -529,56 +688,75 @@ def build_policy(requests: Any, approvals: Any, resolve: ExportsResolver | None
529
688
  raise ValueError(f"{at}: {obj} is listed twice")
530
689
  policy.append(_enrollment_entry(at, approval))
531
690
  continue
532
- request = requested.get(obj)
533
- if request is None:
534
- raise ValueError(f"{at}: {obj} is not requested")
535
- if any(entry["object"] == obj for entry in policy):
536
- raise ValueError(f"{at}: {obj} is approved twice")
537
691
  if obj == APIKEY_OBJECT:
538
692
  if extra := set(approval) - {"object", "limits"}:
539
693
  raise ValueError(f"{at}: unknown keys {sorted(extra)} (the {APIKEY_OBJECT} entry takes only limits)")
694
+ elif extra := set(approval) - _POLICY_KEYS - {ENROLLMENT_KEY}:
695
+ raise ValueError(f"{at}: unknown keys {sorted(extra)}")
696
+ exports = None
697
+ resource = obj.startswith(RESOURCE_PREFIX) and obj.removeprefix(RESOURCE_PREFIX) in RESOURCES
698
+ if resource:
699
+ exports = RESOURCES[obj.removeprefix(RESOURCE_PREFIX)]
700
+ elif resolve is not None and obj.startswith(SERVICE_PREFIX) and any(r["object"] == obj for r in requests):
701
+ declared = resolve(obj.removeprefix(SERVICE_PREFIX))
702
+ if declared is None:
703
+ raise ValueError(f"{at}: {obj} is not a published service")
704
+ exports = parse_exports(f"{obj} exports", declared)
705
+ matched = match_request(at, requests, approval, exports)
706
+ if matched in approved:
707
+ raise ValueError(f"{at}: {_label(requests[matched])} is approved twice")
708
+ approved.add(matched)
709
+ request = requests[matched]
710
+ if obj == APIKEY_OBJECT:
540
711
  validate_limits(f"{at}.limits", approval.get("limits"), apikey=True)
541
712
  asked = request["limits"][API_KEY_LIFESPAN]
542
713
  if approval["limits"][API_KEY_LIFESPAN] > asked:
543
714
  raise ValueError(f"{at}.limits.{API_KEY_LIFESPAN}: the service asks for at most {asked} seconds")
544
715
  policy.append({"object": obj, "limits": dict(approval["limits"])})
545
716
  continue
546
- if extra := set(approval) - _POLICY_KEYS - {ENROLLMENT_KEY}:
547
- raise ValueError(f"{at}: unknown keys {sorted(extra)}")
717
+ fixed = parse_options("options", request.get("options", ""))
548
718
  code = approval.get(ENROLLMENT_KEY)
549
719
  if ENROLLMENT_KEY in approval:
550
720
  if not isinstance(code, str) or not _ENROLLMENT_CODE.match(code):
551
721
  raise ValueError(f"{at}.{ENROLLMENT_KEY} must be an enrollment code, like JYY87Y")
552
722
  if approval.get("options"):
553
723
  raise ValueError(f"{at}.options: an enrollment's params are fixed; it takes no options")
724
+ if fixed:
725
+ raise ValueError(
726
+ f"{at}.{ENROLLMENT_KEY}: the service fixes options of {obj} ({request['options']}), "
727
+ "which an enrollment cannot carry; approve it without one"
728
+ )
554
729
  permissions: list[str] = approval.get("permissions") or []
555
- if not _strings(permissions):
556
- raise ValueError(f"{at}.permissions must be a non-empty list of distinct names")
557
- if not set(permissions) <= set(request["permissions"]):
558
- raise ValueError(f"{at}.permissions: the service requests only {request['permissions']}")
559
- options_text = approval.get("options", "")
560
- options = parse_options(f"{at}.options", options_text)
730
+ if not _strings(permissions) or set(permissions) != set(request["permissions"]):
731
+ raise ValueError(f"{at}.permissions: the service requests exactly {request['permissions']}")
732
+ # The request's values win over an equal value written another way.
733
+ options = {**parse_options(f"{at}.options", approval.get("options", "")), **fixed}
561
734
  limits = approval.get("limits", {})
562
735
  validate_limits(f"{at}.limits", limits)
563
- if resolve is not None:
564
- declared = resolve(obj.removeprefix(SERVICE_PREFIX))
565
- if declared is None:
566
- raise ValueError(f"{at}: {obj} is not a published service")
567
- check_claim(at, obj, permissions, options, parse_exports(f"{obj} exports", declared))
736
+ if resource:
737
+ check_resource(at, obj, permissions, options, limits)
738
+ elif exports is not None:
739
+ check_claim(at, obj, permissions, options, exports)
568
740
  entry: dict[str, Any] = {"object": obj, "permissions": list(permissions)}
569
741
  if code is not None:
570
742
  entry[ENROLLMENT_KEY] = code
571
743
  if options:
572
- entry["options"] = options_text
744
+ entry["options"] = options_text(options)
573
745
  if limits:
574
746
  entry["limits"] = dict(limits)
575
747
  policy.append(entry)
576
- approved = {entry["object"] for entry in policy}
577
- if missing := sorted(obj for obj, request in requested.items() if request.get("required") and obj not in approved):
748
+ if missing := [_label(r) for i, r in enumerate(requests) if r.get("required") and i not in approved]:
578
749
  raise ValueError(f"approvals: the service requires {', '.join(missing)}")
579
750
  return policy
580
751
 
581
752
 
753
+ def options_text(options: dict[str, str]) -> str:
754
+ """``options`` as the one query string a policy stores: names sorted, and
755
+ only what must be escaped escaped (``service=labs/llm-fast``,
756
+ ``profile=a,b``), so equal options are equal text."""
757
+ return urlencode(sorted(options.items()), safe=",/")
758
+
759
+
582
760
  def _enrollment_entry(at: str, approval: dict[str, Any]) -> dict[str, Any]:
583
761
  """This enrollment's own entry: limits only, and at least one."""
584
762
  if extra := set(approval) - {"object", "limits"}: