From 95619848f76be85cb03768d84fb28d82c0c3c6c8 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 12 Nov 2026 13:32:10 +0700 Subject: [PATCH 01/34] fix(identity): admit explicit browser grants across resources Signed-off-by: Jeremi Joslin --- crates/registry-thunderid-tooling/README.md | 9 +- .../src/identity_deployment.rs | 6 +- .../src/identity_generate.rs | 88 +++++++--- .../src/identity_generate_tests.rs | 164 ++++++++++++++++++ .../schemas/identity-deployment.schema.json | 3 +- 5 files changed, 239 insertions(+), 31 deletions(-) diff --git a/crates/registry-thunderid-tooling/README.md b/crates/registry-thunderid-tooling/README.md index 1ab1d43fd4..7518aee6ba 100644 --- a/crates/registry-thunderid-tooling/README.md +++ b/crates/registry-thunderid-tooling/README.md @@ -235,9 +235,12 @@ resolves no secret. issuer identically. - The deployment file states the organization unit, each client's public JWKS file and grants, browser applications, users with explicit claims, extension - user types, and a `secret:env/NAME` reference for every secret. A grant to a - client a product does not admit, an unknown claim, or a JWK carrying `d`, - `p`, `q`, `dp`, `dq` or `qi` is refused. + user types, and a `secret:env/NAME` reference for every secret. A browser + application's `product` remains its one default token audience. Its explicit + grants may authorize the same admitted client for other products, and a user + reaches such a product only when an eligible application grants the user's + exact profile there. A grant to a client a product does not admit, an unknown + claim, or a JWK carrying `d`, `p`, `q`, `dp`, `dq` or `qi` is refused. - The output directory must not exist. It holds `deployment.yaml` (server members to merge into the environment's own file), `resources/resources.yaml` (one multi-document file), `registry-schema/agent-type.yaml` and diff --git a/crates/registry-thunderid-tooling/src/identity_deployment.rs b/crates/registry-thunderid-tooling/src/identity_deployment.rs index 880fdd96fd..7e35dc5c06 100644 --- a/crates/registry-thunderid-tooling/src/identity_deployment.rs +++ b/crates/registry-thunderid-tooling/src/identity_deployment.rs @@ -107,11 +107,15 @@ pub struct BrowserApp { pub origin: String, #[serde(deserialize_with = "set")] pub redirect_uris: Vec, - /// The `product` whose audience the application's tokens carry. + /// The `product` whose audience tokens carry by default. A request still + /// produces a token for one audience. pub product: String, /// Claims the application's tokens carry from the signed-in user. #[serde(deserialize_with = "set")] pub token_attributes: Vec, + /// Profiles granted to the application. A grant outside `product` also + /// lets an eligible signed-in user's matching profile reach that product; + /// it does not change the default audience. pub grants: Vec, /// Extension user types (ids of `userTypes`) that may sign in, beside /// the generated `RegistryPerson`. diff --git a/crates/registry-thunderid-tooling/src/identity_generate.rs b/crates/registry-thunderid-tooling/src/identity_generate.rs index ae224a70f3..ab32d3dfb3 100644 --- a/crates/registry-thunderid-tooling/src/identity_generate.rs +++ b/crates/registry-thunderid-tooling/src/identity_generate.rs @@ -142,15 +142,16 @@ fn admits_any(product: &ProductFacts, profile: &AccessProfile, clients: &[String }) } -/// Resolve grants against the merged facts. `clients` are the client ids -/// whose tokens reach the product for this principal: the client itself, or -/// for a user every browser application that signs them in. +/// Resolve grants against the merged facts. `reaching` returns the client ids +/// whose tokens reach one product profile for this principal: the client +/// itself, or for a user every browser application authorized to carry that +/// profile and sign them in. fn resolve_grants<'a>( findings: &mut Findings<'_>, facts: &'a MergedFacts, pointer: &str, grants: &'a [Grant], - reaching: &dyn Fn(&str) -> Vec, + reaching: &dyn Fn(&str, &str) -> Vec, ) -> Granted<'a> { let mut resolved = Vec::new(); for (index, grant) in grants.iter().enumerate() { @@ -174,7 +175,7 @@ fn resolve_grants<'a>( ); continue; }; - let reachable = reaching(product); + let reachable = reaching(product, &profile.id); if !reachable.iter().any(|client| { product_facts.allowed_clients.admits(client) && requester_allows(profile, client) }) { @@ -182,7 +183,7 @@ fn resolve_grants<'a>( &format!("{at}/accessProfiles/{position}"), "identity.deployment.client-not-admitted", "the product does not admit the client that would present this profile", - "Admit the client in the product's configuration and regenerate its facts, list the user's type on a browser application of the product, or remove the grant.", + "Admit the client in the product's configuration and regenerate its facts. For a user, list its type on a browser application and grant that application the same profile outside its default product. Otherwise remove the grant.", ); continue; } @@ -493,9 +494,10 @@ fn settle_actor_kind( /// A profile none of the principal's `reaching` clients can present is /// never selected for it, whatever its claims: Messaging resolves a profile /// by client id before it reads a scope, so two profiles may require the -/// same scopes for disjoint requester clients. A user reaches a product -/// through any of that product's browser applications that sign in the -/// user's type, as for its grants. +/// same scopes for disjoint requester clients. A user's native client reaches +/// every profile the product admits once an eligible browser application names +/// it as the default or carries any grant for it. The API sees the client and +/// claims, not which declaration made that application eligible. /// /// That skip is safe only while every product that selects by claims states a /// selector on each such profile. Evidence does: it requires at least one @@ -1007,16 +1009,38 @@ pub fn generate(inputs: &Inputs<'_>) -> Result { .map(|server| server.id.clone()) }; - // A user reaches a product only through that product's browser - // applications that sign in the user's type: every application admits - // `RegistryPerson`, and an extension type only where its `userTypes` - // list it. - let user_reaching = |user_type: Option<&str>, product: &str| { + // A user reaches the application's default product as before. A different + // product is reachable only where the application explicitly grants that + // same profile. In both cases the application must sign in the user's + // type: every application admits `RegistryPerson`, and an extension type + // only where its `userTypes` lists it. + let user_reaching = |user_type: Option<&str>, product: &str, profile: &str| { deployment .browser_apps .iter() .filter(|app| { - app.product == product + let product_reachable = app.product == product + || app.grants.iter().any(|grant| { + grant.product == product + && grant + .access_profiles + .iter() + .any(|granted| granted == profile) + }); + product_reachable + && user_type.is_none_or(|wanted| app.user_types.iter().any(|id| id == wanted)) + }) + .map(|app| app.id.clone()) + .collect::>() + }; + let user_native_reaching = |user_type: Option<&str>, product: &str| { + deployment + .browser_apps + .iter() + .filter(|app| { + let product_reachable = app.product == product + || app.grants.iter().any(|grant| grant.product == product); + product_reachable && user_type.is_none_or(|wanted| app.user_types.iter().any(|id| id == wanted)) }) .map(|app| app.id.clone()) @@ -1036,7 +1060,7 @@ pub fn generate(inputs: &Inputs<'_>) -> Result { for (index, client) in deployment.clients.iter().enumerate() { let pointer = format!("/clients/{index}"); - let reaching = |_: &str| vec![client.id.clone()]; + let reaching = |_: &str, _: &str| vec![client.id.clone()]; let found_before = findings.found.len(); let granted = resolve_grants(&mut findings, &facts, &pointer, &client.grants, &reaching); let resolved = findings.found.len() == found_before; @@ -1074,6 +1098,7 @@ pub fn generate(inputs: &Inputs<'_>) -> Result { check_refused_claims(&mut findings, &pointer, &granted, &attributes); } if resolved && settled { + let selection_reaching = |_: &str| vec![client.id.clone()]; check_selection( &mut findings, &facts, @@ -1081,7 +1106,7 @@ pub fn generate(inputs: &Inputs<'_>) -> Result { &attributes, &granted, false, - &reaching, + &selection_reaching, ); check_scope_claims(&mut findings, &facts, &pointer, &attributes, &granted); } @@ -1173,7 +1198,7 @@ pub fn generate(inputs: &Inputs<'_>) -> Result { for (index, app) in deployment.browser_apps.iter().enumerate() { let pointer = format!("/browserApps/{index}"); - let reaching = |_: &str| vec![app.id.clone()]; + let reaching = |_: &str, _: &str| vec![app.id.clone()]; let granted = resolve_grants(&mut findings, &facts, &pointer, &app.grants, &reaching); if granted .iter() @@ -1206,15 +1231,22 @@ pub fn generate(inputs: &Inputs<'_>) -> Result { } // Every user is given registry_actor_kind when a product reads it // (BReg refuses a non-delegated token without it), and the purpose - // their grants give when the application's product requires one - // (BReg refuses a token for such a profile without it). The + // their grants give when any product reachable through the application + // requires one (BReg refuses a token for such a profile without it). The // application's tokens carry both as a machine client's do, listed // or not. - let reads_purpose = reads_purpose(product) + let default_reads_purpose = reads_purpose(product) && product .access_profiles .values() .any(|profile| profile.exchange.is_none() && !profile.purposes.is_empty()); + let granted_reads_purpose = granted.iter().any(|(granted_product, profile)| { + *granted_product != app.product + && profile.exchange.is_none() + && !profile.purposes.is_empty() + && reads_purpose(&facts.products[*granted_product]) + }); + let projects_purpose = default_reads_purpose || granted_reads_purpose; let required = [ ( ACTOR_KIND, @@ -1225,9 +1257,9 @@ pub fn generate(inputs: &Inputs<'_>) -> Result { ), ( PURPOSE, - reads_purpose, + projects_purpose, "identity.deployment.purpose-not-projected", - "the application lists the most token attributes it may carry, so its tokens cannot also carry registry_purpose, which its product requires", + "the application lists the most token attributes it may carry, so its tokens cannot also carry registry_purpose, which a reachable product requires", "List registry_purpose among the token attributes, or remove one so the generator can add it.", ), ]; @@ -1282,7 +1314,9 @@ pub fn generate(inputs: &Inputs<'_>) -> Result { for (index, user) in deployment.users.iter().enumerate() { let pointer = format!("/users/{index}"); - let reaching = |product: &str| user_reaching(user.user_type.as_deref(), product); + let reaching = |product: &str, profile: &str| { + user_reaching(user.user_type.as_deref(), product, profile) + }; let found_before = findings.found.len(); let granted = resolve_grants(&mut findings, &facts, &pointer, &user.grants, &reaching); let resolved = findings.found.len() == found_before; @@ -1329,7 +1363,7 @@ pub fn generate(inputs: &Inputs<'_>) -> Result { if profile.exchange.is_some() { continue; } - for app in user_reaching(user.user_type.as_deref(), product) { + for app in user_reaching(user.user_type.as_deref(), product, &profile.id) { projected_requirements .entry(app) .or_default() @@ -1337,6 +1371,8 @@ pub fn generate(inputs: &Inputs<'_>) -> Result { } } if resolved { + let selection_reaching = + |product: &str| user_native_reaching(user.user_type.as_deref(), product); check_selection( &mut findings, &facts, @@ -1344,7 +1380,7 @@ pub fn generate(inputs: &Inputs<'_>) -> Result { &user_claims, &granted, true, - &reaching, + &selection_reaching, ); check_scope_claims(&mut findings, &facts, &pointer, &user_claims, &granted); } diff --git a/crates/registry-thunderid-tooling/src/identity_generate_tests.rs b/crates/registry-thunderid-tooling/src/identity_generate_tests.rs index cada7ea333..1a89ad0566 100644 --- a/crates/registry-thunderid-tooling/src/identity_generate_tests.rs +++ b/crates/registry-thunderid-tooling/src/identity_generate_tests.rs @@ -620,6 +620,68 @@ fn of_type<'a>(documents: &'a [serde_json::Value], kind: &str) -> Vec<&'a serde_ .collect() } +fn role_permissions( + documents: &[serde_json::Value], + role_name: &str, + audience: &str, +) -> Vec { + let server = of_type(documents, "resource_server") + .into_iter() + .find(|server| server["identifier"] == audience) + .expect("resource server"); + let role = of_type(documents, "role") + .into_iter() + .find(|role| role["name"] == role_name) + .expect("role"); + role["permissions"] + .as_array() + .expect("role permissions") + .iter() + .find(|permission| permission["resourceServerId"] == server["id"]) + .expect("resource permission")["permissions"] + .as_array() + .expect("permission names") + .iter() + .map(|permission| permission.as_str().expect("permission").to_owned()) + .collect() +} + +const CASEWORK_BROWSER: &str = "apiVersion: id.registrystack.org/formats/platform/identity-facts/v1\nkind: PlatformIdentityFacts\nproduct: casework\nissuer: https://id.registry.example\naudience: urn:casework:example\nallowedClients:\n - staff-portal\nclaims:\n registry_actor_kind: string\naccessProfiles:\n - id: review\n scopes: [casework:review]\n actorKind: human\n - id: intake\n scopes: [casework:intake]\n actorKind: human\n"; + +fn cross_resource_browser_case(app_profile: &str) -> Case { + let mut case = case(); + case.facts + .push(("casework".into(), CASEWORK_BROWSER.into())); + case.deployment = case + .deployment + .replace( + " - product: breg\n accessProfiles: [case-read]\nusers:\n", + &format!( + " - product: breg\n accessProfiles: [case-read]\n - product: casework\n accessProfiles: [{app_profile}]\nusers:\n" + ), + ) + .replace( + " - product: breg\n accessProfiles: [case-read, case-write]\n - id: farmer-one\n", + " - product: breg\n accessProfiles: [case-read, case-write]\n - product: casework\n accessProfiles: [review]\n - id: farmer-one\n", + ); + case +} + +fn reverse_cross_resource_browser_case() -> Case { + let mut case = cross_resource_browser_case("review"); + case.deployment = case + .deployment + .replace( + " redirectUris: [https://staff.registry.example/auth/callback]\n product: breg\n", + " redirectUris: [https://staff.registry.example/auth/callback]\n product: casework\n", + ) + .replace( + " accessProfiles: [case-read, case-write]\n - product: casework", + " accessProfiles: [case-read]\n - product: casework", + ); + case +} + #[test] fn machine_clients_carry_public_keys_roles_claims_and_the_crates_ids() { let generated = case().run().unwrap(); @@ -733,6 +795,108 @@ fn browser_apps_users_and_extension_types_render_without_secrets_or_a_logo_by_de assert_eq!(organization[0]["handle"], "registry"); } +#[test] +fn one_browser_app_carries_default_and_explicit_cross_resource_grants() { + let generated = cross_resource_browser_case("review") + .run() + .expect("the admitted browser app reaches both products"); + let documents = resources(&generated); + let app = of_type(&documents, "application")[0]; + assert_eq!( + app["inboundAuthConfig"][0]["config"]["token"]["accessToken"]["defaultAudience"], + "urn:breg:example", + "BrowserApp.product remains the token's one default audience" + ); + assert_eq!( + role_permissions(&documents, "Browser staff-portal", "urn:breg:example"), + ["records:get", "records:search"] + ); + assert_eq!( + role_permissions( + &documents, + "Browser staff-portal", + "urn:casework:example" + ), + ["casework:review"] + ); + assert_eq!( + role_permissions(&documents, "User officer-one", "urn:breg:example"), + ["records:get", "records:patch", "records:search"], + "the default product still lets a user's grant exceed the app's own profile" + ); + assert_eq!( + role_permissions(&documents, "User officer-one", "urn:casework:example"), + ["casework:review"] + ); +} + +#[test] +fn a_cross_resource_user_grant_requires_the_apps_same_access_profile() { + assert_eq!( + cross_resource_browser_case("intake").refusal(), + ["identity.deployment.client-not-admitted"] + ); +} + +#[test] +fn a_cross_resource_apps_client_checks_every_profile_selected_by_user_claims() { + let mut case = cross_resource_browser_case("review"); + case.facts[2].1 = case.facts[2] + .1 + .replace( + " registry_actor_kind: string\n", + " registry_actor_kind: string\n casework_role: string\n", + ) + .replace( + " actorKind: human\n - id: intake", + " actorKind: human\n selectedBy: {casework_role: [staff]}\n - id: intake", + ) + .replace( + " scopes: [casework:intake]\n actorKind: human\n", + " scopes: [casework:intake]\n actorKind: human\n selectedBy: {casework_role: [staff]}\n", + ); + case.deployment = case + .deployment + .replace( + "tokenAttributes: [registry_actor_kind, registry_role]", + "tokenAttributes: [registry_actor_kind, registry_role, casework_role]", + ) + .replace( + " registry_role: officer\n", + " registry_role: officer\n casework_role: staff\n", + ); + assert_eq!( + case.refusal(), + ["identity.deployment.claims-select-ungranted-profile"] + ); +} + +#[test] +fn a_non_default_purpose_grant_is_projected_without_changing_the_default_audience() { + let generated = reverse_cross_resource_browser_case() + .run() + .expect("the reverse cross-resource deployment generates"); + let documents = resources(&generated); + let app = of_type(&documents, "application")[0]; + let token = &app["inboundAuthConfig"][0]["config"]["token"]; + assert_eq!( + token["accessToken"]["defaultAudience"], + "urn:casework:example" + ); + for projection in [ + &token["accessToken"]["userConfig"]["attributes"], + &token["idToken"]["userAttributes"], + ] { + assert!( + projection + .as_array() + .expect("projected attributes") + .contains(&serde_json::json!("registry_purpose")), + "the BReg grant's purpose must be projected" + ); + } +} + #[test] fn the_receipt_records_inputs_subs_the_pin_and_required_environment() { let generated = case().run().unwrap(); diff --git a/products/platform/schemas/identity-deployment.schema.json b/products/platform/schemas/identity-deployment.schema.json index bd24d1e2fb..352da512f2 100644 --- a/products/platform/schemas/identity-deployment.schema.json +++ b/products/platform/schemas/identity-deployment.schema.json @@ -13,6 +13,7 @@ ] }, "grants": { + "description": "Profiles granted to the application. A grant outside `product` also\nlets an eligible signed-in user's matching profile reach that product;\nit does not change the default audience.", "items": { "$ref": "#/$defs/Grant" }, @@ -39,7 +40,7 @@ "type": "string" }, "product": { - "description": "The `product` whose audience the application's tokens carry.", + "description": "The `product` whose audience tokens carry by default. A request still\nproduces a token for one audience.", "type": "string" }, "redirectUris": { From b59f47070945f980a795831afe5cbb90259b5083 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 12 Nov 2026 14:42:55 +0700 Subject: [PATCH 02/34] feat(identity): isolate generated browser SSO flows Signed-off-by: Jeremi Joslin --- crates/registry-thunderid-tooling/README.md | 14 +- .../expected/resources/resources.yaml | 173 +++++++++- .../src/description.rs | 31 +- .../src/identity_generate.rs | 27 +- .../src/identity_generate_tests.rs | 18 +- .../registry-thunderid-tooling/src/local.rs | 12 + .../registry-thunderid-tooling/src/render.rs | 313 +++++++++++++++++- .../src/render_golden_tests.rs | 2 +- 8 files changed, 557 insertions(+), 33 deletions(-) diff --git a/crates/registry-thunderid-tooling/README.md b/crates/registry-thunderid-tooling/README.md index 7518aee6ba..4ea3811472 100644 --- a/crates/registry-thunderid-tooling/README.md +++ b/crates/registry-thunderid-tooling/README.md @@ -247,13 +247,23 @@ resolves no secret. `registry-schema/agents/`, and `identity-receipt.json` (input digests, client id to `sub`, user id to `sub`, the ThunderID pin, required environment variable names). Secrets render as `{{.NAME}}` placeholders; nothing secret is written. +- Each browser application receives its own deterministic native Basic SSO + authentication flow with an application-scoped SSO session. The flow checks + for a reusable session and prompts for credentials when needed. Both paths + pass through the session checkpoint and resource authorization before issuing + the authentication assertion. +- Browser applications share one generated conditional sign-out graph. Each + application pins that graph explicitly, while ThunderID resolves and clears + the session belonging to that application's authentication flow. A logout + without an ID-token hint requires confirmation. The exact application + `origin` is the only generated post-logout return URI. - Identifiers use the crate's `local::agent_id` and scope-tree formulas seeded by the issuer, so output is byte-identical across runs. Regenerate the golden tree under `fixtures/identity/expected` with `REGISTRY_UPDATE_GOLDEN=1 cargo test -p registry-thunderid-tooling` and review -the diff. Development mode (`render::render`) is unchanged and guarded by a -byte-level digest test. +the diff. Development mode (`render::render`) is guarded by a byte-level digest +test. The facts and deployment formats have generated JSON Schemas in `products/platform/schemas` (`identity-facts.schema.json`, diff --git a/crates/registry-thunderid-tooling/fixtures/identity/expected/resources/resources.yaml b/crates/registry-thunderid-tooling/fixtures/identity/expected/resources/resources.yaml index 991ecf6ad2..32aa4397b8 100644 --- a/crates/registry-thunderid-tooling/fixtures/identity/expected/resources/resources.yaml +++ b/crates/registry-thunderid-tooling/fixtures/identity/expected/resources/resources.yaml @@ -753,10 +753,180 @@ ouHandle: registry resource_type: user type: Farmer --- +flowType: SIGNOUT +handle: registry-signout-0ba51a29-b279-7702-852b-804373e53924 +id: 0ba51a29-b279-7702-852b-804373e53924 +name: Registry browser sign-out +nodes: +- id: start + onSuccess: session_signout + type: START +- executor: + name: SessionSignOutExecutor + id: session_signout + onIncomplete: prompt_confirm + onSuccess: end + properties: + promptOnSignOut: true + type: TASK_EXECUTION +- id: prompt_confirm + meta: + components: + - align: center + category: DISPLAY + id: text_signout_title + label: '{{ t(signout:forms.confirm.title) }}' + resourceType: ELEMENT + type: TEXT + variant: HEADING_1 + - align: center + category: DISPLAY + id: text_signout_desc + label: '{{ t(signout:forms.confirm.description) }}' + resourceType: ELEMENT + type: TEXT + variant: BODY_1 + - category: BLOCK + components: + - actionType: CONFIRM + category: ACTION + eventType: SUBMIT + id: action_confirm + label: '{{ t(signout:forms.confirm.actions.submit.label) }}' + resourceType: ELEMENT + type: ACTION + variant: PRIMARY + id: block_signout + resourceType: ELEMENT + type: BLOCK + prompts: + - action: + nextNode: session_signout + ref: action_confirm + type: CONFIRM + type: PROMPT +- id: end + type: END +resource_type: flow +--- +flowType: AUTHENTICATION +handle: registry-auth-2abacd42-1674-7da5-8f7c-19c2f8c262f0 +id: 2abacd42-1674-7da5-8f7c-19c2f8c262f0 +name: staff-portal sign-in +nodes: +- id: start + onSuccess: sso_check + type: START +- executor: + name: SSOCheckExecutor + id: sso_check + onFailure: prompt_credentials + onSuccess: session + properties: + checkpointRef: session + type: TASK_EXECUTION +- id: prompt_credentials + meta: + components: + - alt: '{{ t(signin:images.app_logo.alt) }}' + category: DISPLAY + height: '60' + id: image + resourceType: ELEMENT + src: '{{ meta(application.logoUrl) }}' + type: IMAGE + width: '' + - align: center + category: DISPLAY + id: text_001 + label: '{{ t(signin:forms.credentials.title) }}' + resourceType: ELEMENT + type: TEXT + variant: HEADING_1 + - category: BLOCK + components: + - category: FIELD + hint: '' + id: input_001 + inputType: text + label: '{{ t(signin:forms.credentials.fields.username.label) }}' + placeholder: '{{ t(signin:forms.credentials.fields.username.placeholder) }}' + ref: username + required: true + resourceType: ELEMENT + type: TEXT_INPUT + - category: FIELD + hint: '' + id: input_002 + inputType: text + label: '{{ t(signin:forms.credentials.fields.password.label) }}' + placeholder: '{{ t(signin:forms.credentials.fields.password.placeholder) }}' + ref: password + required: true + resourceType: ELEMENT + type: PASSWORD_INPUT + - category: ACTION + eventType: SUBMIT + id: action_001 + label: '{{ t(signin:forms.credentials.actions.submit.label) }}' + resourceType: ELEMENT + type: ACTION + variant: PRIMARY + id: block_001 + resourceType: ELEMENT + type: BLOCK + prompts: + - action: + nextNode: credentials_auth + ref: action_001 + inputs: + - identifier: username + ref: input_001 + required: true + type: TEXT_INPUT + - identifier: password + ref: input_002 + required: true + type: PASSWORD_INPUT + type: PROMPT +- executor: + inputs: + - identifier: username + ref: input_001 + required: true + type: TEXT_INPUT + - identifier: password + ref: input_002 + required: true + type: PASSWORD_INPUT + name: CredentialsAuthExecutor + id: credentials_auth + onIncomplete: prompt_credentials + onSuccess: session + type: TASK_EXECUTION +- executor: + name: SessionExecutor + id: session + onSuccess: authorization_check + type: TASK_EXECUTION +- executor: + name: AuthorizationExecutor + id: authorization_check + onSuccess: auth_assert + type: TASK_EXECUTION +- executor: + name: AuthAssertExecutor + id: auth_assert + onSuccess: end + type: TASK_EXECUTION +- id: end + type: END +resource_type: flow +--- allowedUserTypes: - RegistryPerson - Farmer -authFlowId: 01900000-0000-7000-8000-000000000068 +authFlowId: 2abacd42-1674-7da5-8f7c-19c2f8c262f0 description: Browser application id: fbc5ffd9-a8ee-76c3-8d0f-443fe31ac655 inboundAuthConfig: @@ -796,6 +966,7 @@ layoutId: 019a05b7-1000-7000-8000-000000000002 name: staff-portal ouHandle: registry resource_type: application +signOutFlowId: 0ba51a29-b279-7702-852b-804373e53924 themeId: 019a05b7-1000-7000-8000-000000000001 type: fullstack url: https://staff.registry.example diff --git a/crates/registry-thunderid-tooling/src/description.rs b/crates/registry-thunderid-tooling/src/description.rs index 5a6ddb0ef5..4f7835ef65 100644 --- a/crates/registry-thunderid-tooling/src/description.rs +++ b/crates/registry-thunderid-tooling/src/description.rs @@ -922,35 +922,34 @@ impl IssuerDescription { } /// Every identifier the renderer derives for a native entity. - pub(crate) fn derived_ids(&self) -> Vec<&str> { - std::iter::once(self.organization_unit.id.as_str()) - .chain( - self.resource_servers - .iter() - .map(|server| server.id.as_str()), - ) - .chain(self.roles.iter().map(|role| role.id.as_str())) + pub(crate) fn derived_ids(&self) -> Vec { + std::iter::once(self.organization_unit.id.clone()) + .chain(self.resource_servers.iter().map(|server| server.id.clone())) + .chain(self.roles.iter().map(|role| role.id.clone())) .chain( self.machine_clients .iter() - .map(|client| client.agent_id.as_str()), + .map(|client| client.agent_id.clone()), ) .chain( self.compatibility_clients .iter() - .map(|client| client.agent_id.as_str()), + .map(|client| client.agent_id.clone()), ) + .chain(self.exchange_issuers.iter().map(|issuer| issuer.id.clone())) .chain( - self.exchange_issuers + self.interactive_applications .iter() - .map(|issuer| issuer.id.as_str()), + .map(|app| app.id.clone()), ) + .chain(self.interactive_applications.iter().map(|app| { + crate::local::application_authentication_flow_id(&self.session.id, &app.id) + })) .chain( - self.interactive_applications - .iter() - .map(|app| app.id.as_str()), + (!self.interactive_applications.is_empty()) + .then(|| crate::local::browser_sign_out_flow_id(&self.session.id)), ) - .chain(self.synthetic_users.iter().map(|user| user.id.as_str())) + .chain(self.synthetic_users.iter().map(|user| user.id.clone())) .collect() } } diff --git a/crates/registry-thunderid-tooling/src/identity_generate.rs b/crates/registry-thunderid-tooling/src/identity_generate.rs index ab32d3dfb3..59269db9b5 100644 --- a/crates/registry-thunderid-tooling/src/identity_generate.rs +++ b/crates/registry-thunderid-tooling/src/identity_generate.rs @@ -880,14 +880,15 @@ fn refused(document: &Document, found: Vec) -> ToolingError { } } -/// Every `{{` the output holds opens a placeholder this run emitted: each -/// `{{.NAME}}` form for the environment variables the deployment names -/// appears exactly once, and the output holds no other template opener or -/// closer. An input string that slipped through would add one, including a -/// verbatim copy of a placeholder this run emits. +/// Every `{{` the output holds opens either a secret placeholder this run +/// emitted or one of the renderer's fixed Gate expressions. Each appears at +/// its exact expected multiplicity, and the output holds no other template +/// opener or closer. An input string that slipped through would add one, +/// including a verbatim copy of an expected expression. fn assert_only_known_placeholders( files: &BTreeMap>, environment: &[String], + browser_applications: usize, ) -> Result<(), ToolingError> { let count = |needle: &str| -> usize { files @@ -899,7 +900,13 @@ fn assert_only_known_placeholders( let each_once = names .iter() .all(|name| count(&format!("{{{{.{name}}}}}")) == 1); - if !each_once || count("{{") != names.len() || count("}}") != names.len() { + let gate = crate::render::gate_template_expression_counts(browser_applications); + let fixed = gate.iter().map(|(_, expected)| expected).sum::(); + let exact_gate = gate + .iter() + .all(|(expression, expected)| count(expression) == *expected); + let expected = names.len() + fixed; + if !each_once || !exact_gate || count("{{") != expected || count("}}") != expected { return Err(ToolingError::InvalidRender { reason: "the output holds template syntax that is not a generated placeholder", }); @@ -1483,7 +1490,7 @@ pub fn generate(inputs: &Inputs<'_>) -> Result { extras .user_types .iter() - .map(|user_type| user_type.id.as_str()), + .map(|user_type| user_type.id.clone()), ), ) { return Err(ToolingError::InvalidDescription { @@ -1549,7 +1556,11 @@ pub fn generate(inputs: &Inputs<'_>) -> Result { receipt_text.push('\n'); files.insert(RECEIPT_FILE.to_owned(), receipt_text.into_bytes()); - assert_only_known_placeholders(&files, &required_environment)?; + assert_only_known_placeholders( + &files, + &required_environment, + description.interactive_applications.len(), + )?; let summary = Summary { issuer: facts.issuer.clone(), diff --git a/crates/registry-thunderid-tooling/src/identity_generate_tests.rs b/crates/registry-thunderid-tooling/src/identity_generate_tests.rs index 1a89ad0566..d2ca60e484 100644 --- a/crates/registry-thunderid-tooling/src/identity_generate_tests.rs +++ b/crates/registry-thunderid-tooling/src/identity_generate_tests.rs @@ -1362,15 +1362,27 @@ fn only_the_keys_member_of_a_key_file_is_accepted() { fn every_generated_placeholder_must_appear_exactly_once() { let one = |text: &str| BTreeMap::from([("a".to_owned(), text.as_bytes().to_vec())]); let names = ["SECRET_A".to_owned()]; - assert!(assert_only_known_placeholders(&one("x: '{{.SECRET_A}}'"), &names).is_ok()); + assert!(assert_only_known_placeholders(&one("x: '{{.SECRET_A}}'"), &names, 0).is_ok()); // A verbatim second copy of a placeholder this run emitted. assert!(assert_only_known_placeholders( &one("x: '{{.SECRET_A}}' y: '{{.SECRET_A}}'"), - &names + &names, + 0, ) .is_err()); // A placeholder that was meant to be emitted but is missing. - assert!(assert_only_known_placeholders(&one("x: plain"), &names).is_err()); + assert!(assert_only_known_placeholders(&one("x: plain"), &names, 0).is_err()); + + let mut browser = "x: '{{.SECRET_A}}'\n".to_owned(); + for (expression, expected) in crate::render::gate_template_expression_counts(1) { + for _ in 0..expected { + browser.push_str(expression); + browser.push('\n'); + } + } + assert!(assert_only_known_placeholders(&one(&browser), &names, 1).is_ok()); + browser.push_str("{{ t(signout:forms.confirm.title) }}\n"); + assert!(assert_only_known_placeholders(&one(&browser), &names, 1).is_err()); } #[test] diff --git a/crates/registry-thunderid-tooling/src/local.rs b/crates/registry-thunderid-tooling/src/local.rs index cd49f7b470..a67bed37b8 100644 --- a/crates/registry-thunderid-tooling/src/local.rs +++ b/crates/registry-thunderid-tooling/src/local.rs @@ -58,6 +58,18 @@ pub(crate) fn derived_uuid(seed: &str) -> String { result } +/// Stable native authentication-flow identity for one browser application. +pub(crate) fn application_authentication_flow_id(session_id: &str, application_id: &str) -> String { + derived_uuid(&format!( + "{session_id}:flow:application:{application_id}:authentication" + )) +} + +/// Stable native sign-out-flow identity shared by this issuer's browser applications. +pub(crate) fn browser_sign_out_flow_id(session_id: &str) -> String { + derived_uuid(&format!("{session_id}:flow:browser-applications:sign-out")) +} + /// The display text a declared scope tree carries. Identifiers and handles /// are the same in both; only names and descriptions differ. #[derive(Clone, Copy)] diff --git a/crates/registry-thunderid-tooling/src/render.rs b/crates/registry-thunderid-tooling/src/render.rs index fc1e77927c..5f42186022 100644 --- a/crates/registry-thunderid-tooling/src/render.rs +++ b/crates/registry-thunderid-tooling/src/render.rs @@ -422,6 +422,202 @@ fn emit( Ok(()) } +/// Native ThunderID 1.0.1 Basic SSO flow, specialized only by stable identity +/// and display text. The graph follows the Apache-2.0 upstream template at +/// ThunderID commit `12f517c4384004e360e26eb7eb1ab0501b678bb2`, file +/// `frontend/apps/console/src/features/flows/data/templates.json` (`BASIC_SSO`): +/// the SSO checkpoint may skip credential entry, but never the authorization +/// check or authentication assertion. +fn browser_authentication_flow(description: &IssuerDescription, app_id: &str, name: &str) -> Value { + let id = crate::local::application_authentication_flow_id(&description.session.id, app_id); + json!({ + "resource_type": "flow", + "id": id, + "name": format!("{name} sign-in"), + "handle": format!("registry-auth-{id}"), + "flowType": "AUTHENTICATION", + "nodes": [ + {"id": "start", "type": "START", "onSuccess": "sso_check"}, + { + "id": "sso_check", "type": "TASK_EXECUTION", + "properties": {"checkpointRef": "session"}, + "executor": {"name": "SSOCheckExecutor"}, + "onSuccess": "session", "onFailure": "prompt_credentials", + }, + { + "id": "prompt_credentials", "type": "PROMPT", + "meta": {"components": [ + { + "alt": "{{ t(signin:images.app_logo.alt) }}", + "category": "DISPLAY", "height": "60", "id": "image", + "resourceType": "ELEMENT", + "src": "{{ meta(application.logoUrl) }}", "type": "IMAGE", "width": "", + }, + { + "align": "center", "category": "DISPLAY", "id": "text_001", + "label": "{{ t(signin:forms.credentials.title) }}", + "resourceType": "ELEMENT", "type": "TEXT", "variant": "HEADING_1", + }, + { + "category": "BLOCK", "id": "block_001", "resourceType": "ELEMENT", + "type": "BLOCK", "components": [ + { + "category": "FIELD", "hint": "", "id": "input_001", + "inputType": "text", + "label": "{{ t(signin:forms.credentials.fields.username.label) }}", + "placeholder": "{{ t(signin:forms.credentials.fields.username.placeholder) }}", + "ref": "username", "required": true, + "resourceType": "ELEMENT", "type": "TEXT_INPUT", + }, + { + "category": "FIELD", "hint": "", "id": "input_002", + "inputType": "text", + "label": "{{ t(signin:forms.credentials.fields.password.label) }}", + "placeholder": "{{ t(signin:forms.credentials.fields.password.placeholder) }}", + "ref": "password", "required": true, + "resourceType": "ELEMENT", "type": "PASSWORD_INPUT", + }, + { + "category": "ACTION", "eventType": "SUBMIT", "id": "action_001", + "label": "{{ t(signin:forms.credentials.actions.submit.label) }}", + "resourceType": "ELEMENT", "type": "ACTION", "variant": "PRIMARY", + }, + ], + }, + ]}, + "prompts": [{ + "inputs": [ + {"ref": "input_001", "type": "TEXT_INPUT", "identifier": "username", "required": true}, + {"ref": "input_002", "type": "PASSWORD_INPUT", "identifier": "password", "required": true}, + ], + "action": {"ref": "action_001", "nextNode": "credentials_auth"}, + }], + }, + { + "id": "credentials_auth", "type": "TASK_EXECUTION", + "executor": { + "name": "CredentialsAuthExecutor", + "inputs": [ + {"ref": "input_001", "type": "TEXT_INPUT", "identifier": "username", "required": true}, + {"ref": "input_002", "type": "PASSWORD_INPUT", "identifier": "password", "required": true}, + ], + }, + "onSuccess": "session", "onIncomplete": "prompt_credentials", + }, + { + "id": "session", "type": "TASK_EXECUTION", + "executor": {"name": "SessionExecutor"}, + "onSuccess": "authorization_check", + }, + { + "id": "authorization_check", "type": "TASK_EXECUTION", + "executor": {"name": "AuthorizationExecutor"}, + "onSuccess": "auth_assert", + }, + { + "id": "auth_assert", "type": "TASK_EXECUTION", + "executor": {"name": "AuthAssertExecutor"}, "onSuccess": "end", + }, + {"id": "end", "type": "END"}, + ], + }) +} + +/// Native ThunderID 1.0.1 Conditional Confirmation sign-out flow from the same +/// pinned Apache-2.0 upstream template file. App Kit sends a client id without +/// an ID-token hint, so `promptOnSignOut` must stay true: the issuer asks the +/// person before ending that app's SSO session. +fn browser_sign_out_flow(description: &IssuerDescription) -> Value { + let id = crate::local::browser_sign_out_flow_id(&description.session.id); + json!({ + "resource_type": "flow", + "id": id, + "name": "Registry browser sign-out", + "handle": format!("registry-signout-{id}"), + "flowType": "SIGNOUT", + "nodes": [ + {"id": "start", "type": "START", "onSuccess": "session_signout"}, + { + "id": "session_signout", "type": "TASK_EXECUTION", + "properties": {"promptOnSignOut": true}, + "executor": {"name": "SessionSignOutExecutor"}, + "onSuccess": "end", "onIncomplete": "prompt_confirm", + }, + { + "id": "prompt_confirm", "type": "PROMPT", + "meta": {"components": [ + { + "align": "center", "category": "DISPLAY", "id": "text_signout_title", + "label": "{{ t(signout:forms.confirm.title) }}", "resourceType": "ELEMENT", + "type": "TEXT", "variant": "HEADING_1", + }, + { + "align": "center", "category": "DISPLAY", "id": "text_signout_desc", + "label": "{{ t(signout:forms.confirm.description) }}", "resourceType": "ELEMENT", + "type": "TEXT", "variant": "BODY_1", + }, + { + "category": "BLOCK", "id": "block_signout", "resourceType": "ELEMENT", + "type": "BLOCK", "components": [{ + "actionType": "CONFIRM", "category": "ACTION", "eventType": "SUBMIT", + "id": "action_confirm", + "label": "{{ t(signout:forms.confirm.actions.submit.label) }}", + "resourceType": "ELEMENT", "type": "ACTION", "variant": "PRIMARY", + }], + }, + ]}, + "prompts": [{"action": { + "ref": "action_confirm", "type": "CONFIRM", "nextNode": "session_signout", + }}], + }, + {"id": "end", "type": "END"}, + ], + }) +} + +/// Fixed Gate expressions emitted by the two pinned native flow graphs. The +/// hosted generator checks these exact multiplicities beside its secret +/// placeholders, so an authored string still cannot introduce template syntax. +pub(crate) fn gate_template_expression_counts( + browser_applications: usize, +) -> [(&'static str, usize); 11] { + let sign_out = usize::from(browser_applications > 0); + [ + ("{{ t(signin:images.app_logo.alt) }}", browser_applications), + ("{{ meta(application.logoUrl) }}", browser_applications), + ( + "{{ t(signin:forms.credentials.title) }}", + browser_applications, + ), + ( + "{{ t(signin:forms.credentials.fields.username.label) }}", + browser_applications, + ), + ( + "{{ t(signin:forms.credentials.fields.username.placeholder) }}", + browser_applications, + ), + ( + "{{ t(signin:forms.credentials.fields.password.label) }}", + browser_applications, + ), + ( + "{{ t(signin:forms.credentials.fields.password.placeholder) }}", + browser_applications, + ), + ( + "{{ t(signin:forms.credentials.actions.submit.label) }}", + browser_applications, + ), + ("{{ t(signout:forms.confirm.title) }}", sign_out), + ("{{ t(signout:forms.confirm.description) }}", sign_out), + ( + "{{ t(signout:forms.confirm.actions.submit.label) }}", + sign_out, + ), + ] +} + /// Render every native resource document for one validated description. /// /// The caller validates first; this function refuses an unvalidated shape @@ -736,6 +932,16 @@ pub(crate) fn build( &document, )?; } + let sign_out_flow_id = (!description.interactive_applications.is_empty()) + .then(|| crate::local::browser_sign_out_flow_id(&description.session.id)); + if let Some(id) = &sign_out_flow_id { + emit( + &mut outputs, + Area::Resources, + format!("flows/{id}.yaml"), + &browser_sign_out_flow(description), + )?; + } for app in &description.interactive_applications { let branding = branding .as_ref() @@ -760,6 +966,14 @@ pub(crate) fn build( .flatten() .map(|name| json!(name)), ); + let auth_flow_id = + crate::local::application_authentication_flow_id(&description.session.id, &app.id); + emit( + &mut outputs, + Area::Resources, + format!("flows/{auth_flow_id}.yaml"), + &browser_authentication_flow(description, &app.id, &app.client_id), + )?; let mut document = json!({ "resource_type": "application", "id": app.id, "name": app.client_id, @@ -770,7 +984,8 @@ pub(crate) fn build( }, "type": "fullstack", "ouHandle": ou_handle, "url": app.origin, - "authFlowId": "01900000-0000-7000-8000-000000000068", + "authFlowId": auth_flow_id, + "signOutFlowId": sign_out_flow_id.as_deref().expect("browser apps render sign-out"), "themeId": branding.theme_id, "layoutId": branding.layout_id, "isRegistrationFlowEnabled": false, "isRecoveryFlowEnabled": false, @@ -1369,6 +1584,17 @@ mod tests { audience: description.resource_servers[0].identifier.clone(), token_attributes: vec!["registry_role".into()], }); + description + .interactive_applications + .push(InteractiveApplication { + id: "0197aaaa-0000-7000-8000-0000000000e3".into(), + client_id: "synthetic-citizen".into(), + client_secret_file: "secrets/app".into(), + origin: "http://127.0.0.1:3001".into(), + redirect_uris: vec!["http://127.0.0.1:3001/auth/callback".into()], + audience: description.resource_servers[0].identifier.clone(), + token_attributes: vec!["registry_role".into()], + }); description.synthetic_users.push(SyntheticUser { id: "0197aaaa-0000-7000-8000-0000000000e2".into(), username: "staff-one".into(), @@ -1414,7 +1640,63 @@ mod tests { .unwrap(), ) .unwrap(); - assert_eq!(app["authFlowId"], "01900000-0000-7000-8000-000000000068"); + let other_app: Value = serde_yaml_parse( + &fs::read_to_string( + rendered + .resources_dir + .join("applications/0197aaaa-0000-7000-8000-0000000000e3.yaml"), + ) + .unwrap(), + ) + .unwrap(); + assert_ne!(app["authFlowId"], "01900000-0000-7000-8000-000000000068"); + assert_ne!(app["authFlowId"], other_app["authFlowId"]); + assert!(app["authFlowId"].is_string()); + assert_eq!(app["signOutFlowId"], other_app["signOutFlowId"]); + assert!(app["signOutFlowId"].is_string()); + + let flows: Vec = fs::read_dir(rendered.resources_dir.join("flows")) + .unwrap() + .map(|entry| { + serde_yaml_parse(&fs::read_to_string(entry.unwrap().path()).unwrap()).unwrap() + }) + .collect(); + assert_eq!( + flows.len(), + 3, + "two authentication flows and one sign-out flow" + ); + let auth_flow = flows + .iter() + .find(|flow| flow["id"] == app["authFlowId"]) + .unwrap(); + let executors: Vec<_> = auth_flow["nodes"] + .as_array() + .unwrap() + .iter() + .filter_map(|node| node["executor"]["name"].as_str()) + .collect(); + assert_eq!( + executors, + [ + "SSOCheckExecutor", + "CredentialsAuthExecutor", + "SessionExecutor", + "AuthorizationExecutor", + "AuthAssertExecutor", + ] + ); + let sign_out_flow = flows + .iter() + .find(|flow| flow["id"] == app["signOutFlowId"]) + .unwrap(); + let sign_out = sign_out_flow["nodes"] + .as_array() + .unwrap() + .iter() + .find(|node| node["executor"]["name"] == "SessionSignOutExecutor") + .unwrap(); + assert_eq!(sign_out["properties"]["promptOnSignOut"], true); assert_eq!(app["themeId"], "019a05b7-1000-7000-8000-000000000001"); assert_eq!(app["layoutId"], "019a05b7-1000-7000-8000-000000000002"); assert_eq!( @@ -1431,6 +1713,10 @@ mod tests { oauth["redirectUris"], json!(["http://127.0.0.1:3000/auth/callback"]) ); + assert_eq!( + oauth["postLogoutRedirectUris"], + json!(["http://127.0.0.1:3000"]) + ); assert_eq!(oauth["grantTypes"], json!(["authorization_code"])); assert_eq!(oauth["responseTypes"], json!(["code"])); assert_eq!(oauth["tokenEndpointAuthMethod"], "client_secret_post"); @@ -1501,6 +1787,29 @@ mod tests { fs::remove_dir_all(&description.state_root).unwrap(); } + #[test] + fn a_machine_only_render_has_no_browser_flow() { + let mut description = crate::testing::synthetic_description(); + description.state_root = std::env::temp_dir().join(format!( + "registry-machine-render-{}", + crate::container::random_urlsafe(16).unwrap() + )); + fs::create_dir(&description.state_root).unwrap(); + fs::set_permissions(&description.state_root, fs::Permissions::from_mode(0o700)).unwrap(); + fs::create_dir(description.state_root.join("secrets")).unwrap(); + fs::write( + description + .state_root + .join("secrets/compatibility-client-secret"), + "fixture-compat-secret", + ) + .unwrap(); + + let rendered = render(&description).unwrap(); + assert!(!rendered.resources_dir.join("flows").exists()); + fs::remove_dir_all(&description.state_root).unwrap(); + } + #[test] fn the_stylesheet_and_the_asset_mount_follow_the_declared_asset_path() { let metadata = branding_metadata().unwrap(); diff --git a/crates/registry-thunderid-tooling/src/render_golden_tests.rs b/crates/registry-thunderid-tooling/src/render_golden_tests.rs index 44b0b095fe..0f60b81043 100644 --- a/crates/registry-thunderid-tooling/src/render_golden_tests.rs +++ b/crates/registry-thunderid-tooling/src/render_golden_tests.rs @@ -14,7 +14,7 @@ use crate::description::{ /// sha256 over `relative path NUL bytes NUL` for every file, in path order. const DEVELOPMENT_RENDER_DIGEST: &str = - "d81752ee306e8659e12d20f668d28083e28728026d58cdd6716ad96a561f97df"; + "f72ce1a797e11e9db5ecc8d59248041310bc27cc09fc001dd1b71d74d03a847c"; fn walk(root: &Path, directory: &Path, hasher: &mut Sha256) { let mut entries: Vec<_> = fs::read_dir(directory) From b6d6b5c69ddced5d2e4a485a9362cbc0fa3f06a1 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 12 Nov 2026 15:49:06 +0700 Subject: [PATCH 03/34] fix(identity): honor declared browser user claims Signed-off-by: Jeremi Joslin --- crates/registry-thunderid-tooling/README.md | 13 +- .../src/identity_deployment.rs | 12 +- .../src/identity_deployment_tests.rs | 19 +++ .../src/identity_generate.rs | 61 ++++++++- .../src/identity_generate_tests.rs | 127 ++++++++++++++++++ .../schemas/identity-deployment.schema.json | 5 +- 6 files changed, 225 insertions(+), 12 deletions(-) diff --git a/crates/registry-thunderid-tooling/README.md b/crates/registry-thunderid-tooling/README.md index 4ea3811472..ec7668ba85 100644 --- a/crates/registry-thunderid-tooling/README.md +++ b/crates/registry-thunderid-tooling/README.md @@ -239,8 +239,19 @@ resolves no secret. application's `product` remains its one default token audience. Its explicit grants may authorize the same admitted client for other products, and a user reaches such a product only when an eligible application grants the user's - exact profile there. A grant to a client a product does not admit, an unknown + exact profile there. An extension user type may declare issuer-owned scalar + attributes for application metadata. A user may carry one only through that + exact type, and an application may project one only when it explicitly admits + a type declaring it. These attributes grant no product permissions. Machine + and exchange clients still use product-declared claims only. If a product + declares the same claim name, its type, selectors and profile checks remain + authoritative. A grant to a client a product does not admit, any other unknown claim, or a JWK carrying `d`, `p`, `q`, `dp`, `dq` or `qi` is refused. +- Generated users are declarative users. Authority-bearing extension attributes + must remain on those users in this deployment path. ThunderID database-backed + users of the same type can edit ordinary custom attributes through their + self-service user endpoint, so operators must not admit or separately provision + such mutable users of these types for authorization decisions. - The output directory must not exist. It holds `deployment.yaml` (server members to merge into the environment's own file), `resources/resources.yaml` (one multi-document file), `registry-schema/agent-type.yaml` and diff --git a/crates/registry-thunderid-tooling/src/identity_deployment.rs b/crates/registry-thunderid-tooling/src/identity_deployment.rs index 7e35dc5c06..563d4dc81e 100644 --- a/crates/registry-thunderid-tooling/src/identity_deployment.rs +++ b/crates/registry-thunderid-tooling/src/identity_deployment.rs @@ -110,7 +110,9 @@ pub struct BrowserApp { /// The `product` whose audience tokens carry by default. A request still /// produces a token for one audience. pub product: String, - /// Claims the application's tokens carry from the signed-in user. + /// Claims the application's tokens carry from the signed-in user. Each + /// is declared by a product or by an extension user type this application + /// explicitly admits. A product declaration remains authoritative. #[serde(deserialize_with = "set")] pub token_attributes: Vec, /// Profiles granted to the application. A grant outside `product` also @@ -147,6 +149,8 @@ pub struct User { /// An extension user type (id of `userTypes`); omitted is `RegistryPerson`. #[serde(default, skip_serializing_if = "Option::is_none")] pub user_type: Option, + /// Product claims, plus scalar issuer-owned attributes declared by this + /// user's exact extension type. `RegistryPerson` has no such extension. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub claims: BTreeMap, pub grants: Vec, @@ -161,7 +165,11 @@ pub struct UserType { pub id: String, /// The ThunderID type name users of this type carry. pub name: String, - /// Optional string attributes beyond username, email and password. + /// Optional issuer-owned string attributes beyond username, email and + /// password. They grant no product authority. A user may carry one only + /// through this exact type, and an application may project one only when + /// it explicitly admits a type that declares it. Product claim types and + /// selectors remain authoritative where a product declares the same name. #[serde( default, skip_serializing_if = "Vec::is_empty", diff --git a/crates/registry-thunderid-tooling/src/identity_deployment_tests.rs b/crates/registry-thunderid-tooling/src/identity_deployment_tests.rs index 65f2494242..abe14db9d0 100644 --- a/crates/registry-thunderid-tooling/src/identity_deployment_tests.rs +++ b/crates/registry-thunderid-tooling/src/identity_deployment_tests.rs @@ -181,6 +181,25 @@ fn an_explicit_actor_kind_is_one_the_runtime_parses() { } } +#[test] +fn extension_user_types_cannot_declare_protected_authority_attributes() { + for name in [ + "registry_grant_id", + "registry_assertion_issuer", + "identity", + "registry_approver", + ] { + let bad = format!( + "{DEPLOYMENT}userTypes:\n - id: staff\n name: Staff\n attributes: [{name}]\n" + ); + assert_eq!( + codes(&bad), + ["identity.deployment.invalid-user-type"], + "accepted {name}" + ); + } +} + /// Every list the format states as a set refuses a repeat at the repeat, /// naming the first, as every set does (CFG-ID-6). #[test] diff --git a/crates/registry-thunderid-tooling/src/identity_generate.rs b/crates/registry-thunderid-tooling/src/identity_generate.rs index 59269db9b5..5d935c2f88 100644 --- a/crates/registry-thunderid-tooling/src/identity_generate.rs +++ b/crates/registry-thunderid-tooling/src/identity_generate.rs @@ -630,21 +630,19 @@ fn claim_value(value: &ClaimValue) -> Value { } } -/// A claim must be one a product declares, with the type it declares. +/// A claim must be one a product declares, with the type it declares, or a +/// scalar interactive claim declared by the exact bound extension user type. +/// A product declaration always takes precedence over the extension schema. fn check_claim( findings: &mut Findings<'_>, facts: &MergedFacts, pointer: &str, name: &str, kind: ClaimType, + interactive: bool, + extension_declares: bool, ) { match facts.claims.get(name) { - None => findings.error( - pointer, - "identity.deployment.unknown-claim", - "no product declares a claim with this name", - "Declare the claim in the product's configuration, or remove it.", - ), Some(declared) if *declared != kind => findings.error( pointer, "identity.deployment.claim-type", @@ -652,9 +650,48 @@ fn check_claim( "Write the value in the declared type: a string or a list of strings.", ), Some(_) => {} + None if extension_declares && kind == ClaimType::String => {} + None => { + let (message, remedy) = if interactive { + ( + "no product or bound extension user type declares a claim with this name", + "Declare the claim in the product's configuration, or bind an interactive scalar claim through an extension user type; otherwise remove it.", + ) + } else { + ( + "no product declares a machine claim with this name", + "Declare the claim in the product's configuration, or remove it.", + ) + }; + findings.error( + pointer, + "identity.deployment.unknown-claim", + message, + remedy, + ); + } } } +fn extension_type_declares( + deployment: &IdentityDeployment, + user_type: Option<&str>, + name: &str, +) -> bool { + user_type.is_some_and(|id| { + deployment + .user_types + .iter() + .find(|declared| declared.id == id) + .is_some_and(|declared| { + declared + .attributes + .iter() + .any(|attribute| attribute == name) + }) + }) +} + /// A key file's refusal: code, message and fix. Repeats no value read. pub(crate) type KeyFileRefusal = (&'static str, &'static str, &'static str); @@ -1088,6 +1125,8 @@ pub fn generate(inputs: &Inputs<'_>) -> Result { &format!("{pointer}/claims"), name, claim_kind(value), + false, + false, ); attributes.insert(name.clone(), claim_value(value)); } @@ -1228,12 +1267,18 @@ pub fn generate(inputs: &Inputs<'_>) -> Result { continue; }; for name in &app.token_attributes { + let extension_declares = app + .user_types + .iter() + .any(|id| extension_type_declares(&deployment, Some(id), name)); check_claim( &mut findings, &facts, &format!("{pointer}/tokenAttributes"), name, ClaimType::String, + true, + extension_declares, ); } // Every user is given registry_actor_kind when a product reads it @@ -1345,6 +1390,8 @@ pub fn generate(inputs: &Inputs<'_>) -> Result { &format!("{pointer}/claims"), name, ClaimType::String, + true, + extension_type_declares(&deployment, user.user_type.as_deref(), name), ); } let mut user_claims: BTreeMap = user diff --git a/crates/registry-thunderid-tooling/src/identity_generate_tests.rs b/crates/registry-thunderid-tooling/src/identity_generate_tests.rs index d2ca60e484..3abc26c64c 100644 --- a/crates/registry-thunderid-tooling/src/identity_generate_tests.rs +++ b/crates/registry-thunderid-tooling/src/identity_generate_tests.rs @@ -285,6 +285,133 @@ fn user_claims_are_validated_against_the_merged_facts() { assert_eq!(client_claim.refusal(), ["identity.deployment.claim-type"]); } +fn typed_extension_claims_case() -> Case { + let mut case = case(); + case.deployment = case + .deployment + .replace( + "tokenAttributes: [registry_actor_kind, registry_role]", + "tokenAttributes: [registry_actor_kind, registry_role, portal_role, casework_profile]", + ) + .replace( + " registry_role: farmer\n", + " registry_role: farmer\n portal_role: nurse\n casework_profile: nursing\n", + ) + .replace( + " attributes: [national_id]", + " attributes: [national_id, portal_role, casework_profile]", + ); + case +} + +#[test] +fn a_bound_extension_type_declares_issuer_owned_user_claims_without_changing_grants() { + let generated = typed_extension_claims_case() + .run() + .expect("the bound extension claims generate"); + let documents = resources(&generated); + let app = of_type(&documents, "application")[0]; + assert_eq!( + app["inboundAuthConfig"][0]["config"]["token"]["accessToken"]["userConfig"] + ["attributes"], + serde_json::json!([ + "registry_actor_kind", + "registry_role", + "portal_role", + "casework_profile", + "registry_purpose" + ]) + ); + let farmer = of_type(&documents, "user") + .into_iter() + .find(|user| user["attributes"]["username"] == "farmer-one") + .expect("farmer user"); + assert_eq!(farmer["attributes"]["portal_role"], "nurse"); + assert_eq!(farmer["attributes"]["casework_profile"], "nursing"); + assert_eq!( + role_permissions(&documents, "User farmer-one", "urn:breg:example"), + ["records:get", "records:search"], + "issuer-owned attributes grant no product permission" + ); + assert_eq!( + role_permissions(&documents, "Browser staff-portal", "urn:breg:example"), + ["records:get", "records:search"] + ); +} + +#[test] +fn an_issuer_owned_claim_requires_the_exact_user_and_application_type_bindings() { + let mut untyped_user = typed_extension_claims_case(); + untyped_user.deployment = untyped_user + .deployment + .replace(" userType: farmer\n", ""); + assert_eq!( + untyped_user.refusal(), + ["identity.deployment.unknown-claim"; 2] + ); + + let mut unbound_app = typed_extension_claims_case(); + unbound_app.deployment = unbound_app + .deployment + .replace(" userTypes: [farmer]\n", ""); + assert_eq!( + unbound_app.refusal(), + [ + "identity.deployment.unknown-claim", + "identity.deployment.unknown-claim", + "identity.deployment.client-not-admitted" + ] + ); +} + +#[test] +fn extension_type_attributes_do_not_admit_machine_claims() { + let mut case = typed_extension_claims_case(); + case.deployment = case.deployment.replacen( + " registry_actor_kind: service\n", + " registry_actor_kind: service\n portal_role: nurse\n", + 1, + ); + assert_eq!(case.refusal(), ["identity.deployment.unknown-claim"]); + let error = case.run().expect_err("the machine claim is refused"); + let diagnostic = error + .report() + .expect("the refusal has a report") + .diagnostics() + .iter() + .find(|diagnostic| diagnostic.code == "identity.deployment.unknown-claim") + .expect("unknown machine claim diagnostic"); + assert_eq!( + diagnostic.suggested_action, + "Declare the claim in the product's configuration, or remove it." + ); +} + +#[test] +fn product_claim_types_and_profile_selection_remain_authoritative() { + let mut conflicting_type = typed_extension_claims_case(); + conflicting_type.facts[0].1 = conflicting_type.facts[0] + .1 + .replace(" registry_role: string\n", " registry_role: string\n portal_role: string-array\n"); + assert_eq!( + conflicting_type.refusal(), + ["identity.deployment.claim-type"; 2] + ); + + let mut selecting_profile = typed_extension_claims_case(); + selecting_profile.facts[0].1 = selecting_profile.facts[0] + .1 + .replace(" registry_role: string\n", " registry_role: string\n portal_role: string\n") + .replace( + " - id: case-write\n scopes: [records:patch]\n", + " - id: case-write\n scopes: [records:patch]\n - id: nurse-write\n scopes: [records:patch]\n selectedBy: {portal_role: [nurse]}\n", + ); + assert_eq!( + selecting_profile.refusal(), + ["identity.deployment.claims-select-ungranted-profile"] + ); +} + #[test] fn several_purposes_need_an_explicit_choice() { let mut case = case(); diff --git a/products/platform/schemas/identity-deployment.schema.json b/products/platform/schemas/identity-deployment.schema.json index 352da512f2..fd9657d666 100644 --- a/products/platform/schemas/identity-deployment.schema.json +++ b/products/platform/schemas/identity-deployment.schema.json @@ -51,7 +51,7 @@ "uniqueItems": true }, "tokenAttributes": { - "description": "Claims the application's tokens carry from the signed-in user.", + "description": "Claims the application's tokens carry from the signed-in user. Each\nis declared by a product or by an extension user type this application\nexplicitly admits. A product declaration remains authoritative.", "items": { "type": "string" }, @@ -213,6 +213,7 @@ "additionalProperties": { "type": "string" }, + "description": "Product claims, plus scalar issuer-owned attributes declared by this\nuser's exact extension type. `RegistryPerson` has no such extension.", "propertyNames": { "$ref": "#/$defs/ExternalId", "allOf": [ @@ -270,7 +271,7 @@ "description": "An extension user type: an additional ThunderID user schema.", "properties": { "attributes": { - "description": "Optional string attributes beyond username, email and password.", + "description": "Optional issuer-owned string attributes beyond username, email and\npassword. They grant no product authority. A user may carry one only\nthrough this exact type, and an application may project one only when\nit explicitly admits a type that declares it. Product claim types and\nselectors remain authoritative where a product declares the same name.", "items": { "type": "string" }, From be5a7067dcc165468bada2d2179f291b0600f14f Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 12 Nov 2026 16:08:27 +0700 Subject: [PATCH 04/34] fix(identity): reserve native ThunderID user fields Signed-off-by: Jeremi Joslin --- crates/registry-thunderid-tooling/README.md | 6 +- .../src/identity_facts.rs | 10 ++- .../src/identity_facts_tests.rs | 2 +- .../src/identity_generate_tests.rs | 80 +++++++++++++++++++ 4 files changed, 91 insertions(+), 7 deletions(-) diff --git a/crates/registry-thunderid-tooling/README.md b/crates/registry-thunderid-tooling/README.md index ec7668ba85..236bc787bb 100644 --- a/crates/registry-thunderid-tooling/README.md +++ b/crates/registry-thunderid-tooling/README.md @@ -245,8 +245,10 @@ resolves no secret. a type declaring it. These attributes grant no product permissions. Machine and exchange clients still use product-declared claims only. If a product declares the same claim name, its type, selectors and profile checks remain - authoritative. A grant to a client a product does not admit, any other unknown - claim, or a JWK carrying `d`, `p`, `q`, `dp`, `dq` or `qi` is refused. + authoritative. The native `username`, `email` and `password` names are + reserved; set them through the user's `username`, `email` and `passwordRef` + fields. A grant to a client a product does not admit, any other unknown claim, + or a JWK carrying `d`, `p`, `q`, `dp`, `dq` or `qi` is refused. - Generated users are declarative users. Authority-bearing extension attributes must remain on those users in this deployment path. ThunderID database-backed users of the same type can edit ordinary custom attributes through their diff --git a/crates/registry-thunderid-tooling/src/identity_facts.rs b/crates/registry-thunderid-tooling/src/identity_facts.rs index 152b5ae716..1566e89f6c 100644 --- a/crates/registry-thunderid-tooling/src/identity_facts.rs +++ b/crates/registry-thunderid-tooling/src/identity_facts.rs @@ -398,10 +398,10 @@ pub(crate) fn template_findings(document: &Document) -> Vec { .collect() } -/// Claim names that JWT, token exchange, JWT access tokens and OpenID Connect -/// (RFC 7519, RFC 8693, RFC 9068, OIDC Core) give a meaning of their own. A -/// deployment's claim never reuses one: a verifier would read it as protocol. -const RESERVED_CLAIM_NAMES: [&str; 34] = [ +/// Names owned by JWT, token exchange, JWT access tokens and OpenID Connect +/// (RFC 7519, RFC 8693, RFC 9068, OIDC Core), or by the native ThunderID user +/// schema. A custom claim must not shadow a protocol claim or a native field. +const RESERVED_CLAIM_NAMES: [&str; 36] = [ "iss", "sub", "aud", @@ -436,6 +436,8 @@ const RESERVED_CLAIM_NAMES: [&str; 34] = [ "family_name", "phone_number", "address", + "username", + "password", ]; pub(crate) fn valid_claim_name(name: &str) -> bool { diff --git a/crates/registry-thunderid-tooling/src/identity_facts_tests.rs b/crates/registry-thunderid-tooling/src/identity_facts_tests.rs index a41d110a78..32447cf038 100644 --- a/crates/registry-thunderid-tooling/src/identity_facts_tests.rs +++ b/crates/registry-thunderid-tooling/src/identity_facts_tests.rs @@ -425,7 +425,7 @@ fn template_syntax_is_refused_wherever_a_string_is_copied() { } #[test] -fn registered_and_protocol_claim_names_are_refused() { +fn protocol_and_native_claim_names_are_refused() { for name in super::RESERVED_CLAIM_NAMES { let bad = BREG.replace("registry_purpose: string", &format!("{name}: string")); assert!( diff --git a/crates/registry-thunderid-tooling/src/identity_generate_tests.rs b/crates/registry-thunderid-tooling/src/identity_generate_tests.rs index 3abc26c64c..659cc06a85 100644 --- a/crates/registry-thunderid-tooling/src/identity_generate_tests.rs +++ b/crates/registry-thunderid-tooling/src/identity_generate_tests.rs @@ -339,6 +339,85 @@ fn a_bound_extension_type_declares_issuer_owned_user_claims_without_changing_gra ); } +fn assert_native_user_attribute_is_refused(name: &str) { + let mut case = typed_extension_claims_case(); + case.deployment = case.deployment.replace("portal_role", name); + let error = match case.run() { + Err(error) => error, + Ok(generated) => { + let documents = resources(&generated); + let user = of_type(&documents, "user") + .into_iter() + .find(|user| user["type"] == "Farmer") + .expect("extension user"); + assert_eq!(user["attributes"][name], "nurse"); + let app = of_type(&documents, "application")[0]; + assert!(app["inboundAuthConfig"][0]["config"]["token"]["accessToken"]["userConfig"] + ["attributes"] + .as_array() + .expect("access token attributes") + .iter() + .any(|attribute| attribute == name)); + panic!("the generator emitted native {name} as a custom attribute and token projection"); + } + }; + let diagnostics = error + .report() + .unwrap_or_else(|| panic!("expected a refusal at the authored fields, got {error}")) + .diagnostics(); + assert_eq!( + diagnostics + .iter() + .map(|finding| (finding.path.as_str(), finding.code.as_str())) + .collect::>(), + BTreeSet::from([ + ("/browserApps/0/tokenAttributes", "identity.deployment.invalid-claim"), + ("/users/1/claims", "identity.deployment.invalid-claim"), + ("/userTypes/0", "identity.deployment.invalid-user-type"), + ]) + ); +} + +#[test] +fn native_user_username_cannot_be_a_custom_claim() { + assert_native_user_attribute_is_refused("username"); +} + +#[test] +fn native_user_password_cannot_be_a_custom_claim() { + assert_native_user_attribute_is_refused("password"); +} + +#[test] +fn native_user_names_cannot_be_declared_without_a_claim_assignment() { + for name in ["username", "password"] { + let mut case = case(); + case.deployment = case.deployment.replace( + "attributes: [national_id]", + &format!("attributes: [national_id, {name}]"), + ); + assert_eq!(case.refusal(), ["identity.deployment.invalid-user-type"]); + } +} + +#[test] +fn native_user_names_cannot_be_projected_without_a_claim_assignment() { + for name in ["username", "password"] { + let mut case = typed_extension_claims_case(); + case.deployment = case + .deployment + .replace("portal_role", name) + .replace(&format!(" {name}: nurse\n"), ""); + assert_eq!( + case.refusal(), + [ + "identity.deployment.invalid-claim", + "identity.deployment.invalid-user-type" + ] + ); + } +} + #[test] fn an_issuer_owned_claim_requires_the_exact_user_and_application_type_bindings() { let mut untyped_user = typed_extension_claims_case(); @@ -918,6 +997,7 @@ fn browser_apps_users_and_extension_types_render_without_secrets_or_a_logo_by_de .unwrap(); assert_eq!(farmer["type"], "Farmer"); assert_eq!(farmer["credentials"]["password"], "{{.FARMER_ONE_PASSWORD}}"); + assert!(farmer["attributes"].get("password").is_none()); let organization = of_type(&documents, "organization_unit"); assert_eq!(organization[0]["handle"], "registry"); } From 44667561566990acd7bdc4de399e970a9d478969 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 03:37:00 +0700 Subject: [PATCH 05/34] feat: add Python service connections and local grants Signed-off-by: Jeremi Joslin --- .github/scripts/ci_changes.py | 9 +- .github/scripts/test_ci_changes.py | 4 + .github/workflows/ci.yml | 70 +- .github/workflows/release-candidate.yml | 59 +- Cargo.lock | 25 + Cargo.toml | 2 + crates/registry-bregctl/src/dev/config.rs | 1 + .../src/project_dev/bindings.rs | 4 + .../src/project_dev/database.rs | 13 +- .../src/project_dev/issuer.rs | 33 +- .../src/project_dev/journey.rs | 1 + .../registry-bregctl/src/project_dev/mod.rs | 89 +- .../src/project_dev/picker.rs | 600 ++++++++ .../registry-bregctl/src/project_dev/plan.rs | 453 +++++- .../src/project_dev/products.rs | 601 +++++++- .../src/project_dev/workload.rs | 466 ++++++ .../tests/catalog_scenarios.rs | 28 +- .../tests/external_wait_postgres.rs | 166 ++- crates/registry-messagingctl/src/lib.rs | 21 +- crates/registry-platform-oidc-py/Cargo.toml | 32 + crates/registry-platform-oidc-py/README.md | 48 + crates/registry-platform-oidc-py/build.rs | 9 + .../registry-platform-oidc-py/pyproject.toml | 32 + .../python/registry_platform_oidc/__init__.py | 3 + .../registry_platform_oidc/__init__.pyi | 69 + .../python/registry_platform_oidc/py.typed | 1 + crates/registry-platform-oidc-py/src/lib.rs | 712 ++++++++++ crates/registry-platform-oidc-py/src/tests.rs | 178 +++ .../tests/python/bootstrap.py | 70 + .../tests/python/test_verifier.py | 210 +++ crates/registry-platform-oidc/src/lib.rs | 50 +- crates/registry-platform-yaml-py/Cargo.toml | 38 + crates/registry-platform-yaml-py/README.md | 49 + crates/registry-platform-yaml-py/build.rs | 9 + .../examples/python-formats-schema.rs | 20 + .../registry-platform-yaml-py/pyproject.toml | 32 + .../python/registry_platform_yaml/__init__.py | 3 + .../registry_platform_yaml/__init__.pyi | 39 + .../python/registry_platform_yaml/py.typed | 1 + .../registry-platform-yaml-py/src/formats.rs | 395 ++++++ crates/registry-platform-yaml-py/src/lib.rs | 192 +++ crates/registry-platform-yaml-py/src/tests.rs | 253 ++++ .../tests/python/bootstrap.py | 70 + .../tests/python/test_reader.py | 125 ++ crates/registry-rstack/src/cli.rs | 22 + crates/registry-rstack/src/grants.rs | 454 ++++++ crates/registry-rstack/src/lib.rs | 1 + crates/registry-rstack/tests/grants.rs | 212 +++ .../registry-stack-client-py/pyproject.toml | 6 + .../python/registry_client/__init__.py | 24 +- .../python/registry_client/__init__.pyi | 17 +- .../_sql/portal_postgres_v1.sql | 64 + .../registry_client/check_connection.py | 143 ++ .../registry_client/check_connection.pyi | 4 + .../python/registry_client/connection.py | 621 ++++++++ .../python/registry_client/connection.pyi | 57 + .../python/registry_client/dev_picker.py | 1253 +++++++++++++++++ .../python/registry_client/dev_picker.pyi | 90 ++ .../python/registry_client/fastapi_adapter.py | 47 + .../registry_client/fastapi_adapter.pyi | 5 + .../python/registry_client/flask_adapter.py | 44 + .../python/registry_client/flask_adapter.pyi | 5 + .../python/registry_client/machine.py | 124 ++ .../python/registry_client/machine.pyi | 33 + .../python/registry_client/portal.py | 896 ++++++++++++ .../python/registry_client/portal.pyi | 239 ++++ .../python/registry_client/portal_fastapi.py | 190 +++ .../python/registry_client/portal_fastapi.pyi | 14 + .../python/registry_client/portal_flask.py | 166 +++ .../python/registry_client/portal_flask.pyi | 14 + .../python/registry_client/portal_postgres.py | 852 +++++++++++ .../registry_client/portal_postgres.pyi | 35 + .../python/registry_client/portal_products.py | 62 + .../registry_client/portal_products.pyi | 20 + .../python/registry_client/portal_verifier.py | 198 +++ .../registry_client/portal_verifier.pyi | 40 + .../python/registry_client/runner.py | 143 ++ .../python/registry_client/web.py | 46 + .../python/registry_client/web.pyi | 11 + .../python/registry_client/workload.py | 110 ++ .../python/registry_client/workload.pyi | 30 + .../python/registry_client/workload_breg.py | 751 ++++++++++ .../python/registry_client/workload_breg.pyi | 406 ++++++ .../registry_client/workload_casework.py | 183 +++ .../registry_client/workload_casework.pyi | 76 + .../tests/test_breg_workload.py | 179 +++ .../tests/test_casework_workload.py | 244 ++++ .../tests/test_connection.py | 665 +++++++++ .../tests/test_dev_picker.py | 555 ++++++++ .../tests/test_framework_adapters.py | 160 +++ .../tests/test_machine_admission.py | 124 ++ .../tests/test_portal.py | 929 ++++++++++++ .../tests/test_portal_fastapi.py | 307 ++++ .../tests/test_portal_frameworks.py | 329 +++++ .../tests/test_portal_postgres.py | 486 +++++++ .../tests/test_portal_products.py | 136 ++ .../tests/test_portal_verifier.py | 236 ++++ crates/registry-stack-client-py/uv.lock | 956 +++++++++++++ crates/registry-thunderid-tooling/README.md | 9 +- .../fixtures/identity/deployment.yaml | 1 + .../identity/expected/identity-receipt.json | 2 +- .../expected/resources/resources.yaml | 2 + .../src/description.rs | 4 + .../src/identity_deployment.rs | 17 + .../src/identity_deployment_tests.rs | 16 + .../src/identity_generate.rs | 4 +- .../src/identity_generate_tests.rs | 41 + .../registry-thunderid-tooling/src/render.rs | 19 +- .../src/render_golden_tests.rs | 1 + .../registry-thunderid-tooling/src/schema.rs | 24 + products/breg/CHANGELOG.md | 4 +- .../tools/project-dev.v1alpha1.schema.json | 113 +- products/coordinator/README.md | 4 +- .../examples/external-job/README.md | 86 +- .../examples/external-job/functions.rhai | 24 +- .../examples/external-job/pyproject.toml | 8 + .../examples/external-job/runtime.yaml | 1 + .../examples/external-job/scenarios.yaml | 86 +- .../examples/external-job/service.py | 398 ++++++ .../external-job/tests/test_postgres.py | 108 ++ .../external-job/tests/test_service.py | 202 +++ .../examples/external-job/workflow.yaml | 81 +- products/messaging/CHANGELOG.md | 5 + .../examples/formats/ctl-report.json | 20 +- products/platform/CHANGELOG.md | 8 +- products/platform/PROJECT-DEV.md | 128 +- .../config-conventions-exceptions.yaml | 36 + products/platform/config-formats.yaml | 172 +++ .../examples/dev-workload-token-stopped.json | 23 + .../identity/identity-deployment.yaml | 1 + .../examples/licensing/casework/casework.yaml | 27 +- .../schemas/application-context.schema.json | 1 + products/platform/examples/licensing/dev.yaml | 168 ++- .../licensing/messaging/messaging.yaml | 24 + .../application-received/1/en/html.j2 | 1 + .../application-received/1/en/subject.j2 | 1 + .../application-received/1/en/text.j2 | 1 + .../application-received/1/schema.json | 8 + .../application-received/1/template.yaml | 6 + .../examples/licensing/registry/registry.yaml | 76 +- .../licensing/registry/tests/journeys.yaml | 14 + .../examples/python-composition/README.md | 36 +- .../python-composition/config.example.json | 16 - .../connection.example.json | 57 + .../examples/python-composition/service.py | 48 +- .../python-composition/tests/test_service.py | 125 +- .../examples/python-machine-service/README.md | 118 ++ .../examples/python-machine-service/effect.py | 614 ++++++++ .../python-machine-service/pyproject.toml | 10 + .../python-machine-service/service.py | 163 +++ .../tests/test_effect.py | 492 +++++++ .../tests/test_service.py | 303 ++++ .../examples/python-machine-service/uv.lock | 210 +++ .../platform/examples/python-portal/README.md | 228 +++ .../python-portal/config.example.toml | 90 ++ .../examples/python-portal/frontend.html | 26 + .../platform/examples/python-portal/portal.js | 25 + .../examples/python-portal/portal_example.py | 1073 ++++++++++++++ .../examples/python-portal/pyproject.toml | 24 + .../examples/python-portal/service.py | 65 + .../tests/test_portal_example.py | 825 +++++++++++ .../platform/examples/python-portal/uv.lock | 1060 ++++++++++++++ .../platform/examples/python-script/README.md | 75 + .../examples/python-script/pyproject.toml | 8 + .../platform/examples/python-script/script.py | 78 + .../python-script/tests/test_script.py | 207 +++ .../platform/examples/python-script/uv.lock | 8 + .../dev-workload-token.v1alpha1.schema.json | 157 +++ .../schemas/identity-deployment.schema.json | 14 + .../python-connection.v1alpha1.schema.json | 384 +++++ products/platform/scripts/test-rstack-dev.py | 125 +- .../assemble-registry-client-packages.py | 35 + .../scripts/assemble-registry-client-wheel.py | 77 +- release/scripts/build-linux-python-client | 20 +- release/scripts/macos_fips_packaging.py | 15 +- .../scripts/smoke-registry-client-extras.py | 138 ++ .../scripts/smoke-registry-client-service.py | 225 +++ .../test_assemble_registry_client_packages.py | 33 +- .../test_assemble_registry_client_wheel.py | 110 +- release/scripts/test_macos_fips_packaging.py | 40 + 180 files changed, 27266 insertions(+), 365 deletions(-) create mode 100644 crates/registry-bregctl/src/project_dev/picker.rs create mode 100644 crates/registry-bregctl/src/project_dev/workload.rs create mode 100644 crates/registry-platform-oidc-py/Cargo.toml create mode 100644 crates/registry-platform-oidc-py/README.md create mode 100644 crates/registry-platform-oidc-py/build.rs create mode 100644 crates/registry-platform-oidc-py/pyproject.toml create mode 100644 crates/registry-platform-oidc-py/python/registry_platform_oidc/__init__.py create mode 100644 crates/registry-platform-oidc-py/python/registry_platform_oidc/__init__.pyi create mode 100644 crates/registry-platform-oidc-py/python/registry_platform_oidc/py.typed create mode 100644 crates/registry-platform-oidc-py/src/lib.rs create mode 100644 crates/registry-platform-oidc-py/src/tests.rs create mode 100644 crates/registry-platform-oidc-py/tests/python/bootstrap.py create mode 100644 crates/registry-platform-oidc-py/tests/python/test_verifier.py create mode 100644 crates/registry-platform-yaml-py/Cargo.toml create mode 100644 crates/registry-platform-yaml-py/README.md create mode 100644 crates/registry-platform-yaml-py/build.rs create mode 100644 crates/registry-platform-yaml-py/examples/python-formats-schema.rs create mode 100644 crates/registry-platform-yaml-py/pyproject.toml create mode 100644 crates/registry-platform-yaml-py/python/registry_platform_yaml/__init__.py create mode 100644 crates/registry-platform-yaml-py/python/registry_platform_yaml/__init__.pyi create mode 100644 crates/registry-platform-yaml-py/python/registry_platform_yaml/py.typed create mode 100644 crates/registry-platform-yaml-py/src/formats.rs create mode 100644 crates/registry-platform-yaml-py/src/lib.rs create mode 100644 crates/registry-platform-yaml-py/src/tests.rs create mode 100644 crates/registry-platform-yaml-py/tests/python/bootstrap.py create mode 100644 crates/registry-platform-yaml-py/tests/python/test_reader.py create mode 100644 crates/registry-rstack/src/grants.rs create mode 100644 crates/registry-rstack/tests/grants.rs create mode 100644 crates/registry-stack-client-py/python/registry_client/_sql/portal_postgres_v1.sql create mode 100644 crates/registry-stack-client-py/python/registry_client/check_connection.py create mode 100644 crates/registry-stack-client-py/python/registry_client/check_connection.pyi create mode 100644 crates/registry-stack-client-py/python/registry_client/connection.py create mode 100644 crates/registry-stack-client-py/python/registry_client/connection.pyi create mode 100644 crates/registry-stack-client-py/python/registry_client/dev_picker.py create mode 100644 crates/registry-stack-client-py/python/registry_client/dev_picker.pyi create mode 100644 crates/registry-stack-client-py/python/registry_client/fastapi_adapter.py create mode 100644 crates/registry-stack-client-py/python/registry_client/fastapi_adapter.pyi create mode 100644 crates/registry-stack-client-py/python/registry_client/flask_adapter.py create mode 100644 crates/registry-stack-client-py/python/registry_client/flask_adapter.pyi create mode 100644 crates/registry-stack-client-py/python/registry_client/machine.py create mode 100644 crates/registry-stack-client-py/python/registry_client/machine.pyi create mode 100644 crates/registry-stack-client-py/python/registry_client/portal.py create mode 100644 crates/registry-stack-client-py/python/registry_client/portal.pyi create mode 100644 crates/registry-stack-client-py/python/registry_client/portal_fastapi.py create mode 100644 crates/registry-stack-client-py/python/registry_client/portal_fastapi.pyi create mode 100644 crates/registry-stack-client-py/python/registry_client/portal_flask.py create mode 100644 crates/registry-stack-client-py/python/registry_client/portal_flask.pyi create mode 100644 crates/registry-stack-client-py/python/registry_client/portal_postgres.py create mode 100644 crates/registry-stack-client-py/python/registry_client/portal_postgres.pyi create mode 100644 crates/registry-stack-client-py/python/registry_client/portal_products.py create mode 100644 crates/registry-stack-client-py/python/registry_client/portal_products.pyi create mode 100644 crates/registry-stack-client-py/python/registry_client/portal_verifier.py create mode 100644 crates/registry-stack-client-py/python/registry_client/portal_verifier.pyi create mode 100644 crates/registry-stack-client-py/python/registry_client/runner.py create mode 100644 crates/registry-stack-client-py/python/registry_client/web.py create mode 100644 crates/registry-stack-client-py/python/registry_client/web.pyi create mode 100644 crates/registry-stack-client-py/python/registry_client/workload.py create mode 100644 crates/registry-stack-client-py/python/registry_client/workload.pyi create mode 100644 crates/registry-stack-client-py/python/registry_client/workload_breg.py create mode 100644 crates/registry-stack-client-py/python/registry_client/workload_breg.pyi create mode 100644 crates/registry-stack-client-py/python/registry_client/workload_casework.py create mode 100644 crates/registry-stack-client-py/python/registry_client/workload_casework.pyi create mode 100644 crates/registry-stack-client-py/tests/test_breg_workload.py create mode 100644 crates/registry-stack-client-py/tests/test_casework_workload.py create mode 100644 crates/registry-stack-client-py/tests/test_connection.py create mode 100644 crates/registry-stack-client-py/tests/test_dev_picker.py create mode 100644 crates/registry-stack-client-py/tests/test_framework_adapters.py create mode 100644 crates/registry-stack-client-py/tests/test_machine_admission.py create mode 100644 crates/registry-stack-client-py/tests/test_portal.py create mode 100644 crates/registry-stack-client-py/tests/test_portal_fastapi.py create mode 100644 crates/registry-stack-client-py/tests/test_portal_frameworks.py create mode 100644 crates/registry-stack-client-py/tests/test_portal_postgres.py create mode 100644 crates/registry-stack-client-py/tests/test_portal_products.py create mode 100644 crates/registry-stack-client-py/tests/test_portal_verifier.py create mode 100644 crates/registry-stack-client-py/uv.lock create mode 100644 products/coordinator/examples/external-job/pyproject.toml create mode 100644 products/coordinator/examples/external-job/service.py create mode 100644 products/coordinator/examples/external-job/tests/test_postgres.py create mode 100644 products/coordinator/examples/external-job/tests/test_service.py create mode 100644 products/platform/examples/dev-workload-token-stopped.json create mode 100644 products/platform/examples/licensing/casework/schemas/application-context.schema.json create mode 100644 products/platform/examples/licensing/messaging/messaging.yaml create mode 100644 products/platform/examples/licensing/messaging/templates/application-received/1/en/html.j2 create mode 100644 products/platform/examples/licensing/messaging/templates/application-received/1/en/subject.j2 create mode 100644 products/platform/examples/licensing/messaging/templates/application-received/1/en/text.j2 create mode 100644 products/platform/examples/licensing/messaging/templates/application-received/1/schema.json create mode 100644 products/platform/examples/licensing/messaging/templates/application-received/1/template.yaml create mode 100644 products/platform/examples/python-composition/connection.example.json create mode 100644 products/platform/examples/python-machine-service/README.md create mode 100644 products/platform/examples/python-machine-service/effect.py create mode 100644 products/platform/examples/python-machine-service/pyproject.toml create mode 100644 products/platform/examples/python-machine-service/service.py create mode 100644 products/platform/examples/python-machine-service/tests/test_effect.py create mode 100644 products/platform/examples/python-machine-service/tests/test_service.py create mode 100644 products/platform/examples/python-machine-service/uv.lock create mode 100644 products/platform/examples/python-portal/README.md create mode 100644 products/platform/examples/python-portal/config.example.toml create mode 100644 products/platform/examples/python-portal/frontend.html create mode 100644 products/platform/examples/python-portal/portal.js create mode 100644 products/platform/examples/python-portal/portal_example.py create mode 100644 products/platform/examples/python-portal/pyproject.toml create mode 100644 products/platform/examples/python-portal/service.py create mode 100644 products/platform/examples/python-portal/tests/test_portal_example.py create mode 100644 products/platform/examples/python-portal/uv.lock create mode 100644 products/platform/examples/python-script/README.md create mode 100644 products/platform/examples/python-script/pyproject.toml create mode 100644 products/platform/examples/python-script/script.py create mode 100644 products/platform/examples/python-script/tests/test_script.py create mode 100644 products/platform/examples/python-script/uv.lock create mode 100644 products/platform/schemas/dev-workload-token.v1alpha1.schema.json create mode 100644 products/platform/schemas/python-connection.v1alpha1.schema.json create mode 100644 release/scripts/smoke-registry-client-extras.py create mode 100644 release/scripts/smoke-registry-client-service.py diff --git a/.github/scripts/ci_changes.py b/.github/scripts/ci_changes.py index 4a9aaaa0d8..0c7d750697 100644 --- a/.github/scripts/ci_changes.py +++ b/.github/scripts/ci_changes.py @@ -39,6 +39,7 @@ "registry-platform-metrics", "registry-platform-objectstore", "registry-platform-oidc", + "registry-platform-oidc-py", "registry-platform-ratelimit", "registry-platform-resilience", "registry-platform-script", @@ -48,6 +49,7 @@ "registry-platform-text", "registry-platform-x509", "registry-platform-yaml", + "registry-platform-yaml-py", ), "mcp": ( "registry-mcp", @@ -522,6 +524,7 @@ | SCHEDULING_BINDING_PACKAGES | COORDINATOR_BINDING_PACKAGES | frozenset({"registry-render-client-node", "registry-render-client-py"}) + | frozenset({"registry-platform-oidc-py", "registry-platform-yaml-py"}) ) # The breg-contracts matrix lanes. Review runs the first two; the merge @@ -559,7 +562,7 @@ # package, so a change under it already selects the complete matrix. ASSEMBLED_PYTHON_CLIENT_PACKAGES = frozenset( package for package in NATIVE_BINDING_PACKAGES if package.endswith("-client-py") -) +) | frozenset({"registry-platform-oidc-py", "registry-platform-yaml-py"}) # The gate builds and runs the registry, the tool that applies its package, and # issuer tooling, because the `bregctl dev` session the tutorial starts issues @@ -1512,8 +1515,12 @@ def classify( complete or bool(affected & NATIVE_BINDING_PACKAGES) or unified_client_changed + or "release/scripts/smoke-registry-client-service.py" in changed_paths + or "release/scripts/smoke-registry-client-extras.py" in changed_paths or any(path.startswith(( "products/platform/examples/python-composition/", + "products/platform/examples/python-machine-service/", + "products/platform/examples/python-portal/", "products/coordinator/examples/reviewed-notice/", )) for path in changed_paths) ) diff --git a/.github/scripts/test_ci_changes.py b/.github/scripts/test_ci_changes.py index 1b3bd9f751..c07ebf9fb0 100644 --- a/.github/scripts/test_ci_changes.py +++ b/.github/scripts/test_ci_changes.py @@ -2865,6 +2865,10 @@ def test_python_composition_and_release_client_example_run_native_clients(self) for path in ( "products/platform/examples/python-composition/service.py", "products/platform/examples/python-composition/uv.lock", + "products/platform/examples/python-machine-service/service.py", + "products/platform/examples/python-portal/portal_example.py", + "release/scripts/smoke-registry-client-service.py", + "release/scripts/smoke-registry-client-extras.py", "products/coordinator/examples/reviewed-notice/released_client.py", "products/coordinator/examples/reviewed-notice/tests/test_released_client.py", ): diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cc32fb0c38..3a936444ac 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2695,7 +2695,8 @@ jobs: cargo build --locked \ -p registry-casework -p registry-caseworkctl \ -p registry-breg --features registry-breg/runtime \ - -p registry-bregctl -p registry-rstack --bins + -p registry-bregctl -p registry-messaging -p registry-messagingctl \ + -p registry-rstack --bins - name: Install native PostgreSQL 18 and PostGIS for project development # The Ubuntu runner's PostgreSQL 16 is below BReg's minimum. @@ -3341,12 +3342,29 @@ jobs: cmp ../../LICENSE LICENSE ) done + for client in registry-platform-oidc-py registry-platform-yaml-py; do + cargo build --locked -p "${client}" --lib --features "${client}/extension-module" + ( + cd "crates/${client}" + python3 -m unittest discover -s tests/python -v + cmp ../../LICENSE LICENSE + ) + done - name: Install uv uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2 with: version: "0.11.16" + - name: Test Python connection facade + working-directory: crates/registry-stack-client-py + shell: bash + run: | + set -euo pipefail + uv run --locked --all-extras --with httpx==0.28.1 \ + python -W error::ResourceWarning -m unittest discover \ + -s tests -p 'test_*.py' -v + - name: Test direct Python composition with the exact checkout client working-directory: products/platform/examples/python-composition shell: bash @@ -3376,6 +3394,56 @@ jobs: fi uv run --locked --with "${wheels[0]}" \ python -m unittest discover -s tests -v + printf 'REGISTRY_CLIENT_PY_WHEEL=%s\n' "${wheels[0]}" >>"${GITHUB_ENV}" + + - name: Exercise installed Python service client on Linux + working-directory: products/platform/examples/python-portal + shell: bash + run: | + set -euo pipefail + uv run --locked --with "${REGISTRY_CLIENT_PY_WHEEL}" \ + python -I "${GITHUB_WORKSPACE}/release/scripts/smoke-registry-client-service.py" + + - name: Test Python machine service + working-directory: products/platform/examples/python-machine-service + shell: bash + run: | + set -euo pipefail + uv run --locked python -W error::ResourceWarning \ + -m unittest discover -s tests -p 'test_*.py' -v + + - name: Check isolated Python service extras + shell: bash + run: | + set -euo pipefail + for mode in core flask fastapi human-flask human-fastapi; do + environment="${RUNNER_TEMP}/client-${mode}" + uv venv "${environment}" + case "${mode}" in + core) + uv pip install --python "${environment}/bin/python" \ + --no-deps "${REGISTRY_CLIENT_PY_WHEEL}" + ;; + flask) + uv pip install --python "${environment}/bin/python" \ + "${REGISTRY_CLIENT_PY_WHEEL}[flask]" + ;; + fastapi) + uv pip install --python "${environment}/bin/python" \ + "${REGISTRY_CLIENT_PY_WHEEL}[fastapi]" httpx==0.28.1 + ;; + human-flask) + uv pip install --python "${environment}/bin/python" \ + "${REGISTRY_CLIENT_PY_WHEEL}[human,flask,postgres]" + ;; + human-fastapi) + uv pip install --python "${environment}/bin/python" \ + "${REGISTRY_CLIENT_PY_WHEEL}[human,fastapi,postgres]" + ;; + esac + "${environment}/bin/python" -I \ + release/scripts/smoke-registry-client-extras.py "${mode}" + done - name: Test released-client Coordinator example working-directory: products/coordinator/examples/reviewed-notice diff --git a/.github/workflows/release-candidate.yml b/.github/workflows/release-candidate.yml index 968f938d6b..af77ee8cce 100644 --- a/.github/workflows/release-candidate.yml +++ b/.github/workflows/release-candidate.yml @@ -1169,7 +1169,62 @@ jobs: exit 1 fi done + oidc_in_release=0 + if (( client_major > 0 || client_minor > 46 || + (client_minor == 46 && client_patch >= 1) )); then + oidc_in_release=1 + oidc_dir="${GITHUB_WORKSPACE}/crates/registry-platform-oidc-py" + configured_version="$(python3 -c 'import tomllib,sys; print(tomllib.load(open(sys.argv[1], "rb"))["project"]["version"])' "${oidc_dir}/pyproject.toml")" + test "${configured_version}" = "${CLIENT_VERSION}" + if [[ "${RUNNER_OS}" == Linux ]]; then + release/scripts/build-linux-python-client \ + --client oidc \ + --target "${{ matrix.target }}" \ + --compatibility manylinux_2_17 \ + --zig-python "${RUNNER_TEMP}/maturin/bin/python" \ + --maturin "${RUNNER_TEMP}/maturin/bin/maturin" \ + --out "${built_wheel_dir}" \ + --profile release + else + (cd "${oidc_dir}" && "${RUNNER_TEMP}/maturin/bin/maturin" build \ + --release --locked --out "${built_wheel_dir}") + fi + test -f "${built_wheel_dir}/registry_platform_oidc-${CLIENT_VERSION}-${{ matrix.registry_wheel_tag }}.whl" + yaml_dir="${GITHUB_WORKSPACE}/crates/registry-platform-yaml-py" + configured_version="$(python3 -c 'import tomllib,sys; print(tomllib.load(open(sys.argv[1], "rb"))["project"]["version"])' "${yaml_dir}/pyproject.toml")" + test "${configured_version}" = "${CLIENT_VERSION}" + if [[ "${RUNNER_OS}" == Linux ]]; then + release/scripts/build-linux-python-client \ + --client yaml \ + --target "${{ matrix.target }}" \ + --compatibility manylinux_2_17 \ + --zig-python "${RUNNER_TEMP}/maturin/bin/python" \ + --maturin "${RUNNER_TEMP}/maturin/bin/maturin" \ + --out "${built_wheel_dir}" \ + --profile release + else + (cd "${yaml_dir}" && "${RUNNER_TEMP}/maturin/bin/maturin" build \ + --release --locked --out "${built_wheel_dir}") + fi + test -f "${built_wheel_dir}/registry_platform_yaml-${CLIENT_VERSION}-${{ matrix.registry_wheel_tag }}.whl" + fi if [[ "${unified_client}" -eq 1 ]]; then + oidc_wheel_args=() + if [[ "${oidc_in_release}" -eq 1 ]]; then + oidc_wheel_args=( + --include-oidc + --oidc-wheel + "${built_wheel_dir}/registry_platform_oidc-${CLIENT_VERSION}-${{ matrix.registry_wheel_tag }}.whl" + ) + fi + yaml_wheel_args=() + if [[ "${oidc_in_release}" -eq 1 ]]; then + yaml_wheel_args=( + --include-yaml + --yaml-wheel + "${built_wheel_dir}/registry_platform_yaml-${CLIENT_VERSION}-${{ matrix.registry_wheel_tag }}.whl" + ) + fi casework_wheel_args=() if [[ "${include_casework}" -eq 1 ]]; then casework_wheel_args=( @@ -1215,7 +1270,9 @@ jobs: ${casework_wheel_args[@]+"${casework_wheel_args[@]}"} \ ${messaging_wheel_args[@]+"${messaging_wheel_args[@]}"} \ ${scheduling_wheel_args[@]+"${scheduling_wheel_args[@]}"} \ - ${coordinator_wheel_args[@]+"${coordinator_wheel_args[@]}"} + ${coordinator_wheel_args[@]+"${coordinator_wheel_args[@]}"} \ + ${oidc_wheel_args[@]+"${oidc_wheel_args[@]}"} \ + ${yaml_wheel_args[@]+"${yaml_wheel_args[@]}"} expected_wheels=1 else cp "${built_wheel_dir}"/*.whl "${wheel_dir}/" diff --git a/Cargo.lock b/Cargo.lock index 4a21ca40b0..ec9c73ed72 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7897,6 +7897,18 @@ dependencies = [ "uuid", ] +[[package]] +name = "registry-platform-oidc-py" +version = "0.46.1" +dependencies = [ + "pyo3", + "pyo3-build-config", + "registry-platform-oidc", + "registry-platform-testing", + "serde_json", + "tokio", +] + [[package]] name = "registry-platform-ratelimit" version = "0.46.1" @@ -8027,6 +8039,19 @@ dependencies = [ "url", ] +[[package]] +name = "registry-platform-yaml-py" +version = "0.46.1" +dependencies = [ + "pyo3", + "pyo3-build-config", + "registry-platform-config", + "registry-platform-yaml", + "schemars", + "serde", + "serde_json", +] + [[package]] name = "registry-record" version = "0.46.1" diff --git a/Cargo.toml b/Cargo.toml index 50d855842b..d1418806ff 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -48,6 +48,7 @@ members = [ "crates/registry-platform-metrics", "crates/registry-platform-objectstore", "crates/registry-platform-oidc", + "crates/registry-platform-oidc-py", "crates/registry-platform-ratelimit", "crates/registry-platform-resilience", "crates/registry-platform-script", @@ -57,6 +58,7 @@ members = [ "crates/registry-platform-text", "crates/registry-platform-x509", "crates/registry-platform-yaml", + "crates/registry-platform-yaml-py", "crates/registry-thunderid-tooling", "crates/registry-manifest-core", "crates/registry-manifest-cli", diff --git a/crates/registry-bregctl/src/dev/config.rs b/crates/registry-bregctl/src/dev/config.rs index 38e0d7cad0..4d3e3af2d3 100644 --- a/crates/registry-bregctl/src/dev/config.rs +++ b/crates/registry-bregctl/src/dev/config.rs @@ -1895,6 +1895,7 @@ pub(super) fn issuer_description( redirect_uris: app.redirect_uris.clone(), audience, token_attributes: app.token_attributes.clone(), + refresh_tokens: false, }); description.roles.push(Role { id: registry_thunderid_tooling::local::agent_id( diff --git a/crates/registry-bregctl/src/project_dev/bindings.rs b/crates/registry-bregctl/src/project_dev/bindings.rs index 29e00d81d6..205735126d 100644 --- a/crates/registry-bregctl/src/project_dev/bindings.rs +++ b/crates/registry-bregctl/src/project_dev/bindings.rs @@ -339,6 +339,7 @@ fn render( "clientAssertionKeyRef": client_assertion_key_ref, }); } + Product::Messaging => {} } } @@ -895,6 +896,8 @@ mod tests { }, ), ]), + workloads: BTreeMap::new(), + development_pickers: Default::default(), bindings: Bindings { breg_review_authority: Some(BregReviewAuthority { id: "casework".to_owned(), @@ -930,6 +933,7 @@ mod tests { named_clients: BTreeSet::new(), }), casework_principals: BTreeMap::from([("producer".to_owned(), "sub".to_owned())]), + messaging_clients: BTreeSet::new(), binaries: BTreeMap::new(), } } diff --git a/crates/registry-bregctl/src/project_dev/database.rs b/crates/registry-bregctl/src/project_dev/database.rs index ebdb4283c8..0fda70c3bc 100644 --- a/crates/registry-bregctl/src/project_dev/database.rs +++ b/crates/registry-bregctl/src/project_dev/database.rs @@ -770,10 +770,10 @@ fn validate_run_id(run_id: &str) -> Result<()> { } fn validate_label(label: &str) -> Result<()> { - if matches!(label, "breg" | "breg_test" | "casework") { + if matches!(label, "breg" | "breg_test" | "casework" | "messaging") { Ok(()) } else { - bail!("the database label must be breg, breg_test, or casework") + bail!("the database label must be breg, breg_test, casework, or messaging") } } @@ -978,7 +978,7 @@ mod tests { #[test] fn only_owned_database_labels_are_accepted() { - for label in ["breg", "breg_test", "casework"] { + for label in ["breg", "breg_test", "casework", "messaging"] { assert!(validate_label(label).is_ok(), "refused {label}"); } for invalid in ["", "breg-test", "casework_test", "postgres"] { @@ -1505,7 +1505,12 @@ mod tests { #[test] fn run_object_names_list_every_name_provision_creates() { - for (label, spatial) in [("breg", true), ("breg_test", false), ("casework", false)] { + for (label, spatial) in [ + ("breg", true), + ("breg_test", false), + ("casework", false), + ("messaging", false), + ] { let names = Names::new(RUN_ID, label); let mut expected = vec![names.migration_role.clone(), names.runtime_role.clone()]; if spatial { diff --git a/crates/registry-bregctl/src/project_dev/issuer.rs b/crates/registry-bregctl/src/project_dev/issuer.rs index 4c093247ae..d22bb20e7c 100644 --- a/crates/registry-bregctl/src/project_dev/issuer.rs +++ b/crates/registry-bregctl/src/project_dev/issuer.rs @@ -71,6 +71,22 @@ impl Issuer { .block_on(self.sign(input, person, product, expires)) } + /// Sign one runner-owned envelope with the exact issuance time written + /// beside it. The supervisor supplies this time once for the whole + /// generation, so Python never has to infer whether files came from the + /// same rotation. + pub(super) fn token_at( + &self, + input: &RunInput, + person: &TestPerson, + product: Product, + issued_at: u64, + expires: u64, + ) -> Result> { + self.runtime + .block_on(self.sign_at(input, person, product, issued_at, expires)) + } + pub(super) async fn sign( &self, input: &RunInput, @@ -79,8 +95,19 @@ impl Issuer { expires: u64, ) -> Result> { let now = clock()?; - let expires = token_expiry(expires, now); - ensure!(expires > now, "the development run has expired"); + self.sign_at(input, person, product, now, expires).await + } + + async fn sign_at( + &self, + input: &RunInput, + person: &TestPerson, + product: Product, + issued_at: u64, + expires: u64, + ) -> Result> { + let expires = token_expiry(expires, issued_at); + ensure!(expires > issued_at, "the development run has expired"); let plan = &input.plan; let grant = &person.grants[&product]; let forward_context = product == Product::Casework && person.casework_context; @@ -117,7 +144,7 @@ impl Issuer { "scope".to_owned(), json!(scopes.into_iter().collect::>().join(" ")), ), - ("iat".to_owned(), json!(now)), + ("iat".to_owned(), json!(issued_at)), ("exp".to_owned(), json!(expires)), ("jti".to_owned(), json!(uuid::Uuid::new_v4())), ]); diff --git a/crates/registry-bregctl/src/project_dev/journey.rs b/crates/registry-bregctl/src/project_dev/journey.rs index 316a531b4b..59aea1fdca 100644 --- a/crates/registry-bregctl/src/project_dev/journey.rs +++ b/crates/registry-bregctl/src/project_dev/journey.rs @@ -736,6 +736,7 @@ mod tests { named_clients: Default::default(), }), casework_principals: BTreeMap::new(), + messaging_clients: Default::default(), binaries: BTreeMap::new(), } } diff --git a/crates/registry-bregctl/src/project_dev/mod.rs b/crates/registry-bregctl/src/project_dev/mod.rs index 3d5c0dbea8..f6947cfc54 100644 --- a/crates/registry-bregctl/src/project_dev/mod.rs +++ b/crates/registry-bregctl/src/project_dev/mod.rs @@ -7,9 +7,11 @@ mod database; pub(crate) mod guard; mod issuer; mod journey; +mod picker; pub(crate) mod plan; mod products; mod recovery; +mod workload; use anyhow::{bail, ensure, Context, Result}; use registry_platform_yaml::{Diagnostic, Report}; @@ -120,6 +122,8 @@ struct RunInput { schema_people: Vec, breg_authority: Option, casework_principals: BTreeMap, + #[serde(default)] + messaging_clients: BTreeSet, binaries: BTreeMap, } @@ -295,6 +299,7 @@ fn provisioned_labels(root: &Path) -> Result> { labels.push(("breg", spatial)); } Product::Casework => labels.push(("casework", false)), + Product::Messaging => labels.push(("messaging", false)), } } Ok(labels) @@ -522,6 +527,18 @@ fn emit(output: &mut dyn Write, report: &Value, machine: bool) -> std::io::Resul if let Some(logs) = report["logs"].as_str() { writeln!(output, " Logs {logs}")?; } + if let Some(connection) = report["connection_file"].as_str() { + writeln!(output, " Python connection {connection}")?; + } + if let Some(pickers) = report["picker_files"].as_object() { + for (persona, descriptor) in pickers { + writeln!( + output, + " Python {persona} picker {}", + descriptor.as_str().expect("picker descriptor path") + )?; + } + } if let Some(people) = report["people"].as_array() { for name in people { writeln!( @@ -663,6 +680,7 @@ fn start(project: &Path, ttl: Option<&str>) -> Result { schema_people, breg_authority: inspection.breg_authority, casework_principals: inspection.casework_principals, + messaging_clients: inspection.messaging_clients, binaries, }; let preparation = (|| { @@ -811,6 +829,8 @@ fn worker(root: &Path, output: &mut dyn Write) -> Result<()> { ensure_private(root, false)?; let mut database = None; let mut expiry = None; + let mut workload_credentials = None; + let mut picker_credentials = None; let prepared = catch_startup(|| { products.check()?; let ca = env::var_os(CA_FILE) @@ -841,13 +861,40 @@ fn worker(root: &Path, output: &mut dyn Write) -> Result<()> { products.services_alive()?, "a product exited during the journey" ); - let expires_at = clock()? + input.ttl_seconds; + let now = clock()?; + let expires_at = now + input.ttl_seconds; expiry = Some(expires_at); - let report = json!({ + workload_credentials = workload::WorkloadCredentials::prepare( + root, + input.clone(), + issuer.clone(), + &urls, + now, + expires_at, + )?; + let workload_connection = workload_credentials + .as_ref() + .map(|credentials| credentials.path()); + picker_credentials = picker::PickerCredentials::prepare( + root, + input.clone(), + issuer, + &urls, + workload_connection.as_deref(), + now, + expires_at, + )?; + let mut report = json!({ "schema_version": SCHEMA, "run_id": input.run_id, "status": "ready", "products": urls, "people": input.plan.people.keys().collect::>(), "journey": journey, "expires_at": expires_at, "logs": root.join("logs"), }); + if let Some(credentials) = &workload_credentials { + report["connection_file"] = json!(credentials.path()); + } + if let Some(credentials) = &picker_credentials { + report["picker_files"] = serde_json::to_value(credentials.paths())?; + } write_private(&root.join(REPORT), &capture_report(&report)?)?; Ok::<_, anyhow::Error>(report) }); @@ -866,6 +913,18 @@ fn worker(root: &Path, output: &mut dyn Write) -> Result<()> { && !stopping(root, &signals) && !expiry.is_some_and(|at| clock().map_or(true, |now| expired(now, at))) { + if let Some(credentials) = workload_credentials.as_mut() { + if let Err(error) = clock().and_then(|now| credentials.rotate_if_due(now)) { + eprintln!("development workload rotation failed: {error:#}"); + break; + } + } + if let Some(credentials) = picker_credentials.as_mut() { + if let Err(error) = clock().and_then(|now| credentials.rotate_if_due(now)) { + eprintln!("development person rotation failed: {error:#}"); + break; + } + } if !products.services_alive().unwrap_or(false) { break; } @@ -875,6 +934,16 @@ fn worker(root: &Path, output: &mut dyn Write) -> Result<()> { } Err(error) => failure = Some(WorkerReply::failed(&error)), } + if let Some(credentials) = picker_credentials.as_mut() { + if let Err(error) = clock().and_then(|now| credentials.invalidate(now)) { + eprintln!("development person invalidation failed: {error:#}"); + } + } + if let Some(credentials) = workload_credentials.as_mut() { + if let Err(error) = clock().and_then(|now| credentials.invalidate(now)) { + eprintln!("development workload invalidation failed: {error:#}"); + } + } let stopped = simple_report(&input.run_id, "stopping"); let mark_stopping = write_private(&root.join(REPORT), &serde_json::to_vec(&stopped)?); let mut told_parent = false; @@ -1007,7 +1076,9 @@ fn token(run_id: &str, person: &str) -> Result { Uuid::new_v4().simple() )); let headers = match product { - Product::Breg => format!("Authorization: Bearer {}\n", &*token), + Product::Breg | Product::Messaging => { + format!("Authorization: Bearer {}\n", &*token) + } Product::Casework => format!("Authorization: Bearer {}\nRegistry-Casework-Profile: {}\nRegistry-Review-Profile: {}\n", &*token, grant.profile, grant.profile), }; @@ -1218,6 +1289,7 @@ fn product_tool(product: Product) -> Result { match product { Product::Breg => "RSTACK_BREGCTL_BIN", Product::Casework => "RSTACK_CASEWORKCTL_BIN", + Product::Messaging => "RSTACK_MESSAGINGCTL_BIN", }, ) } @@ -1232,6 +1304,10 @@ fn binaries(product: Product) -> Result { tool: product_tool(product)?, runtime: binary(product, "RSTACK_CASEWORK_BIN")?, }, + Product::Messaging => Binaries { + tool: product_tool(product)?, + runtime: binary(product, "RSTACK_MESSAGING_BIN")?, + }, }) } @@ -1458,6 +1534,7 @@ mod tests { "named_clients": [] }, "casework_principals": {}, + "messaging_clients": [], "binaries": {} }); fs::write(root.join("input.json"), input.to_string()).unwrap(); @@ -1498,7 +1575,8 @@ mod tests { root, json!([ {"product": "breg", "project": ".", "audience": "registry"}, - {"product": "casework", "project": ".", "audience": "casework"} + {"product": "casework", "project": ".", "audience": "casework"}, + {"product": "messaging", "project": ".", "audience": "messaging"} ]), true, ); @@ -1517,12 +1595,13 @@ mod tests { .iter() .map(|object| object["label"].as_str().unwrap()) .collect(); - assert_eq!(labels, ["breg_test", "breg", "casework"]); + assert_eq!(labels, ["breg_test", "breg", "casework", "messaging"]); let breg = &facts["objects"][1]; assert_eq!(breg["database"], format!("rstack_{RUN_ID}_breg")); // Migration, runtime and the spatial bbox role. assert_eq!(breg["roles"].as_array().unwrap().len(), 3); assert_eq!(facts["objects"][2]["roles"].as_array().unwrap().len(), 2); + assert_eq!(facts["objects"][3]["roles"].as_array().unwrap().len(), 2); let text = recovery_message(RUN_ID, &facts); assert!( text.contains("process \"breg\" pid 4242 pgid 4242"), diff --git a/crates/registry-bregctl/src/project_dev/picker.rs b/crates/registry-bregctl/src/project_dev/picker.rs new file mode 100644 index 0000000000..f3d4b00acb --- /dev/null +++ b/crates/registry-bregctl/src/project_dev/picker.rs @@ -0,0 +1,600 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Live-run descriptors and rotating person credentials for local Python pickers. + +use anyhow::{ensure, Context, Result}; +use serde_json::{json, Map, Value}; +use std::{ + collections::{BTreeMap, BTreeSet}, + io, + net::{Ipv4Addr, TcpListener}, + path::{Path, PathBuf}, + sync::Arc, +}; +use uuid::Uuid; +use zeroize::Zeroizing; + +use super::{ + issuer::{self, Issuer}, + plan::{DevelopmentPicker, PickerPersona, Product, TestPerson}, + private_directory, write_private, RunInput, +}; + +pub(super) const DESCRIPTOR_FORMAT: &str = + "id.registrystack.org/formats/platform/dev-person-picker/v1alpha1"; +pub(super) const DESCRIPTOR_KIND: &str = "PlatformDevPersonPicker"; +pub(super) const TOKEN_FORMAT: &str = + "id.registrystack.org/formats/platform/dev-person-token/v1alpha1"; +pub(super) const TOKEN_KIND: &str = "PlatformDevPersonToken"; +pub(super) const GENERATION_FORMAT: &str = + "id.registrystack.org/formats/platform/dev-person-generation/v1alpha1"; +pub(super) const GENERATION_KIND: &str = "PlatformDevPersonGeneration"; +const DIRECTORY: &str = "python-picker"; +const DESCRIPTOR_FILE: &str = "picker.json"; +const GENERATION_FILE: &str = "generation.json"; +const ROTATION_SECONDS: u64 = 60; + +struct PickerPerson { + alias: String, + selector: String, + token_files: BTreeMap, +} + +struct PickerState { + persona: PickerPersona, + root: PathBuf, + origin: String, + session_namespace: String, + people: Vec, +} + +/// One supervisor-owned credential set for every explicitly configured local +/// picker. The browser receives selectors and labels only; every credential +/// file remains in the owner-only run directory. +pub(super) struct PickerCredentials { + input: Arc, + issuer: Arc, + urls: BTreeMap, + workload_connection: Option, + pickers: Vec, + generation: u64, + next_rotation: u64, + run_expires: u64, +} + +impl PickerCredentials { + pub(super) fn prepare( + root: &Path, + input: Arc, + issuer: Arc, + urls: &BTreeMap, + workload_connection: Option<&Path>, + now: u64, + run_expires: u64, + ) -> Result> { + if input.plan.development_pickers.is_empty() { + return Ok(None); + } + ensure!(now < run_expires, "the development run has expired"); + let base = root.join(DIRECTORY); + make_private_directory(&base).context("cannot create private Python picker state")?; + let mut pickers = Vec::new(); + for (persona, plan) in input.plan.development_pickers.iter() { + let picker_root = base.join(persona.name()); + make_private_directory(&picker_root) + .context("cannot create private Python picker persona state")?; + let reservation = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)) + .context("cannot reserve a loopback Python picker origin")?; + let origin = format!("http://{}", reservation.local_addr()?); + drop(reservation); + let people = plan + .people + .iter() + .enumerate() + .map(|(index, alias)| PickerPerson { + alias: alias.clone(), + selector: Uuid::new_v4().simple().to_string(), + token_files: plan + .person_products + .iter() + .map(|product| { + (*product, format!("person-{index}-{}.json", product.name())) + }) + .collect(), + }) + .collect(); + pickers.push(PickerState { + persona, + root: picker_root, + origin, + session_namespace: Uuid::new_v4().simple().to_string(), + people, + }); + } + let mut credentials = Self { + input, + issuer, + urls: urls.clone(), + workload_connection: workload_connection.map(Path::to_owned), + pickers, + generation: 0, + next_rotation: now, + run_expires, + }; + credentials.rotate(now)?; + for picker in &credentials.pickers { + let descriptor = credentials.descriptor(picker, now)?; + write_private( + &picker.root.join(DESCRIPTOR_FILE), + &serde_json::to_vec(&descriptor)?, + )?; + } + Ok(Some(credentials)) + } + + pub(super) fn paths(&self) -> BTreeMap<&'static str, PathBuf> { + self.pickers + .iter() + .map(|picker| (picker.persona.name(), picker.root.join(DESCRIPTOR_FILE))) + .collect() + } + + pub(super) fn rotate_if_due(&mut self, now: u64) -> Result<()> { + if now >= self.next_rotation && now < self.run_expires { + self.rotate(now)?; + } + Ok(()) + } + + pub(super) fn invalidate(&mut self, now: u64) -> Result<()> { + let generation = self + .generation + .checked_add(1) + .context("person token generation overflow")?; + let stopped_at = now.min(self.run_expires); + for picker in &self.pickers { + for person in &picker.people { + for (product, file) in &person.token_files { + let state = self.token_metadata( + picker, person, *product, generation, stopped_at, stopped_at, + ); + let mut state = state.as_object().expect("token state object").clone(); + state.insert("status".to_owned(), json!("stopped")); + write_private( + &picker.root.join(file), + &serde_json::to_vec(&Value::Object(state))?, + )?; + } + } + self.write_generation(picker, generation, "stopped")?; + } + self.generation = generation; + self.next_rotation = self.run_expires; + Ok(()) + } + + fn rotate(&mut self, now: u64) -> Result<()> { + let generation = self + .generation + .checked_add(1) + .context("person token generation overflow")?; + self.generation = generation; + let expires_at = issuer::token_expiry(self.run_expires, now); + ensure!(expires_at > now, "the development run has expired"); + for picker in &self.pickers { + for person in &picker.people { + let declared = &self.input.plan.people[&person.alias]; + for (product, file) in &person.token_files { + let grant = declared.grants[product].clone(); + let mut claims = grant.claims.clone(); + claims.insert( + "registry_dev_persona".to_owned(), + json!(picker.persona.name()), + ); + let token_person = TestPerson { + subject: declared.subject.clone(), + client: declared.client.clone(), + grants: BTreeMap::from([( + *product, + super::plan::Grant { claims, ..grant }, + )]), + casework_context: declared.casework_context, + }; + let token = self.issuer.token_at( + &self.input, + &token_person, + *product, + now, + expires_at, + )?; + let mut state = self + .token_metadata(picker, person, *product, generation, now, expires_at) + .as_object() + .expect("token state object") + .clone(); + state.insert("token".to_owned(), json!(&*token)); + write_private( + &picker.root.join(file), + Zeroizing::new(serde_json::to_vec(&Value::Object(state))?).as_slice(), + )?; + } + } + // Publishing the marker last makes a mixed file set unusable. + self.write_generation(picker, generation, "ready")?; + } + self.next_rotation = now.saturating_add(ROTATION_SECONDS).min(self.run_expires); + Ok(()) + } + + fn write_generation(&self, picker: &PickerState, generation: u64, status: &str) -> Result<()> { + write_private( + &picker.root.join(GENERATION_FILE), + &serde_json::to_vec(&json!({ + "apiVersion": GENERATION_FORMAT, + "kind": GENERATION_KIND, + "status": status, + "runId": self.input.run_id, + "picker": picker.persona.name(), + "generation": generation, + "runExpiresAt": self.run_expires, + }))?, + ) + } + + fn descriptor(&self, picker: &PickerState, issued_at: u64) -> Result { + let plan = picker_plan(&self.input, picker.persona); + let product_set = plan + .person_products + .iter() + .copied() + .chain( + plan.workloads + .iter() + .map(|name| self.input.plan.workloads[name].product), + ) + .collect::>(); + let products = product_set + .iter() + .map(|product| { + ( + product.name().to_owned(), + json!({ + "url": self.urls[product], + "resource": self.input.plan.product(*product).audience, + }), + ) + }) + .collect::>(); + let people = picker + .people + .iter() + .map(|person| { + let declared = &self.input.plan.people[&person.alias]; + let credentials = person + .token_files + .iter() + .map(|(product, token_ref)| { + let grant = &declared.grants[product]; + ( + product.name().to_owned(), + json!({ + "tokenRef": token_ref, + "profile": grant.profile, + "resource": self.input.plan.product(*product).audience, + "audiences": audiences(&self.input, declared, *product), + "scopes": grant.scopes, + "principalClaim": principal_claim(&self.input, grant, *product), + }), + ) + }) + .collect::>(); + json!({ + "selector": person.selector, + "label": person.alias, + "subject": declared.subject, + "principal": declared.subject, + "clientId": declared.client, + "credentials": credentials, + }) + }) + .collect::>(); + let workloads = plan + .workloads + .iter() + .map(|name| { + let workload = &self.input.plan.workloads[name]; + json!({ + "name": name, + "product": workload.product, + "default": workload.default, + "url": self.urls[&workload.product], + "issuer": self.input.plan.issuer, + "subject": workload.subject, + "clientId": workload.client, + "profile": workload.grant.profile, + "resource": self.input.plan.product(workload.product).audience, + "scopes": workload.grant.scopes, + "claims": workload.grant.claims, + }) + }) + .collect::>(); + let connection_ref = if plan.workloads.is_empty() { + Value::Null + } else { + ensure!( + self.workload_connection.is_some(), + "development picker workloads need the run's generated connection" + ); + json!("../../python-workload/python-connection.json") + }; + Ok(json!({ + "apiVersion": DESCRIPTOR_FORMAT, + "kind": DESCRIPTOR_KIND, + "runId": self.input.run_id, + "persona": picker.persona.name(), + "origin": picker.origin, + "sessionNamespace": picker.session_namespace, + "issuedAt": issued_at, + "expiresAt": self.run_expires, + "generationRef": GENERATION_FILE, + "products": products, + "people": people, + "workloadConnectionRef": connection_ref, + "workloads": workloads, + })) + } + + fn token_metadata( + &self, + picker: &PickerState, + person: &PickerPerson, + product: Product, + generation: u64, + issued_at: u64, + expires_at: u64, + ) -> Value { + let declared = &self.input.plan.people[&person.alias]; + let grant = &declared.grants[&product]; + json!({ + "apiVersion": TOKEN_FORMAT, + "kind": TOKEN_KIND, + "runId": self.input.run_id, + "picker": picker.persona.name(), + "persona": picker.persona.name(), + "selector": person.selector, + "product": product, + "issuer": self.input.plan.issuer, + "subject": declared.subject, + "principal": declared.subject, + "clientId": declared.client, + "profile": grant.profile, + "resource": self.input.plan.product(product).audience, + "audiences": audiences(&self.input, declared, product), + "scopes": grant.scopes, + "principalClaim": principal_claim(&self.input, grant, product), + "generation": generation, + "issuedAt": issued_at, + "expiresAt": expires_at, + "runExpiresAt": self.run_expires, + }) + } +} + +fn picker_plan(input: &RunInput, persona: PickerPersona) -> &DevelopmentPicker { + match persona { + PickerPersona::Holder => input.plan.development_pickers.holder.as_ref(), + PickerPersona::Staff => input.plan.development_pickers.staff.as_ref(), + } + .expect("configured picker") +} + +fn audiences<'a>(input: &'a RunInput, person: &TestPerson, product: Product) -> Vec<&'a str> { + if product == Product::Casework && person.casework_context { + vec![ + &input.plan.product(Product::Casework).audience, + &input.plan.product(Product::Breg).audience, + ] + } else { + vec![&input.plan.product(product).audience] + } +} + +fn principal_claim<'a>( + input: &'a RunInput, + grant: &'a super::plan::Grant, + product: Product, +) -> &'a str { + match product { + Product::Breg => { + &input + .breg_authority + .as_ref() + .expect("BReg authority") + .principal + } + Product::Casework => &input.casework_principals[&grant.profile], + Product::Messaging => "sub", + } +} + +fn make_private_directory(path: &Path) -> Result<()> { + match private_directory(path) { + Ok(()) => Ok(()), + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => { + super::ensure_private(path, false) + } + Err(error) => Err(error.into()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::project_dev::{plan::Plan, BregAuthority, RunInput}; + use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; + use std::{collections::BTreeSet, os::unix::fs::PermissionsExt}; + + fn input(root: &Path) -> Arc { + let plan: Plan = serde_json::from_value(json!({ + "issuer": "https://issuer.example.test", + "products": [ + {"product": "breg", "project": ".", "audience": "urn:test:breg"}, + {"product": "casework", "project": ".", "audience": "urn:test:casework"}, + {"product": "messaging", "project": ".", "audience": "urn:test:messaging"} + ], + "people": {"applicant": { + "subject": "person-one", "client": "portal-client", + "grants": { + "breg": {"profile": "applicant", "scopes": ["breg:read"]}, + "casework": {"profile": "requester", "scopes": ["casework:read"]} + } + }}, + "workloads": {"notices": { + "product": "messaging", "default": true, + "subject": "notice-service", "client": "notice-client", + "grant": {"profile": "service-sender", "scopes": ["messaging:send"]} + }}, + "developmentPickers": {"holder": { + "people": ["applicant"], + "personProducts": ["breg", "casework"], + "workloads": ["notices"] + }}, + "journey": {"id": "read", "steps": [{ + "id": "read", "product": "breg", "as": "applicant", "method": "GET", + "path": "/v1/records", "expect": {"status": 200} + }]} + })) + .unwrap(); + Arc::new(RunInput { + run_id: "0123456789abcdef0123456789abcdef".to_owned(), + project: root.to_owned(), + plan, + ttl_seconds: 600, + schema_people: Vec::new(), + breg_authority: Some(BregAuthority { + principal: "registry_principal".to_owned(), + purpose: false, + requires_postgis: false, + encrypts_fields: false, + named_clients: BTreeSet::new(), + }), + casework_principals: BTreeMap::from([( + "requester".to_owned(), + "registry_principal".to_owned(), + )]), + messaging_clients: BTreeSet::new(), + binaries: BTreeMap::new(), + }) + } + + #[test] + fn descriptor_and_tokens_are_bounded_to_one_live_run_and_rotate_as_a_set() { + let scratch = tempfile::tempdir().unwrap(); + std::fs::set_permissions(scratch.path(), PermissionsExt::from_mode(0o700)).unwrap(); + let workload = scratch.path().join("python-workload"); + make_private_directory(&workload).unwrap(); + let connection = workload.join("python-connection.json"); + write_private(&connection, b"{}").unwrap(); + let input = input(scratch.path()); + let issuer = Arc::new(Issuer::create(scratch.path()).unwrap()); + let now = super::super::clock().unwrap(); + let run_expires = now + 600; + let mut credentials = PickerCredentials::prepare( + scratch.path(), + input, + issuer, + &BTreeMap::from([ + (Product::Breg, "http://127.0.0.1:41001".to_owned()), + (Product::Casework, "http://127.0.0.1:41002".to_owned()), + (Product::Messaging, "http://127.0.0.1:41003".to_owned()), + ]), + Some(&connection), + now, + run_expires, + ) + .unwrap() + .unwrap(); + + let descriptor_path = credentials.paths()["holder"].clone(); + let descriptor_bytes = std::fs::read(&descriptor_path).unwrap(); + let descriptor: Value = serde_json::from_slice(&descriptor_bytes).unwrap(); + assert_eq!(descriptor["kind"], DESCRIPTOR_KIND); + assert_eq!(descriptor["persona"], "holder"); + assert!(descriptor["origin"] + .as_str() + .unwrap() + .starts_with("http://127.0.0.1:")); + assert_eq!(descriptor["people"][0]["label"], "applicant"); + assert_ne!(descriptor["people"][0]["selector"], "applicant"); + assert_eq!( + descriptor["people"][0]["credentials"]["breg"]["tokenRef"], + "person-0-breg.json" + ); + assert_eq!(descriptor["workloads"][0]["name"], "notices"); + assert_eq!( + descriptor["workloadConnectionRef"], + "../../python-workload/python-connection.json" + ); + let descriptor_text = String::from_utf8(descriptor_bytes).unwrap(); + assert!(!descriptor_text.contains("issuer-key")); + assert!(!descriptor_text.contains("\"token\"")); + assert_eq!( + std::fs::metadata(&descriptor_path) + .unwrap() + .permissions() + .mode() + & 0o777, + 0o600 + ); + + let picker_root = descriptor_path.parent().unwrap(); + let breg_path = picker_root.join("person-0-breg.json"); + let first: Value = serde_json::from_slice(&std::fs::read(&breg_path).unwrap()).unwrap(); + assert_eq!(first["generation"], 1); + assert_eq!(first["persona"], "holder"); + let payload = first["token"].as_str().unwrap().split('.').nth(1).unwrap(); + let claims: Value = + serde_json::from_slice(&URL_SAFE_NO_PAD.decode(payload).unwrap()).unwrap(); + assert_eq!(claims["registry_dev_persona"], "holder"); + assert_eq!(claims["aud"], "urn:test:breg"); + assert_eq!(claims["iat"], first["issuedAt"]); + assert_eq!(claims["exp"], first["expiresAt"]); + + credentials.rotate_if_due(now + ROTATION_SECONDS).unwrap(); + let second: Value = serde_json::from_slice(&std::fs::read(&breg_path).unwrap()).unwrap(); + let marker: Value = + serde_json::from_slice(&std::fs::read(picker_root.join(GENERATION_FILE)).unwrap()) + .unwrap(); + assert_eq!(second["generation"], 2); + assert_eq!(marker["generation"], 2); + assert_ne!(first["token"], second["token"]); + for field in [ + "runId", + "picker", + "persona", + "selector", + "product", + "issuer", + "subject", + "principal", + "clientId", + "profile", + "resource", + "audiences", + "scopes", + "principalClaim", + "runExpiresAt", + ] { + assert_eq!(first[field], second[field], "{field}"); + } + + credentials.invalidate(now + ROTATION_SECONDS + 1).unwrap(); + let stopped_marker: Value = + serde_json::from_slice(&std::fs::read(picker_root.join(GENERATION_FILE)).unwrap()) + .unwrap(); + let stopped: Value = serde_json::from_slice(&std::fs::read(&breg_path).unwrap()).unwrap(); + assert_eq!(stopped_marker["status"], "stopped"); + assert_eq!(stopped_marker["generation"], 3); + assert_eq!(stopped["status"], "stopped"); + assert!(stopped.get("token").is_none()); + } +} diff --git a/crates/registry-bregctl/src/project_dev/plan.rs b/crates/registry-bregctl/src/project_dev/plan.rs index 44154e410e..50947e4c9d 100644 --- a/crates/registry-bregctl/src/project_dev/plan.rs +++ b/crates/registry-bregctl/src/project_dev/plan.rs @@ -146,6 +146,7 @@ fn expected_json_schema(generator: &mut schemars::SchemaGenerator) -> schemars:: pub(super) enum Product { Breg, Casework, + Messaging, } impl Product { @@ -153,6 +154,7 @@ impl Product { match self { Self::Breg => "breg", Self::Casework => "casework", + Self::Messaging => "messaging", } } } @@ -173,6 +175,16 @@ pub(super) struct Plan { schemars(schema_with = "keyed_schema::") )] pub people: BTreeMap, + /// Service workload bindings whose short-lived credentials the live run owns and rotates. + #[serde(default)] + #[cfg_attr( + feature = "schema", + schemars(schema_with = "keyed_schema::") + )] + pub workloads: BTreeMap, + /// Explicit local person-picker services. Omit this map for normal production-style connections. + #[serde(default)] + pub development_pickers: DevelopmentPickers, /// The ordered sequence of HTTP requests the run sends to the started products. pub journey: Journey, /// Run-local connections between BReg and Casework. Leave empty when the products do not call each other. @@ -194,7 +206,7 @@ pub(super) struct Plan { pub(super) struct ProductPlan { /// Which product to start. pub product: Product, - /// Relative path from the plan's directory to the product project, or `.` for the plan's own directory. It must contain registry.yaml for BReg or casework.yaml for Casework. + /// Relative path from the plan's directory to the product project, or `.` for the plan's own directory. It must contain registry.yaml for BReg, casework.yaml for Casework, or messaging.yaml for Messaging. pub project: PathBuf, /// Token audience this product accepts: 1 to 256 characters without whitespace or control characters, distinct from the other products' audiences. #[cfg_attr(feature = "schema", schemars(with = "ExternalId"))] @@ -212,7 +224,7 @@ pub(super) struct TestPerson { /// Client identifier of this person's tokens: 1 to 256 characters without whitespace or control characters. #[cfg_attr(feature = "schema", schemars(with = "ExternalId"))] pub client: String, - /// The authority this person holds in each product, keyed by `breg` or `casework`. Give at least one grant, only for products listed in `products`. + /// The authority this person holds in each product, keyed by `breg`, `casework`, or `messaging`. Give at least one grant, only for products listed in `products`. #[serde(deserialize_with = "deserialize_grants")] pub grants: BTreeMap, /// Forward the same authority to both products. Both grants must declare the same scopes and additional claims. @@ -220,8 +232,8 @@ pub(super) struct TestPerson { pub casework_context: bool, } -/// The authority a test person holds in one product. -#[derive(Deserialize, Serialize)] +/// The authority a test person or service workload holds in one product. +#[derive(Clone, Deserialize, Serialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(deny_unknown_fields)] pub(super) struct Grant { @@ -238,11 +250,87 @@ pub(super) struct Grant { pub claims: Map, } +/// One runner-owned service identity and its fixed product authority. +#[derive(Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct Workload { + /// Product this binding calls. Generated workload connections support BReg and Messaging. + pub product: Product, + /// Whether this is the generated connection's default binding for its product. + pub default: bool, + /// Stable subject claim preserved across token generations. + #[cfg_attr(feature = "schema", schemars(with = "ExternalId"))] + pub subject: String, + /// Stable client identifier preserved across token generations. + #[cfg_attr(feature = "schema", schemars(with = "ExternalId"))] + pub client: String, + /// Fixed profile, scopes and additional claims for this binding. + pub grant: Grant, +} + +/// The two deliberately separate local browser personas a development run may expose. +#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] +pub(super) enum PickerPersona { + Holder, + Staff, +} + +impl PickerPersona { + pub(super) fn name(self) -> &'static str { + match self { + Self::Holder => "holder", + Self::Staff => "staff", + } + } +} + +/// Optional local picker services. Holder and staff keep distinct origins and cookies. +#[derive(Default, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(deny_unknown_fields)] +pub(super) struct DevelopmentPickers { + /// A holder-only local admission simulation. + pub holder: Option, + /// A staff-only local admission simulation. + pub staff: Option, +} + +impl DevelopmentPickers { + pub(super) fn iter(&self) -> impl Iterator { + [ + (PickerPersona::Holder, self.holder.as_ref()), + (PickerPersona::Staff, self.staff.as_ref()), + ] + .into_iter() + .filter_map(|(persona, picker)| picker.map(|picker| (persona, picker))) + } + + pub(super) fn is_empty(&self) -> bool { + self.holder.is_none() && self.staff.is_none() + } +} + +/// One runner-generated loopback picker and exactly the authority it may expose. +#[derive(Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct DevelopmentPicker { + /// Test-person aliases eligible for this persona. The browser receives opaque selectors instead. + pub people: Vec, + /// Complete person credential set required before a picker session opens. + pub person_products: Vec, + /// Service workload bindings available to this picker-backed application. + #[serde(default)] + pub workloads: Vec, +} + #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct GrantsDocument { breg: Option, casework: Option, + messaging: Option, } fn deserialize_grants<'de, D>( @@ -255,6 +343,7 @@ where Ok([ grants.breg.map(|grant| (Product::Breg, grant)), grants.casework.map(|grant| (Product::Casework, grant)), + grants.messaging.map(|grant| (Product::Messaging, grant)), ] .into_iter() .flatten() @@ -688,7 +777,7 @@ impl Plan { !self.products.is_empty(), "/products", "The plan must name at least one product.", - "Add a BReg or Casework product to products.", + "Add a BReg, Casework, or Messaging product to products.", )?; let mut products = BTreeSet::new(); let mut audiences = BTreeSet::new(); @@ -720,6 +809,7 @@ impl Plan { let manifest = match entry.product { Product::Breg => "registry.yaml", Product::Casework => "casework.yaml", + Product::Messaging => "messaging.yaml", }; require( root.join(&entry.project) @@ -761,7 +851,7 @@ impl Plan { !person.grants.is_empty(), &format!("{field}/grants"), "The test person must have at least one product grant.", - "Add a BReg or Casework grant for this test person.", + "Add a BReg, Casework, or Messaging grant for this test person.", )?; for (product, grant) in &person.grants { let field = format!("{field}/grants/{}", product.name()); @@ -771,29 +861,7 @@ impl Plan { "The grant names a product that is not started.", "Add the grant's product to products, or remove this grant.", )?; - require( - identifier(&grant.profile), - &format!("{field}/profile"), - "The grant profile must be a local identifier.", - "Set profile to a lowercase local identifier of at most 64 characters.", - )?; - let scopes = grant.scopes.iter().collect::>(); - require( - scopes.len() == grant.scopes.len() - && scopes.len() <= 32 - && scopes.iter().all(|scope| bounded_atom(scope)), - &format!("{field}/scopes"), - "The grant must contain at most 32 distinct bounded scopes.", - "Remove duplicate or excess scopes, and keep each scope within 256 characters without whitespace or control characters.", - )?; - for claim in grant.claims.keys() { - require( - bounded_atom(claim) && !reserved_claim(claim), - &format!("{field}/claims"), - "The grant contains a reserved or invalid additional claim name.", - "Remove the claim or rename it to bounded text that is not reserved by the token contract.", - )?; - } + validate_grant(grant, &field)?; } if person.casework_context { require( @@ -824,6 +892,139 @@ impl Plan { )?; } } + let mut workload_products = BTreeSet::new(); + let mut workload_defaults = BTreeMap::::new(); + for (name, workload) in &self.workloads { + let escaped = escape_pointer_segment(name); + let field = format!("/workloads/{escaped}"); + require( + identifier(name), + "/workloads", + "A workload binding name is not a local identifier.", + "Rename the workload binding with a lowercase local identifier of at most 64 characters.", + )?; + require( + matches!(workload.product, Product::Breg | Product::Messaging) + && products.contains(&workload.product), + &format!("{field}/product"), + "The workload binding must name a started product supported by the generated Python connection.", + "Use a started BReg or Messaging product, or remove this workload binding.", + )?; + require( + bounded_atom(&workload.subject), + &format!("{field}/subject"), + "The workload subject must be bounded text without whitespace or control characters.", + "Set subject to at most 256 characters without whitespace or control characters.", + )?; + require( + bounded_atom(&workload.client), + &format!("{field}/client"), + "The workload client must be a bounded client identifier.", + "Set client to at most 256 characters without whitespace or control characters.", + )?; + let grant_field = format!("{field}/grant"); + validate_grant(&workload.grant, &grant_field)?; + require( + !workload.grant.scopes.is_empty() + && workload.grant.scopes.iter().all(|scope| scope.len() <= 128), + &format!("{grant_field}/scopes"), + "A generated Python workload needs one to 32 scopes of at most 128 characters.", + "Add the exact workload scopes and keep each scope within 128 characters.", + )?; + workload_products.insert(workload.product); + if workload.default { + *workload_defaults.entry(workload.product).or_default() += 1; + } + } + for product in workload_products { + require( + workload_defaults.get(&product) == Some(&1), + "/workloads", + format!( + "The generated connection needs exactly one default workload binding for {}.", + product.name() + ), + format!( + "Mark exactly one {} workload binding as default.", + product.name() + ), + )?; + } + let mut picker_people = BTreeSet::new(); + for (persona, picker) in self.development_pickers.iter() { + let field = format!("/developmentPickers/{}", persona.name()); + let people = picker.people.iter().collect::>(); + require( + (1..=32).contains(&picker.people.len()) && people.len() == picker.people.len(), + &format!("{field}/people"), + "A development picker needs 1 to 32 distinct test people.", + "Name each eligible test person exactly once.", + )?; + for person in &picker.people { + require( + self.people.contains_key(person), + &format!("{field}/people"), + "A development picker names an unknown test person.", + "Name a test person declared in people.", + )?; + require( + picker_people.insert(person), + &format!("{field}/people"), + "One test person cannot be eligible for both local picker personas.", + "Use separate synthetic test people for holder and staff services.", + )?; + } + let person_products = picker.person_products.iter().collect::>(); + require( + !picker.person_products.is_empty() + && person_products.len() == picker.person_products.len(), + &format!("{field}/personProducts"), + "A development picker needs a distinct nonempty person product set.", + "List every product grant required before the local session opens.", + )?; + for product in &picker.person_products { + require( + matches!(product, Product::Breg | Product::Casework) + && products.contains(product), + &format!("{field}/personProducts"), + "A development picker person product must be a started BReg or Casework product.", + "Use BReg and Casework person grants; keep Messaging authority in a declared service workload.", + )?; + for person in &picker.people { + require( + self.people[person].grants.contains_key(product), + &format!("{field}/people"), + format!( + "Test person {person} lacks the complete {} grant required by this picker.", + product.name() + ), + "Add the declared product grant or remove this person from the picker.", + )?; + } + } + let picker_workloads = picker.workloads.iter().collect::>(); + require( + picker.workloads.len() <= 32 && picker_workloads.len() == picker.workloads.len(), + &format!("{field}/workloads"), + "A development picker may name at most 32 distinct workload bindings.", + "Remove duplicate or excess workload binding names.", + )?; + require( + picker_workloads + == self.workloads.keys().collect::>(), + &format!("{field}/workloads"), + "A development picker must explicitly bind the complete runner workload set.", + "List every runner-owned workload binding, or remove workloads not intended for this local service.", + )?; + for workload in &picker.workloads { + require( + self.workloads.contains_key(workload), + &format!("{field}/workloads"), + "A development picker names an unknown workload binding.", + "Name a runner-owned binding declared in workloads.", + )?; + } + } for (journey, steps) in &self.schema_test_people { for (step, person) in steps { let field = format!( @@ -862,6 +1063,33 @@ impl Plan { } } +fn validate_grant(grant: &Grant, field: &str) -> SemanticResult<()> { + require( + identifier(&grant.profile), + &format!("{field}/profile"), + "The grant profile must be a local identifier.", + "Set profile to a lowercase local identifier of at most 64 characters.", + )?; + let scopes = grant.scopes.iter().collect::>(); + require( + scopes.len() == grant.scopes.len() + && scopes.len() <= 32 + && scopes.iter().all(|scope| bounded_atom(scope)), + &format!("{field}/scopes"), + "The grant must contain at most 32 distinct bounded scopes.", + "Remove duplicate or excess scopes, and keep each scope within 256 characters without whitespace or control characters.", + )?; + for claim in grant.claims.keys() { + require( + bounded_atom(claim) && !reserved_claim(claim), + &format!("{field}/claims"), + "The grant contains a reserved or invalid additional claim name.", + "Remove the claim or rename it to bounded text that is not reserved by the token contract.", + )?; + } + Ok(()) +} + impl Journey { fn validate(&self, plan: &Plan) -> SemanticResult<()> { require( @@ -1243,6 +1471,173 @@ mod tests { assert!(!plan.people["operator"].casework_context); } + #[test] + fn workload_bindings_declare_service_authority_without_a_key_or_token() { + let (root, plan) = plan(json!({ + "id": "read", "product": "breg", "as": "operator", + "method": "GET", "path": "/v1/records", "expect": {"status": 200} + })); + let mut value = serde_json::to_value(plan).unwrap(); + value["workloads"] = json!({ + "registry": { + "product": "breg", "default": true, + "subject": "licensing-service", "client": "licensing-service", + "grant": { + "profile": "operator", "scopes": ["registry:read"], + "claims": {"registry_actor_kind": "service"} + } + } + }); + let plan: Plan = serde_json::from_value(value).unwrap(); + + plan.validate(&canonical(&root)).unwrap(); + let binding = &plan.workloads["registry"]; + assert_eq!(binding.product, Product::Breg); + assert!(binding.default); + assert_eq!(binding.grant.profile, "operator"); + } + + #[test] + fn workload_bindings_require_one_default_and_started_products() { + let (root, plan) = plan(json!({ + "id": "read", "product": "breg", "as": "operator", + "method": "GET", "path": "/v1/records", "expect": {"status": 200} + })); + let base = serde_json::to_value(plan).unwrap(); + for workloads in [ + json!({ + "one": {"product": "breg", "default": false, "subject": "service", + "client": "service", "grant": { + "profile": "operator", "scopes": ["registry:read"]}} + }), + json!({ + "one": {"product": "breg", "default": true, "subject": "service", + "client": "service", "grant": { + "profile": "operator", "scopes": ["registry:read"]}}, + "two": {"product": "breg", "default": true, "subject": "service-two", + "client": "service-two", "grant": { + "profile": "operator", "scopes": ["registry:read"]}} + }), + ] { + let mut value = base.clone(); + value["workloads"] = workloads; + let plan: Plan = serde_json::from_value(value).unwrap(); + let error = plan.validate(&canonical(&root)).unwrap_err().to_string(); + assert!(error.contains("default workload binding"), "{error}"); + } + } + + #[test] + fn messaging_people_and_workloads_use_their_own_product_authority() { + let (root, plan) = plan(json!({ + "id": "read", "product": "breg", "as": "operator", + "method": "GET", "path": "/v1/records", "expect": {"status": 200} + })); + fs::create_dir(root.path().join("messaging")).unwrap(); + fs::write(root.path().join("messaging/messaging.yaml"), "fixture").unwrap(); + let mut value = serde_json::to_value(plan).unwrap(); + value["products"].as_array_mut().unwrap().push(json!({ + "product": "messaging", + "project": "messaging", + "audience": "urn:test:messaging" + })); + value["people"]["operator"]["grants"]["messaging"] = json!({ + "profile": "service-sender", + "scopes": ["messaging:send"], + "claims": {"registry_actor_kind": "service"} + }); + value["workloads"] = json!({ + "registry": { + "product": "breg", "default": true, + "subject": "registry-service", "client": "registry-service", + "grant": {"profile": "operator", "scopes": ["registry:read"]} + }, + "notices": { + "product": "messaging", "default": true, + "subject": "notice-service", "client": "notice-service", + "grant": { + "profile": "service-sender", "scopes": ["messaging:send"], + "claims": {"registry_actor_kind": "service"} + } + } + }); + let plan: Plan = serde_json::from_value(value).unwrap(); + + plan.validate(&canonical(&root)).unwrap(); + assert_eq!(plan.workloads["notices"].product, Product::Messaging); + assert_ne!( + plan.product(Product::Breg).audience, + plan.product(Product::Messaging).audience + ); + } + + #[test] + fn development_pickers_explicitly_bind_persona_people_products_and_workloads() { + let (root, plan) = plan(json!({ + "id": "read", "product": "breg", "as": "operator", + "method": "GET", "path": "/v1/records", "expect": {"status": 200} + })); + let mut value = serde_json::to_value(plan).unwrap(); + value["workloads"] = json!({ + "registry": { + "product": "breg", "default": true, + "subject": "portal-service", "client": "portal-service", + "grant": {"profile": "operator", "scopes": ["registry:read"]} + } + }); + value["developmentPickers"] = json!({ + "holder": { + "people": ["operator"], + "personProducts": ["breg"], + "workloads": ["registry"] + } + }); + let plan: Plan = serde_json::from_value(value).unwrap(); + + plan.validate(&canonical(&root)).unwrap(); + let picker = plan.development_pickers.holder.as_ref().unwrap(); + assert_eq!(picker.people, ["operator"]); + assert_eq!(picker.person_products, [Product::Breg]); + assert_eq!(picker.workloads, ["registry"]); + } + + #[test] + fn development_pickers_refuse_implicit_people_incomplete_grants_and_external_workloads() { + let (root, plan) = plan(json!({ + "id": "read", "product": "breg", "as": "operator", + "method": "GET", "path": "/v1/records", "expect": {"status": 200} + })); + let base = serde_json::to_value(plan).unwrap(); + for picker in [ + json!({"holder": { + "people": ["unknown"], "personProducts": ["breg"], "workloads": [] + }}), + json!({"holder": { + "people": ["operator"], "personProducts": ["casework"], "workloads": [] + }}), + json!({"holder": { + "people": ["operator"], "personProducts": ["breg"], + "workloads": ["production"] + }}), + ] { + let mut value = base.clone(); + value["developmentPickers"] = picker; + let plan: Plan = serde_json::from_value(value).unwrap(); + assert!(plan.validate(&canonical(&root)).is_err()); + } + let mut value = base; + value["developmentPickers"] = json!({ + "holder": {"people": ["operator"], "personProducts": ["breg"]}, + "staff": {"people": ["operator"], "personProducts": ["breg"]} + }); + let plan: Plan = serde_json::from_value(value).unwrap(); + assert!(plan + .validate(&canonical(&root)) + .unwrap_err() + .to_string() + .contains("both local picker personas")); + } + #[test] fn validation_accepts_dotted_steps_and_camel_case_captures() { let (root, plan) = plan(json!({ diff --git a/crates/registry-bregctl/src/project_dev/products.rs b/crates/registry-bregctl/src/project_dev/products.rs index 2a9e13ca99..5241cb6121 100644 --- a/crates/registry-bregctl/src/project_dev/products.rs +++ b/crates/registry-bregctl/src/project_dev/products.rs @@ -90,11 +90,16 @@ impl<'a> ProductRunner<'a> { // packaging; the published source is left intact. continue; } - self.tool( - entry.product, - "check", - &[self.input.project.join(&entry.project).as_os_str()], - )?; + let project = self.input.project.join(&entry.project); + if entry.product == Product::Messaging { + self.tool( + entry.product, + "check", + &["--project".as_ref(), project.as_os_str()], + )?; + } else { + self.tool(entry.product, "check", &[project.as_os_str()])?; + } } Ok(()) } @@ -148,6 +153,7 @@ impl<'a> ProductRunner<'a> { Product::Casework => { self.activate_casework(database, &project, bind, breg_package.as_deref())? } + Product::Messaging => self.activate_messaging(database, &project, bind)?, }; let binaries = &self.input.binaries[&product]; let mut command = guard::Command::new( @@ -157,7 +163,7 @@ impl<'a> ProductRunner<'a> { ) .map_err(operational)?; command.arg("--runtime-config").arg(config); - if product == Product::Casework { + if matches!(product, Product::Casework | Product::Messaging) { command.arg("serve"); } let log = open_log(self.root, &format!("{}-runtime", product.name()))?; @@ -366,6 +372,32 @@ impl<'a> ProductRunner<'a> { Ok(config) } + fn activate_messaging( + &self, + database: &mut Database, + project: &Path, + bind: &str, + ) -> Result { + let package = self.root.join("messaging-package"); + self.tool( + Product::Messaging, + "package", + &[ + project.as_os_str(), + "--output".as_ref(), + package.as_os_str(), + ], + )?; + let urls = database + .provision("messaging", false, false) + .map_err(operational)?; + let config = self.config(Product::Messaging, "messaging", bind, &package, urls)?; + let arguments = ["--runtime-config".as_ref(), config.as_os_str()]; + self.tool(Product::Messaging, "apply", &arguments)?; + self.tool(Product::Messaging, "status", &arguments)?; + Ok(config) + } + fn config( &self, product: Product, @@ -444,6 +476,15 @@ impl<'a> ProductRunner<'a> { config } Product::Casework => casework_config(plan, name, self.root, package, &identity, bind), + Product::Messaging => messaging_config( + plan, + name, + self.root, + package, + &identity, + bind, + &self.input.messaging_clients, + ), }; if let Some(bindings) = &self.bindings { bindings.configure(product, &mut config); @@ -742,6 +783,12 @@ fn shared_config( .values() .filter(|person| person.grants.contains_key(&product)) .map(|person| person.client.as_str()) + .chain( + plan.workloads + .values() + .filter(|workload| workload.product == product) + .map(|workload| workload.client.as_str()), + ) .chain(extra_clients.iter().map(String::as_str)) .collect(); let oidc = json!({ @@ -798,6 +845,39 @@ fn casework_config( config } +/// Messaging keeps its own package, database roles, runtime listener and +/// authorization boundary. A project provider without a run-local connection +/// remains deliberately unconfigured; the smoke journey proves acceptance and +/// receipt storage without introducing another broker. +fn messaging_config( + plan: &Plan, + name: &str, + root: &Path, + package: &Path, + identity: &str, + bind: &str, + clients: &BTreeSet, +) -> Value { + let (mut config, oidc) = shared_config(plan, Product::Messaging, name, root, package, clients); + config["apiVersion"] = json!("id.registrystack.org/formats/messaging/runtime/v1alpha1"); + config["kind"] = json!("MessagingRuntimeConfig"); + config["identity"] = json!({"databaseId": identity}); + config["listener"] = json!({ + "bind": bind, + "tlsTermination": "development-loopback", + "networkExposure": "private-address" + }); + config["authentication"] = json!({"oidc": oidc}); + config["audit"]["destination"] = json!("file"); + config["audit"]["path"] = json!(root.join("messaging-audit.jsonl")); + config["retention"] = json!({ + "payloadRetentionDays": 1, + "recordRetentionDays": 1, + "receiptRetentionDays": 1 + }); + config +} + fn random_secret() -> Result> { use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; let mut bytes = zeroize::Zeroizing::new([0u8; 32]); @@ -855,6 +935,7 @@ fn copy_project(source: &Path, target: &Path) -> Result<()> { pub(super) struct ProductInspection { pub(super) breg_authority: Option, pub(super) casework_principals: BTreeMap, + pub(super) messaging_clients: BTreeSet, } #[derive(Debug, thiserror::Error)] @@ -922,9 +1003,11 @@ pub(super) fn inspect( super::bindings::check_with_breg_reader(plan)?; let breg_authority = breg_authority(root, plan)?; let casework_principals = casework_principals(root, plan, breg_authority.as_ref(), terminate)?; + let messaging_clients = check_messaging_project(root, plan, terminate)?; Ok(ProductInspection { breg_authority, casework_principals, + messaging_clients, }) } @@ -958,6 +1041,7 @@ fn product_root( let manifest_name = match product { Product::Breg => "registry.yaml", Product::Casework => "casework.yaml", + Product::Messaging => "messaging.yaml", }; let manifest = project.join(manifest_name).canonicalize().map_err(|_| { plan::SemanticRefusal::new( @@ -1003,6 +1087,7 @@ fn breg_authority(root: &Path, plan: &Plan) -> Result> { .collect(); validate_breg_binding_ids(&plan.bindings, &review_authorities, &actions)?; check_breg_grants(®istry, &plan.people)?; + check_breg_workloads(®istry, &plan.workloads)?; let inventory = registry_breg::authority::authority_inventory(®istry)?; let principal = breg_principal(plan, &project.field, &inventory.principal_claims)?; Ok(Some(BregAuthority { @@ -1043,6 +1128,19 @@ fn breg_principal( )?; } } + for (name, workload) in &plan.workloads { + if workload.product == Product::Breg { + plan::require( + !workload.grant.claims.contains_key(&principal), + &format!( + "/workloads/{}/grant/claims", + registry_platform_yaml::escape_pointer_segment(name) + ), + "The BReg workload claims cannot replace the principal claim selected by the BReg project.", + "Remove the selected principal claim from this workload's additional claims.", + )?; + } + } Ok(principal) } @@ -1111,6 +1209,31 @@ fn check_breg_grants( Ok(()) } +fn check_breg_workloads( + registry: ®istry_breg::CompiledRegistry, + workloads: &BTreeMap, +) -> plan::SemanticResult<()> { + let profiles: BTreeSet<_> = registry + .access_profile_displays() + .iter() + .map(|profile| profile.id.as_str()) + .collect(); + for (name, workload) in workloads { + if workload.product == Product::Breg { + plan::require( + profiles.contains(workload.grant.profile.as_str()), + &format!( + "/workloads/{}/grant/profile", + registry_platform_yaml::escape_pointer_segment(name) + ), + "The BReg workload profile does not name an access profile in the BReg project.", + "Set profile to an access profile defined by the BReg project.", + )?; + } + } + Ok(()) +} + fn breg_requires_postgis(registry: ®istry_breg::CompiledRegistry) -> bool { registry.ddl().requires_postgis } @@ -1208,12 +1331,277 @@ fn casework_principals_from_facts( Ok(principals) } +#[derive(Debug, Eq, PartialEq)] +struct MessagingProfile { + principal_claim: String, + scopes: BTreeSet, + clients: BTreeSet, + actor_kind: Option, + sender: bool, +} + +fn check_messaging_project( + root: &Path, + plan: &Plan, + terminate: &AtomicBool, +) -> Result> { + let Some(project) = product_root(root, plan, Product::Messaging)? else { + return Ok(BTreeSet::new()); + }; + let tool = super::product_tool(Product::Messaging).map_err(|_| { + InspectionUnavailable::new( + &project.field, + "The Messaging project cannot be inspected because its owning tool is unavailable.", + "Install the matching Messaging tools or provide RSTACK_MESSAGINGCTL_BIN, then run the check again.", + ) + })?; + let checked = tool_report( + &tool, + "messagingctl", + "check", + &["--project".as_ref(), project.root.as_os_str()], + terminate, + ); + let (status, report) = match checked { + Ok(checked) => checked, + Err(error) if terminate.load(Ordering::Relaxed) => return Err(error), + Err(error) => { + return Err(InspectionUnavailable::new( + &project.field, + &format!( + "The selected `messagingctl` helper could not inspect the Messaging project: {error:#}." + ), + "Install the matching Messaging tools or provide RSTACK_MESSAGINGCTL_BIN, then run the check again.", + ) + .into()) + } + }; + if status.code() == Some(1) && messaging_domain_refusal(&report) { + return Err(plan::SemanticRefusal::new( + &project.field, + "The Messaging project did not pass validation by its owning tool.", + "Run `messagingctl check --project PROJECT` for authored diagnostics, then correct the Messaging project.", + ) + .into()); + } + if !status.success() { + return Err(InspectionUnavailable::new( + &project.field, + "The selected `messagingctl` helper did not complete the Messaging project check.", + "Install the matching Registry Stack Messaging tools, then run the check again.", + ) + .into()); + } + let profiles = messaging_report_profiles(&report).map_err(|error| { + InspectionUnavailable::new( + &project.field, + &format!( + "The selected `messagingctl` helper returned an incompatible report: {error:#}." + ), + "Install the matching Registry Stack Messaging tools, then run the check again.", + ) + })?; + validate_messaging_grants(plan, &profiles)?; + Ok(profiles + .values() + .flat_map(|profile| profile.clients.iter().cloned()) + .collect()) +} + +fn messaging_domain_refusal(report: &Value) -> bool { + report["apiVersion"] == "id.registrystack.org/formats/messaging/ctl-report/v1alpha1" + && report["kind"] == "MessagingCtlReport" + && report["command"] == "check" + && report["status"] == "domain-refusal" + && report["ok"] == false + && report["diagnostics"] + .as_array() + .is_some_and(|items| !items.is_empty()) +} + +fn messaging_report_profiles(report: &Value) -> Result> { + ensure!( + report["apiVersion"] == "id.registrystack.org/formats/messaging/ctl-report/v1alpha1" + && report["kind"] == "MessagingCtlReport" + && report["command"] == "check" + && report["status"] == "complete" + && report["ok"] == true, + "messagingctl check returned an incompatible envelope" + ); + let entries = report["accessProfiles"] + .as_array() + .context("messagingctl check did not report access profiles")?; + let mut profiles = BTreeMap::new(); + for entry in entries { + let id = entry["id"] + .as_str() + .context("a Messaging access profile has no ID")?; + let principal_claim = entry["principalClaim"] + .as_str() + .filter(|claim| !claim.is_empty()) + .context("a Messaging access profile has no principal claim")?; + let string_set = |member: &str| -> Result> { + let values: Vec = entry[member] + .as_array() + .with_context(|| format!("a Messaging access profile has no {member}"))? + .iter() + .map(|value| { + value + .as_str() + .filter(|value| !value.is_empty()) + .map(str::to_owned) + .with_context(|| { + format!("a Messaging access profile has an invalid {member} value") + }) + }) + .collect::>()?; + let unique: BTreeSet = values.iter().cloned().collect(); + ensure!( + unique.len() == values.len(), + "a Messaging access profile has duplicate {member} values" + ); + Ok(unique) + }; + let actor_kind = match entry.get("actorKind") { + Some(Value::Null) => None, + Some(Value::String(kind)) if matches!(kind.as_str(), "human" | "agent" | "service") => { + Some(kind.clone()) + } + _ => bail!("a Messaging access profile has an invalid actorKind"), + }; + let acts_as = entry["actsAs"] + .as_str() + .context("a Messaging access profile has no actsAs value")?; + ensure!( + matches!(acts_as, "sender" | "operator"), + "a Messaging access profile has an invalid actsAs value" + ); + let profile = MessagingProfile { + principal_claim: principal_claim.to_owned(), + scopes: string_set("requiredScopes")?, + clients: string_set("requesterClients")?, + actor_kind, + sender: acts_as == "sender", + }; + ensure!( + profiles.insert(id.to_owned(), profile).is_none(), + "messagingctl check returned duplicate access profiles" + ); + } + Ok(profiles) +} + +fn validate_messaging_grant( + field: &str, + client_field: &str, + grant: &plan::Grant, + client: &str, + profiles: &BTreeMap, + workload: bool, +) -> plan::SemanticResult<()> { + let profile = profiles.get(&grant.profile).ok_or_else(|| { + plan::SemanticRefusal::new( + format!("{field}/profile"), + "The Messaging grant profile does not name an access profile in the Messaging project.", + "Set profile to an access profile defined by the Messaging project.", + ) + })?; + plan::require( + profile.principal_claim == "sub", + &format!("{field}/profile"), + "The local Messaging runner requires a profile whose principalClaim is `sub`.", + "Use a Messaging profile bound to `sub`, so receipt ownership remains the service subject.", + )?; + plan::require( + profile.clients.contains(client), + client_field, + "The Messaging grant client is not admitted by its access profile.", + "Set client to one of the profile's requesterClients.", + )?; + plan::require( + grant.scopes.iter().cloned().collect::>() == profile.scopes, + &format!("{field}/scopes"), + "The Messaging grant scopes differ from the access profile's requiredScopes.", + "Set scopes to exactly the Messaging access profile's requiredScopes.", + )?; + if let Some(kind) = &profile.actor_kind { + plan::require( + grant + .claims + .get("registry_actor_kind") + .and_then(Value::as_str) + == Some(kind), + &format!("{field}/claims/registry_actor_kind"), + "The Messaging grant actor kind differs from the access profile.", + "Set registry_actor_kind to the actorKind required by the Messaging access profile.", + )?; + } + if workload { + plan::require( + profile.sender, + &format!("{field}/profile"), + "A Messaging workload connection must use a sender access profile.", + "Select a Messaging profile whose actsAs value is sender.", + )?; + } + Ok(()) +} + +fn validate_messaging_grants( + plan: &Plan, + profiles: &BTreeMap, +) -> plan::SemanticResult<()> { + for (name, person) in &plan.people { + if let Some(grant) = person.grants.get(&Product::Messaging) { + let field = format!( + "/people/{}/grants/messaging", + registry_platform_yaml::escape_pointer_segment(name) + ); + let client_field = format!( + "/people/{}/client", + registry_platform_yaml::escape_pointer_segment(name) + ); + validate_messaging_grant( + &field, + &client_field, + grant, + &person.client, + profiles, + false, + )?; + } + } + for (name, workload) in &plan.workloads { + if workload.product == Product::Messaging { + let field = format!( + "/workloads/{}", + registry_platform_yaml::escape_pointer_segment(name) + ); + validate_messaging_grant( + &format!("{field}/grant"), + &format!("{field}/client"), + &workload.grant, + &workload.client, + profiles, + true, + )?; + } + } + Ok(()) +} + fn explain_casework_facts( tool: &Path, project: &Path, terminate: &AtomicBool, ) -> Result { - let (status, report) = casework_report(tool, "explain", &[project.as_os_str()], terminate)?; + let (status, report) = tool_report( + tool, + "caseworkctl", + "explain", + &[project.as_os_str()], + terminate, + )?; if status.success() { return casework_report_facts(&report); } @@ -1223,10 +1611,11 @@ fn explain_casework_facts( anyhow::bail!("caseworkctl explain did not complete successfully") } -/// Runs `caseworkctl --format json ` and returns its -/// exit status with the JSON report it printed. -fn casework_report( +/// Runs a product tool's JSON command and returns its exit status with the +/// report it printed. +fn tool_report( tool: &Path, + tool_name: &str, command: &str, arguments: &[&std::ffi::OsStr], terminate: &AtomicBool, @@ -1238,7 +1627,7 @@ fn casework_report( .args(arguments) .stdout(Stdio::piped()) .spawn() - .with_context(|| format!("cannot start caseworkctl {command}"))?; + .with_context(|| format!("cannot start {tool_name} {command}"))?; let stdout = child.stdout.take().expect("the report output was piped"); let reader = thread::spawn(move || { let mut bytes = Vec::new(); @@ -1251,18 +1640,18 @@ fn casework_report( !terminate.load(Ordering::Relaxed), "development product inspection was interrupted" ); - ensure!(Instant::now() < deadline, "caseworkctl {command} timed out"); + ensure!(Instant::now() < deadline, "{tool_name} {command} timed out"); Ok(()) })?; let bytes = reader .join() - .map_err(|_| anyhow::anyhow!("cannot collect the caseworkctl {command} report"))??; + .map_err(|_| anyhow::anyhow!("cannot collect the {tool_name} {command} report"))??; ensure!( bytes.len() as u64 <= MAX_REPORT, - "the caseworkctl {command} report exceeds the size limit" + "the {tool_name} {command} report exceeds the size limit" ); let report = serde_json::from_slice(&bytes) - .map_err(|_| anyhow::anyhow!("caseworkctl {command} did not emit a JSON report"))?; + .map_err(|_| anyhow::anyhow!("{tool_name} {command} did not emit a JSON report"))?; Ok((status, report)) } @@ -1321,8 +1710,9 @@ fn check_casework_binding( super::bindings::render_for_check(plan, Product::Casework, &mut config); let path = root.join("casework-runtime.yaml"); write_private(&path, &serde_json::to_vec(&config)?)?; - casework_report( + tool_report( tool, + "caseworkctl", "check", &[ project.root.as_os_str(), @@ -2276,6 +2666,157 @@ mod tests { assert!(!written.to_string().contains("password"), "{written}"); } + #[test] + fn messaging_config_uses_its_own_database_audience_and_workload_client() { + let scratch = tempfile::tempdir().unwrap(); + let root = scratch.path().join("run"); + super::super::private_directory(&root).unwrap(); + let terminate = AtomicBool::new(false); + let mut input = breg_input(false); + input.breg_authority = None; + input.plan = serde_json::from_value(json!({ + "issuer": "https://issuer.example.invalid", + "products": [{ + "product": "messaging", "project": ".", + "audience": "urn:example:messaging" + }], + "people": {"sender": { + "subject": "sender", "client": "sender-client", + "grants": {"messaging": { + "profile": "sender", "scopes": ["messaging:send"], + "claims": {"registry_actor_kind": "service"} + }} + }}, + "workloads": {"notices": { + "product": "messaging", "default": true, + "subject": "service", "client": "workload-client", + "grant": { + "profile": "sender", "scopes": ["messaging:send"], + "claims": {"registry_actor_kind": "service"} + } + }}, + "journey": {"id": "send", "steps": [{ + "id": "send", "product": "messaging", "as": "sender", + "method": "POST", "path": "/v1/messages", "body": {}, + "expect": {"status": 202} + }]} + })) + .unwrap(); + input.messaging_clients = BTreeSet::from(["package-operator".to_owned()]); + let runner = ProductRunner::new(Arc::new(input), &root, &terminate).unwrap(); + let urls = DatabaseUrls { + runtime: "postgresql://runtime:password@127.0.0.1:5432/messaging".to_owned(), + migration: "postgresql://migration:password@127.0.0.1:5432/messaging".to_owned(), + }; + let path = runner + .config( + Product::Messaging, + "messaging", + "127.0.0.1:8107", + &root.join("messaging-package"), + urls, + ) + .unwrap(); + let text = fs::read_to_string(path).unwrap(); + let written: Value = serde_json::from_str(&text).unwrap(); + + assert_eq!(written["kind"], "MessagingRuntimeConfig"); + assert_eq!( + written["authentication"]["oidc"]["audience"], + "urn:example:messaging" + ); + assert_eq!( + written["authentication"]["oidc"]["allowedClients"], + json!(["package-operator", "sender-client", "workload-client"]) + ); + assert_eq!( + written["listener"]["tlsTermination"], + "development-loopback" + ); + assert_eq!( + written["database"]["runtimeUrlRef"], + "secret:file/messaging-runtime-url" + ); + assert!(written.get("providers").is_none()); + assert!(!text.contains("password"), "{written}"); + } + + #[test] + fn messaging_workloads_must_match_the_owning_profile_authority() { + let report = json!({ + "apiVersion": "id.registrystack.org/formats/messaging/ctl-report/v1alpha1", + "kind": "MessagingCtlReport", "command": "check", + "status": "complete", "ok": true, "diagnostics": [], + "accessProfiles": [{ + "id": "service-sender", "actsAs": "sender", + "principalClaim": "sub", "requiredScopes": ["messaging:send"], + "requesterClients": ["notice-service"], "actorKind": "service" + }] + }); + let profiles = messaging_report_profiles(&report).unwrap(); + let mut plan: Plan = serde_json::from_value(json!({ + "issuer": "https://issuer.example.invalid", + "products": [{"product": "messaging", "project": ".", "audience": "urn:messaging"}], + "people": {"sender": { + "subject": "sender", "client": "notice-service", + "grants": {"messaging": { + "profile": "service-sender", "scopes": ["messaging:send"], + "claims": {"registry_actor_kind": "service"} + }} + }}, + "workloads": {"notices": { + "product": "messaging", "default": true, + "subject": "service", "client": "notice-service", + "grant": { + "profile": "service-sender", "scopes": ["messaging:send"], + "claims": {"registry_actor_kind": "service"} + } + }}, + "journey": {"id": "send", "steps": [{ + "id": "send", "product": "messaging", "as": "sender", + "method": "POST", "path": "/v1/messages", "body": {}, + "expect": {"status": 202} + }]} + })) + .unwrap(); + + validate_messaging_grants(&plan, &profiles).unwrap(); + plan.workloads.get_mut("notices").unwrap().client = "other-service".to_owned(); + let error = validate_messaging_grants(&plan, &profiles) + .unwrap_err() + .to_string(); + assert!(error.contains("/workloads/notices/client"), "{error}"); + } + + #[test] + fn messaging_reports_refuse_authority_values_the_owning_tool_cannot_emit() { + let report = || { + json!({ + "apiVersion": "id.registrystack.org/formats/messaging/ctl-report/v1alpha1", + "kind": "MessagingCtlReport", "command": "check", + "status": "complete", "ok": true, "diagnostics": [], + "accessProfiles": [{ + "id": "service-sender", "actsAs": "sender", + "principalClaim": "sub", "requiredScopes": ["messaging:send"], + "requesterClients": ["notice-service"], "actorKind": "service" + }] + }) + }; + + let mut duplicate = report(); + duplicate["accessProfiles"][0]["requiredScopes"] = + json!(["messaging:send", "messaging:send"]); + assert!(messaging_report_profiles(&duplicate).is_err()); + + let mut invalid = report(); + invalid["accessProfiles"][0]["actorKind"] = json!("robot"); + assert!(messaging_report_profiles(&invalid).is_err()); + + let mut missing = report(); + missing["accessProfiles"][0]["actsAs"] = Value::Null; + assert!(messaging_report_profiles(&missing).is_err()); + } + #[test] fn a_report_without_the_access_profile_list_is_refused() { let report = json!({ @@ -2435,6 +2976,33 @@ mod tests { check_breg_grants(®istry, &valid).unwrap(); } + #[test] + fn a_breg_workload_naming_an_unknown_profile_is_refused_at_its_pointer() { + let registry = minimal_registry(str::to_owned); + let workload = |profile: &str| { + serde_json::from_value(json!({ + "product": "breg", "default": true, + "subject": "service", "client": "service", + "grant": {"profile": profile, "scopes": []} + })) + .unwrap() + }; + let workloads = BTreeMap::from([("registry".to_owned(), workload("directory-edtor"))]); + let error = check_breg_workloads(®istry, &workloads) + .unwrap_err() + .to_string(); + assert!( + error.contains("/workloads/registry/grant/profile"), + "{error}" + ); + assert!(!error.contains("directory-edtor"), "{error}"); + check_breg_workloads( + ®istry, + &BTreeMap::from([("registry".to_owned(), workload("directory-editor"))]), + ) + .unwrap(); + } + #[test] fn a_breg_grant_may_name_a_profile_with_only_proposal_permissions() { let source = Path::new(env!("CARGO_MANIFEST_DIR")) @@ -2496,6 +3064,7 @@ mod tests { named_clients: BTreeSet::new(), }), casework_principals: BTreeMap::new(), + messaging_clients: BTreeSet::new(), binaries: BTreeMap::new(), } } diff --git a/crates/registry-bregctl/src/project_dev/workload.rs b/crates/registry-bregctl/src/project_dev/workload.rs new file mode 100644 index 0000000000..524d60345a --- /dev/null +++ b/crates/registry-bregctl/src/project_dev/workload.rs @@ -0,0 +1,466 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Runner-owned Python workload connections and rotating short-lived tokens. + +use anyhow::{ensure, Context, Result}; +use serde_json::{json, Value}; +use std::{ + collections::BTreeMap, + path::{Path, PathBuf}, + sync::Arc, +}; +use zeroize::Zeroizing; + +use super::{ + issuer::{self, Issuer}, + plan::{Product, TestPerson}, + private_directory, write_private, RunInput, +}; + +pub(super) const CONNECTION_FORMAT: &str = + "id.registrystack.org/formats/platform/python-connection/v1alpha1"; +pub(super) const CONNECTION_KIND: &str = "PlatformPythonConnection"; +pub(super) const TOKEN_FORMAT: &str = + "id.registrystack.org/formats/platform/dev-workload-token/v1alpha1"; +pub(super) const TOKEN_KIND: &str = "PlatformDevWorkloadToken"; +const CONNECTION_FILE: &str = "python-connection.json"; +const DIRECTORY: &str = "python-workload"; +const ROTATION_SECONDS: u64 = 60; + +/// Live credentials owned by the existing run supervisor, not a second broker. +pub(super) struct WorkloadCredentials { + root: PathBuf, + input: Arc, + issuer: Arc, + urls: BTreeMap, + generation: u64, + next_rotation: u64, + run_expires: u64, +} + +impl WorkloadCredentials { + pub(super) fn prepare( + root: &Path, + input: Arc, + issuer: Arc, + urls: &BTreeMap, + now: u64, + run_expires: u64, + ) -> Result> { + if input.plan.workloads.is_empty() { + return Ok(None); + } + ensure!(now < run_expires, "the development run has expired"); + let root = root.join(DIRECTORY); + private_directory(&root).context("cannot create private Python workload state")?; + let mut credentials = Self { + root, + input, + issuer, + urls: urls.clone(), + generation: 0, + next_rotation: now, + run_expires, + }; + credentials.rotate(now)?; + let connection = credentials.connection_document()?; + write_private( + &credentials.root.join(CONNECTION_FILE), + &serde_json::to_vec(&connection)?, + )?; + Ok(Some(credentials)) + } + + pub(super) fn path(&self) -> PathBuf { + self.root.join(CONNECTION_FILE) + } + + /// Replace each binding's complete token envelope once it is due. Every + /// envelope retains the run expiry; rotation cannot renew the run. + pub(super) fn rotate_if_due(&mut self, now: u64) -> Result<()> { + if now >= self.next_rotation && now < self.run_expires { + self.rotate(now)?; + } + Ok(()) + } + + /// Revoke the file handoff before product cleanup starts. The replacement + /// is complete JSON but deliberately has no token, so a reader cannot use + /// the previous generation during the shutdown window. + pub(super) fn invalidate(&mut self, now: u64) -> Result<()> { + let generation = self + .generation + .checked_add(1) + .context("workload token generation overflow")?; + for (name, workload) in &self.input.plan.workloads { + let state = json!({ + "apiVersion": TOKEN_FORMAT, + "kind": TOKEN_KIND, + "status": "stopped", + "runId": self.input.run_id, + "binding": name, + "product": workload.product, + "issuer": self.input.plan.issuer, + "subject": workload.subject, + "clientId": workload.client, + "profile": workload.grant.profile, + "resource": self.input.plan.product(workload.product).audience, + "scopes": workload.grant.scopes, + "claims": workload.grant.claims, + "generation": generation, + "issuedAt": now.min(self.run_expires), + "expiresAt": now.min(self.run_expires), + "runExpiresAt": self.run_expires, + }); + write_private( + &self.root.join(token_file(name)), + &serde_json::to_vec(&state)?, + )?; + } + self.generation = generation; + self.next_rotation = self.run_expires; + Ok(()) + } + + fn rotate(&mut self, now: u64) -> Result<()> { + let generation = self + .generation + .checked_add(1) + .context("workload token generation overflow")?; + // Reserve the generation before writing any binding. If one later + // binding fails, a retry skips forward instead of changing an already + // observed file under the same generation number. + self.generation = generation; + let expires_at = issuer::token_expiry(self.run_expires, now); + ensure!(expires_at > now, "the development run has expired"); + for (name, workload) in &self.input.plan.workloads { + let person = TestPerson { + subject: workload.subject.clone(), + client: workload.client.clone(), + grants: BTreeMap::from([(workload.product, workload.grant.clone())]), + casework_context: false, + }; + let token = self + .issuer + .token(&self.input, &person, workload.product, expires_at)?; + let state = self.token_document(name, generation, now, expires_at, &token); + write_private( + &self.root.join(token_file(name)), + Zeroizing::new(serde_json::to_vec(&state)?).as_slice(), + )?; + } + self.next_rotation = next_rotation(now, self.run_expires); + Ok(()) + } + + fn connection_document(&self) -> Result { + let bindings = self + .input + .plan + .workloads + .iter() + .map(|(name, workload)| { + let url = self + .urls + .get(&workload.product) + .context("workload product has no live URL")?; + Ok(json!({ + "name": name, + "product": workload.product, + "url": url, + "default": workload.default, + "credential": { + "type": "runner-token", + "tokenRef": format!("secret:file/{}", token_file(name)), + "runId": self.input.run_id, + "binding": name, + "issuer": self.input.plan.issuer, + "subject": workload.subject, + "clientId": workload.client, + "profile": workload.grant.profile, + "resource": self.input.plan.product(workload.product).audience, + "scopes": workload.grant.scopes, + "claims": workload.grant.claims, + "runExpiresAt": self.run_expires, + } + })) + }) + .collect::>>()?; + Ok(json!({ + "apiVersion": CONNECTION_FORMAT, + "kind": CONNECTION_KIND, + "service": format!("rstack-dev-{}", self.input.run_id), + "audience": "service", + "secretProviders": {"file": {"root": self.root}}, + "bindings": bindings, + })) + } + + fn token_document( + &self, + name: &str, + generation: u64, + issued_at: u64, + expires_at: u64, + token: &str, + ) -> Value { + let workload = &self.input.plan.workloads[name]; + json!({ + "apiVersion": TOKEN_FORMAT, + "kind": TOKEN_KIND, + "runId": self.input.run_id, + "binding": name, + "product": workload.product, + "issuer": self.input.plan.issuer, + "subject": workload.subject, + "clientId": workload.client, + "profile": workload.grant.profile, + "resource": self.input.plan.product(workload.product).audience, + "scopes": workload.grant.scopes, + "claims": workload.grant.claims, + "generation": generation, + "issuedAt": issued_at, + "expiresAt": expires_at, + "runExpiresAt": self.run_expires, + "token": token, + }) + } +} + +fn token_file(name: &str) -> String { + format!("workload-{name}.json") +} + +fn next_rotation(now: u64, run_expires: u64) -> u64 { + now.saturating_add(ROTATION_SECONDS).min(run_expires) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::project_dev::{plan::Plan, BregAuthority, RunInput}; + use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; + use serde_json::json; + use std::{collections::BTreeSet, os::unix::fs::PermissionsExt}; + + #[test] + fn rotation_schedule_never_extends_the_run() { + assert_eq!(next_rotation(100, 1_000), 160); + assert_eq!(next_rotation(980, 1_000), 1_000); + assert_eq!(next_rotation(u64::MAX - 1, u64::MAX), u64::MAX); + } + + #[test] + fn token_file_names_are_binding_local_and_do_not_name_keys() { + assert_eq!(token_file("registry"), "workload-registry.json"); + assert!(!token_file("registry").contains("key")); + } + + #[test] + fn one_private_atomic_file_replaces_a_complete_generation() { + let scratch = tempfile::tempdir().unwrap(); + std::fs::set_permissions( + scratch.path(), + std::os::unix::fs::PermissionsExt::from_mode(0o700), + ) + .unwrap(); + let path = scratch.path().join(token_file("registry")); + let first = json!({"generation": 1, "token": "first"}); + let second = json!({"generation": 2, "token": "second"}); + write_private(&path, &serde_json::to_vec(&first).unwrap()).unwrap(); + write_private(&path, &serde_json::to_vec(&second).unwrap()).unwrap(); + let observed: Value = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap(); + assert_eq!(observed, second); + } + + #[test] + fn prepared_connection_survives_two_generations_for_separate_product_authorities() { + let scratch = tempfile::tempdir().unwrap(); + std::fs::set_permissions( + scratch.path(), + std::os::unix::fs::PermissionsExt::from_mode(0o700), + ) + .unwrap(); + let run_id = "0123456789abcdef0123456789abcdef"; + let plan: Plan = serde_json::from_value(json!({ + "issuer": "https://issuer.example.invalid", + "products": [ + {"product": "breg", "project": ".", "audience": "urn:test:breg"}, + {"product": "messaging", "project": ".", "audience": "urn:test:messaging"} + ], + "people": {"reader": { + "subject": "reader", "client": "reader", + "grants": {"breg": {"profile": "reader", "scopes": []}} + }}, + "workloads": {"registry": { + "product": "breg", "default": true, + "subject": "service", "client": "service-client", + "grant": {"profile": "service", "scopes": ["registry:read"]} + }, "notices": { + "product": "messaging", "default": true, + "subject": "notice-service", "client": "notice-client", + "grant": { + "profile": "service-sender", "scopes": ["messaging:send"], + "claims": {"registry_actor_kind": "service"} + } + }}, + "journey": {"id": "read", "steps": [{ + "id": "read", "product": "breg", "as": "reader", "method": "GET", + "path": "/v1/records", "expect": {"status": 200} + }]} + })) + .unwrap(); + let input = Arc::new(RunInput { + run_id: run_id.to_owned(), + project: scratch.path().to_owned(), + plan, + ttl_seconds: 600, + schema_people: Vec::new(), + breg_authority: Some(BregAuthority { + principal: "registry_principal".to_owned(), + purpose: false, + requires_postgis: false, + encrypts_fields: false, + named_clients: BTreeSet::new(), + }), + casework_principals: BTreeMap::new(), + messaging_clients: BTreeSet::new(), + binaries: BTreeMap::new(), + }); + let issuer = Arc::new(Issuer::create(scratch.path()).unwrap()); + let now = super::super::clock().unwrap(); + let run_expires = now + 600; + let mut credentials = WorkloadCredentials::prepare( + scratch.path(), + input, + issuer, + &BTreeMap::from([ + (Product::Breg, "http://127.0.0.1:9999".to_owned()), + (Product::Messaging, "http://127.0.0.1:9998".to_owned()), + ]), + now, + run_expires, + ) + .unwrap() + .unwrap(); + + let connection_bytes = std::fs::read(credentials.path()).unwrap(); + assert_eq!( + std::fs::metadata(credentials.path()) + .unwrap() + .permissions() + .mode() + & 0o777, + 0o600 + ); + let connection: Value = serde_json::from_slice(&connection_bytes).unwrap(); + assert_eq!(connection["kind"], CONNECTION_KIND); + assert_eq!( + connection["bindings"][0]["credential"]["type"], + "runner-token" + ); + assert_eq!( + connection["bindings"][0]["credential"]["tokenRef"], + "secret:file/workload-notices.json" + ); + assert_eq!(connection["bindings"][0]["product"], "messaging"); + assert_eq!( + connection["bindings"][0]["credential"]["resource"], + "urn:test:messaging" + ); + assert_eq!( + connection["bindings"][0]["credential"]["claims"]["registry_actor_kind"], + "service" + ); + assert_eq!(connection["bindings"][1]["product"], "breg"); + let connection_text = String::from_utf8(connection_bytes).unwrap(); + assert!(!connection_text.contains("issuer-key")); + assert!(!connection_text.contains("\"token\"")); + + let token_path = scratch.path().join(DIRECTORY).join(token_file("registry")); + let messaging_path = scratch.path().join(DIRECTORY).join(token_file("notices")); + let first_messaging: Value = + serde_json::from_slice(&std::fs::read(&messaging_path).unwrap()).unwrap(); + assert_eq!(first_messaging["kind"], TOKEN_KIND); + assert_eq!(first_messaging["product"], "messaging"); + assert_eq!(first_messaging["resource"], "urn:test:messaging"); + assert_eq!(first_messaging["claims"]["registry_actor_kind"], "service"); + assert_ne!(first_messaging["token"], Value::Null); + assert_eq!( + std::fs::metadata(&token_path).unwrap().permissions().mode() & 0o777, + 0o600 + ); + let first: Value = serde_json::from_slice(&std::fs::read(&token_path).unwrap()).unwrap(); + assert_eq!(first["generation"], 1); + assert_eq!(first["runExpiresAt"], run_expires); + assert!(first["token"] + .as_str() + .is_some_and(|value| !value.is_empty())); + credentials.rotate_if_due(now + ROTATION_SECONDS).unwrap(); + let second: Value = serde_json::from_slice(&std::fs::read(token_path).unwrap()).unwrap(); + let second_messaging: Value = + serde_json::from_slice(&std::fs::read(&messaging_path).unwrap()).unwrap(); + assert_eq!(second["generation"], 2); + assert_eq!(second["runExpiresAt"], run_expires); + assert_ne!(first["token"], second["token"]); + assert_eq!(second_messaging["generation"], 2); + assert_ne!(first_messaging["token"], second_messaging["token"]); + assert!(second["expiresAt"].as_u64().unwrap() <= run_expires); + for field in [ + "runId", + "binding", + "product", + "issuer", + "subject", + "clientId", + "profile", + "resource", + "scopes", + "claims", + "runExpiresAt", + ] { + assert_eq!(first[field], second[field], "{field}"); + } + let claims = |state: &Value| { + let encoded = state["token"].as_str().unwrap().split('.').nth(1).unwrap(); + serde_json::from_slice::(&URL_SAFE_NO_PAD.decode(encoded).unwrap()).unwrap() + }; + let first_claims = claims(&first); + let second_claims = claims(&second); + for field in [ + "iss", + "aud", + "sub", + "client_id", + "scope", + "registry_principal", + ] { + assert_eq!(first_claims[field], second_claims[field], "{field}"); + } + assert_eq!(second_claims["aud"], "urn:test:breg"); + assert_eq!(second_claims["sub"], "service"); + assert_eq!(second_claims["client_id"], "service-client"); + assert!(second_claims["exp"].as_u64().unwrap() <= run_expires); + let messaging_claims = claims(&second_messaging); + assert_eq!(messaging_claims["aud"], "urn:test:messaging"); + assert_eq!(messaging_claims["sub"], "notice-service"); + assert_eq!(messaging_claims["client_id"], "notice-client"); + assert_eq!(messaging_claims["scope"], "messaging:send"); + assert_eq!(messaging_claims["registry_actor_kind"], "service"); + + credentials.invalidate(now + ROTATION_SECONDS + 1).unwrap(); + let stopped: Value = serde_json::from_slice( + &std::fs::read(scratch.path().join(DIRECTORY).join(token_file("registry"))).unwrap(), + ) + .unwrap(); + assert_eq!(stopped["status"], "stopped"); + assert_eq!(stopped["kind"], TOKEN_KIND); + assert_eq!(stopped["generation"], 3); + assert!(stopped.get("token").is_none()); + assert_eq!(stopped["expiresAt"], stopped["issuedAt"]); + let messaging_stopped: Value = + serde_json::from_slice(&std::fs::read(messaging_path).unwrap()).unwrap(); + assert_eq!(messaging_stopped["status"], "stopped"); + assert_eq!(messaging_stopped["generation"], 3); + assert!(messaging_stopped.get("token").is_none()); + } +} diff --git a/crates/registry-coordinator/tests/catalog_scenarios.rs b/crates/registry-coordinator/tests/catalog_scenarios.rs index 83a3f19b45..b5ab8ebaca 100644 --- a/crates/registry-coordinator/tests/catalog_scenarios.rs +++ b/crates/registry-coordinator/tests/catalog_scenarios.rs @@ -198,7 +198,7 @@ fn declared_refusal_without_an_authored_edge_preserves_refused_behavior() { } #[test] -fn external_job_example_observes_one_saved_read_through_a_bounded_completion() { +fn external_job_example_admits_then_observes_one_saved_read_through_a_bounded_completion() { use registry_coordinator::definition::Step; let (definition, document) = fixture("external-job"); assert_eq!(definition.workflow.steps.values().filter(|step| matches!(step, Step::Call { call, .. } if call.operation == Operation::ExternalGet)).count(), 1); @@ -236,7 +236,31 @@ fn external_job_example_observes_one_saved_read_through_a_bounded_completion() { .unwrap(); assert_eq!(timeout.outcome.as_deref(), Some("job-wait-expired")); assert_eq!(timeout.elapsed_seconds, 600); - assert!(reports.iter().all(|report| report.frozen_commands == 0)); + assert!(reports.iter().all(|report| report.frozen_commands == 1)); + let refused_admission = reports + .iter() + .find(|r| r.name == "invalid-job-is-a-declared-no-effect-refusal") + .unwrap(); + assert_eq!( + refused_admission.output, + Some(json!({"refusalCode":"invalid-job"})) + ); + let uncertain = reports + .iter() + .find(|r| r.name == "unusable-admission-response-is-uncertain") + .unwrap(); + assert_eq!(uncertain.state, "uncertain"); + let conflict = reports + .iter() + .find(|r| r.name == "changed-command-conflict-is-uncertain") + .unwrap(); + assert_eq!(conflict.state, "uncertain"); + let recovered = reports + .iter() + .find(|r| r.name == "lost-admission-reply-recovers-the-same-command") + .unwrap(); + assert_eq!(recovered.call_attempts["admit"], 2); + assert_eq!(recovered.frozen_commands, 1); } #[test] diff --git a/crates/registry-coordinator/tests/external_wait_postgres.rs b/crates/registry-coordinator/tests/external_wait_postgres.rs index e573f7e92f..3213347ba1 100644 --- a/crates/registry-coordinator/tests/external_wait_postgres.rs +++ b/crates/registry-coordinator/tests/external_wait_postgres.rs @@ -16,7 +16,7 @@ use registry_coordinator::{ use serde_json::{json, Value}; use uuid::Uuid; use wiremock::{ - matchers::{method, path, query_param}, + matchers::{body_json, header_exists, method, path, query_param}, Mock, MockServer, ResponseTemplate, }; @@ -31,9 +31,46 @@ impl AdapterSet for ExternalAdapter { } async fn call(&self, request: &CallRequest) -> CallOutcome { - assert_eq!(request.operation, Operation::ExternalGet); assert_eq!(request.connection, "jobs"); - self.0.get(&request.input, false).await + match request.operation { + Operation::ExternalGet => self.0.get(&request.input, false).await, + Operation::ExternalCommand => { + self.0 + .command( + &request.input, + request + .idempotency_key + .as_deref() + .expect("the durable admission has a frozen command key"), + false, + ) + .await + } + operation => panic!("unexpected external-job operation {operation:?}"), + } + } + + async fn call_attempt( + &self, + request: &CallRequest, + prepared: Option<&[u8]>, + final_attempt: bool, + ) -> CallOutcome { + assert!(prepared.is_none(), "external HTTP has no prepared evidence"); + if request.operation == Operation::ExternalCommand { + return self + .0 + .command( + &request.input, + request + .idempotency_key + .as_deref() + .expect("the durable admission has a frozen command key"), + final_attempt, + ) + .await; + } + self.call(request).await } async fn observe_completion( @@ -78,6 +115,7 @@ impl Harness { let server = MockServer::start().await; let config: ExternalHttpConfig = serde_json::from_value(json!({ "baseUrl":server.uri(), "paths":["jobs/status"], "queryParameters":["id"], + "commandPath":"jobs", "responseSchema":{"type":"object"} })) .unwrap(); @@ -115,11 +153,31 @@ impl Harness { .await; } + async fn admitted(&self, state: &str) { + self.server.reset().await; + Mock::given(method("POST")) + .and(path("/jobs")) + .and(header_exists("idempotency-key")) + .and(body_json(json!({"reference":"case-001"}))) + .respond_with(ResponseTemplate::new(201).set_body_json(json!({"jobId":JOB}))) + .expect(1) + .mount(&self.server) + .await; + Mock::given(method("GET")) + .and(path("/jobs/status")) + .and(query_param("id", JOB)) + .respond_with( + ResponseTemplate::new(200).set_body_json(json!({"jobId":JOB,"state":state})), + ) + .mount(&self.server) + .await; + } + async fn start(&self) -> Uuid { self.store .admit( &self.definition, - json!({"jobId":JOB}), + json!({"reference":"case-001"}), "external-fixture-producer", &Uuid::new_v4().to_string(), self.adapters.binding_digest(), @@ -160,7 +218,7 @@ impl Harness { } async fn begin_wait(&self) -> Uuid { - self.state("running").await; + self.admitted("running").await; let run = self.start().await; self.drain(&self.worker()).await; let inspection = self @@ -171,10 +229,101 @@ impl Harness { assert_eq!(inspection.run.step, "await-terminal"); assert_eq!(inspection.waits.len(), 1); assert_eq!(inspection.waits[0].observations, 1); + assert_eq!(inspection.effects.len(), 1); + assert_eq!( + serde_json::to_value(&inspection.effects[0]).unwrap()["state"], + "accepted" + ); run } } +#[tokio::test] +async fn declared_admission_refusal_takes_the_authored_no_effect_route() { + let h = Harness::new().await; + Mock::given(method("POST")) + .and(path("/jobs")) + .and(header_exists("idempotency-key")) + .and(body_json(json!({"reference":"case-001"}))) + .respond_with(ResponseTemplate::new(422).set_body_json(json!({"reason":"invalid-job"}))) + .expect(1) + .mount(&h.server) + .await; + + let run = h.start().await; + h.drain(&h.worker()).await; + let inspection = h + .store + .inspect(run, h.adapters.binding_digest()) + .await + .unwrap(); + assert_eq!(inspection.run.state, "finished"); + assert_eq!( + inspection.run.outcome.as_deref(), + Some("job-admission-refused") + ); + assert_eq!( + inspection.run.output, + Some(json!({"refusalCode":"invalid-job"})) + ); + assert!( + inspection.effects.is_empty(), + "a refusal claims no admitted job" + ); + assert!(inspection.waits.is_empty()); +} + +#[tokio::test] +async fn unusable_post_commit_response_is_unknown_and_same_command_recovers() { + let h = Harness::new().await; + Mock::given(method("POST")) + .and(path("/jobs")) + .and(header_exists("idempotency-key")) + .respond_with(ResponseTemplate::new(201).set_body_string("not-json-after-admission")) + .expect(1) + .mount(&h.server) + .await; + let run = h.start().await; + h.drain(&h.worker()).await; + let held = h + .store + .inspect(run, h.adapters.binding_digest()) + .await + .unwrap(); + assert_eq!(held.run.state, "attention"); + assert!(held.run.uncertain); + assert_eq!( + serde_json::to_value(&held.effects[0]).unwrap()["state"], + "unknown" + ); + assert!(held.recovery.retry_allowed); + let first = h.server.received_requests().await.unwrap(); + let key = first[0].headers["idempotency-key"] + .to_str() + .unwrap() + .to_owned(); + + h.admitted("running").await; + h.store + .retry_same(run, h.adapters.binding_digest()) + .await + .unwrap(); + h.drain(&h.worker()).await; + let recovered = h + .store + .inspect(run, h.adapters.binding_digest()) + .await + .unwrap(); + assert_eq!(recovered.run.step, "await-terminal"); + assert_eq!(recovered.waits.len(), 1); + let requests = h.server.received_requests().await.unwrap(); + let post = requests + .iter() + .find(|request| request.method.as_str() == "POST") + .unwrap(); + assert_eq!(post.headers["idempotency-key"].to_str().unwrap(), key); +} + #[tokio::test] async fn frozen_external_read_survives_restart_and_inspects_its_bounded_wait() { let h = Harness::new().await; @@ -189,9 +338,10 @@ async fn frozen_external_read_survives_restart_and_inspects_its_bounded_wait() { assert_eq!(wait.completion, "terminal"); assert_eq!(wait.minimum_interval_seconds, 30); assert_eq!(wait.observation_limit, 21); - assert!( - before.effects.is_empty(), - "GET acceptance is not a mutation effect" + assert_eq!( + before.effects.len(), + 1, + "only durable admission is an effect" ); assert!(!serde_json::to_string(&before).unwrap().contains(JOB)); diff --git a/crates/registry-messagingctl/src/lib.rs b/crates/registry-messagingctl/src/lib.rs index 6a69ed111b..ac5873ae40 100644 --- a/crates/registry-messagingctl/src/lib.rs +++ b/crates/registry-messagingctl/src/lib.rs @@ -1371,7 +1371,16 @@ fn package_report(loaded: &LoadedPackage) -> Result { let profiles: Vec = package .access_profiles() .iter() - .map(|profile| json!({"id": profile.id, "actsAs": profile.acts_as})) + .map(|profile| { + json!({ + "id": profile.id, + "actsAs": profile.acts_as, + "principalClaim": profile.principal_claim, + "requiredScopes": profile.required_scopes, + "requesterClients": profile.requester_clients, + "actorKind": profile.actor_kind, + }) + }) .collect(); let mut templates = Vec::new(); for template in package.templates() { @@ -2619,6 +2628,16 @@ audit: assert_eq!(report["metricsListener"], "127.0.0.1:9107"); assert_eq!(report["accessProfiles"][0]["id"], "operations"); assert_eq!(report["accessProfiles"][0]["actsAs"], "operator"); + assert_eq!(report["accessProfiles"][0]["principalClaim"], "sub"); + assert_eq!( + report["accessProfiles"][0]["requiredScopes"], + json!(["messaging:operate"]) + ); + assert_eq!( + report["accessProfiles"][0]["requesterClients"], + json!(["operations-console"]) + ); + assert_eq!(report["accessProfiles"][0]["actorKind"], Value::Null); assert_eq!(report["retention"]["payloadRetentionDays"], 7); let (exit, stdout, stderr) = run(&[ diff --git a/crates/registry-platform-oidc-py/Cargo.toml b/crates/registry-platform-oidc-py/Cargo.toml new file mode 100644 index 0000000000..563ce002ff --- /dev/null +++ b/crates/registry-platform-oidc-py/Cargo.toml @@ -0,0 +1,32 @@ +[package] +name = "registry-platform-oidc-py" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "Bounded Python token verification over Registry Stack OIDC primitives." +readme = "README.md" +repository.workspace = true +publish = false + +[lib] +name = "registry_platform_oidc" +crate-type = ["cdylib", "rlib"] + +[lints] +workspace = true + +[features] +extension-module = ["pyo3/extension-module"] + +[dependencies] +pyo3.workspace = true +oidc_core = { package = "registry-platform-oidc", path = "../registry-platform-oidc" } +serde_json.workspace = true +tokio.workspace = true + +[build-dependencies] +pyo3-build-config.workspace = true + +[dev-dependencies] +pyo3 = { workspace = true, features = ["auto-initialize"] } +registry-platform-testing.workspace = true diff --git a/crates/registry-platform-oidc-py/README.md b/crates/registry-platform-oidc-py/README.md new file mode 100644 index 0000000000..c0c3745312 --- /dev/null +++ b/crates/registry-platform-oidc-py/README.md @@ -0,0 +1,48 @@ +# registry-platform-oidc-py + +Internal PyO3 binding for exact Registry Stack access-token and related ID-token +verification. The unified Python client may assemble this module; it is not a +separate published package. + +`AccessTokenVerifier` fixes one issuer, resource, client, asymmetric signing +algorithm, access-token media type, clock policy and bounded set of projected +scalar claims. `verify()` returns a `VerifiedToken` and never returns or stores +the bearer. A related ID token is checked separately with an expected nonce. + +The public constructor is: + +```python +AccessTokenVerifier( + issuer, + resource, + client_id, + *, + algorithm, + maximum_access_token_lifetime_seconds, + access_token_type="at+jwt", + maximum_id_token_lifetime_seconds=3600, + clock_skew_seconds=60, + claim_names=(), + jwks_uri=None, + allow_insecure_http=False, +) +``` + +`from_static_jwks(jwks_json, issuer, resource, client_id, ...)` supplies the +same policy without network access and accepts only the platform primitive's +public asymmetric JWKS format. `verify(token)` and `verify_access_token(token)` +return immutable `VerifiedToken` objects with `kind`, `issuer`, `audiences`, +`subject`, `client_id`, `scopes`, `expires_at`, `issued_at`, `not_before`, and a +copy of the explicitly selected scalar `claims`. `verify_id_token(token, +expected_nonce)` applies the related ID-token profile and an exact nonce check. + +The boundary admits one of `EdDSA`, `ES256`, `ES384`, `RS256`, or `RS384`. +Tokens are limited to 128 KiB, static JWKS documents to 256 KiB, selected claim +names to 32, audiences to 16, scopes to 256 and 32 KiB total, individual scopes +to 512 bytes, selected values and identifiers to 2 KiB, configured lifetimes to +24 hours, and clock skew to five minutes. Failures expose only the stable +`configuration`, `verification`, or `runtime` kind and a fixed message. + +The wrapper verifies authentication only. Python service configuration owns +persona and profile requirements, and each Registry Stack product remains the +authority for its operations, rows and fields. diff --git a/crates/registry-platform-oidc-py/build.rs b/crates/registry-platform-oidc-py/build.rs new file mode 100644 index 0000000000..58605dd92f --- /dev/null +++ b/crates/registry-platform-oidc-py/build.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: Apache-2.0 + +fn main() { + if std::env::var_os("CARGO_FEATURE_EXTENSION_MODULE").is_some() { + pyo3_build_config::add_extension_module_link_args(); + } else { + pyo3_build_config::add_libpython_rpath_link_args(); + } +} diff --git a/crates/registry-platform-oidc-py/pyproject.toml b/crates/registry-platform-oidc-py/pyproject.toml new file mode 100644 index 0000000000..34fc1010b8 --- /dev/null +++ b/crates/registry-platform-oidc-py/pyproject.toml @@ -0,0 +1,32 @@ +[build-system] +requires = ["maturin>=1.7,<2.0"] +build-backend = "maturin" + +[project] +name = "registry-platform-oidc" +version = "0.46.1" +description = "Bounded Python token verification over Registry Stack OIDC primitives." +readme = "README.md" +license = { text = "Apache-2.0" } +requires-python = ">=3.11" +keywords = ["oidc", "registry", "registrystack"] +classifiers = [ + "Development Status :: 4 - Beta", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", +] + +[project.urls] +Documentation = "https://docs.registrystack.org/" +Issues = "https://github.com/registrystack/registry-stack/issues" +Repository = "https://github.com/registrystack/registry-stack" + +[tool.maturin] +python-source = "python" +module-name = "registry_platform_oidc.registry_platform_oidc" +features = ["extension-module"] diff --git a/crates/registry-platform-oidc-py/python/registry_platform_oidc/__init__.py b/crates/registry-platform-oidc-py/python/registry_platform_oidc/__init__.py new file mode 100644 index 0000000000..1d3309bb17 --- /dev/null +++ b/crates/registry-platform-oidc-py/python/registry_platform_oidc/__init__.py @@ -0,0 +1,3 @@ +"""Bounded native verification for Registry Stack access and ID tokens.""" + +from .registry_platform_oidc import * # noqa: F401,F403 diff --git a/crates/registry-platform-oidc-py/python/registry_platform_oidc/__init__.pyi b/crates/registry-platform-oidc-py/python/registry_platform_oidc/__init__.pyi new file mode 100644 index 0000000000..92904980cd --- /dev/null +++ b/crates/registry-platform-oidc-py/python/registry_platform_oidc/__init__.pyi @@ -0,0 +1,69 @@ +from collections.abc import Mapping, Sequence +from typing import Literal + +TokenAlgorithm = Literal["EdDSA", "ES256", "ES384", "RS256", "RS384"] +TokenKind = Literal["access", "id"] + +class TokenVerificationError(Exception): + """A stable failure that contains no token or configured identity values.""" + + kind: Literal["configuration", "verification", "runtime"] + +class VerifiedToken: + @property + def kind(self) -> TokenKind: ... + @property + def issuer(self) -> str: ... + @property + def audiences(self) -> tuple[str, ...]: ... + @property + def subject(self) -> str: ... + @property + def client_id(self) -> str: ... + @property + def scopes(self) -> tuple[str, ...]: ... + @property + def expires_at(self) -> int: ... + @property + def issued_at(self) -> int: ... + @property + def not_before(self) -> int | None: ... + @property + def claims(self) -> Mapping[str, str]: ... + +class AccessTokenVerifier: + def __init__( + self, + issuer: str, + resource: str, + client_id: str, + *, + algorithm: TokenAlgorithm, + maximum_access_token_lifetime_seconds: int, + access_token_type: str = ..., + maximum_id_token_lifetime_seconds: int = ..., + clock_skew_seconds: int = ..., + claim_names: Sequence[str] = ..., + additional_audiences: Sequence[str] = ..., + jwks_uri: str | None = ..., + allow_insecure_http: bool = ..., + ) -> None: ... + @classmethod + def from_static_jwks( + cls, + jwks_json: str, + issuer: str, + resource: str, + client_id: str, + *, + algorithm: TokenAlgorithm, + maximum_access_token_lifetime_seconds: int, + access_token_type: str = ..., + maximum_id_token_lifetime_seconds: int = ..., + clock_skew_seconds: int = ..., + claim_names: Sequence[str] = ..., + additional_audiences: Sequence[str] = ..., + ) -> AccessTokenVerifier: ... + def verify(self, token: str) -> VerifiedToken: ... + def verify_access_token(self, token: str) -> VerifiedToken: ... + def verify_id_token(self, token: str, expected_nonce: str) -> VerifiedToken: ... diff --git a/crates/registry-platform-oidc-py/python/registry_platform_oidc/py.typed b/crates/registry-platform-oidc-py/python/registry_platform_oidc/py.typed new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/crates/registry-platform-oidc-py/python/registry_platform_oidc/py.typed @@ -0,0 +1 @@ + diff --git a/crates/registry-platform-oidc-py/src/lib.rs b/crates/registry-platform-oidc-py/src/lib.rs new file mode 100644 index 0000000000..3640b3a4b7 --- /dev/null +++ b/crates/registry-platform-oidc-py/src/lib.rs @@ -0,0 +1,712 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Bounded Python token verification over `registry-platform-oidc`. + +#![deny(unsafe_code)] + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; +use std::time::Duration; + +use oidc_core::{ + access_token_typ_set, fetch_discovery_for_issuer, parse_static_jwks, AccessTokenAlgorithm, + Audience, Claims, JwksFetcher, JwksFetcherConfig, OidcDiscoveryConfig, TokenVerifier, + TokenVerifierConfig, +}; +use pyo3::exceptions::PyException; +use pyo3::prelude::*; +use pyo3::types::{PyDict, PyTuple, PyType}; +use serde_json::Value; + +const MAXIMUM_TOKEN_BYTES: usize = 128 * 1024; +const MAXIMUM_JWKS_BYTES: usize = 256 * 1024; +const MAXIMUM_IDENTIFIER_BYTES: usize = 2 * 1024; +const MAXIMUM_CLAIM_NAMES: usize = 32; +const MAXIMUM_CLAIM_NAME_BYTES: usize = 128; +const MAXIMUM_CLAIM_VALUE_BYTES: usize = 2 * 1024; +const MAXIMUM_AUDIENCES: usize = 16; +const MAXIMUM_SCOPES: usize = 256; +const MAXIMUM_SCOPE_BYTES: usize = 512; +const MAXIMUM_TOTAL_SCOPE_BYTES: usize = 32 * 1024; +const MAXIMUM_TOKEN_LIFETIME_SECONDS: u64 = 86_400; +const MAXIMUM_CLOCK_SKEW_SECONDS: u64 = 300; +const MAXIMUM_NONCE_BYTES: usize = 512; +const PRIVATE_JWK_MEMBERS: [&str; 8] = ["d", "p", "q", "dp", "dq", "qi", "oth", "k"]; + +pyo3::create_exception!( + registry_platform_oidc, + TokenVerificationError, + PyException, + "A stable token verification failure that contains no token or configured identity values." +); + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum FailureKind { + Configuration, + Verification, + Runtime, +} + +impl FailureKind { + const fn name(self) -> &'static str { + match self { + Self::Configuration => "configuration", + Self::Verification => "verification", + Self::Runtime => "runtime", + } + } + + const fn message(self) -> &'static str { + match self { + Self::Configuration => "Token verifier configuration is invalid", + Self::Verification => "Token verification failed", + Self::Runtime => "Token verifier runtime failed", + } + } +} + +fn py_error(py: Python<'_>, kind: FailureKind) -> PyErr { + let error = TokenVerificationError::new_err(kind.message()); + error + .value(py) + .setattr("kind", kind.name()) + .expect("fresh exception accepts attributes"); + error +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum TokenKind { + Access, + Id, +} + +impl TokenKind { + const fn name(self) -> &'static str { + match self { + Self::Access => "access", + Self::Id => "id", + } + } +} + +#[derive(Debug)] +struct Policy { + issuer: String, + resource: String, + additional_audiences: Vec, + client_id: String, + algorithm: AccessTokenAlgorithm, + access_token_type: String, + maximum_access_token_lifetime: Duration, + maximum_id_token_lifetime: Duration, + clock_skew: Duration, + claim_names: Vec, +} + +#[allow(clippy::too_many_arguments)] +fn policy( + issuer: String, + resource: String, + client_id: String, + algorithm_name: &str, + access_token_type: String, + maximum_access_token_lifetime_seconds: u64, + maximum_id_token_lifetime_seconds: u64, + clock_skew_seconds: u64, + claim_names: Vec, + additional_audiences: Vec, +) -> Result { + bounded_identifier(&issuer)?; + bounded_identifier(&resource)?; + if additional_audiences.len() > 3 + || additional_audiences + .iter() + .any(|value| bounded_identifier(value).is_err()) + || additional_audiences.iter().any(|value| value == &resource) + || additional_audiences + .iter() + .collect::>() + .len() + != additional_audiences.len() + { + return Err(FailureKind::Configuration); + } + bounded_identifier(&client_id)?; + if access_token_type.is_empty() + || access_token_type.len() > 64 + || !access_token_type + .bytes() + .all(|byte| byte.is_ascii_graphic()) + { + return Err(FailureKind::Configuration); + } + let algorithm = algorithm(algorithm_name)?; + let maximum_access_token_lifetime = bounded_positive_seconds( + maximum_access_token_lifetime_seconds, + MAXIMUM_TOKEN_LIFETIME_SECONDS, + )?; + let maximum_id_token_lifetime = bounded_positive_seconds( + maximum_id_token_lifetime_seconds, + MAXIMUM_TOKEN_LIFETIME_SECONDS, + )?; + if clock_skew_seconds > MAXIMUM_CLOCK_SKEW_SECONDS { + return Err(FailureKind::Configuration); + } + let claim_names = checked_claim_names(claim_names)?; + Ok(Policy { + issuer, + resource, + additional_audiences, + client_id, + algorithm, + access_token_type, + maximum_access_token_lifetime, + maximum_id_token_lifetime, + clock_skew: Duration::from_secs(clock_skew_seconds), + claim_names, + }) +} + +fn bounded_identifier(value: &str) -> Result<(), FailureKind> { + if value.is_empty() + || value.len() > MAXIMUM_IDENTIFIER_BYTES + || value.chars().any(char::is_control) + { + return Err(FailureKind::Configuration); + } + Ok(()) +} + +fn bounded_positive_seconds(value: u64, maximum: u64) -> Result { + if value == 0 || value > maximum { + return Err(FailureKind::Configuration); + } + Ok(Duration::from_secs(value)) +} + +fn algorithm(value: &str) -> Result { + match value { + "EdDSA" => Ok(AccessTokenAlgorithm::EdDSA), + "ES256" => Ok(AccessTokenAlgorithm::ES256), + "ES384" => Ok(AccessTokenAlgorithm::ES384), + "RS256" => Ok(AccessTokenAlgorithm::RS256), + "RS384" => Ok(AccessTokenAlgorithm::RS384), + _ => Err(FailureKind::Configuration), + } +} + +fn checked_claim_names(names: Vec) -> Result, FailureKind> { + if names.len() > MAXIMUM_CLAIM_NAMES { + return Err(FailureKind::Configuration); + } + let mut unique = BTreeSet::new(); + for name in &names { + if name.is_empty() + || name.len() > MAXIMUM_CLAIM_NAME_BYTES + || !name.bytes().all(|byte| { + byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b':' | b'-') + }) + || matches!( + name.as_str(), + "iss" + | "aud" + | "sub" + | "exp" + | "iat" + | "nbf" + | "azp" + | "client_id" + | "scope" + | "nonce" + ) + || !unique.insert(name.clone()) + { + return Err(FailureKind::Configuration); + } + } + Ok(names) +} + +fn runtime() -> Result { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .map_err(|_| FailureKind::Runtime) +} + +struct Verifiers { + access: TokenVerifier, + id: TokenVerifier, +} + +fn verifiers(policy: &Policy, fetcher: Arc) -> Verifiers { + let common = || { + TokenVerifierConfig::access_token_profile( + policy.issuer.clone(), + std::iter::once(policy.resource.clone()) + .chain(policy.additional_audiences.iter().cloned()) + .collect(), + vec![policy.algorithm.to_jsonwebtoken()], + access_token_typ_set(&policy.access_token_type), + ) + .with_allowed_clients(vec![policy.client_id.clone()]) + .with_leeway(policy.clock_skew) + }; + let access = TokenVerifier::new( + common().with_max_token_lifetime(Some(policy.maximum_access_token_lifetime)), + Arc::clone(&fetcher), + ); + let id = TokenVerifier::new( + common().with_max_token_lifetime(Some(policy.maximum_id_token_lifetime)), + fetcher, + ); + Verifiers { access, id } +} + +#[pyclass(frozen, module = "registry_platform_oidc", skip_from_py_object)] +#[derive(Clone, Debug)] +struct VerifiedToken { + kind: TokenKind, + issuer: String, + audiences: Vec, + subject: String, + client_id: String, + scopes: Vec, + expires_at: i64, + issued_at: i64, + not_before: Option, + claims: BTreeMap, +} + +#[pymethods] +impl VerifiedToken { + #[getter] + fn kind(&self) -> &'static str { + self.kind.name() + } + + #[getter] + fn issuer(&self) -> &str { + &self.issuer + } + + #[getter] + fn audiences(&self, py: Python<'_>) -> PyResult> { + Ok(PyTuple::new(py, &self.audiences)?.unbind()) + } + + #[getter] + fn subject(&self) -> &str { + &self.subject + } + + #[getter] + fn client_id(&self) -> &str { + &self.client_id + } + + #[getter] + fn scopes(&self, py: Python<'_>) -> PyResult> { + Ok(PyTuple::new(py, &self.scopes)?.unbind()) + } + + #[getter] + const fn expires_at(&self) -> i64 { + self.expires_at + } + + #[getter] + const fn issued_at(&self) -> i64 { + self.issued_at + } + + #[getter] + const fn not_before(&self) -> Option { + self.not_before + } + + #[getter] + fn claims(&self, py: Python<'_>) -> PyResult> { + let claims = PyDict::new(py); + for (name, value) in &self.claims { + claims.set_item(name, value)?; + } + Ok(claims.unbind()) + } +} + +#[pyclass(module = "registry_platform_oidc")] +struct AccessTokenVerifier { + access: TokenVerifier, + id: TokenVerifier, + runtime: tokio::runtime::Runtime, + policy: Policy, +} + +impl AccessTokenVerifier { + fn from_parts(policy: Policy, fetcher: Arc) -> Result { + let runtime = runtime()?; + let Verifiers { access, id } = verifiers(&policy, fetcher); + Ok(Self { + access, + id, + runtime, + policy, + }) + } + + fn verify_access(&self, token: &str) -> Result { + bounded_token(token)?; + let verified = self + .runtime + .block_on(self.access.verify(token)) + .map_err(|_| FailureKind::Verification)?; + bounded_verified_token( + TokenKind::Access, + verified.claims, + verified.scopes, + &self.policy, + ) + } + + fn verify_id(&self, token: &str, expected_nonce: &str) -> Result { + bounded_token(token)?; + if expected_nonce.is_empty() || expected_nonce.len() > MAXIMUM_NONCE_BYTES { + return Err(FailureKind::Verification); + } + let verified = self + .runtime + .block_on(self.id.verify_related_token(token)) + .map_err(|_| FailureKind::Verification)?; + if verified.claims.extra.get("nonce").and_then(Value::as_str) != Some(expected_nonce) { + return Err(FailureKind::Verification); + } + bounded_verified_token( + TokenKind::Id, + verified.claims, + verified.scopes, + &self.policy, + ) + } +} + +#[pymethods] +impl AccessTokenVerifier { + #[new] + #[pyo3(signature = ( + issuer, + resource, + client_id, + *, + algorithm, + maximum_access_token_lifetime_seconds, + access_token_type="at+jwt".to_owned(), + maximum_id_token_lifetime_seconds=3600, + clock_skew_seconds=60, + claim_names=Vec::new(), + additional_audiences=Vec::new(), + jwks_uri=None, + allow_insecure_http=false, + ))] + #[allow(clippy::too_many_arguments)] + fn new( + py: Python<'_>, + issuer: String, + resource: String, + client_id: String, + algorithm: String, + maximum_access_token_lifetime_seconds: u64, + access_token_type: String, + maximum_id_token_lifetime_seconds: u64, + clock_skew_seconds: u64, + claim_names: Vec, + additional_audiences: Vec, + jwks_uri: Option, + allow_insecure_http: bool, + ) -> PyResult { + let policy = policy( + issuer, + resource, + client_id, + &algorithm, + access_token_type, + maximum_access_token_lifetime_seconds, + maximum_id_token_lifetime_seconds, + clock_skew_seconds, + claim_names, + additional_audiences, + ) + .map_err(|kind| py_error(py, kind))?; + if jwks_uri + .as_deref() + .is_some_and(|uri| bounded_identifier(uri).is_err()) + { + return Err(py_error(py, FailureKind::Configuration)); + } + let runtime = runtime().map_err(|kind| py_error(py, kind))?; + let discovery = OidcDiscoveryConfig { + issuer: policy.issuer.clone(), + jwks_uri_override: jwks_uri, + discovery_timeout: Duration::from_secs(5), + max_doc_bytes: 1024 * 1024, + }; + let (document, fetch_policy) = py + .detach(|| { + runtime.block_on(fetch_discovery_for_issuer(&discovery, allow_insecure_http)) + }) + .map_err(|_| py_error(py, FailureKind::Configuration))?; + let fetcher = Arc::new(JwksFetcher::new_with_fetch_url_policy( + document.jwks_uri, + JwksFetcherConfig::defaults(), + fetch_policy, + )); + let Verifiers { access, id } = verifiers(&policy, fetcher); + Ok(Self { + access, + id, + runtime, + policy, + }) + } + + #[classmethod] + #[pyo3(signature = ( + jwks_json, + issuer, + resource, + client_id, + *, + algorithm, + maximum_access_token_lifetime_seconds, + access_token_type="at+jwt".to_owned(), + maximum_id_token_lifetime_seconds=3600, + clock_skew_seconds=60, + claim_names=Vec::new(), + additional_audiences=Vec::new(), + ))] + #[allow(clippy::too_many_arguments)] + fn from_static_jwks( + _class: &Bound<'_, PyType>, + py: Python<'_>, + jwks_json: String, + issuer: String, + resource: String, + client_id: String, + algorithm: String, + maximum_access_token_lifetime_seconds: u64, + access_token_type: String, + maximum_id_token_lifetime_seconds: u64, + clock_skew_seconds: u64, + claim_names: Vec, + additional_audiences: Vec, + ) -> PyResult { + if jwks_json.len() > MAXIMUM_JWKS_BYTES { + return Err(py_error(py, FailureKind::Configuration)); + } + ensure_public_static_jwks(jwks_json.as_bytes()).map_err(|kind| py_error(py, kind))?; + let policy = policy( + issuer, + resource, + client_id, + &algorithm, + access_token_type, + maximum_access_token_lifetime_seconds, + maximum_id_token_lifetime_seconds, + clock_skew_seconds, + claim_names, + additional_audiences, + ) + .map_err(|kind| py_error(py, kind))?; + let jwks = parse_static_jwks(jwks_json.as_bytes()) + .map_err(|_| py_error(py, FailureKind::Configuration))?; + Self::from_parts( + policy, + Arc::new(JwksFetcher::new_static(jwks, JwksFetcherConfig::defaults())), + ) + .map_err(|kind| py_error(py, kind)) + } + + fn verify(&self, py: Python<'_>, token: &str) -> PyResult { + py.detach(|| self.verify_access(token)) + .map_err(|kind| py_error(py, kind)) + } + + fn verify_access_token(&self, py: Python<'_>, token: &str) -> PyResult { + py.detach(|| self.verify_access(token)) + .map_err(|kind| py_error(py, kind)) + } + + fn verify_id_token( + &self, + py: Python<'_>, + token: &str, + expected_nonce: &str, + ) -> PyResult { + py.detach(|| self.verify_id(token, expected_nonce)) + .map_err(|kind| py_error(py, kind)) + } +} + +fn ensure_public_static_jwks(bytes: &[u8]) -> Result<(), FailureKind> { + let document: Value = serde_json::from_slice(bytes).map_err(|_| FailureKind::Configuration)?; + let keys = document + .get("keys") + .and_then(Value::as_array) + .ok_or(FailureKind::Configuration)?; + for key in keys { + let key = key.as_object().ok_or(FailureKind::Configuration)?; + if PRIVATE_JWK_MEMBERS + .iter() + .any(|member| key.contains_key(*member)) + { + return Err(FailureKind::Configuration); + } + } + Ok(()) +} + +fn bounded_token(token: &str) -> Result<(), FailureKind> { + if token.is_empty() || token.len() > MAXIMUM_TOKEN_BYTES { + return Err(FailureKind::Verification); + } + Ok(()) +} + +fn bounded_verified_token( + kind: TokenKind, + claims: Claims, + scopes: Vec, + policy: &Policy, +) -> Result { + if let (Some(azp), Some(client_id)) = (claims.azp.as_deref(), claims.client_id.as_deref()) { + if azp != client_id { + return Err(FailureKind::Verification); + } + } + let issuer = required_bounded(claims.iss.as_deref())?; + if issuer != policy.issuer { + return Err(FailureKind::Verification); + } + let subject = required_bounded(claims.sub.as_deref())?; + let audiences = bounded_audiences(claims.aud.as_ref())?; + let expected_audiences = std::iter::once(policy.resource.as_str()) + .chain(policy.additional_audiences.iter().map(String::as_str)) + .collect::>(); + match kind { + TokenKind::Access + if audiences.len() != expected_audiences.len() + || audiences + .iter() + .map(String::as_str) + .collect::>() + != expected_audiences => + { + return Err(FailureKind::Verification); + } + TokenKind::Id + if !audiences + .iter() + .any(|audience| audience == &policy.client_id) => + { + return Err(FailureKind::Verification); + } + TokenKind::Access | TokenKind::Id => {} + } + let presented_client = claims.azp.as_deref().or(claims.client_id.as_deref()); + let client_id = match (kind, presented_client) { + (_, Some(client)) if client == policy.client_id => client, + (TokenKind::Id, None) => policy.client_id.as_str(), + (TokenKind::Access | TokenKind::Id, _) => return Err(FailureKind::Verification), + }; + let scopes = bounded_scopes(scopes)?; + let expires_at = claims.exp.ok_or(FailureKind::Verification)?; + let issued_at = claims.iat.ok_or(FailureKind::Verification)?; + let selected = selected_claims(&claims.extra, &policy.claim_names)?; + Ok(VerifiedToken { + kind, + issuer: issuer.to_owned(), + audiences, + subject: subject.to_owned(), + client_id: client_id.to_owned(), + scopes, + expires_at, + issued_at, + not_before: claims.nbf, + claims: selected, + }) +} + +fn required_bounded(value: Option<&str>) -> Result<&str, FailureKind> { + value + .filter(|value| { + !value.is_empty() + && value.len() <= MAXIMUM_IDENTIFIER_BYTES + && !value.chars().any(char::is_control) + }) + .ok_or(FailureKind::Verification) +} + +fn bounded_audiences(audience: Option<&Audience>) -> Result, FailureKind> { + let audiences = match audience { + Some(Audience::One(value)) => vec![value.clone()], + Some(Audience::Many(values)) => values.clone(), + None => return Err(FailureKind::Verification), + }; + if audiences.is_empty() + || audiences.len() > MAXIMUM_AUDIENCES + || audiences.iter().any(|value| { + value.is_empty() + || value.len() > MAXIMUM_IDENTIFIER_BYTES + || value.chars().any(char::is_control) + }) + { + return Err(FailureKind::Verification); + } + Ok(audiences) +} + +fn bounded_scopes(scopes: Vec) -> Result, FailureKind> { + if scopes.len() > MAXIMUM_SCOPES + || scopes.iter().any(|scope| { + scope.is_empty() + || scope.len() > MAXIMUM_SCOPE_BYTES + || !scope.bytes().all(|byte| byte.is_ascii_graphic()) + }) + || scopes.iter().map(String::len).sum::() > MAXIMUM_TOTAL_SCOPE_BYTES + { + return Err(FailureKind::Verification); + } + Ok(scopes) +} + +fn selected_claims( + extra: &serde_json::Map, + names: &[String], +) -> Result, FailureKind> { + let mut selected = BTreeMap::new(); + for name in names { + let Some(value) = extra.get(name) else { + continue; + }; + let value = value.as_str().ok_or(FailureKind::Verification)?; + if value.is_empty() || value.len() > MAXIMUM_CLAIM_VALUE_BYTES { + return Err(FailureKind::Verification); + } + selected.insert(name.clone(), value.to_owned()); + } + Ok(selected) +} + +#[cfg(test)] +mod tests; + +#[pymodule] +fn registry_platform_oidc(module: &Bound<'_, PyModule>) -> PyResult<()> { + module.add_class::()?; + module.add_class::()?; + module.add( + "TokenVerificationError", + module.py().get_type::(), + )?; + module.add("__version__", env!("CARGO_PKG_VERSION"))?; + Ok(()) +} diff --git a/crates/registry-platform-oidc-py/src/tests.rs b/crates/registry-platform-oidc-py/src/tests.rs new file mode 100644 index 0000000000..cab6526eb8 --- /dev/null +++ b/crates/registry-platform-oidc-py/src/tests.rs @@ -0,0 +1,178 @@ +use std::time::{SystemTime, UNIX_EPOCH}; + +use oidc_core::{parse_static_jwks, JwksFetcher, JwksFetcherConfig}; +use registry_platform_testing::{fixtures, sign_ed25519_compact_jwt_with_key}; +use serde_json::json; + +use super::*; + +const ISSUER: &str = "https://issuer.example"; +const RESOURCE: &str = "urn:registry:service"; +const CLIENT: &str = "service-client"; + +fn now() -> i64 { + i64::try_from( + SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("the test clock is after the Unix epoch") + .as_secs(), + ) + .expect("the test clock fits in i64") +} + +fn test_policy() -> Policy { + policy( + ISSUER.to_owned(), + RESOURCE.to_owned(), + CLIENT.to_owned(), + "EdDSA", + "at+jwt".to_owned(), + 600, + 3_600, + 0, + vec!["registry_principal".to_owned(), "actor_kind".to_owned()], + ) + .expect("test policy") +} + +fn verifier() -> AccessTokenVerifier { + let (_, public) = fixtures::ed25519_pair(); + let jwks = parse_static_jwks( + serde_json::to_vec(&json!({"keys": [public]})) + .expect("serialize public JWKS") + .as_slice(), + ) + .expect("parse public JWKS"); + AccessTokenVerifier::from_parts( + test_policy(), + Arc::new(JwksFetcher::new_static(jwks, JwksFetcherConfig::defaults())), + ) + .expect("build verifier") +} + +fn claims(audience: Value) -> Value { + let now = now(); + json!({ + "iss": ISSUER, + "aud": audience, + "sub": "subject-1", + "azp": CLIENT, + "exp": now + 300, + "iat": now, + "nbf": now - 1, + "scope": "command:submit job:read", + "registry_principal": "principal-1", + "actor_kind": "service", + "unselected": "must-not-cross-the-binding", + }) +} + +fn sign(typ: &str, claims: Value) -> String { + let (private, _) = fixtures::ed25519_pair(); + sign_ed25519_compact_jwt_with_key(&private, typ, "registry-platform-testing-ed25519-1", claims) +} + +#[test] +fn configuration_requires_one_exact_asymmetric_algorithm() { + assert!(algorithm("RS256").is_ok()); + assert!(algorithm("HS256").is_err()); + assert!(algorithm("rs256").is_err()); + assert_eq!( + ensure_public_static_jwks( + format!(r#"{{"keys":[{}]}}"#, fixtures::ED25519_PRIVATE_JWK).as_bytes() + ), + Err(FailureKind::Configuration) + ); +} + +#[test] +fn a_valid_access_token_returns_only_bounded_selected_claims() { + let verifier = verifier(); + let token = sign("at+jwt", claims(json!(RESOURCE))); + let verified = verifier.verify_access(&token).expect("token verifies"); + assert_eq!(verified.kind, TokenKind::Access); + assert_eq!(verified.issuer, ISSUER); + assert_eq!(verified.audiences, vec![RESOURCE.to_owned()]); + assert_eq!(verified.subject, "subject-1"); + assert_eq!(verified.client_id, CLIENT); + assert_eq!( + verified.scopes, + vec!["command:submit".to_owned(), "job:read".to_owned()] + ); + assert_eq!( + verified.claims, + BTreeMap::from([ + ("actor_kind".to_owned(), "service".to_owned()), + ("registry_principal".to_owned(), "principal-1".to_owned()), + ]) + ); + assert!(!verified.claims.contains_key("unselected")); +} + +#[test] +fn conflicting_client_claims_and_extra_audiences_are_refused() { + let verifier = verifier(); + let mut conflict = claims(json!(RESOURCE)); + conflict["client_id"] = json!("other-client"); + let token = sign("at+jwt", conflict); + assert_eq!( + verifier + .verify_access(&token) + .expect_err("conflict refuses"), + FailureKind::Verification + ); + + let token = sign("at+jwt", claims(json!([RESOURCE, "urn:registry:other"]))); + assert_eq!( + verifier + .verify_access(&token) + .expect_err("extra audience refuses"), + FailureKind::Verification + ); +} + +#[test] +fn related_id_token_requires_the_expected_nonce_and_client_audience() { + let verifier = verifier(); + let mut id_claims = claims(json!(CLIENT)); + id_claims["nonce"] = json!("pending-nonce"); + id_claims + .as_object_mut() + .expect("claims are an object") + .remove("scope"); + id_claims + .as_object_mut() + .expect("claims are an object") + .remove("azp"); + let token = sign("JWT", id_claims); + let verified = verifier + .verify_id(&token, "pending-nonce") + .expect("ID token verifies"); + assert_eq!(verified.kind, TokenKind::Id); + assert_eq!(verified.audiences, vec![CLIENT.to_owned()]); + assert_eq!( + verifier + .verify_id(&token, "different-nonce") + .expect_err("wrong nonce refuses"), + FailureKind::Verification + ); +} + +#[test] +fn token_and_output_bounds_fail_closed() { + let policy = test_policy(); + assert_eq!( + bounded_token(&"x".repeat(MAXIMUM_TOKEN_BYTES + 1)), + Err(FailureKind::Verification) + ); + assert!(checked_claim_names(vec!["scope".to_owned()]).is_err()); + let mut extra = serde_json::Map::new(); + extra.insert( + "registry_principal".to_owned(), + json!("x".repeat(MAXIMUM_CLAIM_VALUE_BYTES + 1)), + ); + assert_eq!( + selected_claims(&extra, &policy.claim_names), + Err(FailureKind::Verification) + ); +} diff --git a/crates/registry-platform-oidc-py/tests/python/bootstrap.py b/crates/registry-platform-oidc-py/tests/python/bootstrap.py new file mode 100644 index 0000000000..e3982b8a6b --- /dev/null +++ b/crates/registry-platform-oidc-py/tests/python/bootstrap.py @@ -0,0 +1,70 @@ +"""Build and import the platform OIDC PyO3 module for stdlib-only tests.""" + +from __future__ import annotations + +import functools +import json +import pathlib +import platform +import shutil +import subprocess +import sys + +_CRATE_ROOT = pathlib.Path(__file__).resolve().parents[2] +_WORKSPACE_ROOT = _CRATE_ROOT.parents[1] +_MODULE_NAME = "registry_platform_oidc" + + +@functools.cache +def _target_debug() -> pathlib.Path: + metadata = subprocess.run( + ["cargo", "metadata", "--locked", "--format-version", "1", "--no-deps"], + cwd=_WORKSPACE_ROOT, + capture_output=True, + check=False, + text=True, + ) + if metadata.returncode != 0: + raise RuntimeError( + "cargo metadata failed, so the Cargo target directory is unknown:\n" + + metadata.stderr + ) + return pathlib.Path(json.loads(metadata.stdout)["target_directory"]) / "debug" + + +def _library() -> pathlib.Path: + suffix = {"Darwin": ".dylib", "Linux": ".so"}.get(platform.system()) + if suffix is None: + raise RuntimeError("the OIDC Python tests support macOS and Linux") + return _target_debug() / f"lib{_MODULE_NAME}{suffix}" + + +@functools.cache +def ensure_built() -> None: + subprocess.run( + [ + "cargo", + "build", + "--locked", + "-p", + "registry-platform-oidc-py", + "--lib", + "--features", + "registry-platform-oidc-py/extension-module", + ], + cwd=_WORKSPACE_ROOT, + check=True, + ) + source = _library() + if not source.is_file(): + raise RuntimeError(f"cargo did not produce {source}") + import_root = _target_debug() / "platform_oidc_python_module" + import_package = import_root / _MODULE_NAME + import_package.mkdir(parents=True, exist_ok=True) + shutil.copyfile( + _CRATE_ROOT / "python" / _MODULE_NAME / "__init__.py", + import_package / "__init__.py", + ) + shutil.copyfile(source, import_package / f"{_MODULE_NAME}.so") + if str(import_root) not in sys.path: + sys.path.insert(0, str(import_root)) diff --git a/crates/registry-platform-oidc-py/tests/python/test_verifier.py b/crates/registry-platform-oidc-py/tests/python/test_verifier.py new file mode 100644 index 0000000000..788ba9fadc --- /dev/null +++ b/crates/registry-platform-oidc-py/tests/python/test_verifier.py @@ -0,0 +1,210 @@ +"""Python contract tests for the bounded native OIDC verifier.""" + +from __future__ import annotations + +import base64 +import json +import os +import pathlib +import subprocess +import tempfile +import time +import unittest + +from bootstrap import ensure_built + +ensure_built() + +from registry_platform_oidc import ( # noqa: E402 + AccessTokenVerifier, + TokenVerificationError, +) + +ISSUER = "https://issuer.example" +RESOURCE = "urn:registry:service" +CLIENT = "service-client" +KID = "registry-platform-testing-ed25519-1" +PUBLIC_X = "1aj_rLJsGFgw-5v925EMmeZj5JqP44xegafEKfZbdxc" +PRIVATE_D = "2oPoxdKuO7Kpd-3JLfNW_4xwpFxItbS-fxe03ZybYEw" + + +def _base64url(value: bytes) -> str: + return base64.urlsafe_b64encode(value).rstrip(b"=").decode("ascii") + + +def _decode_base64url(value: str) -> bytes: + return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4)) + + +def _sign(typ: str, claims: dict[str, object]) -> str: + header = {"alg": "EdDSA", "kid": KID, "typ": typ} + parts = [ + _base64url(json.dumps(value, separators=(",", ":")).encode("utf-8")) + for value in (header, claims) + ] + signing_input = ".".join(parts).encode("ascii") + pkcs8 = bytes.fromhex("302e020100300506032b657004220420") + _decode_base64url( + PRIVATE_D + ) + pem = ( + "-----BEGIN PRIVATE KEY-----\n" + + "\n".join( + base64.b64encode(pkcs8).decode("ascii")[offset : offset + 64] + for offset in range(0, len(base64.b64encode(pkcs8)), 64) + ) + + "\n-----END PRIVATE KEY-----\n" + ) + with tempfile.TemporaryDirectory() as directory: + key_path = pathlib.Path(directory) / "signing-key.pem" + input_path = pathlib.Path(directory) / "signing-input" + key_path.write_text(pem, encoding="ascii") + input_path.write_bytes(signing_input) + os.chmod(key_path, 0o600) + os.chmod(input_path, 0o600) + signed = subprocess.run( + [ + "openssl", + "pkeyutl", + "-sign", + "-rawin", + "-inkey", + str(key_path), + "-in", + str(input_path), + ], + capture_output=True, + check=True, + ).stdout + return f"{parts[0]}.{parts[1]}.{_base64url(signed)}" + + +def _claims(audience: str | list[str]) -> dict[str, object]: + now = int(time.time()) + return { + "iss": ISSUER, + "aud": audience, + "sub": "subject-1", + "azp": CLIENT, + "exp": now + 300, + "iat": now, + "nbf": now - 1, + "scope": "command:submit job:read", + "registry_principal": "principal-1", + "actor_kind": "service", + "unselected": "must-not-cross-the-binding", + } + + +def _verifier() -> AccessTokenVerifier: + jwks = json.dumps( + {"keys": [{"kty": "OKP", "crv": "Ed25519", "kid": KID, "x": PUBLIC_X}]} + ) + return AccessTokenVerifier.from_static_jwks( + jwks, + ISSUER, + RESOURCE, + CLIENT, + algorithm="EdDSA", + maximum_access_token_lifetime_seconds=600, + clock_skew_seconds=0, + claim_names=("registry_principal", "actor_kind"), + ) + + +class VerifierTests(unittest.TestCase): + def test_access_token_returns_only_bounded_selected_claims(self) -> None: + token = _sign("at+jwt", _claims(RESOURCE)) + verified = _verifier().verify(token) + self.assertEqual(verified.kind, "access") + self.assertEqual(verified.issuer, ISSUER) + self.assertEqual(verified.audiences, (RESOURCE,)) + self.assertEqual(verified.subject, "subject-1") + self.assertEqual(verified.client_id, CLIENT) + self.assertEqual(verified.scopes, ("command:submit", "job:read")) + self.assertEqual( + dict(verified.claims), + {"actor_kind": "service", "registry_principal": "principal-1"}, + ) + + def test_conflicting_client_claims_and_extra_audience_fail_closed(self) -> None: + conflict = _claims(RESOURCE) + conflict["client_id"] = "other-client" + for token in ( + _sign("at+jwt", conflict), + _sign("at+jwt", _claims([RESOURCE, "urn:registry:other"])), + ): + with self.subTest(token_shape=token.count(".")): + with self.assertRaises(TokenVerificationError) as raised: + _verifier().verify(token) + self.assertEqual(raised.exception.kind, "verification") + self.assertEqual(str(raised.exception), "Token verification failed") + self.assertNotIn(token, repr(raised.exception)) + + def test_configured_forward_audience_requires_exact_audience_set(self) -> None: + jwks = json.dumps( + {"keys": [{"kty": "OKP", "crv": "Ed25519", "kid": KID, "x": PUBLIC_X}]} + ) + verifier = AccessTokenVerifier.from_static_jwks( + jwks, + ISSUER, + RESOURCE, + CLIENT, + algorithm="EdDSA", + maximum_access_token_lifetime_seconds=600, + clock_skew_seconds=0, + additional_audiences=("urn:registry:breg",), + ) + self.assertEqual( + verifier.verify( + _sign("at+jwt", _claims([RESOURCE, "urn:registry:breg"])) + ).audiences, + (RESOURCE, "urn:registry:breg"), + ) + self.assertEqual( + verifier.verify( + _sign("at+jwt", _claims(["urn:registry:breg", RESOURCE])) + ).audiences, + ("urn:registry:breg", RESOURCE), + ) + for audiences in ( + RESOURCE, + [RESOURCE, "urn:registry:other"], + [RESOURCE, "urn:registry:breg", "urn:registry:other"], + ): + with ( + self.subTest(audiences=audiences), + self.assertRaises(TokenVerificationError), + ): + verifier.verify(_sign("at+jwt", _claims(audiences))) + + def test_related_id_token_requires_expected_nonce(self) -> None: + claims = _claims(CLIENT) + claims.pop("scope") + claims.pop("azp") + claims["nonce"] = "pending-nonce" + token = _sign("JWT", claims) + verified = _verifier().verify_id_token(token, "pending-nonce") + self.assertEqual(verified.kind, "id") + self.assertEqual(verified.audiences, (CLIENT,)) + with self.assertRaises(TokenVerificationError) as raised: + _verifier().verify_id_token(token, "different-nonce") + self.assertEqual(raised.exception.kind, "verification") + + def test_configuration_rejects_symmetric_algorithms_without_values(self) -> None: + with self.assertRaises(TokenVerificationError) as raised: + AccessTokenVerifier.from_static_jwks( + '{"keys":[]}', + ISSUER, + RESOURCE, + CLIENT, + algorithm="HS256", # type: ignore[arg-type] + maximum_access_token_lifetime_seconds=600, + ) + self.assertEqual(raised.exception.kind, "configuration") + self.assertEqual( + str(raised.exception), "Token verifier configuration is invalid" + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/crates/registry-platform-oidc/src/lib.rs b/crates/registry-platform-oidc/src/lib.rs index 820476fa45..44d214ed33 100644 --- a/crates/registry-platform-oidc/src/lib.rs +++ b/crates/registry-platform-oidc/src/lib.rs @@ -469,26 +469,41 @@ impl fmt::Debug for JwksFetcher { } /// Parse an operator-supplied static JWKS document for -/// [`JwksFetcher::new_static`]: a non-empty key set of RSA or elliptic-curve +/// [`JwksFetcher::new_static`]: a non-empty key set of RSA, elliptic-curve, or Ed25519 /// keys, each with a non-empty `kid` no other key in the set repeats. A -/// symmetric key or an unnamed key is refused here, at startup, rather than +/// symmetric or private key, or an unnamed key, is refused here at startup rather than /// when a token first selects it. pub fn parse_static_jwks(bytes: &[u8]) -> Result { - let jwks: JwkSet = serde_json::from_slice(bytes).map_err(|_| OidcError::Parse)?; + let raw: serde_json::Value = serde_json::from_slice(bytes).map_err(|_| OidcError::Parse)?; + let jwks: JwkSet = serde_json::from_value(raw.clone()).map_err(|_| OidcError::Parse)?; if jwks.keys.is_empty() { return Err(OidcError::EmptyKeySet); } let mut kids = BTreeSet::new(); - let all_named_asymmetric = jwks.keys.iter().all(|key| { - matches!( - key.algorithm, - AlgorithmParameters::RSA(_) | AlgorithmParameters::EllipticCurve(_) - ) && key - .common - .key_id - .as_deref() - .is_some_and(|kid| !kid.is_empty() && kids.insert(kid)) + let public_only = raw["keys"].as_array().is_some_and(|keys| { + keys.iter().all(|key| { + key.as_object().is_some_and(|fields| { + ["d", "p", "q", "dp", "dq", "qi", "oth", "k"] + .iter() + .all(|field| !fields.contains_key(*field)) + }) + }) }); + let all_named_asymmetric = public_only + && jwks.keys.iter().all(|key| { + (matches!( + key.algorithm, + AlgorithmParameters::RSA(_) | AlgorithmParameters::EllipticCurve(_) + ) || matches!( + &key.algorithm, + AlgorithmParameters::OctetKeyPair(parameters) + if parameters.curve == EllipticCurve::Ed25519 + )) && key + .common + .key_id + .as_deref() + .is_some_and(|kid| !kid.is_empty() && kids.insert(kid)) + }); if all_named_asymmetric { Ok(jwks) } else { @@ -4590,10 +4605,10 @@ mod tests { #[test] fn a_static_key_set_requires_unique_named_asymmetric_keys() { let keys = parse_static_jwks( - br#"{"keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"},{"kty":"EC","kid":"two","crv":"P-256","x":"f83OJ3D2xF4k1JQWctzS0r8uXH6Gz-l4WfXccj5WHv0","y":"x_FEzRu9dVvZt2pSuGQgH7u9tZxU7I5oUJu-4G8Azjo"}]}"#, + br#"{"keys":[{"kty":"RSA","kid":"one","n":"AQAB","e":"AQAB"},{"kty":"EC","kid":"two","crv":"P-256","x":"f83OJ3D2xF4k1JQWctzS0r8uXH6Gz-l4WfXccj5WHv0","y":"x_FEzRu9dVvZt2pSuGQgH7u9tZxU7I5oUJu-4G8Azjo"},{"kty":"OKP","kid":"three","crv":"Ed25519","x":"1aj_rLJsGFgw-5v925EMmeZj5JqP44xegafEKfZbdxc"}]}"#, ) - .expect("RSA and EC keys with distinct kids"); - assert_eq!(keys.keys.len(), 2); + .expect("RSA, EC, and Ed25519 keys with distinct kids"); + assert_eq!(keys.keys.len(), 3); for (reason, invalid, expected) in [ ("no keys member", br#"{}"#.as_slice(), "parse"), @@ -4604,6 +4619,11 @@ mod tests { br#"{"keys":[{"kty":"oct","kid":"one","k":"AA"}]}"#, "jwk", ), + ( + "a private Ed25519 key", + br#"{"keys":[{"kty":"OKP","kid":"one","crv":"Ed25519","x":"1aj_rLJsGFgw-5v925EMmeZj5JqP44xegafEKfZbdxc","d":"private"}]}"#, + "jwk", + ), ( "a key without kid", br#"{"keys":[{"kty":"RSA","n":"AQAB","e":"AQAB"}]}"#, diff --git a/crates/registry-platform-yaml-py/Cargo.toml b/crates/registry-platform-yaml-py/Cargo.toml new file mode 100644 index 0000000000..2f6b38b7b9 --- /dev/null +++ b/crates/registry-platform-yaml-py/Cargo.toml @@ -0,0 +1,38 @@ +[package] +name = "registry-platform-yaml-py" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "Bounded Python access to the Registry Stack configuration reader." +readme = "README.md" +repository.workspace = true +publish = false + +[lib] +name = "registry_platform_yaml" +crate-type = ["cdylib", "rlib"] + +[lints] +workspace = true + +[features] +extension-module = ["pyo3/extension-module"] +schema = ["dep:schemars", "platform_config/schema", "yaml_core/schema"] + +[dependencies] +pyo3.workspace = true +platform_config = { package = "registry-platform-config", path = "../registry-platform-config" } +schemars = { workspace = true, optional = true } +serde.workspace = true +yaml_core = { package = "registry-platform-yaml", path = "../registry-platform-yaml" } +serde_json.workspace = true + +[build-dependencies] +pyo3-build-config.workspace = true + +[dev-dependencies] +pyo3 = { workspace = true, features = ["auto-initialize"] } + +[[example]] +name = "python-formats-schema" +required-features = ["schema"] diff --git a/crates/registry-platform-yaml-py/README.md b/crates/registry-platform-yaml-py/README.md new file mode 100644 index 0000000000..a292b548ea --- /dev/null +++ b/crates/registry-platform-yaml-py/README.md @@ -0,0 +1,49 @@ +# registry-platform-yaml-py + +Internal PyO3 binding for the shared Registry Stack configuration reader. The +unified Python client may assemble this module; it is not a separately +published package. + +The public function is: + +```python +read_document( + contents: bytes, + *, + file: str, + api_version: str, + kind: str, +) -> dict[str, JSONValue] +``` + +It accepts bytes so the native reader owns UTF-8, input-size and syntax +decisions. JSON is read as YAML 1.2 flow content through +`registry-platform-yaml`, including duplicate-key, alias, tag, depth and +envelope checks. The caller supplies one expected current `apiVersion` and +`kind`; product-specific field and policy validation remains with the caller. + +A refused document raises `ConfigReadError` with the fixed message +`Configuration document was refused`. Its `diagnostics` attribute is a tuple +of the shared reader's JSON diagnostic objects. The reader caps the input at +1 MiB and depth at 128. It retains at most 100 individual diagnostics and may +add one `config.too-many-problems` overflow diagnostic. +Diagnostic messages do not repeat scalar values from the document. The +binding additionally bounds the diagnostic file name to 4 KiB and each +expected format identifier to 256 bytes. The registered Python connection and +development workload-token envelopes are decoded into their closed native +types at the same boundary, including their non-empty authority sets. Other +formats receive the generic envelope and structural checks before their +product-specific validation. + +The standalone development import is: + +```python +from registry_platform_yaml import ConfigReadError, read_document +``` + +When the package is relocated into the unified client wheel, the intended +import is: + +```python +from registry_client.yaml import ConfigReadError, read_document +``` diff --git a/crates/registry-platform-yaml-py/build.rs b/crates/registry-platform-yaml-py/build.rs new file mode 100644 index 0000000000..58605dd92f --- /dev/null +++ b/crates/registry-platform-yaml-py/build.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: Apache-2.0 + +fn main() { + if std::env::var_os("CARGO_FEATURE_EXTENSION_MODULE").is_some() { + pyo3_build_config::add_extension_module_link_args(); + } else { + pyo3_build_config::add_libpython_rpath_link_args(); + } +} diff --git a/crates/registry-platform-yaml-py/examples/python-formats-schema.rs b/crates/registry-platform-yaml-py/examples/python-formats-schema.rs new file mode 100644 index 0000000000..9b246c943d --- /dev/null +++ b/crates/registry-platform-yaml-py/examples/python-formats-schema.rs @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: Apache-2.0 + +fn main() -> Result<(), Box> { + let mut arguments = std::env::args_os().skip(1); + if arguments.next().as_deref() != Some(std::ffi::OsStr::new("--output")) { + return Err("usage: python-formats-schema --output ".into()); + } + let output = arguments.next().ok_or("--output requires a directory")?; + if arguments.next().is_some() { + return Err("unexpected argument".into()); + } + let directory = std::path::Path::new(&output); + std::fs::create_dir_all(directory)?; + for (name, schema) in registry_platform_yaml::schema_documents() { + let mut text = serde_json::to_string_pretty(&schema)?; + text.push('\n'); + std::fs::write(directory.join(name), text)?; + } + Ok(()) +} diff --git a/crates/registry-platform-yaml-py/pyproject.toml b/crates/registry-platform-yaml-py/pyproject.toml new file mode 100644 index 0000000000..a04e88a004 --- /dev/null +++ b/crates/registry-platform-yaml-py/pyproject.toml @@ -0,0 +1,32 @@ +[build-system] +requires = ["maturin>=1.7,<2.0"] +build-backend = "maturin" + +[project] +name = "registry-platform-yaml" +version = "0.46.1" +description = "Bounded Python access to the Registry Stack configuration reader." +readme = "README.md" +license = { text = "Apache-2.0" } +requires-python = ">=3.11" +keywords = ["configuration", "registry", "registrystack", "yaml"] +classifiers = [ + "Development Status :: 4 - Beta", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", +] + +[project.urls] +Documentation = "https://docs.registrystack.org/" +Issues = "https://github.com/registrystack/registry-stack/issues" +Repository = "https://github.com/registrystack/registry-stack" + +[tool.maturin] +python-source = "python" +module-name = "registry_platform_yaml.registry_platform_yaml" +features = ["extension-module"] diff --git a/crates/registry-platform-yaml-py/python/registry_platform_yaml/__init__.py b/crates/registry-platform-yaml-py/python/registry_platform_yaml/__init__.py new file mode 100644 index 0000000000..ee612a9c02 --- /dev/null +++ b/crates/registry-platform-yaml-py/python/registry_platform_yaml/__init__.py @@ -0,0 +1,3 @@ +"""Bounded access to the shared Registry Stack configuration reader.""" + +from .registry_platform_yaml import * # noqa: F401,F403 diff --git a/crates/registry-platform-yaml-py/python/registry_platform_yaml/__init__.pyi b/crates/registry-platform-yaml-py/python/registry_platform_yaml/__init__.pyi new file mode 100644 index 0000000000..1ffe33fde6 --- /dev/null +++ b/crates/registry-platform-yaml-py/python/registry_platform_yaml/__init__.pyi @@ -0,0 +1,39 @@ +from typing import NotRequired, TypeAlias, TypedDict + +JSONScalar: TypeAlias = None | bool | int | float | str +JSONValue: TypeAlias = JSONScalar | list["JSONValue"] | dict[str, "JSONValue"] + +class Source(TypedDict): + file: str + line: NotRequired[int] + column: NotRequired[int] + +class Related(TypedDict): + file: str + line: NotRequired[int] + column: NotRequired[int] + path: str + message: str + +class Diagnostic(TypedDict): + severity: str + code: str + artifact: NotRequired[str] + path: str + message: str + suggestedAction: str + source: NotRequired[Source] + related: NotRequired[list[Related]] + +class ConfigReadError(Exception): + """A configuration document was refused with value-free diagnostics.""" + + diagnostics: tuple[Diagnostic, ...] + +def read_document( + contents: bytes, + *, + file: str, + api_version: str, + kind: str, +) -> dict[str, JSONValue]: ... diff --git a/crates/registry-platform-yaml-py/python/registry_platform_yaml/py.typed b/crates/registry-platform-yaml-py/python/registry_platform_yaml/py.typed new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/crates/registry-platform-yaml-py/python/registry_platform_yaml/py.typed @@ -0,0 +1 @@ + diff --git a/crates/registry-platform-yaml-py/src/formats.rs b/crates/registry-platform-yaml-py/src/formats.rs new file mode 100644 index 0000000000..acfd17ebb3 --- /dev/null +++ b/crates/registry-platform-yaml-py/src/formats.rs @@ -0,0 +1,395 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Typed structure and schemas for the two Python service read-back formats. + +use std::{collections::BTreeMap, hash::Hash}; + +use platform_config::SecretProvidersConfig; +use registry_platform_yaml::{ + ApiVersion, BoundedU64, Decoded, EnvelopeRule, Expect, ExternalId, FormatSpec, Reader, Report, + SecretReference, UniqueList, Url, +}; +use serde::{de, Deserialize, Deserializer}; +use serde_json::Value; +use yaml_core as registry_platform_yaml; + +pub const PYTHON_CONNECTION_API_VERSION: &str = + "id.registrystack.org/formats/platform/python-connection/v1alpha1"; +pub const PYTHON_CONNECTION_KIND: &str = "PlatformPythonConnection"; +pub const PYTHON_CONNECTION_SCHEMA_ID: &str = "https://id.registrystack.org/schemas/platform/python-connection/python-connection.v1alpha1.schema.json"; +pub const PYTHON_CONNECTION_SCHEMA_FILE: &str = "python-connection.v1alpha1.schema.json"; +pub const DEV_WORKLOAD_TOKEN_API_VERSION: &str = + "id.registrystack.org/formats/platform/dev-workload-token/v1alpha1"; +pub const DEV_WORKLOAD_TOKEN_KIND: &str = "PlatformDevWorkloadToken"; +pub const DEV_WORKLOAD_TOKEN_SCHEMA_ID: &str = "https://id.registrystack.org/schemas/platform/dev-workload-token/dev-workload-token.v1alpha1.schema.json"; +pub const DEV_WORKLOAD_TOKEN_SCHEMA_FILE: &str = "dev-workload-token.v1alpha1.schema.json"; + +pub const PYTHON_CONNECTION_FORMAT: FormatSpec<'static> = FormatSpec { + kind: PYTHON_CONNECTION_KIND, + envelope: EnvelopeRule::ApiVersionKind { + api_versions: &[ApiVersion::current(PYTHON_CONNECTION_API_VERSION)], + retired_api_versions: &[], + }, + removed_keys: &[], +}; + +pub const DEV_WORKLOAD_TOKEN_FORMAT: FormatSpec<'static> = FormatSpec { + kind: DEV_WORKLOAD_TOKEN_KIND, + envelope: EnvelopeRule::ApiVersionKind { + api_versions: &[ApiVersion::current(DEV_WORKLOAD_TOKEN_API_VERSION)], + retired_api_versions: &[], + }, + removed_keys: &[], +}; + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ServiceAudience { + Service, + Holder, + Staff, +} + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum WorkloadProduct { + Breg, + Messaging, +} + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Deserialize)] +pub enum TokenAlgorithm { + EdDSA, + ES256, + ES384, + RS256, + RS384, +} + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct MachineAdmission { + pub issuer: Url, + pub resource: ExternalId, + pub client_id: ExternalId, + pub profile: ExternalId, + #[serde(deserialize_with = "non_empty_unique_list")] + #[cfg_attr(feature = "schema", schemars(length(min = 1)))] + pub required_scopes: UniqueList, + #[serde(deserialize_with = "non_empty_map")] + #[cfg_attr(feature = "schema", schemars(length(min = 1)))] + pub required_claims: BTreeMap, + pub algorithm: TokenAlgorithm, + pub access_token_type: ExternalId, + pub maximum_access_token_lifetime_seconds: BoundedU64<1, 7200>, + #[serde( + default, + deserialize_with = "present_option", + skip_serializing_if = "Option::is_none" + )] + pub jwks_uri: Option, + #[serde( + default, + deserialize_with = "present_option", + skip_serializing_if = "Option::is_none" + )] + pub clock_skew_seconds: Option>, + #[serde( + default, + deserialize_with = "present_option", + skip_serializing_if = "Option::is_none" + )] + pub allow_insecure_http: Option, +} + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[cfg_attr( + feature = "schema", + schemars( + !remote, + tag = "type", + rename_all = "kebab-case", + rename_all_fields = "camelCase" + ) +)] +#[derive(Deserialize)] +#[serde( + remote = "Self", + rename_all = "kebab-case", + rename_all_fields = "camelCase", + deny_unknown_fields +)] +pub enum WorkloadCredential { + PrivateKeyJwt { + issuer: Url, + subject: ExternalId, + token_endpoint: Url, + client_id: ExternalId, + profile: ExternalId, + client_key_ref: SecretReference, + resource: ExternalId, + #[serde(deserialize_with = "non_empty_unique_list")] + #[cfg_attr(feature = "schema", schemars(length(min = 1)))] + scopes: UniqueList, + #[cfg_attr(feature = "schema", schemars(schema_with = "authority_claims_schema"))] + claims: BTreeMap, + }, + RunnerToken { + token_ref: SecretReference, + run_id: ExternalId, + binding: ExternalId, + issuer: Url, + subject: ExternalId, + client_id: ExternalId, + profile: ExternalId, + resource: ExternalId, + #[serde(deserialize_with = "non_empty_unique_list")] + #[cfg_attr(feature = "schema", schemars(length(min = 1)))] + scopes: UniqueList, + #[cfg_attr(feature = "schema", schemars(schema_with = "authority_claims_schema"))] + claims: BTreeMap, + run_expires_at: BoundedU64<1, { u64::MAX }>, + }, +} +yaml_core::tagged_union!(WorkloadCredential, tag = "type"); + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct WorkloadBinding { + #[cfg_attr( + feature = "schema", + schemars(regex(pattern = "^[a-z][a-z0-9-]{0,63}$")) + )] + pub name: String, + pub product: WorkloadProduct, + pub url: Url, + pub default: bool, + pub credential: WorkloadCredential, +} + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PythonConnection { + #[cfg_attr(feature = "schema", schemars(length(min = 1, max = 512)))] + pub service: String, + pub audience: ServiceAudience, + pub secret_providers: SecretProvidersConfig, + pub bindings: Vec, + #[serde( + default, + deserialize_with = "present_option", + skip_serializing_if = "Option::is_none" + )] + pub admission: Option, +} + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum WorkloadTokenStatus { + Stopped, +} + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct DevWorkloadToken { + pub run_id: ExternalId, + pub binding: ExternalId, + pub product: WorkloadProduct, + pub issuer: Url, + pub subject: ExternalId, + pub client_id: ExternalId, + pub profile: ExternalId, + pub resource: ExternalId, + #[serde(deserialize_with = "non_empty_unique_list")] + #[cfg_attr(feature = "schema", schemars(length(min = 1)))] + pub scopes: UniqueList, + #[cfg_attr(feature = "schema", schemars(schema_with = "authority_claims_schema"))] + pub claims: BTreeMap, + pub generation: BoundedU64<1, { u64::MAX }>, + pub issued_at: BoundedU64<0, { u64::MAX }>, + pub expires_at: BoundedU64<0, { u64::MAX }>, + pub run_expires_at: BoundedU64<1, { u64::MAX }>, + #[serde( + default, + deserialize_with = "present_option", + skip_serializing_if = "Option::is_none" + )] + pub status: Option, + #[serde( + default, + deserialize_with = "present_option", + skip_serializing_if = "Option::is_none" + )] + #[cfg_attr( + feature = "schema", + schemars(length(min = 1, max = 8192), regex(pattern = "^\\S+$")) + )] + pub token: Option, +} + +fn non_empty_unique_list<'de, D, T>(deserializer: D) -> Result, D::Error> +where + D: Deserializer<'de>, + T: Deserialize<'de> + Eq + Hash, +{ + let values = UniqueList::::deserialize(deserializer)?; + if values.is_empty() { + return Err(de::Error::custom("must contain at least one item")); + } + Ok(values) +} + +fn non_empty_map<'de, D, K, V>(deserializer: D) -> Result, D::Error> +where + D: Deserializer<'de>, + K: Deserialize<'de> + Ord, + V: Deserialize<'de>, +{ + let values = BTreeMap::::deserialize(deserializer)?; + if values.is_empty() { + return Err(de::Error::custom("must contain at least one member")); + } + Ok(values) +} + +#[cfg(feature = "schema")] +fn authority_claims_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema { + schemars::json_schema!({ + "type": "object", + "propertyNames": generator.subschema_for::(), + "additionalProperties": true, + "x-registry-passthrough": "Claim values are written into the workload token as declared.", + }) +} + +fn present_option<'de, D, T>(deserializer: D) -> Result, D::Error> +where + D: Deserializer<'de>, + T: Deserialize<'de>, +{ + T::deserialize(deserializer).map(Some) +} + +fn document_value(decoded: Decoded) -> Value { + decoded.document.to_json_value() +} + +pub fn read_python_connection(file: &str, bytes: &[u8]) -> Result { + Reader::new(file) + .decode::(bytes, &Expect::one(&PYTHON_CONNECTION_FORMAT)) + .map(document_value) +} + +pub fn read_dev_workload_token(file: &str, bytes: &[u8]) -> Result { + Reader::new(file) + .decode::(bytes, &Expect::one(&DEV_WORKLOAD_TOKEN_FORMAT)) + .map(document_value) +} + +#[cfg(feature = "schema")] +fn schema(api_version: &str, kind: &str, id: &str) -> Value { + let mut schema = serde_json::to_value(schemars::schema_for!(T)).expect("schema is JSON"); + schema["$id"] = Value::String(id.to_owned()); + schema["properties"]["apiVersion"] = + serde_json::json!({"type": "string", "const": api_version}); + schema["properties"]["kind"] = serde_json::json!({"type": "string", "const": kind}); + let required = schema["required"] + .as_array_mut() + .expect("a document schema requires its members"); + required.insert(0, Value::String("kind".to_owned())); + required.insert(0, Value::String("apiVersion".to_owned())); + schema +} + +#[cfg(feature = "schema")] +fn object_definition_mut<'a>(schema: &'a mut Value, name: &str) -> &'a mut Value { + schema + .get_mut("$defs") + .and_then(Value::as_object_mut) + .and_then(|definitions| definitions.get_mut(name)) + .unwrap_or_else(|| panic!("generated schema has no {name} definition")) +} + +#[cfg(feature = "schema")] +fn refuse_null(schema: &mut Value) { + let only_type = schema + .get_mut("type") + .and_then(Value::as_array_mut) + .and_then(|types| { + types.retain(|value| value != "null"); + if types.len() == 1 { + Some(types[0].clone()) + } else { + None + } + }); + if let Some(only_type) = only_type { + schema["type"] = only_type; + } + let only_alternative = schema + .get_mut("anyOf") + .and_then(Value::as_array_mut) + .and_then(|alternatives| { + alternatives + .retain(|alternative| alternative.get("type") != Some(&serde_json::json!("null"))); + if alternatives.len() == 1 { + Some(alternatives[0].clone()) + } else { + None + } + }); + if let Some(only_alternative) = only_alternative { + *schema = only_alternative; + } +} + +#[cfg(feature = "schema")] +pub fn schema_documents() -> [(&'static str, Value); 2] { + let mut connection = schema::( + PYTHON_CONNECTION_API_VERSION, + PYTHON_CONNECTION_KIND, + PYTHON_CONNECTION_SCHEMA_ID, + ); + object_definition_mut(&mut connection, "MachineAdmission")["properties"]["requiredClaims"] + ["propertyNames"] = serde_json::json!({"$ref": "#/$defs/ExternalId"}); + object_definition_mut(&mut connection, "MachineAdmission")["properties"]["requiredClaims"] + ["minProperties"] = serde_json::json!(1); + for name in ["jwksUri", "clockSkewSeconds", "allowInsecureHttp"] { + refuse_null( + &mut object_definition_mut(&mut connection, "MachineAdmission")["properties"][name], + ); + } + refuse_null(&mut connection["properties"]["admission"]); + let mut token = schema::( + DEV_WORKLOAD_TOKEN_API_VERSION, + DEV_WORKLOAD_TOKEN_KIND, + DEV_WORKLOAD_TOKEN_SCHEMA_ID, + ); + token["oneOf"] = serde_json::json!([ + {"required": ["token"], "not": {"required": ["status"]}}, + {"required": ["status"], "not": {"required": ["token"]}} + ]); + token["properties"]["issuedAt"]["minimum"] = serde_json::json!(0); + token["properties"]["expiresAt"]["minimum"] = serde_json::json!(0); + token["properties"]["issuedAt"] + .as_object_mut() + .expect("issuedAt is an integer schema") + .remove("format"); + token["properties"]["expiresAt"] + .as_object_mut() + .expect("expiresAt is an integer schema") + .remove("format"); + refuse_null(&mut token["properties"]["status"]); + refuse_null(&mut token["properties"]["token"]); + [ + (PYTHON_CONNECTION_SCHEMA_FILE, connection), + (DEV_WORKLOAD_TOKEN_SCHEMA_FILE, token), + ] +} diff --git a/crates/registry-platform-yaml-py/src/lib.rs b/crates/registry-platform-yaml-py/src/lib.rs new file mode 100644 index 0000000000..839dfef9c2 --- /dev/null +++ b/crates/registry-platform-yaml-py/src/lib.rs @@ -0,0 +1,192 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Bounded Python access to `registry-platform-yaml`. + +#![deny(unsafe_code)] + +mod formats; + +use pyo3::exceptions::{PyException, PyValueError}; +use pyo3::prelude::*; +use pyo3::types::{PyBytes, PyDict, PyList, PyTuple}; +use pyo3::IntoPyObjectExt; +use serde_json::Value; +use yaml_core::{ + ApiVersion, EnvelopeRule, Expect, FormatSpec, Reader, Report, MAXIMUM_DIAGNOSTICS_PER_FILE, +}; + +#[cfg(feature = "schema")] +pub use formats::schema_documents; +pub use formats::{ + read_dev_workload_token, read_python_connection, DevWorkloadToken, PythonConnection, + DEV_WORKLOAD_TOKEN_API_VERSION, DEV_WORKLOAD_TOKEN_KIND, DEV_WORKLOAD_TOKEN_SCHEMA_FILE, + DEV_WORKLOAD_TOKEN_SCHEMA_ID, PYTHON_CONNECTION_API_VERSION, PYTHON_CONNECTION_KIND, + PYTHON_CONNECTION_SCHEMA_FILE, PYTHON_CONNECTION_SCHEMA_ID, +}; + +const MAXIMUM_FILE_BYTES: usize = 4 * 1024; +const MAXIMUM_FORMAT_BYTES: usize = 256; + +pyo3::create_exception!( + registry_platform_yaml, + ConfigReadError, + PyException, + "A configuration document was refused with value-free diagnostics." +); + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum Argument { + File, + ApiVersion, + Kind, +} + +impl Argument { + const fn name(self) -> &'static str { + match self { + Self::File => "file", + Self::ApiVersion => "api_version", + Self::Kind => "kind", + } + } +} + +fn validate_file(file: &str) -> Result<(), Argument> { + if file.is_empty() || file.len() > MAXIMUM_FILE_BYTES || file.chars().any(char::is_control) { + return Err(Argument::File); + } + Ok(()) +} + +fn validate_format_parameter(value: &str, argument: Argument) -> Result<(), Argument> { + if value.is_empty() + || value.len() > MAXIMUM_FORMAT_BYTES + || !value.bytes().all(|byte| byte.is_ascii_graphic()) + { + return Err(argument); + } + Ok(()) +} + +fn read_checked( + contents: &[u8], + file: &str, + api_version: &str, + kind: &str, +) -> Result { + if (api_version, kind) == (PYTHON_CONNECTION_API_VERSION, PYTHON_CONNECTION_KIND) { + return read_python_connection(file, contents); + } + if (api_version, kind) == (DEV_WORKLOAD_TOKEN_API_VERSION, DEV_WORKLOAD_TOKEN_KIND) { + return read_dev_workload_token(file, contents); + } + let api_versions = [ApiVersion::current(api_version)]; + let format = FormatSpec { + kind, + envelope: EnvelopeRule::ApiVersionKind { + api_versions: &api_versions, + retired_api_versions: &[], + }, + removed_keys: &[], + }; + Reader::new(file) + .read(contents, &Expect::one(&format)) + .map(|document| document.to_json_value()) +} + +fn json_to_python<'py>(py: Python<'py>, value: &Value) -> PyResult> { + match value { + Value::Null => Ok(py.None().into_bound(py)), + Value::Bool(value) => value.into_bound_py_any(py), + Value::Number(value) => { + if let Some(value) = value.as_i64() { + value.into_bound_py_any(py) + } else if let Some(value) = value.as_u64() { + value.into_bound_py_any(py) + } else if let Some(value) = value.as_f64() { + value.into_bound_py_any(py) + } else { + Err(PyValueError::new_err( + "a configuration number is not representable", + )) + } + } + Value::String(value) => value.as_str().into_bound_py_any(py), + Value::Array(values) => { + let values = values + .iter() + .map(|value| json_to_python(py, value)) + .collect::>>()?; + Ok(PyList::new(py, values)?.into_any()) + } + Value::Object(values) => { + let result = PyDict::new(py); + for (key, value) in values { + result.set_item(key, json_to_python(py, value)?)?; + } + Ok(result.into_any()) + } + } +} + +fn config_error(py: Python<'_>, report: &Report) -> PyErr { + debug_assert!(report.diagnostics().len() <= MAXIMUM_DIAGNOSTICS_PER_FILE + 1); + let Value::Array(diagnostics) = report.to_json_value() else { + unreachable!("a configuration report serializes as an array") + }; + let diagnostics = diagnostics + .iter() + .map(|diagnostic| json_to_python(py, diagnostic)) + .collect::>>() + .expect("a diagnostic has only representable JSON members"); + let diagnostics = + PyTuple::new(py, diagnostics).expect("a bounded diagnostic tuple can be allocated"); + let error = ConfigReadError::new_err("Configuration document was refused"); + error + .value(py) + .setattr("diagnostics", diagnostics) + .expect("a fresh exception accepts attributes"); + error +} + +#[pyfunction(name = "read_document")] +#[pyo3(signature = (contents, *, file, api_version, kind))] +fn py_read_document( + py: Python<'_>, + contents: &Bound<'_, PyBytes>, + file: &str, + api_version: &str, + kind: &str, +) -> PyResult> { + validate_file(file).map_err(|argument| { + PyValueError::new_err(format!( + "{} is invalid or exceeds its bound", + argument.name() + )) + })?; + validate_format_parameter(api_version, Argument::ApiVersion).map_err(|argument| { + PyValueError::new_err(format!( + "{} is invalid or exceeds its bound", + argument.name() + )) + })?; + validate_format_parameter(kind, Argument::Kind).map_err(|argument| { + PyValueError::new_err(format!( + "{} is invalid or exceeds its bound", + argument.name() + )) + })?; + let value = read_checked(contents.as_bytes(), file, api_version, kind) + .map_err(|report| config_error(py, &report))?; + Ok(json_to_python(py, &value)?.unbind()) +} + +#[cfg(test)] +mod tests; + +#[pymodule] +fn registry_platform_yaml(module: &Bound<'_, PyModule>) -> PyResult<()> { + module.add_function(wrap_pyfunction!(py_read_document, module)?)?; + module.add("ConfigReadError", module.py().get_type::())?; + module.add("__version__", env!("CARGO_PKG_VERSION"))?; + Ok(()) +} diff --git a/crates/registry-platform-yaml-py/src/tests.rs b/crates/registry-platform-yaml-py/src/tests.rs new file mode 100644 index 0000000000..5f485a78d1 --- /dev/null +++ b/crates/registry-platform-yaml-py/src/tests.rs @@ -0,0 +1,253 @@ +use super::*; + +const API_VERSION: &str = "id.registrystack.org/formats/platform/python-connection/v1alpha1"; +const KIND: &str = "PlatformPythonConnection"; + +fn read(bytes: &[u8]) -> Result { + read_checked(bytes, "connection.json", API_VERSION, KIND) +} + +#[test] +fn valid_json_preserves_plain_json_values() { + let document = read( + br#"{ + "apiVersion":"id.registrystack.org/formats/platform/python-connection/v1alpha1", + "kind":"PlatformPythonConnection", + "service":"example-service", + "audience":"service", + "secretProviders":{"environment":{}}, + "bindings":[] + }"#, + ) + .expect("valid document"); + assert_eq!(document["service"], "example-service"); + assert_eq!( + document["secretProviders"]["environment"], + serde_json::json!({}) + ); + assert_eq!(document["bindings"], serde_json::json!([])); +} + +#[test] +fn duplicate_json_keys_are_refused_with_both_positions() { + let report = read( + br#"{ + "apiVersion":"id.registrystack.org/formats/platform/python-connection/v1alpha1", + "kind":"PlatformPythonConnection", + "service":"first", + "service":"second" + }"#, + ) + .expect_err("duplicate refuses"); + let diagnostic = &report.diagnostics()[0]; + assert_eq!(diagnostic.code, "yaml.duplicate-key"); + assert_eq!( + diagnostic.source.as_ref().and_then(|source| source.line), + Some(5) + ); + assert_eq!(diagnostic.related[0].line, Some(4)); +} + +#[test] +fn reports_are_bounded_and_do_not_repeat_rejected_values() { + let canary = "secret-canary-that-must-not-cross-the-reader"; + let input = format!(r#"{{"apiVersion":"{API_VERSION}","kind":"wrong-{canary}"}}"#); + let report = read(input.as_bytes()).expect_err("wrong kind refuses"); + assert!(report.diagnostics().len() <= MAXIMUM_DIAGNOSTICS_PER_FILE); + assert!(!report.to_json_value().to_string().contains(canary)); +} + +#[test] +fn diagnostic_floods_keep_only_the_shared_bounded_report() { + let duplicate_members = (0..150) + .map(|index| format!(r#""duplicate":"value-{index}""#)) + .collect::>() + .join(","); + let input = format!(r#"{{"apiVersion":"{API_VERSION}","kind":"{KIND}",{duplicate_members}}}"#); + let report = read(input.as_bytes()).expect_err("duplicates refuse"); + assert!(report.diagnostics().len() <= MAXIMUM_DIAGNOSTICS_PER_FILE + 1); + assert_eq!( + report + .diagnostics() + .last() + .map(|diagnostic| diagnostic.code.as_str()), + Some("config.too-many-problems") + ); +} + +#[test] +fn format_parameter_bounds_are_checked_without_repeating_values() { + assert_eq!( + validate_file(&"x".repeat(MAXIMUM_FILE_BYTES + 1)), + Err(Argument::File) + ); + assert_eq!( + validate_format_parameter(&"x".repeat(MAXIMUM_FORMAT_BYTES + 1), Argument::ApiVersion), + Err(Argument::ApiVersion) + ); + assert_eq!( + validate_format_parameter("bad\nkind", Argument::Kind), + Err(Argument::Kind) + ); +} + +#[test] +fn registered_connection_reader_refuses_unknown_members_at_their_position() { + let input = br#"{ + "apiVersion":"id.registrystack.org/formats/platform/python-connection/v1alpha1", + "kind":"PlatformPythonConnection", + "service":"example-service", + "audience":"service", + "secretProviders":{"environment":{}}, + "bindings":[], + "unexpected":"value-canary" + }"#; + let report = crate::read_python_connection("connection.json", input) + .expect_err("an unknown connection member refuses"); + assert_eq!(report.diagnostics()[0].code, "config.unknown-key"); + assert_eq!(report.diagnostics()[0].path, "/unexpected"); + assert_eq!( + report.diagnostics()[0] + .source + .as_ref() + .and_then(|source| source.line), + Some(8) + ); + assert!(!report.to_json_value().to_string().contains("value-canary")); +} + +#[test] +fn registered_connection_reader_requires_type_for_the_credential_union() { + let input = br#"{ + "apiVersion":"id.registrystack.org/formats/platform/python-connection/v1alpha1", + "kind":"PlatformPythonConnection", + "service":"example-service", + "audience":"service", + "secretProviders":{"environment":{}}, + "bindings":[{ + "name":"registry", + "product":"breg", + "url":"https://registry.example.test/", + "default":true, + "credential":{ + "kind":"private-key-jwt", + "tokenEndpoint":"https://identity.example.test/token", + "clientId":"service-1", + "clientKeyRef":"secret:env/SERVICE_KEY", + "resource":"urn:example:breg", + "scopes":["registry.read"] + } + }] + }"#; + let report = crate::read_python_connection("connection.json", input) + .expect_err("kind is not the credential discriminator"); + assert_eq!(report.diagnostics()[0].code, "config.missing-key"); + assert_eq!(report.diagnostics()[0].path, "/bindings/0/credential"); +} + +#[test] +fn registered_connection_reader_refuses_empty_authority_sets() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let connection = std::fs::read( + root.join("products/platform/examples/python-composition/connection.example.json"), + ) + .expect("connection example"); + let mut connection: serde_json::Value = + serde_json::from_slice(&connection).expect("connection example JSON"); + connection["bindings"][0]["credential"]["scopes"] = serde_json::json!([]); + let connection = serde_json::to_vec(&connection).expect("connection example JSON"); + let report = crate::read_python_connection("connection.example.json", &connection) + .expect_err("an empty authority set refuses"); + assert!(report + .diagnostics() + .iter() + .any(|diagnostic| diagnostic.path == "/bindings/0/credential/scopes")); +} + +#[test] +fn registered_readers_accept_the_committed_examples() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let connection = std::fs::read( + root.join("products/platform/examples/python-composition/connection.example.json"), + ) + .expect("connection example"); + let token = + std::fs::read(root.join("products/platform/examples/dev-workload-token-stopped.json")) + .expect("token example"); + crate::read_python_connection("connection.example.json", &connection) + .expect("connection example reads"); + let token = crate::read_dev_workload_token("dev-workload-token-stopped.json", &token) + .expect("token example reads"); + assert_eq!(token["claims"]["registry_actor_kind"], "service"); +} + +#[test] +fn registered_token_reader_refuses_wrong_types_without_repeating_the_token() { + let input = br#"{ + "apiVersion":"id.registrystack.org/formats/platform/dev-workload-token/v1alpha1", + "kind":"PlatformDevWorkloadToken", + "runId":"run-1", + "binding":"registry", + "product":"breg", + "issuer":"https://identity.example.test/", + "subject":"service-1", + "clientId":"service-1", + "profile":"writer", + "resource":"urn:example:breg", + "scopes":["registry.write"], + "claims":{"registry_actor_kind":"service"}, + "generation":"1", + "issuedAt":1, + "expiresAt":2, + "runExpiresAt":3, + "token":"value-canary" + }"#; + let report = crate::read_dev_workload_token("workload-registry.json", input) + .expect_err("a quoted generation refuses"); + assert_eq!(report.diagnostics()[0].code, "config.expected-integer"); + assert_eq!(report.diagnostics()[0].path, "/generation"); + assert!(!report.to_json_value().to_string().contains("value-canary")); +} + +#[test] +fn registered_token_reader_does_not_treat_null_as_omission() { + let input = br#"{ + "apiVersion":"id.registrystack.org/formats/platform/dev-workload-token/v1alpha1", + "kind":"PlatformDevWorkloadToken", + "runId":"run-1", + "binding":"registry", + "product":"breg", + "issuer":"https://identity.example.test/", + "subject":"service-1", + "clientId":"service-1", + "profile":"writer", + "resource":"urn:example:breg", + "scopes":["registry.write"], + "claims":{"registry_actor_kind":"service"}, + "generation":1, + "issuedAt":1, + "expiresAt":2, + "runExpiresAt":3, + "token":null + }"#; + let report = crate::read_dev_workload_token("workload-registry.json", input) + .expect_err("an explicit null token refuses"); + assert_eq!(report.diagnostics()[0].path, "/token"); +} + +#[cfg(feature = "schema")] +#[test] +fn generated_schema_documents_match_the_committed_files() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + for (name, document) in crate::schema_documents() { + let path = root.join("products/platform/schemas").join(name); + let mut expected = serde_json::to_string_pretty(&document).expect("schema JSON"); + expected.push('\n'); + assert_eq!( + std::fs::read_to_string(&path).expect("committed schema"), + expected, + "{} drifted", + path.display() + ); + } +} diff --git a/crates/registry-platform-yaml-py/tests/python/bootstrap.py b/crates/registry-platform-yaml-py/tests/python/bootstrap.py new file mode 100644 index 0000000000..d1653197d6 --- /dev/null +++ b/crates/registry-platform-yaml-py/tests/python/bootstrap.py @@ -0,0 +1,70 @@ +"""Build and import the platform YAML PyO3 module for stdlib-only tests.""" + +from __future__ import annotations + +import functools +import json +import pathlib +import platform +import shutil +import subprocess +import sys + +_CRATE_ROOT = pathlib.Path(__file__).resolve().parents[2] +_WORKSPACE_ROOT = _CRATE_ROOT.parents[1] +_MODULE_NAME = "registry_platform_yaml" + + +@functools.cache +def _target_debug() -> pathlib.Path: + metadata = subprocess.run( + ["cargo", "metadata", "--locked", "--format-version", "1", "--no-deps"], + cwd=_WORKSPACE_ROOT, + capture_output=True, + check=False, + text=True, + ) + if metadata.returncode != 0: + raise RuntimeError( + "cargo metadata failed, so the Cargo target directory is unknown:\n" + + metadata.stderr + ) + return pathlib.Path(json.loads(metadata.stdout)["target_directory"]) / "debug" + + +def _library() -> pathlib.Path: + suffix = {"Darwin": ".dylib", "Linux": ".so"}.get(platform.system()) + if suffix is None: + raise RuntimeError("the platform YAML Python tests support macOS and Linux") + return _target_debug() / f"lib{_MODULE_NAME}{suffix}" + + +@functools.cache +def ensure_built() -> None: + subprocess.run( + [ + "cargo", + "build", + "--locked", + "-p", + "registry-platform-yaml-py", + "--lib", + "--features", + "registry-platform-yaml-py/extension-module", + ], + cwd=_WORKSPACE_ROOT, + check=True, + ) + source = _library() + if not source.is_file(): + raise RuntimeError(f"cargo did not produce {source}") + import_root = _target_debug() / "platform_yaml_python_module" + import_package = import_root / _MODULE_NAME + import_package.mkdir(parents=True, exist_ok=True) + shutil.copyfile( + _CRATE_ROOT / "python" / _MODULE_NAME / "__init__.py", + import_package / "__init__.py", + ) + shutil.copyfile(source, import_package / f"{_MODULE_NAME}.so") + if str(import_root) not in sys.path: + sys.path.insert(0, str(import_root)) diff --git a/crates/registry-platform-yaml-py/tests/python/test_reader.py b/crates/registry-platform-yaml-py/tests/python/test_reader.py new file mode 100644 index 0000000000..22175d80a7 --- /dev/null +++ b/crates/registry-platform-yaml-py/tests/python/test_reader.py @@ -0,0 +1,125 @@ +"""Python contract tests for the shared configuration reader binding.""" + +from __future__ import annotations + +import unittest + +from bootstrap import ensure_built + +ensure_built() + +from registry_platform_yaml import ConfigReadError, read_document # noqa: E402 + +API_VERSION = "id.registrystack.org/formats/platform/python-connection/v1alpha1" +KIND = "PlatformPythonConnection" + + +def read(contents: bytes): + return read_document( + contents, + file="connection.json", + api_version=API_VERSION, + kind=KIND, + ) + + +class ReaderTests(unittest.TestCase): + def test_valid_json_returns_plain_python_values(self): + document = read( + b'{"apiVersion":"id.registrystack.org/formats/platform/' + b'python-connection/v1alpha1","kind":"PlatformPythonConnection",' + b'"service":"example-service","audience":"service",' + b'"secretProviders":{"environment":{}},"bindings":[]}' + ) + self.assertEqual(document["kind"], KIND) + self.assertEqual(document["service"], "example-service") + self.assertEqual(document["secretProviders"], {"environment": {}}) + self.assertEqual(document["bindings"], []) + + def test_duplicate_json_key_is_refused_with_both_lines(self): + contents = ( + b'{\n "apiVersion":"' + API_VERSION.encode() + b'",\n' + b' "kind":"PlatformPythonConnection",\n' + b' "service":"first",\n "service":"second"\n}' + ) + with self.assertRaises(ConfigReadError) as caught: + read(contents) + self.assertIsInstance(caught.exception.diagnostics, tuple) + diagnostic = caught.exception.diagnostics[0] + self.assertEqual(diagnostic["code"], "yaml.duplicate-key") + self.assertEqual(diagnostic["source"]["line"], 5) + self.assertEqual(diagnostic["related"][0]["line"], 4) + + def test_diagnostics_and_exception_do_not_repeat_scalar_values(self): + canary = "secret-canary-that-must-not-cross-the-reader" + contents = ( + b'{"apiVersion":"' + API_VERSION.encode() + b'",' + b'"kind":"wrong-' + canary.encode() + b'"}' + ) + with self.assertRaises(ConfigReadError) as caught: + read(contents) + self.assertEqual(str(caught.exception), "Configuration document was refused") + self.assertNotIn(canary, repr(caught.exception.diagnostics)) + + def test_diagnostic_flood_is_bounded(self): + members = b",".join( + b'"duplicate":"value-' + str(index).encode() + b'"' for index in range(150) + ) + contents = ( + b'{"apiVersion":"' + API_VERSION.encode() + b'",' + b'"kind":"PlatformPythonConnection",' + members + b"}" + ) + with self.assertRaises(ConfigReadError) as caught: + read(contents) + self.assertLessEqual(len(caught.exception.diagnostics), 101) + self.assertEqual( + caught.exception.diagnostics[-1]["code"], "config.too-many-problems" + ) + + def test_input_and_expected_format_parameters_are_bounded(self): + with self.assertRaisesRegex(ValueError, "file"): + read_document(b"{}", file="x" * 4097, api_version=API_VERSION, kind=KIND) + with self.assertRaisesRegex(ValueError, "api_version"): + read_document( + b"{}", file="connection.json", api_version="x" * 257, kind=KIND + ) + with self.assertRaisesRegex(ValueError, "kind"): + read_document( + b"{}", file="connection.json", api_version=API_VERSION, kind="bad\nkind" + ) + + def test_registered_connection_format_refuses_unknown_keys(self): + contents = ( + b'{"apiVersion":"' + API_VERSION.encode() + b'",' + b'"kind":"PlatformPythonConnection","service":"example-service",' + b'"audience":"service","secretProviders":{"environment":{}},' + b'"bindings":[],"unknown":"value-canary"}' + ) + with self.assertRaises(ConfigReadError) as caught: + read(contents) + self.assertEqual(caught.exception.diagnostics[0]["code"], "config.unknown-key") + self.assertEqual(caught.exception.diagnostics[0]["path"], "/unknown") + self.assertNotIn("value-canary", repr(caught.exception.diagnostics)) + + def test_registered_connection_format_requires_type_discriminator(self): + contents = ( + b'{"apiVersion":"' + API_VERSION.encode() + b'",' + b'"kind":"PlatformPythonConnection","service":"example-service",' + b'"audience":"service","secretProviders":{"environment":{}},' + b'"bindings":[{"name":"registry","product":"breg",' + b'"url":"https://registry.example.test/","default":true,' + b'"credential":{"kind":"private-key-jwt",' + b'"tokenEndpoint":"https://identity.example.test/token",' + b'"clientId":"service-1","clientKeyRef":"secret:env/SERVICE_KEY",' + b'"resource":"urn:example:breg","scopes":["registry.read"]}}]}' + ) + with self.assertRaises(ConfigReadError) as caught: + read(contents) + self.assertEqual(caught.exception.diagnostics[0]["code"], "config.missing-key") + self.assertEqual( + caught.exception.diagnostics[0]["path"], "/bindings/0/credential" + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/crates/registry-rstack/src/cli.rs b/crates/registry-rstack/src/cli.rs index fa57a6304b..9444bf9a98 100644 --- a/crates/registry-rstack/src/cli.rs +++ b/crates/registry-rstack/src/cli.rs @@ -1,5 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 +use crate::grants; use crate::identity::{self, DrivenTool, Failure, GenerateOptions, Input, ProductSpec}; use crate::install::{self, BootstrapOptions}; use crate::store::{GenerationStore, InvocationLease}; @@ -154,6 +155,15 @@ enum Command { #[command(subcommand)] command: IdentityCommand, }, + /// Report configured bindings and known profile facts without certifying live grants. + Grants { + /// Python service connection file. + #[arg(value_name = "CONNECTION")] + connection: PathBuf, + /// Product identity facts file; repeat for each known product. + #[arg(long = "facts", value_name = "FILE")] + facts: Vec, + }, /// Run and inspect a local Registry Stack development environment. #[command( long_about = "Run and inspect a local Registry Stack development environment.\n\nFor a walk-through from a project checkout to a running registry and review service, see `https://docs.registrystack.org/configure/run-a-project-with-rstack-dev/`" @@ -669,6 +679,7 @@ fn execute(cli: Cli, format_supplied: bool, evidence_junit: bool) -> Result<(), reportln!("rstack [options]"); reportln!("Use rstack help for offline product help."); reportln!("Use rstack dev --help for local development commands."); + reportln!("Use rstack grants --help for the advisory grants report."); reportln!("Use rstack components list to inspect installation availability."); reportln!("Products: {}", PRODUCTS.join(", ")); } @@ -858,6 +869,17 @@ fn execute(cli: Cli, format_supplied: bool, evidence_junit: bool) -> Result<(), } } }, + Some(Command::Grants { connection, facts }) => { + let report = grants::build(connection, facts).map_err(CliFailure::domain)?; + match format { + ReportFormat::Human => reportln!("{}", grants::human(&report)), + ReportFormat::Json => reportln!( + "{}", + serde_json::to_string(&report) + .map_err(|error| CliFailure::operational(error.to_string()))? + ), + } + } Some(Command::Product(arguments)) => { let product = arguments .first() diff --git a/crates/registry-rstack/src/grants.rs b/crates/registry-rstack/src/grants.rs new file mode 100644 index 0000000000..5b56fffd6e --- /dev/null +++ b/crates/registry-rstack/src/grants.rs @@ -0,0 +1,454 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Read-only, advisory reporting over configured Python service bindings. + +use registry_platform_yaml::{ + ApiVersion, EnvelopeRule, Expect, ExternalId, ForeignValue, FormatSpec, Reader, +}; +use registry_thunderid_tooling::identity_facts::{self, IdentityFacts}; +use serde::{Deserialize, Serialize}; +use std::fs; +use std::path::{Path, PathBuf}; + +const CONNECTION_API_VERSION: &str = + "id.registrystack.org/formats/platform/python-connection/v1alpha1"; +const CONNECTION_KIND: &str = "PlatformPythonConnection"; +const CONNECTION_FORMAT: FormatSpec<'static> = FormatSpec { + kind: CONNECTION_KIND, + envelope: EnvelopeRule::ApiVersionKind { + api_versions: &[ApiVersion::current(CONNECTION_API_VERSION)], + retired_api_versions: &[], + }, + removed_keys: &[], +}; + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ConnectionView { + service: String, + audience: String, + secret_providers: ForeignValue, + bindings: Vec, + #[serde(default)] + admission: Option, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct BindingView { + name: ExternalId, + product: ExternalId, + url: ForeignValue, + default: bool, + credential: CredentialView, +} + +#[derive(Deserialize)] +#[serde( + remote = "Self", + rename_all = "kebab-case", + rename_all_fields = "camelCase", + deny_unknown_fields +)] +enum CredentialView { + PrivateKeyJwt { + token_endpoint: ForeignValue, + client_id: ExternalId, + client_key_ref: ForeignValue, + resource: ExternalId, + scopes: Vec, + }, + RunnerToken { + token_ref: ForeignValue, + run_id: ExternalId, + binding: ExternalId, + issuer: ForeignValue, + subject: ExternalId, + client_id: ExternalId, + profile: ExternalId, + resource: ExternalId, + scopes: Vec, + run_expires_at: u64, + }, +} + +registry_platform_yaml::tagged_union!(CredentialView, tag = "type"); + +#[derive(Serialize)] +pub(crate) struct GrantsReport { + schema_version: &'static str, + status: &'static str, + connection: ConnectionFact, + bindings: Vec, + facts: Vec, + omissions: Vec, +} + +#[derive(Serialize)] +struct ConnectionFact { + source: String, + service: String, + audience: String, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct BindingFact { + source: String, + path: String, + name: String, + product: String, + default: bool, + credential_type: &'static str, + resource: String, + configured_scopes: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + configured_profile: Option, + profile_knowledge: &'static str, + known_profiles: Vec, + omissions: Vec, +} + +#[derive(Clone, Serialize)] +#[serde(rename_all = "camelCase")] +struct KnownProfile { + source: String, + path: String, + id: String, + scopes: Vec, + purposes: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + actor_kind: Option, + required_claims: Vec, + match_basis: &'static str, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct ProductFacts { + source: String, + product: String, + resource: String, + profiles: Vec, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct ProfileFact { + source: String, + path: String, + id: String, + scopes: Vec, + purposes: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + actor_kind: Option, + required_claims: Vec, +} + +#[derive(Serialize)] +struct Omission { + code: &'static str, + message: &'static str, + source: String, + #[serde(skip_serializing_if = "Option::is_none")] + path: Option, +} + +struct FactsSource { + source: String, + value: IdentityFacts, +} + +pub(crate) fn build(connection: &Path, facts: &[PathBuf]) -> Result { + let connection_source = source_name(connection, "connection")?; + let bytes = + fs::read(connection).map_err(|_| "cannot read the Python connection file".to_owned())?; + let decoded = Reader::new(&connection_source) + .decode::(&bytes, &Expect::one(&CONNECTION_FORMAT)) + .map_err(|report| report.render_human())?; + let connection_value = decoded.value; + let _ = ( + &connection_value.secret_providers, + &connection_value.admission, + ); + + let mut fact_sources = Vec::with_capacity(facts.len()); + for file in facts { + let source = source_name(file, "facts")?; + let bytes = fs::read(file).map_err(|_| "cannot read an identity facts file".to_owned())?; + let value = identity_facts::read(&source, &bytes).map_err(|error| error.to_string())?; + fact_sources.push(FactsSource { source, value }); + } + + let bindings = connection_value + .bindings + .into_iter() + .enumerate() + .map(|(index, binding)| binding_fact(index, binding, &connection_source, &fact_sources)) + .collect(); + let facts = fact_sources.iter().map(product_facts).collect(); + Ok(GrantsReport { + schema_version: "registry.rstack.grants.v1", + status: "advisory", + connection: ConnectionFact { + source: connection_source, + service: connection_value.service, + audience: connection_value.audience, + }, + bindings, + facts, + omissions: vec![ + Omission { + code: "live-grants-not-inspected", + message: "This report reads configuration and supplied identity facts; it does not query an issuer or product and cannot certify live grants.", + source: "report-method".to_owned(), + path: None, + }, + Omission { + code: "record-sensitivity-not-classified", + message: "This report does not inspect registry records and cannot classify their personal-data sensitivity.", + source: "report-method".to_owned(), + path: None, + }, + Omission { + code: "product-enforcement-not-exercised", + message: "Row, field, purpose, disclosure and effect boundaries remain enforced by the owning product and are not exercised by this report.", + source: "report-method".to_owned(), + path: None, + }, + ], + }) +} + +fn source_name(path: &Path, label: &str) -> Result { + let Some(source) = path.to_str() else { + return Err(format!("the {label} path must be UTF-8")); + }; + if source.len() > 4096 || source.chars().any(char::is_control) { + return Err(format!( + "the {label} path is too long or contains a control character" + )); + } + Ok(source.to_owned()) +} + +fn binding_fact( + index: usize, + binding: BindingView, + source: &str, + facts: &[FactsSource], +) -> BindingFact { + let BindingView { + name, + product, + url, + default, + credential, + } = binding; + let _ = url; + let (credential_type, resource, scopes, configured_profile) = credential.facts(); + let product = product.into_string(); + let path = format!("/bindings/{index}"); + let known_profiles = matching_profiles( + &product, + resource.as_str(), + &scopes, + configured_profile.as_deref(), + facts, + ); + let profile_knowledge = if known_profiles.is_empty() { + "unknown" + } else if configured_profile.is_some() { + "declared" + } else { + "candidate" + }; + let omissions = if known_profiles.is_empty() { + vec![Omission { + code: "binding-profile-not-confirmed", + message: "No supplied product facts confirm a profile for this configured binding; an external or otherwise unknown grant remains possible and is not a startup refusal.", + source: source.to_owned(), + path: Some(path.clone()), + }] + } else if configured_profile.is_none() { + vec![Omission { + code: "binding-profile-derived-from-scopes", + message: "The listed profiles are candidates derived from configured scopes, not declared or live profile grants.", + source: source.to_owned(), + path: Some(path.clone()), + }] + } else { + Vec::new() + }; + + BindingFact { + source: source.to_owned(), + path, + name: name.into_string(), + product, + default, + credential_type, + resource: resource.into_string(), + configured_scopes: scopes, + configured_profile, + profile_knowledge, + known_profiles, + omissions, + } +} + +impl CredentialView { + fn facts(self) -> (&'static str, ExternalId, Vec, Option) { + match self { + CredentialView::PrivateKeyJwt { + token_endpoint, + client_id, + client_key_ref, + resource, + scopes, + } => { + let _ = (token_endpoint, client_id, client_key_ref); + ("private-key-jwt", resource, strings(scopes), None) + } + CredentialView::RunnerToken { + token_ref, + run_id, + binding, + issuer, + subject, + client_id, + profile, + resource, + scopes, + run_expires_at, + } => { + let _ = ( + token_ref, + run_id, + binding, + issuer, + subject, + client_id, + run_expires_at, + ); + ( + "runner-token", + resource, + strings(scopes), + Some(profile.into_string()), + ) + } + } + } +} + +fn strings(values: Vec) -> Vec { + values.into_iter().map(ExternalId::into_string).collect() +} + +fn matching_profiles( + product: &str, + resource: &str, + configured_scopes: &[String], + configured_profile: Option<&str>, + facts: &[FactsSource], +) -> Vec { + let mut profiles = Vec::new(); + for fact in facts { + if fact.value.product != product || fact.value.audience != resource { + continue; + } + for (index, profile) in fact.value.access_profiles.iter().enumerate() { + let name_matches = configured_profile.is_none_or(|name| profile.id == name); + let scopes_fit = profile + .scopes + .iter() + .all(|scope| configured_scopes.contains(scope)); + if name_matches && scopes_fit { + profiles.push(KnownProfile { + source: fact.source.clone(), + path: format!("/accessProfiles/{index}"), + id: profile.id.clone(), + scopes: profile.scopes.clone(), + purposes: profile.purposes.clone(), + actor_kind: actor_kind(profile), + required_claims: profile.required_claims.clone(), + match_basis: if configured_profile.is_some() { + "declared-profile" + } else { + "scope-subset" + }, + }); + } + } + } + profiles +} + +fn product_facts(facts: &FactsSource) -> ProductFacts { + ProductFacts { + source: facts.source.clone(), + product: facts.value.product.clone(), + resource: facts.value.audience.clone(), + profiles: facts + .value + .access_profiles + .iter() + .enumerate() + .map(|(index, profile)| ProfileFact { + source: facts.source.clone(), + path: format!("/accessProfiles/{index}"), + id: profile.id.clone(), + scopes: profile.scopes.clone(), + purposes: profile.purposes.clone(), + actor_kind: actor_kind(profile), + required_claims: profile.required_claims.clone(), + }) + .collect(), + } +} + +fn actor_kind(profile: &identity_facts::AccessProfile) -> Option { + profile.actor_kind.map(|kind| kind.as_str().to_owned()) +} + +pub(crate) fn human(report: &GrantsReport) -> String { + let mut output = format!( + "Advisory grants report for {:?} ({})\nSource: {}\n", + report.connection.service, report.connection.audience, report.connection.source + ); + for binding in &report.bindings { + output.push_str(&format!( + "\n{}: {} binding, resource {:?}, scopes [{}]\n Source: {}{}\n", + binding.name, + binding.product, + binding.resource, + binding.configured_scopes.join(", "), + binding.source, + binding.path + )); + if binding.known_profiles.is_empty() { + output.push_str(" Known profiles: none confirmed by the supplied facts\n"); + } else { + output.push_str(" Known profiles:\n"); + for profile in &binding.known_profiles { + output.push_str(&format!( + " {} ({}, source: {}{})\n", + profile.id, profile.match_basis, profile.source, profile.path + )); + } + } + } + output.push_str("\nOmissions:\n"); + for omission in &report.omissions { + output.push_str(&format!(" {}: {}\n", omission.code, omission.message)); + } + for binding in &report.bindings { + for omission in &binding.omissions { + output.push_str(&format!( + " {} ({}): {}\n", + omission.code, binding.name, omission.message + )); + } + } + output.trim_end().to_owned() +} diff --git a/crates/registry-rstack/src/lib.rs b/crates/registry-rstack/src/lib.rs index e81f2890bf..d3c5107ff5 100644 --- a/crates/registry-rstack/src/lib.rs +++ b/crates/registry-rstack/src/lib.rs @@ -3,6 +3,7 @@ pub mod assets; mod cli; +mod grants; mod identity; pub mod install; mod model; diff --git a/crates/registry-rstack/tests/grants.rs b/crates/registry-rstack/tests/grants.rs new file mode 100644 index 0000000000..965dc31ac3 --- /dev/null +++ b/crates/registry-rstack/tests/grants.rs @@ -0,0 +1,212 @@ +use std::fs; +use std::process::Command; + +fn run(arguments: &[&str]) -> std::process::Output { + Command::new(env!("CARGO_BIN_EXE_rstack")) + .args(arguments) + .output() + .expect("run rstack") +} + +fn write_connection(directory: &std::path::Path, scope: &str) -> std::path::PathBuf { + let path = directory.join("connection.json"); + fs::write( + &path, + serde_json::to_vec_pretty(&serde_json::json!({ + "apiVersion": "id.registrystack.org/formats/platform/python-connection/v1alpha1", + "kind": "PlatformPythonConnection", + "service": "licensing-portal", + "audience": "holder", + "secretProviders": {"environment": {}}, + "bindings": [{ + "name": "licensing-registry", + "product": "breg", + "url": "https://registry.example.invalid/secret-looking-path", + "default": true, + "credential": { + "type": "private-key-jwt", + "tokenEndpoint": "https://identity.example.invalid/oauth/token", + "clientId": "licensing-portal", + "clientKeyRef": "secret:env/GRANTS_REPORT_CANARY", + "resource": "urn:example:licensing", + "scopes": [scope] + } + }] + })) + .unwrap(), + ) + .unwrap(); + path +} + +fn write_facts(directory: &std::path::Path) -> std::path::PathBuf { + let path = directory.join("breg-facts.yaml"); + fs::write( + &path, + r#"apiVersion: id.registrystack.org/formats/platform/identity-facts/v1 +kind: PlatformIdentityFacts +product: breg +issuer: https://identity.example.invalid +audience: urn:example:licensing +allowedClients: [licensing-portal] +claims: + registry_principal: string +accessProfiles: + - id: holder-read + scopes: [licensing:read] + requiredClaims: [registry_principal] +"#, + ) + .unwrap(); + path +} + +#[test] +fn json_report_names_known_binding_profile_provenance_and_limits() { + let scratch = tempfile::tempdir().unwrap(); + let connection = write_connection(scratch.path(), "licensing:read"); + let facts = write_facts(scratch.path()); + + let output = run(&[ + "grants", + connection.to_str().unwrap(), + "--facts", + facts.to_str().unwrap(), + "--format", + "json", + ]); + + assert!(output.status.success(), "{output:?}"); + assert!(output.stderr.is_empty(), "{output:?}"); + let report: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(report["schema_version"], "registry.rstack.grants.v1"); + assert_eq!(report["status"], "advisory"); + assert_eq!(report["connection"]["source"], connection.to_str().unwrap()); + assert_eq!(report["bindings"][0]["name"], "licensing-registry"); + assert_eq!(report["bindings"][0]["product"], "breg"); + assert_eq!( + report["bindings"][0]["source"], + connection.to_str().unwrap() + ); + assert_eq!(report["bindings"][0]["path"], "/bindings/0"); + assert_eq!(report["bindings"][0]["resource"], "urn:example:licensing"); + assert_eq!( + report["bindings"][0]["configuredScopes"], + serde_json::json!(["licensing:read"]) + ); + assert_eq!( + report["bindings"][0]["knownProfiles"][0]["id"], + "holder-read" + ); + assert_eq!( + report["bindings"][0]["knownProfiles"][0]["source"], + facts.to_str().unwrap() + ); + assert_eq!( + report["bindings"][0]["knownProfiles"][0]["matchBasis"], + "scope-subset" + ); + assert!(report["bindings"][0]["omissions"] + .as_array() + .unwrap() + .iter() + .any(|item| item["code"] == "binding-profile-derived-from-scopes")); + assert_eq!(report["facts"][0]["product"], "breg"); + assert_eq!(report["facts"][0]["resource"], "urn:example:licensing"); + assert_eq!(report["facts"][0]["source"], facts.to_str().unwrap()); + assert_eq!( + report["facts"][0]["profiles"][0]["path"], + "/accessProfiles/0" + ); + assert!(report["omissions"] + .as_array() + .unwrap() + .iter() + .any(|item| item["code"] == "live-grants-not-inspected")); + assert!(report["omissions"] + .as_array() + .unwrap() + .iter() + .any(|item| item["code"] == "record-sensitivity-not-classified")); + + let text = String::from_utf8(output.stdout).unwrap(); + assert!(!text.contains("GRANTS_REPORT_CANARY"), "{text}"); + assert!(!text.contains("secret-looking-path"), "{text}"); + assert!(!text.contains("oauth/token"), "{text}"); +} + +#[test] +fn unknown_external_grant_is_reported_without_refusal_or_false_certificate() { + let scratch = tempfile::tempdir().unwrap(); + let connection = write_connection(scratch.path(), "external:unknown"); + let facts = write_facts(scratch.path()); + + let output = run(&[ + "--format=json", + "grants", + connection.to_str().unwrap(), + "--facts", + facts.to_str().unwrap(), + ]); + + assert!(output.status.success(), "{output:?}"); + let report: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(report["status"], "advisory"); + assert_eq!( + report["bindings"][0]["knownProfiles"], + serde_json::json!([]) + ); + assert_eq!(report["bindings"][0]["profileKnowledge"], "unknown"); + assert!(report["bindings"][0]["omissions"] + .as_array() + .unwrap() + .iter() + .any(|item| item["code"] == "binding-profile-not-confirmed")); +} + +#[test] +fn human_report_keeps_provenance_and_limits_next_to_the_result() { + let scratch = tempfile::tempdir().unwrap(); + let connection = write_connection(scratch.path(), "licensing:read"); + let facts = write_facts(scratch.path()); + + let output = run(&[ + "grants", + connection.to_str().unwrap(), + "--facts", + facts.to_str().unwrap(), + ]); + + assert!(output.status.success(), "{output:?}"); + let text = String::from_utf8(output.stdout).unwrap(); + assert!(text.contains("Advisory grants report"), "{text}"); + assert!( + text.contains("holder-read (scope-subset, source:"), + "{text}" + ); + assert!(text.contains("live-grants-not-inspected"), "{text}"); + assert!( + text.contains("binding-profile-derived-from-scopes"), + "{text}" + ); + assert!(!text.contains("GRANTS_REPORT_CANARY"), "{text}"); +} + +#[test] +fn refused_input_does_not_repeat_values_from_the_connection() { + let scratch = tempfile::tempdir().unwrap(); + let connection = scratch.path().join("connection.json"); + fs::write( + &connection, + r#"{"service":"DO-NOT-REPEAT-THIS","bindings":"DO-NOT-REPEAT-EITHER"}"#, + ) + .unwrap(); + + let output = run(&["grants", connection.to_str().unwrap(), "--format", "json"]); + + assert_eq!(output.status.code(), Some(1), "{output:?}"); + let text = String::from_utf8(output.stdout).unwrap(); + assert!(!text.contains("DO-NOT-REPEAT"), "{text}"); + let report: serde_json::Value = serde_json::from_str(&text).unwrap(); + assert_eq!(report["error"]["class"], "domain"); +} diff --git a/crates/registry-stack-client-py/pyproject.toml b/crates/registry-stack-client-py/pyproject.toml index 7779967358..9ca9cbb55b 100644 --- a/crates/registry-stack-client-py/pyproject.toml +++ b/crates/registry-stack-client-py/pyproject.toml @@ -21,3 +21,9 @@ classifiers = [ Documentation = "https://docs.registrystack.org/" Issues = "https://github.com/registrystack/registry-stack/issues" Repository = "https://github.com/registrystack/registry-stack" + +[project.optional-dependencies] +flask = ["Flask>=3.1,<4"] +fastapi = ["fastapi>=0.115,<1"] +human = ["Authlib>=1.9.5,<2", "requests>=2.31,<3"] +postgres = ["cryptography>=50.0.2,<51", "psycopg[binary]>=3.3.6,<4"] diff --git a/crates/registry-stack-client-py/python/registry_client/__init__.py b/crates/registry-stack-client-py/python/registry_client/__init__.py index 4bc7d0401f..90b7bd446e 100644 --- a/crates/registry-stack-client-py/python/registry_client/__init__.py +++ b/crates/registry-stack-client-py/python/registry_client/__init__.py @@ -9,6 +9,28 @@ import registry_client.scheduling as scheduling import registry_client.render as render import registry_client.coordinator as coordinator +from .connection import ( + Connection, + ConnectionError, + UnsupportedOperationError, + WorkloadAuthority, + connect, +) -__all__ = ["auth", "breg", "casework", "discovery", "evidence", "messaging", "scheduling", "render", "coordinator"] +__all__ = [ + "auth", + "breg", + "casework", + "discovery", + "evidence", + "messaging", + "scheduling", + "render", + "coordinator", + "Connection", + "ConnectionError", + "UnsupportedOperationError", + "WorkloadAuthority", + "connect", +] __version__ = "0.46.1" diff --git a/crates/registry-stack-client-py/python/registry_client/__init__.pyi b/crates/registry-stack-client-py/python/registry_client/__init__.pyi index 92d783f7c8..a85d2c5bbb 100644 --- a/crates/registry-stack-client-py/python/registry_client/__init__.pyi +++ b/crates/registry-stack-client-py/python/registry_client/__init__.pyi @@ -1,7 +1,22 @@ -from . import auth, breg, casework, discovery, evidence, messaging, scheduling +from . import ( + auth as auth, + breg as breg, + casework as casework, + discovery as discovery, + evidence as evidence, + messaging as messaging, + scheduling as scheduling, +) __all__: list[str] __version__: str from . import render as render from . import coordinator as coordinator +from .connection import ( + Connection as Connection, + ConnectionError as ConnectionError, + UnsupportedOperationError as UnsupportedOperationError, + WorkloadAuthority as WorkloadAuthority, + connect as connect, +) diff --git a/crates/registry-stack-client-py/python/registry_client/_sql/portal_postgres_v1.sql b/crates/registry-stack-client-py/python/registry_client/_sql/portal_postgres_v1.sql new file mode 100644 index 0000000000..5be887e0a7 --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/_sql/portal_postgres_v1.sql @@ -0,0 +1,64 @@ +CREATE SCHEMA IF NOT EXISTS registry_client_portal; + +CREATE TABLE IF NOT EXISTS registry_client_portal.migrations ( + version smallint PRIMARY KEY, + checksum text NOT NULL, + applied_at timestamptz NOT NULL DEFAULT transaction_timestamp(), + CONSTRAINT migrations_version_positive CHECK (version > 0), + CONSTRAINT migrations_checksum_bounded CHECK (length(checksum) = 64) +); + +CREATE TABLE IF NOT EXISTS registry_client_portal.key_state ( + singleton boolean PRIMARY KEY DEFAULT true, + active_key_id text NOT NULL, + updated_at timestamptz NOT NULL DEFAULT transaction_timestamp(), + CONSTRAINT key_state_singleton CHECK (singleton), + CONSTRAINT key_state_key_id_bounded CHECK ( + length(active_key_id) BETWEEN 1 AND 128 + ) +); + +CREATE TABLE IF NOT EXISTS registry_client_portal.chains ( + chain_digest bytea PRIMARY KEY, + closed boolean NOT NULL DEFAULT false, + updated_at timestamptz NOT NULL DEFAULT transaction_timestamp(), + CONSTRAINT chains_digest_length CHECK (octet_length(chain_digest) = 32) +); + +CREATE TABLE IF NOT EXISTS registry_client_portal.pending ( + state_digest bytea PRIMARY KEY, + chain_digest bytea NOT NULL REFERENCES registry_client_portal.chains(chain_digest) + ON DELETE CASCADE, + expires_at double precision NOT NULL, + key_id text NOT NULL, + ciphertext bytea NOT NULL, + CONSTRAINT pending_state_digest_length CHECK (octet_length(state_digest) = 32), + CONSTRAINT pending_chain_digest_length CHECK (octet_length(chain_digest) = 32), + CONSTRAINT pending_expiry_finite CHECK ( + expires_at NOT IN ('Infinity'::double precision, '-Infinity'::double precision, 'NaN'::double precision) + ), + CONSTRAINT pending_key_id_bounded CHECK (length(key_id) BETWEEN 1 AND 128), + CONSTRAINT pending_ciphertext_bounded CHECK ( + octet_length(ciphertext) BETWEEN 29 AND 1048604 + ) +); + +CREATE INDEX IF NOT EXISTS pending_chain + ON registry_client_portal.pending(chain_digest); + +CREATE TABLE IF NOT EXISTS registry_client_portal.sessions ( + session_digest bytea PRIMARY KEY, + generation bigint NOT NULL, + expires_at double precision NOT NULL, + key_id text NOT NULL, + ciphertext bytea NOT NULL, + CONSTRAINT sessions_digest_length CHECK (octet_length(session_digest) = 32), + CONSTRAINT sessions_generation_nonnegative CHECK (generation >= 0), + CONSTRAINT sessions_expiry_finite CHECK ( + expires_at NOT IN ('Infinity'::double precision, '-Infinity'::double precision, 'NaN'::double precision) + ), + CONSTRAINT sessions_key_id_bounded CHECK (length(key_id) BETWEEN 1 AND 128), + CONSTRAINT sessions_ciphertext_bounded CHECK ( + octet_length(ciphertext) BETWEEN 29 AND 1048604 + ) +); diff --git a/crates/registry-stack-client-py/python/registry_client/check_connection.py b/crates/registry-stack-client-py/python/registry_client/check_connection.py new file mode 100644 index 0000000000..47f125aff9 --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/check_connection.py @@ -0,0 +1,143 @@ +"""Offline checks for Python connection and development token read-back files.""" + +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import stat +from typing import Any, Mapping + +from .connection import API_VERSION, ConnectionError, _secret, connect +from .runner import TOKEN_VERSION, RunnerTokenSource, check_runner_document + + +_MAXIMUM_PRINTED_DIAGNOSTICS = 10 + + +def _bounded_field(value: Any, maximum: int, fallback: str) -> str: + if not isinstance(value, str): + return fallback + value = "".join( + character if ord(character) >= 32 and character != "\x7f" else "?" + for character in value + ) + return value[:maximum] or fallback + + +def _diagnostic_lines(diagnostics: tuple[Mapping[str, Any], ...]) -> list[str]: + lines = [] + for diagnostic in diagnostics[:_MAXIMUM_PRINTED_DIAGNOSTICS]: + code = _bounded_field(diagnostic.get("code"), 128, "configuration.refused") + path = _bounded_field(diagnostic.get("path"), 512, "/") + line = f"{code} at {path}" + source = diagnostic.get("source") + if isinstance(source, Mapping): + file = _bounded_field(source.get("file"), 512, "") + source_line = source.get("line") + column = source.get("column") + if isinstance(source_line, int) and not isinstance(source_line, bool) and source_line > 0: + file += f":{source_line}" + if isinstance(column, int) and not isinstance(column, bool) and column > 0: + file += f":{column}" + line += f" ({file})" + lines.append(line) + omitted = len(diagnostics) - len(lines) + if omitted > 0: + lines.append(f"{omitted} additional diagnostics omitted") + return lines + + +def _document(path: Path) -> tuple[str, dict[str, Any]]: + try: + descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + with os.fdopen(descriptor, "rb") as source: + metadata = os.fstat(source.fileno()) + if not stat.S_ISREG(metadata.st_mode) or metadata.st_size > 1_048_576: + raise ConnectionError("the read-back file must be a bounded regular file") + raw = source.read(1_048_577) + if len(raw) > 1_048_576: + raise ConnectionError("the read-back file exceeds the size limit") + except OSError as exc: + raise ConnectionError("the read-back file is unavailable") from exc + from .yaml import ConfigReadError, read_document # pyright: ignore[reportMissingImports] + + for api_version, kind in ( + (API_VERSION, "PlatformPythonConnection"), + (TOKEN_VERSION, "PlatformDevWorkloadToken"), + ): + try: + document = read_document(raw, file=os.fspath(path), api_version=api_version, kind=kind) + return kind, document + except ConfigReadError as exc: + wrong_kind = bool(exc.diagnostics) and all( + diagnostic.get("code") == "config.wrong-kind" + for diagnostic in exc.diagnostics + ) + if kind == "PlatformPythonConnection" and wrong_kind: + continue + raise ConnectionError( + "the read-back document was refused", diagnostics=exc.diagnostics + ) from None + raise ConnectionError("the read-back document was refused") + + +def check_file(path: str | Path) -> None: + """Check shape and local references without contacting an issuer or product.""" + selected = Path(path) + kind, document = _document(selected) + if kind == "PlatformPythonConnection": + connection = connect(path=selected) + for binding in connection._bindings.values(): + if binding.credential["type"] == "runner-token": + RunnerTokenSource(binding, connection._providers).current() + else: + try: + key = json.loads( + _secret(binding.credential["clientKeyRef"], connection._providers) + ) + except (json.JSONDecodeError, UnicodeError): + raise ConnectionError("the declared client key is not a JWK object") from None + if not isinstance(key, dict): + raise ConnectionError("the declared client key is not a JWK object") + return + if kind == "PlatformDevWorkloadToken": + check_runner_document(document, allow_stopped=True) + if document.get("status") != "stopped": + providers = {"file": {"root": str(selected.parent)}} + from .yaml import ConfigReadError, read_document # pyright: ignore[reportMissingImports] + + try: + private_document = read_document( + _secret(f"secret:file/{selected.name}", providers).encode("utf-8"), + file=os.fspath(selected), api_version=TOKEN_VERSION, + kind="PlatformDevWorkloadToken", + ) + except ConfigReadError as exc: + raise ConnectionError( + "runner token document was refused", diagnostics=exc.diagnostics + ) from None + check_runner_document(private_document) + return + raise ConnectionError("the read-back kind is unsupported") + + +def main() -> int: + parser = argparse.ArgumentParser( + description="Check a Python connection or runner token file without network calls." + ) + parser.add_argument("file", help="connection or stopped/live token JSON file") + args = parser.parse_args() + try: + check_file(args.file) + except ConnectionError as exc: + lines = _diagnostic_lines(exc.diagnostics) + detail = "".join(f"{line}\n" for line in lines) + parser.exit(2, f"{exc}\n{detail}") + print("read-back file valid") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/crates/registry-stack-client-py/python/registry_client/check_connection.pyi b/crates/registry-stack-client-py/python/registry_client/check_connection.pyi new file mode 100644 index 0000000000..269b64f572 --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/check_connection.pyi @@ -0,0 +1,4 @@ +from pathlib import Path + +def check_file(path: str | Path) -> None: ... +def main() -> int: ... diff --git a/crates/registry-stack-client-py/python/registry_client/connection.py b/crates/registry-stack-client-py/python/registry_client/connection.py new file mode 100644 index 0000000000..d311dea8be --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/connection.py @@ -0,0 +1,621 @@ +"""Explicit workload bindings for ordinary Python scripts and services.""" + +from __future__ import annotations + +from dataclasses import dataclass, field as dataclass_field +import hashlib +import json +import os +from pathlib import Path +import re +import stat +import threading +from types import MappingProxyType +from typing import Any, Mapping +from urllib.parse import urlsplit + + +API_VERSION = "id.registrystack.org/formats/platform/python-connection/v1alpha1" +CONNECTION_ENV = "REGISTRY_STACK_CONNECTION" +_REFERENCE = re.compile( + r"secret:(?:file/[a-z][a-z0-9._-]{0,127}|env/[A-Z][A-Z0-9_]{0,127})\Z" +) +_NAME = re.compile(r"[a-z][a-z0-9-]{0,63}\Z") +_SUPPORTED_PRODUCTS = frozenset(("breg", "messaging")) +_RESERVED_AUTHORITY_CLAIMS = frozenset( + ( + "iss", + "aud", + "sub", + "client_id", + "azp", + "exp", + "iat", + "nbf", + "jti", + "scope", + "registry_principal", + "registry_assertion_issuer", + ) +) + + +class ConnectionError(ValueError): + """A connection cannot select the declared workload authority.""" + + def __init__(self, message: str, *, diagnostics: tuple[Mapping[str, Any], ...] = ()): + super().__init__(message) + self.diagnostics = tuple(diagnostics) + + +class UnsupportedOperationError(AttributeError): + """A product method is outside the supported token-free surface.""" + + code = "client.operation-not-supported" + + def __init__(self, product: str, operation: str): + self.product = product + self.operation = operation + super().__init__(f"{self.code}: {product}.{operation}") + + +def _object( + value: Any, path: str, allowed: set[str], required: set[str] +) -> dict[str, Any]: + if not isinstance(value, dict): + raise ConnectionError(f"{path} must be an object") + unexpected = set(value) - allowed + missing = required - set(value) + if unexpected: + raise ConnectionError(f"{path}.{sorted(unexpected)[0]} is unsupported") + if missing: + raise ConnectionError(f"{path}.{sorted(missing)[0]} is required") + return value + + +def _string(value: Any, path: str) -> str: + if not isinstance(value, str) or not value or value.strip() != value: + raise ConnectionError(f"{path} must be a nonempty string") + return value + + +def _url(value: Any, path: str) -> str: + value = _string(value, path) + try: + parsed = urlsplit(value) + except ValueError as exc: + raise ConnectionError( + f"{path} must be a credential-free HTTPS or loopback URL" + ) from exc + if ( + not ( + parsed.scheme == "https" + or ( + parsed.scheme == "http" + and parsed.hostname in ("localhost", "127.0.0.1", "::1") + ) + ) + or not parsed.hostname + or parsed.username is not None + or parsed.password is not None + or parsed.fragment + or parsed.query + or any(ord(char) < 33 or char == "\\" for char in value) + ): + raise ConnectionError(f"{path} must be a credential-free HTTPS or loopback URL") + return value + + +def _resource(value: Any, path: str) -> str: + value = _string(value, path) + try: + parsed = urlsplit(value) + except ValueError as exc: + raise ConnectionError(f"{path} must be an absolute resource URI") from exc + if ( + not parsed.scheme + or not parsed.path + or parsed.fragment + or parsed.username is not None + or parsed.password is not None + or any(char.isspace() or ord(char) < 33 for char in value) + ): + raise ConnectionError(f"{path} must be an absolute resource URI") + return value + + +def _reference(value: Any, path: str, providers: Mapping[str, Any]) -> str: + if not isinstance(value, str) or not _REFERENCE.fullmatch(value): + raise ConnectionError(f"{path} must be a secret:file or secret:env reference") + provider = value[7:].split("/", 1)[0] + if provider not in providers: + raise ConnectionError(f"{path} needs the declared {provider} secret provider") + return value + + +def _claims(value: Any, path: str) -> dict[str, Any]: + """Validate and copy declared, non-secret additional token claims.""" + if not isinstance(value, dict) or len(value) > 64: + raise ConnectionError(f"{path} must be an object with at most 64 claims") + for name in value: + if ( + not isinstance(name, str) + or not name + or len(name.encode("utf-8")) > 512 + or any(ord(character) < 33 or ord(character) == 127 for character in name) + or name in _RESERVED_AUTHORITY_CLAIMS + or name.startswith("registry_grant_") + ): + raise ConnectionError(f"{path} contains an unsupported claim name") + try: + encoded = json.dumps( + value, + allow_nan=False, + ensure_ascii=False, + separators=(",", ":"), + sort_keys=True, + ) + except (TypeError, ValueError, RecursionError) as exc: + raise ConnectionError(f"{path} must contain JSON values") from exc + if len(encoded.encode("utf-8")) > 16_384: + raise ConnectionError(f"{path} exceeds the 16384-byte limit") + return json.loads(encoded) + + +def _freeze_json(value: Any) -> Any: + if isinstance(value, dict): + return MappingProxyType({name: _freeze_json(member) for name, member in value.items()}) + if isinstance(value, list): + return tuple(_freeze_json(member) for member in value) + return value + + +def _providers(value: Any) -> Mapping[str, Any]: + value = _object(value, "secretProviders", {"file", "environment"}, set()) + if not value: + raise ConnectionError("secretProviders needs at least one provider") + if "file" in value: + file = _object(value["file"], "secretProviders.file", {"root"}, {"root"}) + root = Path(_string(file["root"], "secretProviders.file.root")) + if not root.is_absolute(): + raise ConnectionError("secretProviders.file.root must be absolute") + if "environment" in value: + _object(value["environment"], "secretProviders.environment", set(), set()) + return MappingProxyType(value) + + +@dataclass(frozen=True) +class WorkloadAuthority: + """Declared non-secret authority metadata for one product binding.""" + + fingerprint: str + product: str + issuer: str = dataclass_field(repr=False) + subject: str = dataclass_field(repr=False) + client_id: str + profile: str + resource: str + scopes: tuple[str, ...] + claims: Mapping[str, Any] = dataclass_field(repr=False) + + +@dataclass(frozen=True) +class _Binding: + name: str + product: str + url: str + credential: Mapping[str, Any] + default: bool + + +def _binding(value: Any, index: int, providers: Mapping[str, Any]) -> _Binding: + path = f"bindings[{index}]" + value = _object( + value, + path, + {"name", "product", "url", "default", "credential"}, + {"name", "product", "url", "default", "credential"}, + ) + name = _string(value["name"], f"{path}.name") + if not _NAME.fullmatch(name): + raise ConnectionError(f"{path}.name must be kebab-case") + product = _string(value["product"], f"{path}.product") + if product not in _SUPPORTED_PRODUCTS: + raise ConnectionError(f"{path}.product {product!r} is unsupported") + if not isinstance(value["default"], bool): + raise ConnectionError(f"{path}.default must be a boolean") + raw_credential = value["credential"] + if not isinstance(raw_credential, dict): + raise ConnectionError(f"{path}.credential must be an object") + credential_type = raw_credential.get("type") + if credential_type == "private-key-jwt": + fields = { + "type", "issuer", "subject", "tokenEndpoint", "clientId", "profile", + "clientKeyRef", "resource", "scopes", "claims", + } + credential = _object(raw_credential, f"{path}.credential", fields, fields) + _url(credential["issuer"], f"{path}.credential.issuer") + _url(credential["tokenEndpoint"], f"{path}.credential.tokenEndpoint") + for field_name in ("subject", "clientId", "profile"): + _string(credential[field_name], f"{path}.credential.{field_name}") + _reference(credential["clientKeyRef"], f"{path}.credential.clientKeyRef", providers) + elif credential_type == "runner-token": + fields = {"type", "tokenRef", "runId", "binding", "issuer", "subject", + "clientId", "profile", "resource", "scopes", "claims", "runExpiresAt"} + credential = _object(raw_credential, f"{path}.credential", fields, fields) + reference = _reference(credential["tokenRef"], f"{path}.credential.tokenRef", providers) + if not reference.startswith("secret:file/"): + raise ConnectionError(f"{path}.credential.tokenRef must be a runner file reference") + for field in ("runId", "binding", "issuer", "subject", "clientId", "profile"): + _string(credential[field], f"{path}.credential.{field}") + if credential["binding"] != name: + raise ConnectionError(f"{path}.credential.binding must match the named binding") + _url(credential["issuer"], f"{path}.credential.issuer") + if (not isinstance(credential["runExpiresAt"], int) + or isinstance(credential["runExpiresAt"], bool) + or credential["runExpiresAt"] <= 0): + raise ConnectionError(f"{path}.credential.runExpiresAt must be a positive epoch second") + else: + raise ConnectionError(f"{path}.credential.type is unsupported") + _resource(credential["resource"], f"{path}.credential.resource") + scopes = credential["scopes"] + if ( + not isinstance(scopes, list) + or not scopes + or len(scopes) > 32 + or any( + not isinstance(scope, str) + or not scope + or len(scope) > 128 + or any(char.isspace() for char in scope) + for scope in scopes + ) + or len(set(scopes)) != len(scopes) + ): + raise ConnectionError(f"{path}.credential.scopes must be distinct scope tokens") + normalized_credential = dict(credential) + normalized_credential["claims"] = _claims( + credential["claims"], f"{path}.credential.claims" + ) + return _Binding( + name, + product, + _url(value["url"], f"{path}.url"), + MappingProxyType(normalized_credential), + value["default"], + ) + + +def _machine_admission(value: Any, audience: str) -> Mapping[str, Any]: + if audience != "service": + raise ConnectionError("connection.admission is valid only for a service audience") + required = {"issuer", "resource", "clientId", "profile", "requiredScopes", + "requiredClaims", "algorithm", "accessTokenType", + "maximumAccessTokenLifetimeSeconds"} + optional = {"jwksUri", "clockSkewSeconds", "allowInsecureHttp"} + value = _object(value, "connection.admission", required | optional, required) + _url(value["issuer"], "connection.admission.issuer") + _resource(value["resource"], "connection.admission.resource") + for field in ("clientId", "profile", "accessTokenType"): + _string(value[field], f"connection.admission.{field}") + if value["algorithm"] not in ("EdDSA", "ES256", "ES384", "RS256", "RS384"): + raise ConnectionError("connection.admission.algorithm is unsupported") + lifetime = value["maximumAccessTokenLifetimeSeconds"] + if not isinstance(lifetime, int) or isinstance(lifetime, bool) or not 1 <= lifetime <= 7200: + raise ConnectionError("connection.admission.maximumAccessTokenLifetimeSeconds must be 1..7200") + scopes = value["requiredScopes"] + if (not isinstance(scopes, list) or not scopes + or any(not isinstance(scope, str) or not scope or len(scope) > 128 + or any(char.isspace() for char in scope) for scope in scopes) + or len(set(scopes)) != len(scopes)): + raise ConnectionError("connection.admission.requiredScopes must be distinct scope tokens") + claims = value["requiredClaims"] + if (not isinstance(claims, dict) or not claims + or any(not isinstance(name, str) or not name or not isinstance(expected, str) + or not expected for name, expected in claims.items())): + raise ConnectionError("connection.admission.requiredClaims must name exact claim values") + if "jwksUri" in value: + _url(value["jwksUri"], "connection.admission.jwksUri") + if "clockSkewSeconds" in value: + skew = value["clockSkewSeconds"] + if not isinstance(skew, int) or isinstance(skew, bool) or not 0 <= skew <= 300: + raise ConnectionError("connection.admission.clockSkewSeconds must be 0..300") + if "allowInsecureHttp" in value and not isinstance(value["allowInsecureHttp"], bool): + raise ConnectionError("connection.admission.allowInsecureHttp must be boolean") + return MappingProxyType(value) + + +def _secret(reference: str, providers: Mapping[str, Any]) -> str: + kind, name = reference[7:].split("/", 1) + if kind == "env": + value = os.environ.get(name) + if not value: + raise ConnectionError("the declared environment secret is unavailable") + return value + root = Path(providers["file"]["root"]) + try: + directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + root_metadata = os.fstat(directory) + if (not stat.S_ISDIR(root_metadata.st_mode) + or root_metadata.st_uid != os.getuid() + or root_metadata.st_mode & 0o077): + raise ConnectionError("the file secret root must be a private directory") + entry_metadata = os.stat(name, dir_fd=directory, follow_symlinks=False) + if not stat.S_ISREG(entry_metadata.st_mode): + raise ConnectionError("the declared file secret must be a private regular file") + descriptor = os.open(name, os.O_RDONLY | os.O_NOFOLLOW, dir_fd=directory) + with os.fdopen(descriptor, "r", encoding="utf-8") as secret_file: + metadata = os.fstat(secret_file.fileno()) + if (not stat.S_ISREG(metadata.st_mode) + or metadata.st_nlink != 1 + or metadata.st_uid != os.getuid() + or metadata.st_mode & 0o177): + raise ConnectionError( + "the declared file secret must be a private regular file" + ) + value = secret_file.read(1_048_577) + if len(value) > 1_048_576: + raise ConnectionError("the declared file secret exceeds the size limit") + return value + finally: + os.close(directory) + except OSError as exc: + raise ConnectionError("the declared file secret is unavailable") from exc + + +class BoundConnection: + def __init__(self, owner: Connection, binding: _Binding): + self._owner = owner + self._binding = binding + + @property + def breg(self): + return self._owner._client(self._binding, "breg") + + @property + def messaging(self): + return self._owner._client(self._binding, "messaging") + + @property + def authority(self) -> WorkloadAuthority: + return self._owner._authority(self._binding) + + +class Connection: + """Immutable declarations; native clients are constructed lazily after fork.""" + + def __init__( + self, + bindings: Mapping[str, _Binding], + defaults: Mapping[str, str], + providers: Mapping[str, Any], + audience: str, + admission: Mapping[str, Any] | None, + ): + self._bindings = MappingProxyType(dict(bindings)) + self._defaults = MappingProxyType(dict(defaults)) + self._providers = providers + self._audience = audience + self._admission_config = admission + self._admission = None + self._clients: dict[str, Any] = {} + self._pid = os.getpid() + self._lock = threading.Lock() + + def using(self, name: str) -> BoundConnection: + binding = self._bindings.get(name) + if binding is None: + raise ConnectionError("unknown workload binding") + return BoundConnection(self, binding) + + def authority(self, product: str) -> WorkloadAuthority: + """Describe the default binding's declared non-secret authority.""" + name = self._defaults.get(product) + if name is None: + raise ConnectionError(f"no default {product} binding") + return self._authority(self._bindings[name]) + + def admit(self, request_values: Mapping[str, Any]): + """Verify a service-audience caller without changing workload identity.""" + if self._audience != "service" or self._admission_config is None: + raise ConnectionError("machine admission is not configured for this service") + if os.getpid() != self._pid: + if self._clients or self._admission is not None: + raise ConnectionError("construct the connection after the server forks") + self._pid = os.getpid() + self._lock = threading.Lock() + with self._lock: + if self._admission is None: + from .oidc import AccessTokenVerifier + from .machine import MachineAdmission + + config = self._admission_config + verifier = AccessTokenVerifier( + config["issuer"], config["resource"], config["clientId"], + algorithm=config["algorithm"], + access_token_type=config["accessTokenType"], + maximum_access_token_lifetime_seconds=config["maximumAccessTokenLifetimeSeconds"], + clock_skew_seconds=config.get("clockSkewSeconds", 60), + claim_names=tuple(config["requiredClaims"]), + jwks_uri=config.get("jwksUri"), + allow_insecure_http=config.get("allowInsecureHttp", False), + ) + self._admission = MachineAdmission( + verifier, + issuer=config["issuer"], + resource=config["resource"], + client_id=config["clientId"], + profile=config["profile"], + required_scopes=tuple(config["requiredScopes"]), + required_claims=config["requiredClaims"], + ) + admission = self._admission + return admission.admit(request_values) + + @property + def breg(self): + return self._default("breg") + + @property + def messaging(self): + return self._default("messaging") + + def _default(self, product: str): + name = self._defaults.get(product) + if name is None: + raise ConnectionError(f"no default {product} binding") + return self._client(self._bindings[name], product) + + @staticmethod + def _authority(binding: _Binding) -> WorkloadAuthority: + credential = binding.credential + scopes = tuple(sorted(credential["scopes"])) + identity = { + "claims": credential["claims"], + "clientId": credential["clientId"], + "issuer": credential["issuer"], + "product": binding.product, + "profile": credential["profile"], + "resource": credential["resource"], + "scopes": scopes, + "subject": credential["subject"], + } + encoded = json.dumps( + identity, + ensure_ascii=False, + separators=(",", ":"), + sort_keys=True, + ).encode("utf-8") + return WorkloadAuthority( + fingerprint=hashlib.sha256( + b"registry-stack-workload-authority/v1\0" + encoded + ).hexdigest(), + product=binding.product, + issuer=credential["issuer"], + subject=credential["subject"], + client_id=credential["clientId"], + profile=credential["profile"], + resource=credential["resource"], + scopes=scopes, + claims=_freeze_json(credential["claims"]), + ) + + def _client(self, binding: _Binding, product: str): + if binding.product != product: + raise ConnectionError( + f"binding {binding.name!r} does not provide {product}" + ) + if os.getpid() != self._pid: + if self._clients: + raise ConnectionError("construct the connection after the server forks") + self._pid = os.getpid() + self._lock = threading.Lock() + with self._lock: + existing = self._clients.get(binding.name) + if existing is not None: + return existing + if binding.credential["type"] == "runner-token": + from .runner import RotatingNativeBReg, RunnerTokenSource + source = RunnerTokenSource(binding, self._providers) + if product == "breg": + from .workload_breg import BRegWorkload + client = BRegWorkload(RotatingNativeBReg(binding.url, source)) + else: + from . import messaging + from .workload import MessagingWorkload + client = MessagingWorkload(messaging.MessagingClient(binding.url), source) + self._clients[binding.name] = client + return client + try: + key = json.loads( + _secret(binding.credential["clientKeyRef"], self._providers) + ) + except (json.JSONDecodeError, UnicodeError) as exc: + raise ConnectionError( + "the declared client key is not a JWK object" + ) from exc + if not isinstance(key, dict): + raise ConnectionError("the declared client key is not a JWK object") + native_config = { + "token_endpoint": binding.credential["tokenEndpoint"], + "client_id": binding.credential["clientId"], + "client_key": key, + "resource": binding.credential["resource"], + "scopes": binding.credential["scopes"], + } + if product == "breg": + from . import breg + from .workload_breg import BRegWorkload + + client = BRegWorkload( + breg.BaseRegistryClient( + binding.url, authorization={"private_key_jwt": native_config} + ) + ) + else: + from . import breg, messaging + from .workload import MessagingWorkload + + provider = breg.PrivateKeyJwt(native_config) + client = MessagingWorkload( + messaging.MessagingClient(binding.url), provider + ) + self._clients[binding.name] = client + return client + + +def connect(*, path: str | Path | None = None) -> Connection: + """Load the configured service's declared workload bindings.""" + selected = path if path is not None else os.environ.get(CONNECTION_ENV) + if not selected: + raise ConnectionError(f"set {CONNECTION_ENV} or pass path") + try: + contents = Path(selected).read_bytes() + except OSError as exc: + raise ConnectionError( + "the connection file is unavailable" + ) from exc + from .yaml import ConfigReadError, read_document # pyright: ignore[reportMissingImports] + + try: + document = read_document( + contents, file=os.fspath(selected), api_version=API_VERSION, + kind="PlatformPythonConnection", + ) + except ConfigReadError as exc: + raise ConnectionError( + "the connection document was refused", + diagnostics=exc.diagnostics, + ) from None + document = _object( + document, + "connection", + {"apiVersion", "kind", "service", "audience", "secretProviders", "bindings", "admission"}, + {"apiVersion", "kind", "service", "audience", "secretProviders", "bindings"}, + ) + _string(document["service"], "connection.service") + if document["audience"] not in ("service", "holder", "staff"): + raise ConnectionError("connection.audience must be service, holder or staff") + providers = _providers(document["secretProviders"]) + values = document["bindings"] + if not isinstance(values, list): + raise ConnectionError("connection.bindings must be a list") + bindings: dict[str, _Binding] = {} + defaults: dict[str, str] = {} + for index, value in enumerate(values): + binding = _binding(value, index, providers) + if binding.name in bindings: + raise ConnectionError(f"duplicate binding name {binding.name!r}") + bindings[binding.name] = binding + if binding.default: + if binding.product in defaults: + raise ConnectionError(f"duplicate default {binding.product} binding") + defaults[binding.product] = binding.name + for product in {binding.product for binding in bindings.values()} - set(defaults): + raise ConnectionError(f"missing default {product} binding") + admission = ( + _machine_admission(document["admission"], document["audience"]) + if "admission" in document else None + ) + return Connection(bindings, defaults, providers, document["audience"], admission) diff --git a/crates/registry-stack-client-py/python/registry_client/connection.pyi b/crates/registry-stack-client-py/python/registry_client/connection.pyi new file mode 100644 index 0000000000..faf82c5293 --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/connection.pyi @@ -0,0 +1,57 @@ +from pathlib import Path + +from .workload import MessagingWorkload +from .workload_breg import BRegWorkload +from .machine import MachineContext +from typing import Any, Mapping + +API_VERSION: str +CONNECTION_ENV: str + +class ConnectionError(ValueError): + diagnostics: tuple[Mapping[str, Any], ...] + def __init__(self, message: str, *, diagnostics: tuple[Mapping[str, Any], ...] = ...) -> None: ... + +class UnsupportedOperationError(AttributeError): + code: str + product: str + operation: str + def __init__(self, product: str, operation: str) -> None: ... + +class WorkloadAuthority: + fingerprint: str + product: str + issuer: str + subject: str + client_id: str + profile: str + resource: str + scopes: tuple[str, ...] + claims: Mapping[str, Any] + +class _Binding: + name: str + product: str + credential: Mapping[str, Any] + +class BoundConnection: + @property + def authority(self) -> WorkloadAuthority: ... + @property + def breg(self) -> BRegWorkload: ... + @property + def messaging(self) -> MessagingWorkload: ... + +class Connection: + _bindings: Mapping[str, _Binding] + _providers: Mapping[str, Any] + def using(self, name: str) -> BoundConnection: ... + def authority(self, product: str) -> WorkloadAuthority: ... + def admit(self, request_values: Mapping[str, Any]) -> MachineContext: ... + @property + def breg(self) -> BRegWorkload: ... + @property + def messaging(self) -> MessagingWorkload: ... + +def connect(*, path: str | Path | None = None) -> Connection: ... +def _secret(reference: str, providers: Mapping[str, Any]) -> str: ... diff --git a/crates/registry-stack-client-py/python/registry_client/dev_picker.py b/crates/registry-stack-client-py/python/registry_client/dev_picker.py new file mode 100644 index 0000000000..959ecd7914 --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/dev_picker.py @@ -0,0 +1,1253 @@ +"""Runner-bound local person selection for a trusted developer machine. + +This simulates admission for the local edit loop. It is not OIDC, does not +mint credentials, and cannot be enabled by a boolean or a production +connection. The only entry point is an owner-only descriptor beneath a live +``rstack dev`` run whose supervisor still holds its run lock. +""" + +from __future__ import annotations + +import base64 +from dataclasses import dataclass +import fcntl +import hashlib +import hmac +import html +import json +import math +import os +from pathlib import Path +import re +import secrets +import stat +import threading +import time +from types import MappingProxyType +from typing import Any, Callable, Mapping, MutableMapping +from urllib.parse import parse_qs, urlsplit + +from .connection import ConnectionError, _claims +from .portal import CSRFError, PortalContext, ReauthenticationRequired + + +DESCRIPTOR_VERSION = "id.registrystack.org/formats/platform/dev-person-picker/v1alpha1" +TOKEN_VERSION = "id.registrystack.org/formats/platform/dev-person-token/v1alpha1" +GENERATION_VERSION = "id.registrystack.org/formats/platform/dev-person-generation/v1alpha1" +CONNECTION_VERSION = "id.registrystack.org/formats/platform/python-connection/v1alpha1" +_RUN_ID = re.compile(r"[0-9a-f]{32}\Z") +_LOCAL_NAME = re.compile(r"[a-z][a-z0-9-]{0,63}\Z") +_OPAQUE = re.compile(r"[A-Za-z0-9_-]{20,128}\Z") +_SCOPE = re.compile(r"\S{1,128}\Z") +_MAXIMUM_FILE_BYTES = 1_048_576 +_MAXIMUM_FORM_BYTES = 65_536 + + +class PickerUnavailable(ValueError): + """The development run or one of its exact credentials is unavailable.""" + + code = "development-picker.unavailable" + + def __init__(self, detail: str = "development picker is unavailable"): + super().__init__(f"{self.code}: {detail}") + + +class PickerAdmissionError(ValueError): + """A local browser selection did not establish one complete person.""" + + code = "development-picker.admission-refused" + + def __init__(self): + super().__init__(self.code) + + +@dataclass(frozen=True) +class PickerChoice: + """The only non-secret person facts rendered into the selection form.""" + + label: str + selector: str + + +@dataclass(frozen=True, repr=False) +class PickerForm: + pending_id: str + csrf_token: str + choices: tuple[PickerChoice, ...] + + +@dataclass(frozen=True, repr=False) +class PickerSession: + session_id: str + csrf_token: str + expires_at: float + + +class DevelopmentPerson: + """Request-local person facts and endpoint-bound product clients.""" + + __slots__ = ("_context", "_person", "_products") + + def __init__( + self, + context: PortalContext, + person: _Person, + products: Mapping[str, Mapping[str, str]], + ): + self._context = context + self._person = person + self._products = products + + @property + def subject(self) -> str: + return self._context.subject + + @property + def session_id(self) -> str: + return self._context.session_id + + @property + def principal(self) -> str: + return self._context.principal + + @property + def persona(self) -> str: + return self._context.persona + + @property + def csrf_token(self) -> str: + return self._context.csrf_token + + @property + def expires_at(self) -> float: + return self._context.expires_at + + @property + def breg(self): + credential = self._person.credentials.get("breg") + target = self._products.get("breg") + if credential is None or target is None: + raise ReauthenticationRequired() + from . import breg + from .workload_breg import BRegWorkload + + return BRegWorkload( + breg.BaseRegistryClient( + target["url"], authorization={"static": self._context._token_for("breg")} + ) + ) + + @property + def casework(self): + credential = self._person.credentials.get("casework") + target = self._products.get("casework") + if credential is None or target is None: + raise ReauthenticationRequired() + from . import casework + from .workload_casework import CaseworkWorkload + + return CaseworkWorkload( + casework.CaseworkClient(target["url"]), + self._context._token_for("casework"), + credential.profile, + ) + + +@dataclass(frozen=True, repr=False) +class _Credential: + token_ref: str + profile: str + resource: str + audiences: tuple[str, ...] + scopes: tuple[str, ...] + principal_claim: str + + +@dataclass(frozen=True, repr=False) +class _Person: + selector: str + label: str + subject: str + principal: str + client_id: str + credentials: Mapping[str, _Credential] + + +@dataclass(frozen=True, repr=False) +class _StoredSession: + session_id: str + selector: str + subject: str + principal: str + client_id: str + csrf_token: str + expires_at: float + + +def _json(path: Path) -> Any: + _private_file(path) + try: + contents = path.read_bytes() + except OSError as exc: + raise PickerUnavailable("runner state is unavailable") from exc + if len(contents) > _MAXIMUM_FILE_BYTES: + raise PickerUnavailable("runner state exceeds its size limit") + + def unique(pairs): + value = {} + for name, member in pairs: + if name in value: + raise PickerUnavailable("runner state contains a duplicate field") + value[name] = member + return value + + try: + return json.loads(contents, object_pairs_hook=unique) + except (UnicodeError, json.JSONDecodeError) as exc: + raise PickerUnavailable("runner state is malformed") from exc + + +def _private_file(path: Path) -> os.stat_result: + try: + metadata = path.lstat() + except OSError as exc: + raise PickerUnavailable("runner state is unavailable") from exc + if ( + not stat.S_ISREG(metadata.st_mode) + or metadata.st_nlink != 1 + or metadata.st_uid != os.getuid() + or metadata.st_mode & 0o177 + ): + raise PickerUnavailable("runner state must be an owner-only regular file") + return metadata + + +def _private_directory(path: Path) -> None: + try: + metadata = path.lstat() + except OSError as exc: + raise PickerUnavailable("runner directory is unavailable") from exc + if ( + not stat.S_ISDIR(metadata.st_mode) + or metadata.st_uid != os.getuid() + or metadata.st_mode & 0o077 + ): + raise PickerUnavailable("runner directory must be owner-only") + + +def _object(value: Any, *, fields: set[str], name: str) -> dict[str, Any]: + if not isinstance(value, dict) or set(value) != fields: + raise PickerUnavailable(f"{name} has unsupported or missing fields") + return value + + +def _text(value: Any, *, name: str, maximum: int = 256) -> str: + if ( + not isinstance(value, str) + or not 1 <= len(value) <= maximum + or value.strip() != value + or any(ord(character) < 32 or ord(character) == 127 for character in value) + ): + raise PickerUnavailable(f"{name} is malformed") + return value + + +def _epoch(value: Any, *, name: str) -> int: + if not isinstance(value, int) or isinstance(value, bool) or value <= 0: + raise PickerUnavailable(f"{name} is malformed") + return value + + +def _scopes(value: Any, *, name: str) -> tuple[str, ...]: + if ( + not isinstance(value, list) + or not value + or len(value) > 32 + or any(not isinstance(scope, str) or not _SCOPE.fullmatch(scope) for scope in value) + or len(set(value)) != len(value) + ): + raise PickerUnavailable(f"{name} is malformed") + return tuple(value) + + +def _resource(value: Any, *, name: str) -> str: + value = _text(value, name=name, maximum=512) + try: + parsed = urlsplit(value) + except ValueError as exc: + raise PickerUnavailable(f"{name} is malformed") from exc + if ( + not parsed.scheme + or not (parsed.netloc or parsed.path) + or parsed.username is not None + or parsed.password is not None + or parsed.fragment + or any(character.isspace() for character in value) + ): + raise PickerUnavailable(f"{name} is malformed") + return value + + +def _loopback_origin(value: Any, *, name: str) -> str: + value = _text(value, name=name, maximum=512) + try: + parsed = urlsplit(value) + port = parsed.port + except ValueError as exc: + raise PickerUnavailable(f"{name} must be an exact loopback HTTP origin") from exc + if ( + parsed.scheme != "http" + or parsed.hostname not in ("127.0.0.1", "::1") + or port is None + or parsed.username is not None + or parsed.password is not None + or parsed.path not in ("", "/") + or parsed.query + or parsed.fragment + ): + raise PickerUnavailable(f"{name} must be an exact loopback HTTP origin") + return value.rstrip("/") + + +def _relative_file(root: Path, reference: Any, *, name: str, allow_parent: bool = False) -> Path: + reference = _text(reference, name=name, maximum=256) + candidate = Path(reference) + if candidate.is_absolute() or "\\" in reference: + raise PickerUnavailable(f"{name} must be a runner-local file reference") + parts = candidate.parts + if not allow_parent and any(part in ("", ".", "..") for part in parts): + raise PickerUnavailable(f"{name} must be a runner-local file reference") + try: + resolved = (root / candidate).resolve(strict=True) + except OSError as exc: + raise PickerUnavailable(f"{name} is unavailable") from exc + return resolved + + +def _b64_json(segment: str) -> Mapping[str, Any]: + try: + raw = base64.urlsafe_b64decode(segment + "=" * (-len(segment) % 4)) + value = json.loads(raw) + except (ValueError, UnicodeError, json.JSONDecodeError) as exc: + raise PickerUnavailable("runner person token is malformed") from exc + if not isinstance(value, dict): + raise PickerUnavailable("runner person token is malformed") + return value + + +def _host(origin: str) -> str: + return urlsplit(origin).netloc + + +class DevelopmentPicker: + """One persona's run-scoped, memory-only local admission simulation.""" + + def __init__(self, path: Path, document: Mapping[str, Any], digest: bytes): + self._path = path + self._digest = digest + self._root = path.parents[2] + self._picker_root = path.parent + self._run_id = document["runId"] + self._persona = document["persona"] + self._origin = document["origin"] + self._namespace = document["sessionNamespace"] + self._issued_at = document["issuedAt"] + self._expires_at = document["expiresAt"] + self._generation_path = _relative_file( + self._picker_root, document["generationRef"], name="generationRef" + ) + self._products = document["products"] + self._people = document["people"] + self._workload_connection_path = document["workloadConnectionPath"] + self._workloads = document["workloads"] + self._pending: dict[str, tuple[str, float]] = {} + self._sessions: dict[str, _StoredSession] = {} + self._lock = threading.Lock() + + @classmethod + def from_descriptor(cls, path: str | Path) -> DevelopmentPicker: + """Load only a descriptor at the fixed location of a live runner.""" + selected = Path(path) + if not selected.is_absolute() or selected.name != "picker.json": + raise PickerUnavailable("descriptor is not a private live development run reference") + try: + selected = selected.resolve(strict=True) + except OSError as exc: + raise PickerUnavailable("descriptor is unavailable") from exc + if len(selected.parents) < 3 or selected.parent.parent.name != "python-picker": + raise PickerUnavailable("descriptor is not a private live development run reference") + for directory in (selected.parent, selected.parent.parent, selected.parents[2]): + _private_directory(directory) + raw = selected.read_bytes() + document = _json(selected) + document = cls._parse_descriptor(selected, document) + picker = cls(selected, document, hashlib.sha256(raw).digest()) + picker._check_live() + picker._read_generation() + picker._validate_workload_connection() + return picker + + @staticmethod + def _parse_descriptor(path: Path, document: Any) -> Mapping[str, Any]: + fields = { + "apiVersion", "kind", "runId", "persona", "origin", "sessionNamespace", + "issuedAt", "expiresAt", "generationRef", "products", "people", + "workloadConnectionRef", "workloads", + } + document = _object(document, fields=fields, name="picker descriptor") + if ( + document["apiVersion"] != DESCRIPTOR_VERSION + or document["kind"] != "PlatformDevPersonPicker" + ): + raise PickerUnavailable("descriptor has an unsupported format") + run_id = _text(document["runId"], name="runId", maximum=32) + if not _RUN_ID.fullmatch(run_id) or path.parents[2].name != run_id: + raise PickerUnavailable("descriptor run does not match its private run directory") + persona = document["persona"] + if persona not in ("holder", "staff") or path.parent.name != persona: + raise PickerUnavailable("descriptor persona does not match its private directory") + document["origin"] = _loopback_origin(document["origin"], name="origin") + namespace = _text(document["sessionNamespace"], name="sessionNamespace", maximum=64) + if not _OPAQUE.fullmatch(namespace): + raise PickerUnavailable("sessionNamespace must be opaque runner state") + issued_at = _epoch(document["issuedAt"], name="issuedAt") + expires_at = _epoch(document["expiresAt"], name="expiresAt") + if issued_at >= expires_at or expires_at <= int(time.time()): + raise PickerUnavailable("development run has expired") + if not isinstance(document["products"], dict) or not document["products"]: + raise PickerUnavailable("descriptor needs exact product endpoints") + products = {} + for product, raw in document["products"].items(): + if not isinstance(product, str) or not _LOCAL_NAME.fullmatch(product): + raise PickerUnavailable("descriptor product name is malformed") + raw = _object(raw, fields={"url", "resource"}, name=f"products.{product}") + products[product] = MappingProxyType({ + "url": _loopback_origin(raw["url"], name=f"products.{product}.url"), + "resource": _resource(raw["resource"], name=f"products.{product}.resource"), + }) + document["products"] = MappingProxyType(products) + raw_people = document["people"] + if not isinstance(raw_people, list) or not 1 <= len(raw_people) <= 32: + raise PickerUnavailable("descriptor needs 1 to 32 eligible test people") + people: dict[str, _Person] = {} + credential_products: set[str] | None = None + for index, raw in enumerate(raw_people): + raw = _object( + raw, + fields={"selector", "label", "subject", "principal", "clientId", "credentials"}, + name=f"people[{index}]", + ) + selector = _text(raw["selector"], name="selector", maximum=128) + if not _OPAQUE.fullmatch(selector) or selector in people: + raise PickerUnavailable("test-person selectors must be distinct and opaque") + label = _text(raw["label"], name="label", maximum=128) + subject = _text(raw["subject"], name="subject") + principal = _text(raw["principal"], name="principal") + client_id = _text(raw["clientId"], name="clientId") + if selector in (label, subject, principal, client_id): + raise PickerUnavailable("test-person selector exposes an identity field") + if not isinstance(raw["credentials"], dict) or not raw["credentials"]: + raise PickerUnavailable("each test person needs a complete product grant set") + current_products = set(raw["credentials"]) + if credential_products is None: + credential_products = current_products + elif current_products != credential_products: + raise PickerUnavailable("all eligible people need the same complete product set") + credentials = {} + for product, grant in raw["credentials"].items(): + if product not in products: + raise PickerUnavailable("person credential names an undeclared product") + grant = _object( + grant, + fields={ + "tokenRef", "profile", "resource", "audiences", "scopes", + "principalClaim", + }, + name=f"people[{index}].credentials.{product}", + ) + token_ref = _text(grant["tokenRef"], name="tokenRef", maximum=128) + _relative_file(path.parent, token_ref, name="tokenRef") + profile = _text(grant["profile"], name="profile", maximum=64) + if not _LOCAL_NAME.fullmatch(profile): + raise PickerUnavailable("person credential profile is malformed") + resource = _resource(grant["resource"], name="resource") + if resource != products[product]["resource"]: + raise PickerUnavailable("person credential resource differs from its run product") + audiences = grant["audiences"] + if ( + not isinstance(audiences, list) + or not audiences + or len(audiences) > 4 + or any(not isinstance(value, str) for value in audiences) + or len(set(audiences)) != len(audiences) + or resource not in audiences + ): + raise PickerUnavailable("person credential audiences are malformed") + audiences = tuple(_resource(value, name="audience") for value in audiences) + credentials[product] = _Credential( + token_ref, + profile, + resource, + audiences, + _scopes(grant["scopes"], name="scopes"), + _text(grant["principalClaim"], name="principalClaim", maximum=128), + ) + people[selector] = _Person( + selector, label, subject, principal, client_id, MappingProxyType(credentials) + ) + document["people"] = MappingProxyType(people) + connection_reference = document["workloadConnectionRef"] + connection_path = None + if connection_reference is not None: + connection_path = _relative_file( + path.parent, + connection_reference, + name="workloadConnectionRef", + allow_parent=True, + ) + run_root = path.parents[2] + try: + connection_path.relative_to(run_root) + except ValueError as exc: + raise PickerUnavailable( + "workload connection is outside the development run" + ) from exc + document["workloadConnectionPath"] = connection_path + del document["workloadConnectionRef"] + raw_workloads = document["workloads"] + if not isinstance(raw_workloads, list) or len(raw_workloads) > 32: + raise PickerUnavailable("descriptor workloads are malformed") + workloads = {} + workload_fields = { + "name", "product", "default", "url", "issuer", "subject", "clientId", + "profile", "resource", "scopes", "claims", + } + for index, raw in enumerate(raw_workloads): + raw = _object(raw, fields=workload_fields, name=f"workloads[{index}]") + name = _text(raw["name"], name="workload name", maximum=64) + product = _text(raw["product"], name="workload product", maximum=64) + if ( + not _LOCAL_NAME.fullmatch(name) + or name in workloads + or product not in products + or not isinstance(raw["default"], bool) + ): + raise PickerUnavailable("descriptor workloads are malformed") + workload = dict(raw) + workload["url"] = _loopback_origin(raw["url"], name="workload url") + workload["issuer"] = _resource(raw["issuer"], name="workload issuer") + workload["resource"] = _resource(raw["resource"], name="workload resource") + workload["scopes"] = _scopes(raw["scopes"], name="workload scopes") + try: + workload["claims"] = _claims(raw["claims"], "workload claims") + except ConnectionError as exc: + raise PickerUnavailable("descriptor workload claims are malformed") from exc + for field in ("subject", "clientId", "profile"): + workload[field] = _text(raw[field], name=f"workload {field}") + if ( + workload["url"] != products[product]["url"] + or workload["resource"] != products[product]["resource"] + ): + raise PickerUnavailable("workload target differs from its run product") + workloads[name] = MappingProxyType(workload) + if bool(workloads) != (connection_path is not None): + raise PickerUnavailable( + "workload connection reference must match the declared run workloads" + ) + document["workloads"] = MappingProxyType(workloads) + return MappingProxyType(document) + + @property + def origin(self) -> str: + return self._origin + + @property + def persona(self) -> str: + return self._persona + + @property + def session_cookie(self) -> str: + return f"registry-dev-{self._namespace}-session" + + @property + def pending_cookie(self) -> str: + return f"registry-dev-{self._namespace}-pending" + + def choices(self) -> tuple[PickerChoice, ...]: + self._check_live() + return tuple( + PickerChoice(person.label, person.selector) + for person in self._people.values() + ) + + def begin(self) -> PickerForm: + self._check_live() + now = time.time() + pending_id = secrets.token_urlsafe(24) + csrf_token = secrets.token_urlsafe(32) + with self._lock: + self._pending = { + key: pending + for key, pending in self._pending.items() + if pending[1] > now + } + self._pending[pending_id] = (csrf_token, min(now + 300, self._expires_at)) + return PickerForm(pending_id, csrf_token, self.choices()) + + def select( + self, + pending_id: str, + *, + selector: str, + origin: str, + host: str, + csrf_token: str, + ) -> PickerSession: + self._check_live() + now = time.time() + with self._lock: + pending = self._pending.get(pending_id) + if ( + pending is None + or pending[1] <= now + or origin != self._origin + or host.lower() != _host(self._origin).lower() + or not hmac.compare_digest(pending[0], csrf_token) + ): + raise PickerAdmissionError() + person = self._people.get(selector) + if person is None: + raise PickerAdmissionError() + try: + self._person_tokens(person, admission=True) + except PickerUnavailable: + raise PickerAdmissionError() from None + session_id = secrets.token_urlsafe(32) + stored = _StoredSession( + session_id, + selector, + person.subject, + person.principal, + person.client_id, + secrets.token_urlsafe(32), + float(self._expires_at), + ) + with self._lock: + current = self._pending.get(pending_id) + if current != pending or session_id in self._sessions: + raise PickerAdmissionError() + self._sessions[session_id] = stored + del self._pending[pending_id] + return PickerSession(session_id, stored.csrf_token, stored.expires_at) + + def context(self, session_id: str) -> DevelopmentPerson: + try: + self._check_live() + marker = self._read_generation() + except PickerUnavailable: + self._drop_session(session_id) + raise ReauthenticationRequired() from None + if marker["status"] != "ready": + self._drop_session(session_id) + raise ReauthenticationRequired() + with self._lock: + stored = self._sessions.get(session_id) + now = time.time() + if stored is None or stored.expires_at <= now: + self._drop_session(session_id) + raise ReauthenticationRequired() + person = self._people.get(stored.selector) + if ( + person is None + or person.subject != stored.subject + or person.principal != stored.principal + or person.client_id != stored.client_id + ): + self._drop_session(session_id) + raise ReauthenticationRequired() + try: + tokens = self._person_tokens(person, admission=False) + except ReauthenticationRequired: + self._drop_session(session_id) + raise + context = PortalContext( + stored.session_id, + stored.subject, + stored.principal, + self._persona, + tokens, + stored.csrf_token, + stored.expires_at, + ) + return DevelopmentPerson(context, person, self._products) + + def authorize_mutation( + self, session_id: str, *, origin: str, csrf_token: str + ) -> DevelopmentPerson: + person = self.context(session_id) + if origin != self._origin or not hmac.compare_digest( + person.csrf_token, csrf_token + ): + raise CSRFError() + return person + + def logout(self, session_id: str) -> None: + self._drop_session(session_id) + + def session_count(self) -> int: + with self._lock: + return len(self._sessions) + + @property + def workloads(self): + """Load only the runner-token connection fixed by this descriptor.""" + self._check_live() + if self._workload_connection_path is None: + raise PickerUnavailable("this picker declares no service workload authority") + self._validate_workload_connection() + from .connection import connect + + return connect(path=self._workload_connection_path) + + def _drop_session(self, session_id: str) -> None: + with self._lock: + self._sessions.pop(session_id, None) + + def _check_live(self) -> None: + if (self._root / "stop").exists(): + raise PickerUnavailable("development run is stopping") + try: + current = self._path.read_bytes() + except OSError as exc: + raise PickerUnavailable("descriptor is unavailable") from exc + _private_file(self._path) + if not hmac.compare_digest(hashlib.sha256(current).digest(), self._digest): + raise PickerUnavailable("descriptor changed during the development run") + lock_path = self._root / "worker.lock" + _private_file(lock_path) + try: + with lock_path.open("rb") as lock: + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + pass + else: + fcntl.flock(lock, fcntl.LOCK_UN) + raise PickerUnavailable("descriptor is not owned by a live development run") + except OSError as exc: + raise PickerUnavailable("live development run cannot be verified") from exc + report = _json(self._root / "report.json") + if ( + not isinstance(report, dict) + or report.get("schema_version") != "registry.rstack.dev.v1" + or report.get("run_id") != self._run_id + or report.get("status") != "ready" + or report.get("expires_at") != self._expires_at + or int(time.time()) >= self._expires_at + ): + raise PickerUnavailable("descriptor is not owned by a ready live development run") + + def _read_generation(self) -> Mapping[str, Any]: + state = _object( + _json(self._generation_path), + fields={ + "apiVersion", "kind", "status", "runId", "picker", "generation", + "runExpiresAt", + }, + name="person generation", + ) + if ( + state["apiVersion"] != GENERATION_VERSION + or state["kind"] != "PlatformDevPersonGeneration" + or state["status"] not in ("ready", "stopped") + or state["runId"] != self._run_id + or state["picker"] != self._persona + or not isinstance(state["generation"], int) + or isinstance(state["generation"], bool) + or state["generation"] < 1 + or state["runExpiresAt"] != self._expires_at + ): + raise PickerUnavailable("person credential generation is malformed") + return state + + def _person_tokens(self, person: _Person, *, admission: bool) -> Mapping[str, str]: + first = self._read_generation() + if first["status"] != "ready": + raise ReauthenticationRequired() + tokens = {} + for product, credential in person.credentials.items(): + path = _relative_file( + self._picker_root, credential.token_ref, name="person token reference" + ) + state = _json(path) + if not isinstance(state, dict) or state.get("generation") != first["generation"]: + raise PickerUnavailable("person credentials rotated during admission") + try: + tokens[product] = self._person_token( + state, person=person, product=product, credential=credential, + generation=first["generation"], + ) + except PickerUnavailable: + if admission: + raise + raise ReauthenticationRequired() from None + second = self._read_generation() + if second != first: + raise PickerUnavailable("person credentials rotated during admission") + return MappingProxyType(tokens) + + def _person_token( + self, + state: Any, + *, + person: _Person, + product: str, + credential: _Credential, + generation: int, + ) -> str: + fields = { + "apiVersion", "kind", "runId", "picker", "persona", "selector", "product", + "issuer", "subject", "principal", "clientId", "profile", "resource", + "audiences", "scopes", "principalClaim", "generation", "issuedAt", + "expiresAt", "runExpiresAt", "token", + } + state = _object(state, fields=fields, name="person token") + expected = { + "apiVersion": TOKEN_VERSION, + "kind": "PlatformDevPersonToken", + "runId": self._run_id, + "picker": self._persona, + "persona": self._persona, + "selector": person.selector, + "product": product, + "subject": person.subject, + "principal": person.principal, + "clientId": person.client_id, + "profile": credential.profile, + "resource": credential.resource, + "audiences": list(credential.audiences), + "scopes": list(credential.scopes), + "principalClaim": credential.principal_claim, + "generation": generation, + "runExpiresAt": self._expires_at, + } + if any(state.get(name) != value for name, value in expected.items()): + raise PickerUnavailable("person token differs from the declared run authority") + issuer = _resource(state["issuer"], name="person token issuer") + issued = _epoch(state["issuedAt"], name="person token issuedAt") + expires = _epoch(state["expiresAt"], name="person token expiresAt") + now = int(time.time()) + if ( + issued > now + 60 + or issued > expires + or expires - issued > 300 + or expires > self._expires_at + or now >= expires + ): + raise PickerUnavailable("person token is expired or has an invalid lifetime") + token = state["token"] + if ( + not isinstance(token, str) + or not token + or len(token) > 8192 + or any(character.isspace() for character in token) + or token.count(".") != 2 + ): + raise PickerUnavailable("person token is malformed") + claims = _b64_json(token.split(".")[1]) + audience = claims.get("aud") + token_audiences = [audience] if isinstance(audience, str) else audience + if ( + claims.get("iss") != issuer + or token_audiences != list(credential.audiences) + or claims.get("sub") != person.subject + or claims.get("client_id") != person.client_id + or claims.get("scope") != " ".join(sorted(credential.scopes)) + or claims.get(credential.principal_claim) != person.principal + or claims.get("registry_dev_persona") != self._persona + or claims.get("iat") != issued + or claims.get("exp") != expires + ): + raise PickerUnavailable("person token claims differ from the declared run authority") + return token + + def _validate_workload_connection(self) -> None: + if self._workload_connection_path is None: + if self._workloads: + raise PickerUnavailable("workload connection is incomplete for this picker run") + return + document = _json(self._workload_connection_path) + if not isinstance(document, dict): + raise PickerUnavailable("workload connection is malformed") + required = { + "apiVersion", "kind", "service", "audience", "secretProviders", "bindings" + } + if ( + set(document) != required + or document.get("apiVersion") != CONNECTION_VERSION + or document.get("kind") != "PlatformPythonConnection" + or document.get("service") != f"rstack-dev-{self._run_id}" + or document.get("audience") != "service" + or document.get("secretProviders") + != {"file": {"root": str(self._workload_connection_path.parent)}} + or not isinstance(document.get("bindings"), list) + ): + raise PickerUnavailable("workload connection is not confined to this development run") + observed = {} + for raw in document["bindings"]: + if not isinstance(raw, dict) or set(raw) != { + "name", "product", "url", "default", "credential" + }: + raise PickerUnavailable("workload binding is malformed") + name = raw.get("name") + expected = self._workloads.get(name) + credential = raw.get("credential") + if ( + expected is None + or not isinstance(credential, dict) + or credential.get("type") != "runner-token" + or set(credential) != { + "type", "tokenRef", "runId", "binding", "issuer", "subject", + "clientId", "profile", "resource", "scopes", "claims", + "runExpiresAt", + } + or raw.get("product") != expected["product"] + or raw.get("default") != expected["default"] + or raw.get("url") != expected["url"] + or credential.get("runId") != self._run_id + or credential.get("binding") != name + or credential.get("issuer") != expected["issuer"] + or credential.get("subject") != expected["subject"] + or credential.get("clientId") != expected["clientId"] + or credential.get("profile") != expected["profile"] + or credential.get("resource") != expected["resource"] + or credential.get("scopes") != list(expected["scopes"]) + or credential.get("claims") != expected["claims"] + or credential.get("runExpiresAt") != self._expires_at + or not isinstance(credential.get("tokenRef"), str) + or not credential["tokenRef"].startswith("secret:file/") + ): + raise PickerUnavailable("workload binding differs from the picker run") + token_name = credential["tokenRef"][12:] + if not token_name or "/" in token_name or token_name in (".", ".."): + raise PickerUnavailable("workload token reference is not runner-local") + observed[name] = True + if set(observed) != set(self._workloads): + raise PickerUnavailable("workload connection is incomplete for this picker run") + + +def _parse_form(content_type: str, body: bytes) -> Mapping[str, str]: + if ( + content_type.split(";", 1)[0].strip().lower() + != "application/x-www-form-urlencoded" + or not 1 <= len(body) <= _MAXIMUM_FORM_BYTES + ): + raise PickerAdmissionError() + try: + fields = parse_qs( + body.decode("ascii"), + keep_blank_values=True, + strict_parsing=True, + max_num_fields=16, + encoding="utf-8", + errors="strict", + ) + except (UnicodeError, ValueError): + raise PickerAdmissionError() from None + required = {"pending_id", "selector", "csrf_token"} + if set(fields) != required or any(len(fields[name]) != 1 for name in required): + raise PickerAdmissionError() + return MappingProxyType({name: fields[name][0] for name in required}) + + +def _picker_html(form: PickerForm) -> str: + options = "".join( + f'" + for choice in form.choices + ) + return ( + "Choose test person" + '
' + f'' + f'' + f'
' + ) + + +def _clear_cookie(response: Any, name: str) -> None: + response.set_cookie( + name, "", max_age=0, expires=0, secure=False, httponly=True, + samesite="strict", path="/", + ) + + +def install_flask( + app: Any, + picker: DevelopmentPicker, + *, + person_factory: Callable[[DevelopmentPerson], Any], + request_seconds: float, +) -> None: + """Protect a loopback Flask starter with the run-bound picker.""" + from flask import Response, g, jsonify, redirect, request + from .web import form_csrf_token, is_public + from .workload import request_budget + + if not math.isfinite(request_seconds) or request_seconds <= 0: + raise ValueError("request_seconds must be finite and positive") + picker.choices() + auth_paths = frozenset(("/auth/dev", "/auth/dev/logout")) + + def error(code: str, status: int): + response = jsonify({"code": code}) + response.status_code = status + response.headers["Cache-Control"] = "no-store" + return response + + def exact_origin() -> bool: + return request.host_url.rstrip("/") == picker.origin + + def authorized_mutation(): + session_id = request.cookies.get(picker.session_cookie) + if not session_id: + raise ReauthenticationRequired() + csrf = request.headers.get("X-CSRF-Token", "") + if not csrf and request.mimetype == "application/x-www-form-urlencoded": + length = request.content_length + if length is not None and 1 <= length <= _MAXIMUM_FORM_BYTES: + csrf = form_csrf_token( + content_type=request.content_type or "", + content_length=length, + body=request.get_data(cache=True), + ) + return picker.authorize_mutation( + session_id, origin=request.headers.get("Origin", ""), csrf_token=csrf + ) + + @app.before_request + def admit_request(): + budget = request_budget(request_seconds) + budget.__enter__() + g._registry_dev_budget = budget + try: + picker._check_live() + except PickerUnavailable: + return error(PickerUnavailable.code, 503) + if not exact_origin(): + return error("development-picker.origin-refused", 400) + if request.path in auth_paths or is_public(app.view_functions.get(request.endpoint)): + return None + session_id = request.cookies.get(picker.session_cookie) + if not session_id: + return error(ReauthenticationRequired.code, 401) + try: + context = ( + picker.context(session_id) + if request.method in ("GET", "HEAD", "OPTIONS") + else authorized_mutation() + ) + g.registry_person = person_factory(context) + except ReauthenticationRequired: + return error(ReauthenticationRequired.code, 401) + except CSRFError: + return error(CSRFError.code, 403) + return None + + @app.teardown_request + def finish_request(_error): + budget = getattr(g, "_registry_dev_budget", None) + if budget is not None: + budget.__exit__(None, None, None) + + @app.get("/auth/dev") + def registry_dev_login(): + form = picker.begin() + response = Response(_picker_html(form), content_type="text/html; charset=utf-8") + response.set_cookie( + picker.pending_cookie, form.pending_id, secure=False, httponly=True, + samesite="Strict", path="/auth/dev", + ) + response.headers["Cache-Control"] = "no-store" + return response + + @app.post("/auth/dev") + def registry_dev_select(): + try: + values = _parse_form(request.content_type or "", request.get_data(cache=True)) + if request.cookies.get(picker.pending_cookie) != values["pending_id"]: + raise PickerAdmissionError() + session = picker.select( + values["pending_id"], + selector=values["selector"], + origin=request.headers.get("Origin", ""), + host=request.host, + csrf_token=values["csrf_token"], + ) + except PickerAdmissionError: + return error(PickerAdmissionError.code, 403) + response = redirect("/") + response.set_cookie( + picker.session_cookie, session.session_id, secure=False, httponly=True, + samesite="Strict", path="/", + ) + _clear_cookie(response, picker.pending_cookie) + response.headers["Cache-Control"] = "no-store" + return response + + @app.post("/auth/dev/logout") + def registry_dev_logout(): + try: + authorized_mutation() + except ReauthenticationRequired: + return error(ReauthenticationRequired.code, 401) + except (CSRFError, PickerAdmissionError): + return error(CSRFError.code, 403) + picker.logout(request.cookies[picker.session_cookie]) + response = redirect("/auth/dev") + _clear_cookie(response, picker.session_cookie) + response.headers["Cache-Control"] = "no-store" + return response + + +def install_fastapi( + app: Any, + picker: DevelopmentPicker, + *, + person_factory: Callable[[DevelopmentPerson], Any], + request_seconds: float, +) -> None: + """Protect a loopback FastAPI starter with the same picker contract.""" + import asyncio + from fastapi import Request + from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse + from starlette.routing import Match + from .web import form_csrf_token, is_public + from .workload import request_budget + + # FastAPI resolves deferred annotations from module globals. Preserve the + # core module's lazy optional dependency while exposing the real Request + # type once this integration is explicitly installed. + globals()["Request"] = Request + + if not math.isfinite(request_seconds) or request_seconds <= 0: + raise ValueError("request_seconds must be finite and positive") + picker.choices() + auth_paths = frozenset(("/auth/dev", "/auth/dev/logout")) + + def error(code: str, status: int): + return JSONResponse( + {"code": code}, status_code=status, headers={"Cache-Control": "no-store"} + ) + + def route_is_public(scope: MutableMapping[str, Any]) -> bool: + for route in app.router.routes: + match, _ = route.matches(scope) + if match == Match.FULL: + return is_public(getattr(route, "endpoint", None)) + return False + + def request_origin(request: Request) -> str: + return f"{request.url.scheme}://{request.headers.get('host', '')}" + + async def authorized_mutation(request: Request): + session_id = request.cookies.get(picker.session_cookie) + if not session_id: + raise ReauthenticationRequired() + csrf = request.headers.get("x-csrf-token", "") + if not csrf: + length = request.headers.get("content-length", "") + if length.isascii() and length.isdecimal() and 1 <= int(length) <= _MAXIMUM_FORM_BYTES: + csrf = form_csrf_token( + content_type=request.headers.get("content-type", ""), + content_length=int(length), + body=await request.body(), + ) + return await asyncio.to_thread( + picker.authorize_mutation, + session_id, + origin=request.headers.get("origin", ""), + csrf_token=csrf, + ) + + @app.middleware("http") + async def admit_request(request: Request, call_next: Callable): + with request_budget(request_seconds): + try: + await asyncio.to_thread(picker._check_live) + except PickerUnavailable: + return error(PickerUnavailable.code, 503) + if request_origin(request) != picker.origin: + return error("development-picker.origin-refused", 400) + if request.url.path in auth_paths or route_is_public(request.scope): + return await call_next(request) + session_id = request.cookies.get(picker.session_cookie) + if not session_id: + return error(ReauthenticationRequired.code, 401) + try: + context = ( + await asyncio.to_thread(picker.context, session_id) + if request.method in ("GET", "HEAD", "OPTIONS") + else await authorized_mutation(request) + ) + request.state.registry_person = await asyncio.to_thread( + person_factory, context + ) + except ReauthenticationRequired: + return error(ReauthenticationRequired.code, 401) + except (CSRFError, PickerAdmissionError): + return error(CSRFError.code, 403) + return await call_next(request) + + @app.get("/auth/dev") + async def registry_dev_login(): + form = await asyncio.to_thread(picker.begin) + response = HTMLResponse( + _picker_html(form), headers={"Cache-Control": "no-store"} + ) + response.set_cookie( + picker.pending_cookie, form.pending_id, secure=False, httponly=True, + samesite="strict", path="/auth/dev", + ) + return response + + @app.post("/auth/dev") + async def registry_dev_select(request: Request): + try: + values = _parse_form( + request.headers.get("content-type", ""), await request.body() + ) + if request.cookies.get(picker.pending_cookie) != values["pending_id"]: + raise PickerAdmissionError() + session = await asyncio.to_thread( + picker.select, + values["pending_id"], + selector=values["selector"], + origin=request.headers.get("origin", ""), + host=request.headers.get("host", ""), + csrf_token=values["csrf_token"], + ) + except PickerAdmissionError: + return error(PickerAdmissionError.code, 403) + response = RedirectResponse("/", status_code=302) + response.set_cookie( + picker.session_cookie, session.session_id, secure=False, httponly=True, + samesite="strict", path="/", + ) + _clear_cookie(response, picker.pending_cookie) + response.headers["Cache-Control"] = "no-store" + return response + + @app.post("/auth/dev/logout") + async def registry_dev_logout(request: Request): + try: + await authorized_mutation(request) + except ReauthenticationRequired: + return error(ReauthenticationRequired.code, 401) + except (CSRFError, PickerAdmissionError): + return error(CSRFError.code, 403) + picker.logout(request.cookies[picker.session_cookie]) + response = RedirectResponse("/auth/dev", status_code=302) + _clear_cookie(response, picker.session_cookie) + response.headers["Cache-Control"] = "no-store" + return response diff --git a/crates/registry-stack-client-py/python/registry_client/dev_picker.pyi b/crates/registry-stack-client-py/python/registry_client/dev_picker.pyi new file mode 100644 index 0000000000..4bf869c631 --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/dev_picker.pyi @@ -0,0 +1,90 @@ +from pathlib import Path +from typing import Any, Callable + +from .connection import Connection +from .workload_breg import BRegWorkload +from .workload_casework import CaseworkWorkload + +class PickerUnavailable(ValueError): + code: str +class PickerAdmissionError(ValueError): + code: str + +class PickerChoice: + label: str + selector: str + +class PickerForm: + pending_id: str + csrf_token: str + choices: tuple[PickerChoice, ...] + +class PickerSession: + session_id: str + csrf_token: str + expires_at: float + +class DevelopmentPerson: + @property + def session_id(self) -> str: ... + @property + def subject(self) -> str: ... + @property + def principal(self) -> str: ... + @property + def persona(self) -> str: ... + @property + def csrf_token(self) -> str: ... + @property + def expires_at(self) -> float: ... + @property + def breg(self) -> BRegWorkload: ... + @property + def casework(self) -> CaseworkWorkload: ... + +class DevelopmentPicker: + @classmethod + def from_descriptor(cls, path: str | Path) -> DevelopmentPicker: ... + @property + def origin(self) -> str: ... + @property + def persona(self) -> str: ... + @property + def session_cookie(self) -> str: ... + @property + def pending_cookie(self) -> str: ... + @property + def workloads(self) -> Connection: ... + def choices(self) -> tuple[PickerChoice, ...]: ... + def begin(self) -> PickerForm: ... + def select( + self, + pending_id: str, + *, + selector: str, + origin: str, + host: str, + csrf_token: str, + ) -> PickerSession: ... + def context(self, session_id: str) -> DevelopmentPerson: ... + def authorize_mutation( + self, session_id: str, *, origin: str, csrf_token: str + ) -> DevelopmentPerson: ... + def logout(self, session_id: str) -> None: ... + def session_count(self) -> int: ... + +def install_flask( + app: Any, + picker: DevelopmentPicker, + *, + person_factory: Callable[[DevelopmentPerson], Any], + request_seconds: float, +) -> None: ... + +def install_fastapi( + app: Any, + picker: DevelopmentPicker, + *, + person_factory: Callable[[DevelopmentPerson], Any], + request_seconds: float, +) -> None: ... diff --git a/crates/registry-stack-client-py/python/registry_client/fastapi_adapter.py b/crates/registry-stack-client-py/python/registry_client/fastapi_adapter.py new file mode 100644 index 0000000000..cbdc32fe34 --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/fastapi_adapter.py @@ -0,0 +1,47 @@ +"""FastAPI request translation for a configured Registry Stack service.""" + +from __future__ import annotations + +import asyncio +from typing import Any + +from .machine import AdmissionError, AdmissionUnavailable +from .web import is_public +from .workload import request_budget + + +def install(app: Any, stack: Any, *, request_seconds: float) -> None: + """Protect every route unless its endpoint is explicitly decorated public.""" + from fastapi import Request + from fastapi.responses import JSONResponse + from starlette.routing import Match + + def route_is_public(scope: dict[str, Any]) -> bool: + for route in app.router.routes: + match, _ = route.matches(scope) + if match == Match.FULL: + return is_public(getattr(route, "endpoint", None)) + return False + + @app.middleware("http") + async def admit_request(request: Request, call_next): + with request_budget(request_seconds): + if not route_is_public(request.scope): + try: + request.state.registry_context = await asyncio.to_thread( + stack.admit, + {"authorization": request.headers.getlist("authorization")}, + ) + except AdmissionError: + return JSONResponse( + {"code": AdmissionError.code}, + status_code=401, + headers={"Cache-Control": "no-store"}, + ) + except AdmissionUnavailable: + return JSONResponse( + {"code": AdmissionUnavailable.code}, + status_code=503, + headers={"Cache-Control": "no-store"}, + ) + return await call_next(request) diff --git a/crates/registry-stack-client-py/python/registry_client/fastapi_adapter.pyi b/crates/registry-stack-client-py/python/registry_client/fastapi_adapter.pyi new file mode 100644 index 0000000000..45ef5131f1 --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/fastapi_adapter.pyi @@ -0,0 +1,5 @@ +from fastapi import FastAPI + +from .connection import Connection + +def install(app: FastAPI, stack: Connection, *, request_seconds: float) -> None: ... diff --git a/crates/registry-stack-client-py/python/registry_client/flask_adapter.py b/crates/registry-stack-client-py/python/registry_client/flask_adapter.py new file mode 100644 index 0000000000..2d09d1ebf9 --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/flask_adapter.py @@ -0,0 +1,44 @@ +"""Flask request translation for a configured Registry Stack service.""" + +from __future__ import annotations + +from typing import Any + +from .machine import AdmissionError, AdmissionUnavailable +from .web import is_public +from .workload import request_budget + + +def install(app: Any, stack: Any, *, request_seconds: float) -> None: + """Protect every route unless its view is explicitly decorated public.""" + from flask import g, jsonify, request + + @app.before_request + def admit_request(): + budget = request_budget(request_seconds) + budget.__enter__() + g._registry_budget = budget + view = app.view_functions.get(request.endpoint) + if is_public(view): + return None + try: + g.registry_context = stack.admit( + {"authorization": request.headers.getlist("Authorization")} + ) + except AdmissionError: + response = jsonify({"code": AdmissionError.code}) + response.status_code = 401 + response.headers["Cache-Control"] = "no-store" + return response + except AdmissionUnavailable: + response = jsonify({"code": AdmissionUnavailable.code}) + response.status_code = 503 + response.headers["Cache-Control"] = "no-store" + return response + return None + + @app.teardown_request + def finish_request(_error): + budget = getattr(g, "_registry_budget", None) + if budget is not None: + budget.__exit__(None, None, None) diff --git a/crates/registry-stack-client-py/python/registry_client/flask_adapter.pyi b/crates/registry-stack-client-py/python/registry_client/flask_adapter.pyi new file mode 100644 index 0000000000..9bfe693715 --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/flask_adapter.pyi @@ -0,0 +1,5 @@ +from flask import Flask + +from .connection import Connection + +def install(app: Flask, stack: Connection, *, request_seconds: float) -> None: ... diff --git a/crates/registry-stack-client-py/python/registry_client/machine.py b/crates/registry-stack-client-py/python/registry_client/machine.py new file mode 100644 index 0000000000..aa99d3205f --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/machine.py @@ -0,0 +1,124 @@ +"""Framework-neutral admission of a caller to one machine service.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Mapping, Protocol + + +class AdmissionError(ValueError): + """The request has no verified machine authority for this service.""" + + code = "authentication.refused" + + def __init__(self): + super().__init__(self.code) + + +class AdmissionUnavailable(RuntimeError): + """The verifier cannot establish caller authority at this time.""" + + code = "authentication.unavailable" + + def __init__(self): + super().__init__(self.code) + + +class _Verifier(Protocol): + def verify(self, token: str) -> Any: ... + + +@dataclass(frozen=True) +class MachineContext: + """A verified invoker, separate from the service's workload bindings.""" + + subject: str + client_id: str + profile: str + issuer: str + resource: str + persona: str = "service" + + +class MachineAdmission: + """Apply exact machine persona policy after native signature verification.""" + + def __init__( + self, + verifier: _Verifier, + *, + issuer: str, + resource: str, + client_id: str, + profile: str, + required_scopes: tuple[str, ...], + required_claims: Mapping[str, str], + ): + self._verifier = verifier + self._issuer = issuer + self._resource = resource + self._client_id = client_id + self._profile = profile + self._required_scopes = frozenset(required_scopes) + self._required_claims = dict(required_claims) + if ( + not issuer + or not resource + or not client_id + or not profile + or not required_scopes + or not required_claims + ): + raise ValueError( + "machine admission needs exact client, profile, scope and claim policy" + ) + + def admit(self, request_values: Mapping[str, Any]) -> MachineContext: + """Read exactly one bearer; cookies and browser headers confer no authority.""" + authorization = request_values.get("authorization") + if isinstance(authorization, str): + headers = (authorization,) + elif isinstance(authorization, (list, tuple)): + headers = tuple(authorization) + else: + headers = () + if len(headers) != 1 or not isinstance(headers[0], str): + raise AdmissionError() + header = headers[0] + if ( + not header.startswith("Bearer ") + or len(header) > 8192 + or not header[7:] + or any(char.isspace() for char in header[7:]) + ): + raise AdmissionError() + try: + verified = self._verifier.verify(header[7:]) + except Exception as exc: + if getattr(exc, "kind", None) == "verification": + raise AdmissionError() from None + raise AdmissionUnavailable() from None + claims = getattr(verified, "claims", None) + scopes = getattr(verified, "scopes", None) + if ( + getattr(verified, "kind", None) != "access" + or getattr(verified, "issuer", None) != self._issuer + or getattr(verified, "audiences", None) != (self._resource,) + or getattr(verified, "client_id", None) != self._client_id + or not getattr(verified, "subject", None) + or not isinstance(scopes, (tuple, list)) + or not self._required_scopes.issubset(scopes) + or not isinstance(claims, Mapping) + or any( + claims.get(name) != value + for name, value in self._required_claims.items() + ) + ): + raise AdmissionError() + return MachineContext( + verified.subject, + verified.client_id, + self._profile, + verified.issuer, + self._resource, + ) diff --git a/crates/registry-stack-client-py/python/registry_client/machine.pyi b/crates/registry-stack-client-py/python/registry_client/machine.pyi new file mode 100644 index 0000000000..a6223471be --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/machine.pyi @@ -0,0 +1,33 @@ +from typing import Any, Mapping, Protocol + +class AdmissionError(ValueError): + code: str + +class AdmissionUnavailable(RuntimeError): + code: str + def __init__(self) -> None: ... + +class TokenVerifier(Protocol): + def verify(self, token: str) -> Any: ... + +class MachineContext: + subject: str + client_id: str + profile: str + issuer: str + resource: str + persona: str + +class MachineAdmission: + def __init__( + self, + verifier: TokenVerifier, + *, + issuer: str, + resource: str, + client_id: str, + profile: str, + required_scopes: tuple[str, ...], + required_claims: Mapping[str, str], + ) -> None: ... + def admit(self, request_values: Mapping[str, Any]) -> MachineContext: ... diff --git a/crates/registry-stack-client-py/python/registry_client/portal.py b/crates/registry-stack-client-py/python/registry_client/portal.py new file mode 100644 index 0000000000..b904e56d00 --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/portal.py @@ -0,0 +1,896 @@ +"""Framework-neutral OIDC sign-in and renewable server-side sessions. + +Authlib owns authorization-code, PKCE, token endpoint, and refresh protocol +mechanics. This module owns the Registry Stack binding across resource grants +and the atomic session lifecycle. Framework adapters own cookies and routes. +""" + +from __future__ import annotations + +from contextlib import contextmanager +from dataclasses import dataclass, replace +import hmac +import math +import secrets +import threading +import time +from types import MappingProxyType +from typing import Any, Callable, ContextManager, Iterator, Mapping, Protocol +from urllib.parse import parse_qs, urlencode, urlsplit, urlunsplit +from weakref import WeakValueDictionary + + +class AdmissionError(ValueError): + """A browser callback did not establish the complete configured identity.""" + + code = "authentication.refused" + + def __init__(self): + super().__init__(self.code) + + +class ReauthenticationRequired(ValueError): + """No complete usable server-side session remains.""" + + code = "authentication.reauthenticate" + + def __init__(self): + super().__init__(self.code) + + +class CSRFError(ValueError): + """A cookie-authorized mutation failed its origin or CSRF binding.""" + + code = "authentication.csrf-refused" + + def __init__(self): + super().__init__(self.code) + + +@dataclass(frozen=True) +class GrantPolicy: + """One required product grant for a configured holder or staff persona.""" + + name: str + resource: str + scopes: tuple[str, ...] + profile: str + required_claims: Mapping[str, str] + forward_resource: str | None = None + + def __post_init__(self): + if ( + not _token(self.name) + or not _resource_uri(self.resource) + or not self.scopes + or len(set(self.scopes)) != len(self.scopes) + or any(not _token(scope) for scope in self.scopes) + or not _token(self.profile) + or not self.required_claims + or any( + not _token(name) or not _text(value) + for name, value in self.required_claims.items() + ) + or ( + self.forward_resource is not None + and ( + not _resource_uri(self.forward_resource) + or self.forward_resource == self.resource + ) + ) + ): + raise ValueError( + "grant policy needs exact resource, profile, scopes and claims" + ) + object.__setattr__(self, "scopes", tuple(self.scopes)) + object.__setattr__( + self, "required_claims", MappingProxyType(dict(self.required_claims)) + ) + + @property + def requested_resources(self) -> tuple[str, ...]: + if self.forward_resource is None: + return (self.resource,) + return (self.resource, self.forward_resource) + + +@dataclass(frozen=True) +class PortalConfig: + issuer: str + client_id: str + redirect_uri: str + origin: str + persona: str + grants: tuple[GrantPolicy, ...] + session_seconds: float = 900 + pending_seconds: float = 300 + + def __post_init__(self): + if ( + not _absolute_url(self.issuer) + or not _token(self.client_id) + or not _absolute_url(self.redirect_uri) + or not _origin(self.origin) + or self.persona not in ("holder", "staff") + or not self.grants + or not math.isfinite(self.session_seconds) + or self.session_seconds <= 0 + or not math.isfinite(self.pending_seconds) + or self.pending_seconds <= 0 + ): + raise ValueError("portal configuration is incomplete or unsafe") + redirect = urlsplit(self.redirect_uri) + origin = urlsplit(self.origin) + if (redirect.scheme, redirect.netloc) != (origin.scheme, origin.netloc): + raise ValueError("redirect_uri must use the configured origin") + names = [grant.name for grant in self.grants] + resources = [grant.resource for grant in self.grants] + if len(set(names)) != len(names) or len(set(resources)) != len(resources): + raise ValueError("portal grants need distinct names and resources") + object.__setattr__(self, "grants", tuple(self.grants)) + + +@dataclass(frozen=True, repr=False) +class VerifiedGrant: + """A token set already verified by the configured token verifier.""" + + access_token: str + refresh_token: str + id_token: str | None + expires_at: float + issuer: str + client_id: str + subject: str + principal: str + persona: str + resource: str + profile: str + scopes: tuple[str, ...] + claims: Mapping[str, Any] + authorized_party: str | None = None + client_id_claim: str | None = None + + def __post_init__(self): + object.__setattr__(self, "scopes", tuple(self.scopes)) + object.__setattr__(self, "claims", MappingProxyType(dict(self.claims))) + + +@dataclass(frozen=True, repr=False) +class PendingGrant: + state: str + chain_id: str + nonce: str + code_verifier: str + grant_index: int + created_at: float + expires_at: float + return_to: str + grants: tuple[VerifiedGrant, ...] + + +@dataclass(frozen=True) +class AuthorizationRequest: + url: str + state: str + chain_id: str + + +@dataclass(frozen=True) +class CallbackResult: + authorization: AuthorizationRequest | None + session_id: str | None + return_to: str | None + + +@dataclass(frozen=True) +class LogoutResult: + end_session_url: str | None + issuer_logout_available: bool + + +@dataclass(frozen=True, repr=False) +class PortalContext: + session_id: str + subject: str + principal: str + persona: str + _access_tokens: Mapping[str, str] + csrf_token: str + expires_at: float + + def __post_init__(self): + object.__setattr__( + self, "_access_tokens", MappingProxyType(dict(self._access_tokens)) + ) + + def _token_for(self, product: str) -> str: + """Internal adapter hook; holder handlers receive product clients instead.""" + try: + return self._access_tokens[product] + except KeyError: + raise ReauthenticationRequired() from None + + +@dataclass(frozen=True, repr=False) +class PortalSession: + session_id: str + subject: str + principal: str + persona: str + grants: tuple[VerifiedGrant, ...] + csrf_token: str + created_at: float + expires_at: float + generation: int + + +class OIDCClient(Protocol): + def authorization_url( + self, + grant_policy: GrantPolicy, + *, + state: str, + nonce: str, + code_verifier: str, + ) -> str: ... + + def exchange( + self, callback_url: str, pending: PendingGrant, grant_policy: GrantPolicy + ) -> VerifiedGrant: ... + + def refresh( + self, current: VerifiedGrant, grant_policy: GrantPolicy + ) -> VerifiedGrant: ... + + def end_session_url( + self, session: PortalSession, *, state: str, switch: bool = False + ) -> str: ... + + +class SessionStore(Protocol): + def refresh_lock(self, session_id: str) -> ContextManager[None]: ... + + def put_pending(self, pending: PendingGrant) -> bool: ... + + def consume_pending(self, state: str) -> PendingGrant | None: ... + + def close_chain(self, chain_id: str) -> None: ... + + def create_session(self, chain_id: str, session: PortalSession) -> bool: ... + + def get_session(self, session_id: str) -> PortalSession | None: ... + + def replace_session( + self, session_id: str, expected_generation: int, session: PortalSession + ) -> bool: ... + + def delete_session( + self, session_id: str, expected_generation: int | None = None + ) -> PortalSession | None: ... + + +class MemorySessionStore: + """Single-process session state. A new store intentionally loses all sessions.""" + + def __init__(self): + self._pending: dict[str, PendingGrant] = {} + self._sessions: dict[str, PortalSession] = {} + self._closed_chains: set[str] = set() + self._lock = threading.Lock() + self._refresh_locks = WeakValueDictionary() + self._refresh_locks_guard = threading.Lock() + + @contextmanager + def refresh_lock(self, session_id: str) -> Iterator[None]: + with self._refresh_locks_guard: + lock = self._refresh_locks.get(session_id) + if lock is None: + lock = threading.Lock() + self._refresh_locks[session_id] = lock + with lock: + yield + + def put_pending(self, pending: PendingGrant) -> bool: + with self._lock: + if ( + pending.chain_id in self._closed_chains + or pending.state in self._pending + ): + return False + self._pending[pending.state] = pending + return True + + def consume_pending(self, state: str) -> PendingGrant | None: + with self._lock: + pending = self._pending.pop(state, None) + if pending is None or pending.chain_id in self._closed_chains: + return None + return pending + + def close_chain(self, chain_id: str) -> None: + with self._lock: + self._closed_chains.add(chain_id) + self._pending = { + state: pending + for state, pending in self._pending.items() + if pending.chain_id != chain_id + } + + def create_session(self, chain_id: str, session: PortalSession) -> bool: + with self._lock: + if chain_id in self._closed_chains or session.session_id in self._sessions: + return False + self._sessions[session.session_id] = session + self._closed_chains.add(chain_id) + return True + + def get_session(self, session_id: str) -> PortalSession | None: + with self._lock: + return self._sessions.get(session_id) + + def replace_session( + self, session_id: str, expected_generation: int, session: PortalSession + ) -> bool: + with self._lock: + current = self._sessions.get(session_id) + if current is None or current.generation != expected_generation: + return False + self._sessions[session_id] = session + return True + + def delete_session( + self, session_id: str, expected_generation: int | None = None + ) -> PortalSession | None: + with self._lock: + current = self._sessions.get(session_id) + if current is None or ( + expected_generation is not None + and current.generation != expected_generation + ): + return None + return self._sessions.pop(session_id) + + def session_count(self) -> int: + with self._lock: + return len(self._sessions) + + +class PortalSessions: + """Complete multi-resource sign-in and generation-checked renewal.""" + + def __init__( + self, + config: PortalConfig, + oidc: OIDCClient, + store: SessionStore, + *, + clock: Callable[[], float] = time.time, + ): + self._config = config + self._oidc = oidc + self._store = store + self._clock = clock + + def start(self, return_to: str = "/") -> AuthorizationRequest: + _return_target(return_to) + chain_id = secrets.token_urlsafe(32) + return self._authorization(chain_id, 0, (), return_to) + + def replace_account( + self, session_id: str, return_to: str = "/" + ) -> AuthorizationRequest: + self._store.delete_session(session_id) + return self.start(return_to) + + def callback(self, callback_url: str, *, state: str) -> CallbackResult: + pending = self._store.consume_pending(state) + if pending is None: + raise AdmissionError() + now = self._clock() + try: + if ( + pending.expires_at <= now + or not _same_callback(callback_url, self._config.redirect_uri) + or not _callback_state(callback_url, state) + ): + raise AdmissionError() + grant_policy = self._config.grants[pending.grant_index] + grant = self._oidc.exchange(callback_url, pending, grant_policy) + if not grant.id_token: + raise AdmissionError() + self._validate_grant(grant, grant_policy, now) + grants = pending.grants + (grant,) + if grants[:-1]: + baseline = grants[0] + if ( + grant.issuer != baseline.issuer + or grant.client_id != baseline.client_id + or grant.subject != baseline.subject + or grant.principal != baseline.principal + or grant.persona != baseline.persona + ): + raise AdmissionError() + next_index = pending.grant_index + 1 + if next_index < len(self._config.grants): + request = self._authorization( + pending.chain_id, next_index, grants, pending.return_to + ) + return CallbackResult(request, None, None) + session_id = secrets.token_urlsafe(32) + session = PortalSession( + session_id=session_id, + subject=grant.subject, + principal=grant.principal, + persona=grant.persona, + grants=grants, + csrf_token=secrets.token_urlsafe(32), + created_at=now, + expires_at=now + self._config.session_seconds, + generation=0, + ) + if not self._store.create_session(pending.chain_id, session): + raise AdmissionError() + return CallbackResult(None, session_id, pending.return_to) + except AdmissionError: + self._store.close_chain(pending.chain_id) + raise + except Exception: + self._store.close_chain(pending.chain_id) + raise AdmissionError() from None + + def cancel(self, chain_id: str) -> None: + self._store.close_chain(chain_id) + + def context( + self, session_id: str, *, minimum_valid_seconds: float = 30 + ) -> PortalContext: + if minimum_valid_seconds < 0 or not math.isfinite(minimum_valid_seconds): + raise ValueError("minimum_valid_seconds must be finite and nonnegative") + session = self._store.get_session(session_id) + now = self._clock() + if session is None or session.expires_at <= now: + if session is not None: + self._store.delete_session(session_id, session.generation) + raise ReauthenticationRequired() + if any( + grant.expires_at <= now + minimum_valid_seconds for grant in session.grants + ): + session = self._refresh(session, minimum_valid_seconds) + return self._context(session) + + def authorize_mutation( + self, session_id: str, *, origin: str, csrf_token: str + ) -> PortalContext: + context = self.context(session_id, minimum_valid_seconds=0) + if origin != self._config.origin or not hmac.compare_digest( + csrf_token, context.csrf_token + ): + raise CSRFError() + return context + + def logout(self, session_id: str, *, switch: bool = False) -> LogoutResult: + session = self._store.delete_session(session_id) + if session is None: + return LogoutResult(None, False) + try: + url = self._oidc.end_session_url( + session, state=secrets.token_urlsafe(24), switch=switch + ) + return LogoutResult(url, True) + except Exception: + return LogoutResult(None, False) + + def _authorization( + self, + chain_id: str, + grant_index: int, + grants: tuple[VerifiedGrant, ...], + return_to: str, + ) -> AuthorizationRequest: + now = self._clock() + pending = PendingGrant( + state=secrets.token_urlsafe(32), + chain_id=chain_id, + nonce=secrets.token_urlsafe(32), + code_verifier=secrets.token_urlsafe(64), + grant_index=grant_index, + created_at=now, + expires_at=now + self._config.pending_seconds, + return_to=return_to, + grants=grants, + ) + if not self._store.put_pending(pending): + raise AdmissionError() + try: + url = self._oidc.authorization_url( + self._config.grants[grant_index], + state=pending.state, + nonce=pending.nonce, + code_verifier=pending.code_verifier, + ) + return AuthorizationRequest(url, pending.state, chain_id) + except Exception: + self._store.close_chain(chain_id) + raise AdmissionError() from None + + def _refresh( + self, session: PortalSession, minimum_valid_seconds: float + ) -> PortalSession: + with self._store.refresh_lock(session.session_id): + current = self._store.get_session(session.session_id) + now = self._clock() + if current is None or current.expires_at <= now: + raise ReauthenticationRequired() + if not any( + grant.expires_at <= now + minimum_valid_seconds + for grant in current.grants + ): + return current + return self._refresh_locked(current, minimum_valid_seconds) + + def _refresh_locked( + self, session: PortalSession, minimum_valid_seconds: float + ) -> PortalSession: + now = self._clock() + updated: list[VerifiedGrant] = [] + try: + for grant, policy in zip(session.grants, self._config.grants, strict=True): + candidate = grant + if grant.expires_at <= now + minimum_valid_seconds: + candidate = self._oidc.refresh(grant, policy) + self._validate_grant(candidate, policy, now) + if ( + candidate.subject != session.subject + or candidate.principal != session.principal + or candidate.persona != session.persona + ): + raise AdmissionError() + updated.append(candidate) + except Exception: + current = self._store.get_session(session.session_id) + if current is not None and current.generation != session.generation: + return current + self._store.delete_session(session.session_id, session.generation) + raise ReauthenticationRequired() from None + now = self._clock() + if session.expires_at <= now: + self._store.delete_session(session.session_id, session.generation) + raise ReauthenticationRequired() + replacement = replace( + session, grants=tuple(updated), generation=session.generation + 1 + ) + if self._store.replace_session( + session.session_id, session.generation, replacement + ): + return replacement + current = self._store.get_session(session.session_id) + if current is None or current.expires_at <= now: + raise ReauthenticationRequired() + return current + + def _validate_grant( + self, grant: VerifiedGrant, policy: GrantPolicy, now: float + ) -> None: + if ( + not grant.access_token + or not grant.refresh_token + or not math.isfinite(grant.expires_at) + or grant.expires_at <= now + or grant.issuer != self._config.issuer + or grant.client_id != self._config.client_id + or grant.authorized_party not in (None, self._config.client_id) + or grant.client_id_claim not in (None, self._config.client_id) + or not grant.subject + or not grant.principal + or grant.persona != self._config.persona + or grant.resource != policy.resource + or grant.profile != policy.profile + or not set(policy.scopes).issubset(grant.scopes) + or any( + grant.claims.get(name) != value + for name, value in policy.required_claims.items() + ) + ): + raise AdmissionError() + + def _context(self, session: PortalSession) -> PortalContext: + return PortalContext( + session_id=session.session_id, + subject=session.subject, + principal=session.principal, + persona=session.persona, + _access_tokens={ + grant_policy.name: grant.access_token + for grant_policy, grant in zip( + self._config.grants, session.grants, strict=True + ) + }, + csrf_token=session.csrf_token, + expires_at=session.expires_at, + ) + + +TokenVerifier = Callable[ + [Mapping[str, Any], str | None, GrantPolicy, VerifiedGrant | None], + VerifiedGrant, +] + + +class AuthlibOIDCClient: + """Authlib authorization-code/PKCE transport plus exact token verification.""" + + def __init__( + self, + *, + client_id: str, + client_secret: str | None, + redirect_uri: str, + authorization_endpoint: str, + token_endpoint: str, + end_session_endpoint: str | None, + verify_token: TokenVerifier, + switch_redirect_uri: str | None = None, + timeout_seconds: float = 5, + ): + if ( + not _token(client_id) + or not _absolute_url(redirect_uri) + or not _absolute_url(authorization_endpoint) + or not _absolute_url(token_endpoint) + or ( + end_session_endpoint is not None + and not _absolute_url(end_session_endpoint) + ) + or ( + switch_redirect_uri is not None + and ( + end_session_endpoint is None + or not _absolute_url(switch_redirect_uri) + or switch_redirect_uri + != urlunsplit( + urlsplit(redirect_uri)._replace( + path="/auth/login", query="", fragment="" + ) + ) + ) + ) + or not math.isfinite(timeout_seconds) + or timeout_seconds <= 0 + ): + raise ValueError("Authlib OIDC endpoints and timeout must be bounded") + self._client_id = client_id + self._client_secret = client_secret + self._redirect_uri = redirect_uri + self._authorization_endpoint = authorization_endpoint + self._token_endpoint = token_endpoint + self._end_session_endpoint = end_session_endpoint + self._switch_redirect_uri = switch_redirect_uri + self._verify_token = verify_token + self._timeout_seconds = timeout_seconds + + def authorization_url( + self, + grant_policy: GrantPolicy, + *, + state: str, + nonce: str, + code_verifier: str, + ) -> str: + client = self._session(grant_policy) + try: + url, returned_state = client.create_authorization_url( + self._authorization_endpoint, + state=state, + nonce=nonce, + code_verifier=code_verifier, + resource=( + grant_policy.resource + if grant_policy.forward_resource is None + else grant_policy.requested_resources + ), + ) + finally: + client.close() # pyright: ignore[reportAttributeAccessIssue] + if returned_state != state: + raise AdmissionError() + return url + + def exchange( + self, callback_url: str, pending: PendingGrant, grant_policy: GrantPolicy + ) -> VerifiedGrant: + client = self._session(grant_policy, state=pending.state) + try: + token = client.fetch_token( + self._token_endpoint, + authorization_response=callback_url, + state=pending.state, + code_verifier=pending.code_verifier, + body=urlencode( + [("resource", value) for value in grant_policy.requested_resources] + ), + ) + finally: + client.close() # pyright: ignore[reportAttributeAccessIssue] + return self._verify_token(token, pending.nonce, grant_policy, None) + + def refresh( + self, current: VerifiedGrant, grant_policy: GrantPolicy + ) -> VerifiedGrant: + client = self._session(grant_policy) + try: + token = client.refresh_token( + self._token_endpoint, + refresh_token=current.refresh_token, + body=urlencode( + [("resource", value) for value in grant_policy.requested_resources] + ), + scope=" ".join(grant_policy.scopes), + ) + finally: + client.close() # pyright: ignore[reportAttributeAccessIssue] + if "refresh_token" not in token: + token["refresh_token"] = current.refresh_token + return self._verify_token(token, None, grant_policy, current) + + def end_session_url( + self, session: PortalSession, *, state: str, switch: bool = False + ) -> str: + if self._end_session_endpoint is None: + raise RuntimeError("the issuer has no end-session endpoint") + id_token = next( + (grant.id_token for grant in session.grants if grant.id_token), None + ) + query = {"client_id": self._client_id, "state": state} + if switch: + if self._switch_redirect_uri is None or id_token is None: + raise RuntimeError("the issuer account-switch return is unavailable") + query["post_logout_redirect_uri"] = self._switch_redirect_uri + if id_token is not None: + query["id_token_hint"] = id_token + parts = urlsplit(self._end_session_endpoint) + return urlunsplit(parts._replace(query=urlencode(query))) + + def _session(self, grant_policy: GrantPolicy, *, state: str | None = None): + from authlib.integrations.requests_client import OAuth2Session # pyright: ignore[reportMissingModuleSource] + + class ResourceSession(OAuth2Session): + # Authlib 1.9.6 converts token form fields to a dict, dropping + # repeated RFC 8707 resource parameters. Preserve the form body. + def _fetch_token( + self, url, body="", headers=None, auth=None, method="POST", **kwargs + ): + if method.upper() != "POST": + raise AdmissionError() + response = self.session.post( + url, data=body, headers=headers, auth=auth, **kwargs + ) + for hook in self.compliance_hook["access_token_response"]: + response = hook(response) + return self.parse_response_token(response) + + def _http_post(self, url, body=None, auth=None, headers=None, **kwargs): + return self.session.post( + url, data=body, headers=headers, auth=auth, **kwargs + ) + + scopes = tuple( + dict.fromkeys(("openid", "offline_access", *grant_policy.scopes)) + ) + return ResourceSession( + client_id=self._client_id, + client_secret=self._client_secret, + token_endpoint_auth_method=( + "client_secret_post" if self._client_secret else "none" + ), + redirect_uri=self._redirect_uri, + scope=" ".join(scopes), + state=state, + code_challenge_method="S256", + default_timeout=self._timeout_seconds, + ) + + +def _callback_state(callback_url: str, expected: str) -> bool: + try: + query = parse_qs( + urlsplit(callback_url).query, + strict_parsing=True, + keep_blank_values=True, + max_num_fields=8, + ) + return ( + query.get("state") == [expected] + and len(query.get("code", ())) == 1 + and bool(query["code"][0]) + and "error" not in query + ) + except (ValueError, KeyError): + return False + + +def _same_callback(received: str, configured: str) -> bool: + try: + actual = urlsplit(received) + expected = urlsplit(configured) + except ValueError: + return False + return ( + actual.scheme, + actual.netloc, + actual.path, + actual.fragment, + ) == ( + expected.scheme, + expected.netloc, + expected.path, + "", + ) + + +def _return_target(value: str) -> None: + if ( + not isinstance(value, str) + or not value.startswith("/") + or value.startswith("//") + or any(ord(character) < 32 or ord(character) == 127 for character in value) + ): + raise ValueError("return_to must be a local absolute path") + + +def _absolute_url(value: str) -> bool: + if not _text(value): + return False + try: + parts = urlsplit(value) + except ValueError: + return False + return bool( + parts.scheme == "https" + and parts.hostname + and parts.username is None + and parts.password is None + and not parts.fragment + ) + + +def _resource_uri(value: str) -> bool: + if not _text(value) or any(character.isspace() for character in value): + return False + try: + parts = urlsplit(value) + parts.port + except ValueError: + return False + return bool( + parts.scheme + and (parts.path or parts.netloc) + and not parts.fragment + and parts.username is None + and parts.password is None + and (parts.scheme not in ("http", "https") or parts.hostname) + ) + + +def _origin(value: str) -> bool: + if not _absolute_url(value): + return False + parts = urlsplit(value) + return not parts.path.strip("/") and not parts.query + + +def _token(value: str) -> bool: + return bool( + isinstance(value, str) + and 1 <= len(value) <= 256 + and value.strip() == value + and not any(character.isspace() or ord(character) < 33 for character in value) + ) + + +def _text(value: str) -> bool: + return bool( + isinstance(value, str) + and value + and value.strip() == value + and not any(ord(character) < 32 or ord(character) == 127 for character in value) + ) diff --git a/crates/registry-stack-client-py/python/registry_client/portal.pyi b/crates/registry-stack-client-py/python/registry_client/portal.pyi new file mode 100644 index 0000000000..bced59175a --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/portal.pyi @@ -0,0 +1,239 @@ +from collections.abc import Callable, Mapping +from typing import Any, ContextManager, Protocol + +class AdmissionError(ValueError): + code: str + +class ReauthenticationRequired(ValueError): + code: str + +class CSRFError(ValueError): + code: str + +class GrantPolicy: + name: str + resource: str + scopes: tuple[str, ...] + profile: str + required_claims: Mapping[str, str] + forward_resource: str | None + requested_resources: tuple[str, ...] + def __init__( + self, + name: str, + resource: str, + scopes: tuple[str, ...], + profile: str, + required_claims: Mapping[str, str], + forward_resource: str | None = ..., + ) -> None: ... + +class PortalConfig: + issuer: str + client_id: str + redirect_uri: str + origin: str + persona: str + grants: tuple[GrantPolicy, ...] + session_seconds: float + pending_seconds: float + def __init__( + self, + issuer: str, + client_id: str, + redirect_uri: str, + origin: str, + persona: str, + grants: tuple[GrantPolicy, ...], + session_seconds: float = ..., + pending_seconds: float = ..., + ) -> None: ... + +class VerifiedGrant: + access_token: str + refresh_token: str + id_token: str | None + expires_at: float + issuer: str + client_id: str + subject: str + principal: str + persona: str + resource: str + profile: str + scopes: tuple[str, ...] + claims: Mapping[str, Any] + authorized_party: str | None + client_id_claim: str | None + def __init__( + self, + access_token: str, + refresh_token: str, + id_token: str | None, + expires_at: float, + issuer: str, + client_id: str, + subject: str, + principal: str, + persona: str, + resource: str, + profile: str, + scopes: tuple[str, ...], + claims: Mapping[str, Any], + authorized_party: str | None = ..., + client_id_claim: str | None = ..., + ) -> None: ... + +class PendingGrant: + state: str + chain_id: str + nonce: str + code_verifier: str + grant_index: int + created_at: float + expires_at: float + return_to: str + grants: tuple[VerifiedGrant, ...] + +class AuthorizationRequest: + url: str + state: str + chain_id: str + +class CallbackResult: + authorization: AuthorizationRequest | None + session_id: str | None + return_to: str | None + +class LogoutResult: + end_session_url: str | None + issuer_logout_available: bool + +class PortalContext: + session_id: str + subject: str + principal: str + persona: str + csrf_token: str + expires_at: float + def _token_for(self, product: str) -> str: ... + +class PortalSession: + session_id: str + subject: str + principal: str + persona: str + grants: tuple[VerifiedGrant, ...] + csrf_token: str + created_at: float + expires_at: float + generation: int + +class OIDCClient(Protocol): + def authorization_url( + self, + grant_policy: GrantPolicy, + *, + state: str, + nonce: str, + code_verifier: str, + ) -> str: ... + def exchange( + self, callback_url: str, pending: PendingGrant, grant_policy: GrantPolicy + ) -> VerifiedGrant: ... + def refresh( + self, current: VerifiedGrant, grant_policy: GrantPolicy + ) -> VerifiedGrant: ... + def end_session_url( + self, session: PortalSession, *, state: str, switch: bool = ... + ) -> str: ... + +class SessionStore(Protocol): + def refresh_lock(self, session_id: str) -> ContextManager[None]: ... + def put_pending(self, pending: PendingGrant) -> bool: ... + def consume_pending(self, state: str) -> PendingGrant | None: ... + def close_chain(self, chain_id: str) -> None: ... + def create_session(self, chain_id: str, session: PortalSession) -> bool: ... + def get_session(self, session_id: str) -> PortalSession | None: ... + def replace_session( + self, session_id: str, expected_generation: int, session: PortalSession + ) -> bool: ... + def delete_session( + self, session_id: str, expected_generation: int | None = ... + ) -> PortalSession | None: ... + +class MemorySessionStore(SessionStore): + def __init__(self) -> None: ... + def refresh_lock(self, session_id: str) -> ContextManager[None]: ... + def put_pending(self, pending: PendingGrant) -> bool: ... + def consume_pending(self, state: str) -> PendingGrant | None: ... + def close_chain(self, chain_id: str) -> None: ... + def create_session(self, chain_id: str, session: PortalSession) -> bool: ... + def get_session(self, session_id: str) -> PortalSession | None: ... + def replace_session( + self, session_id: str, expected_generation: int, session: PortalSession + ) -> bool: ... + def delete_session( + self, session_id: str, expected_generation: int | None = ... + ) -> PortalSession | None: ... + def session_count(self) -> int: ... + +class PortalSessions: + def __init__( + self, + config: PortalConfig, + oidc: OIDCClient, + store: SessionStore, + *, + clock: Callable[[], float] = ..., + ) -> None: ... + def start(self, return_to: str = ...) -> AuthorizationRequest: ... + def replace_account( + self, session_id: str, return_to: str = ... + ) -> AuthorizationRequest: ... + def callback(self, callback_url: str, *, state: str) -> CallbackResult: ... + def cancel(self, chain_id: str) -> None: ... + def context( + self, session_id: str, *, minimum_valid_seconds: float = ... + ) -> PortalContext: ... + def authorize_mutation( + self, session_id: str, *, origin: str, csrf_token: str + ) -> PortalContext: ... + def logout(self, session_id: str, *, switch: bool = ...) -> LogoutResult: ... + +TokenVerifier = Callable[ + [Mapping[str, Any], str | None, GrantPolicy, VerifiedGrant | None], + VerifiedGrant, +] + +class AuthlibOIDCClient(OIDCClient): + def __init__( + self, + *, + client_id: str, + client_secret: str | None, + redirect_uri: str, + authorization_endpoint: str, + token_endpoint: str, + end_session_endpoint: str | None, + verify_token: TokenVerifier, + switch_redirect_uri: str | None = ..., + timeout_seconds: float = ..., + ) -> None: ... + def authorization_url( + self, + grant_policy: GrantPolicy, + *, + state: str, + nonce: str, + code_verifier: str, + ) -> str: ... + def exchange( + self, callback_url: str, pending: PendingGrant, grant_policy: GrantPolicy + ) -> VerifiedGrant: ... + def refresh( + self, current: VerifiedGrant, grant_policy: GrantPolicy + ) -> VerifiedGrant: ... + def end_session_url( + self, session: PortalSession, *, state: str, switch: bool = ... + ) -> str: ... diff --git a/crates/registry-stack-client-py/python/registry_client/portal_fastapi.py b/crates/registry-stack-client-py/python/registry_client/portal_fastapi.py new file mode 100644 index 0000000000..a0d51dde3d --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/portal_fastapi.py @@ -0,0 +1,190 @@ +"""FastAPI routes and host-only cookies for a holder or staff portal.""" + +import asyncio +from typing import Any, Callable, MutableMapping + +from .portal import ( + AdmissionError, + CSRFError, + PortalContext, + PortalSessions, + ReauthenticationRequired, +) +from .web import form_csrf_token, is_public +from .workload import request_budget + + +def install( + app: Any, + sessions: PortalSessions, + *, + origin: str, + persona: str, + person_factory: Callable[[PortalContext], Any], + request_seconds: float, + same_site: str = "Lax", +) -> None: + """Protect application routes and mount a complete multi-grant login flow.""" + from fastapi import Request + from fastapi.responses import JSONResponse, RedirectResponse + from starlette.routing import Match + + if persona not in ("holder", "staff") or same_site not in ("Lax", "Strict"): + raise ValueError("portal persona and SameSite policy are unsupported") + cookie_name = f"__Host-registry-{persona}" + auth_paths = frozenset( + ("/auth/login", "/auth/callback", "/auth/logout", "/auth/switch") + ) + + def error(code: str, status: int) -> JSONResponse: + return JSONResponse( + {"code": code}, + status_code=status, + headers={"Cache-Control": "no-store"}, + ) + + def route_is_public(scope: MutableMapping[str, Any]) -> bool: + for route in app.router.routes: + match, _ = route.matches(scope) + if match == Match.FULL: + return is_public(getattr(route, "endpoint", None)) + return False + + def request_origin(request: Request) -> str: + return f"{request.url.scheme}://{request.headers.get('host', '')}" + + def clear_cookie(response: Any) -> None: + response.set_cookie( + cookie_name, + "", + max_age=0, + expires=0, + secure=True, + httponly=True, + samesite="lax" if same_site == "Lax" else "strict", + path="/", + ) + + async def authorized_mutation(request: Request) -> PortalContext: + session_id = request.cookies.get(cookie_name) + if not session_id: + raise ReauthenticationRequired() + csrf_token = request.headers.get("x-csrf-token", "") + length_text = request.headers.get("content-length", "") + if ( + not csrf_token + and request.headers.get("content-type", "").split(";", 1)[0].strip().lower() + == "application/x-www-form-urlencoded" + and length_text.isascii() + and length_text.isdecimal() + and 1 <= int(length_text) <= 65_536 + ): + csrf_token = form_csrf_token( + content_type=request.headers["content-type"], + content_length=int(length_text), + body=await request.body(), + ) + return await asyncio.to_thread( + sessions.authorize_mutation, + session_id, + origin=request.headers.get("origin", ""), + csrf_token=csrf_token, + ) + + @app.middleware("http") + async def admit_request(request: Request, call_next: Callable): + with request_budget(request_seconds): + if request_origin(request) != origin: + return error("authentication.origin-refused", 400) + if request.url.path in auth_paths or route_is_public(request.scope): + return await call_next(request) + session_id = request.cookies.get(cookie_name) + if not session_id: + return error(ReauthenticationRequired.code, 401) + try: + if request.method in ("GET", "HEAD", "OPTIONS"): + context = await asyncio.to_thread(sessions.context, session_id) + else: + context = await authorized_mutation(request) + if context.persona != persona: + raise ReauthenticationRequired() + request.state.registry_person = await asyncio.to_thread( + person_factory, context + ) + except ReauthenticationRequired: + return error(ReauthenticationRequired.code, 401) + except CSRFError: + return error(CSRFError.code, 403) + return await call_next(request) + + @app.get("/auth/login") + async def registry_login(request: Request): + try: + authorization = await asyncio.to_thread( + sessions.start, request.query_params.get("return_to", "/") + ) + except ValueError: + return error(AdmissionError.code, 400) + response = RedirectResponse(authorization.url, status_code=302) + response.headers["Cache-Control"] = "no-store" + return response + + @app.get("/auth/callback") + async def registry_callback(request: Request): + try: + result = await asyncio.to_thread( + sessions.callback, + str(request.url), + state=request.query_params.get("state", ""), + ) + except AdmissionError: + return error(AdmissionError.code, 401) + if result.authorization is not None: + response = RedirectResponse(result.authorization.url, status_code=302) + else: + if result.session_id is None or result.return_to is None: + return error(AdmissionError.code, 401) + response = RedirectResponse(result.return_to, status_code=302) + response.set_cookie( + cookie_name, + result.session_id, + secure=True, + httponly=True, + samesite="lax" if same_site == "Lax" else "strict", + path="/", + ) + response.headers["Cache-Control"] = "no-store" + return response + + @app.post("/auth/logout") + async def registry_logout(request: Request): + try: + await authorized_mutation(request) + except ReauthenticationRequired: + return error(ReauthenticationRequired.code, 401) + except CSRFError: + return error(CSRFError.code, 403) + result = await asyncio.to_thread(sessions.logout, request.cookies[cookie_name]) + response = RedirectResponse(result.end_session_url or "/", status_code=302) + clear_cookie(response) + response.headers["Cache-Control"] = "no-store" + return response + + @app.post("/auth/switch") + async def registry_switch(request: Request): + try: + await authorized_mutation(request) + except ReauthenticationRequired: + return error(ReauthenticationRequired.code, 401) + except CSRFError: + return error(CSRFError.code, 403) + result = await asyncio.to_thread( + sessions.logout, request.cookies[cookie_name], switch=True + ) + if result.end_session_url is not None: + response = RedirectResponse(result.end_session_url, status_code=302) + else: + response = error("authentication.account-switch-unavailable", 409) + clear_cookie(response) + response.headers["Cache-Control"] = "no-store" + return response diff --git a/crates/registry-stack-client-py/python/registry_client/portal_fastapi.pyi b/crates/registry-stack-client-py/python/registry_client/portal_fastapi.pyi new file mode 100644 index 0000000000..1932436485 --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/portal_fastapi.pyi @@ -0,0 +1,14 @@ +from typing import Any, Callable + +from .portal import PortalContext, PortalSessions + +def install( + app: Any, + sessions: PortalSessions, + *, + origin: str, + persona: str, + person_factory: Callable[[PortalContext], Any], + request_seconds: float, + same_site: str = ..., +) -> None: ... diff --git a/crates/registry-stack-client-py/python/registry_client/portal_flask.py b/crates/registry-stack-client-py/python/registry_client/portal_flask.py new file mode 100644 index 0000000000..ae79fc404f --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/portal_flask.py @@ -0,0 +1,166 @@ +"""Flask routes and host-only cookies for a holder or staff portal.""" + +from __future__ import annotations + +from typing import Any, Callable + +from .portal import ( + AdmissionError, + CSRFError, + PortalContext, + PortalSessions, + ReauthenticationRequired, +) +from .web import form_csrf_token, is_public +from .workload import request_budget + + +def install( + app: Any, + sessions: PortalSessions, + *, + origin: str, + persona: str, + person_factory: Callable[[PortalContext], Any], + request_seconds: float, + same_site: str = "Lax", +) -> None: + """Protect application routes and mount a complete multi-grant login flow.""" + from flask import g, jsonify, make_response, redirect, request # pyright: ignore[reportMissingImports] + + if persona not in ("holder", "staff") or same_site not in ("Lax", "Strict"): + raise ValueError("portal persona and SameSite policy are unsupported") + cookie_name = f"__Host-registry-{persona}" + auth_paths = frozenset( + ("/auth/login", "/auth/callback", "/auth/logout", "/auth/switch") + ) + + def error(code: str, status: int): + response = jsonify({"code": code}) + response.status_code = status + response.headers["Cache-Control"] = "no-store" + return response + + def authorized_mutation(): + session_id = request.cookies.get(cookie_name) + if not session_id: + raise ReauthenticationRequired() + csrf_token = request.headers.get("X-CSRF-Token", "") + if not csrf_token and request.mimetype == "application/x-www-form-urlencoded": + length = request.content_length + if length is not None and 1 <= length <= 65_536: + csrf_token = form_csrf_token( + content_type=request.content_type or "", + content_length=length, + body=request.get_data(cache=True), + ) + return sessions.authorize_mutation( + session_id, + origin=request.headers.get("Origin", ""), + csrf_token=csrf_token, + ) + + @app.before_request + def admit_request(): + budget = request_budget(request_seconds) + budget.__enter__() + g._registry_portal_budget = budget + if request.host_url.rstrip("/") != origin: + return error("authentication.origin-refused", 400) + if request.path in auth_paths or is_public( + app.view_functions.get(request.endpoint) + ): + return None + session_id = request.cookies.get(cookie_name) + if not session_id: + return error(ReauthenticationRequired.code, 401) + try: + if request.method in ("GET", "HEAD", "OPTIONS"): + context = sessions.context(session_id) + else: + context = authorized_mutation() + if context.persona != persona: + raise ReauthenticationRequired() + g.registry_person = person_factory(context) + except ReauthenticationRequired: + return error(ReauthenticationRequired.code, 401) + except CSRFError: + return error(CSRFError.code, 403) + return None + + @app.teardown_request + def finish_request(_error): + budget = getattr(g, "_registry_portal_budget", None) + if budget is not None: + budget.__exit__(None, None, None) + + @app.get("/auth/login") + def registry_login(): + try: + authorization = sessions.start(request.args.get("return_to", "/")) + except ValueError: + return error(AdmissionError.code, 400) + response = redirect(authorization.url) + response.headers["Cache-Control"] = "no-store" + return response + + @app.get("/auth/callback") + def registry_callback(): + try: + result = sessions.callback(request.url, state=request.args.get("state", "")) + except AdmissionError: + return error(AdmissionError.code, 401) + if result.authorization is not None: + response = redirect(result.authorization.url) + else: + if result.session_id is None or result.return_to is None: + return error(AdmissionError.code, 401) + response = redirect(result.return_to) + response.set_cookie( + cookie_name, + result.session_id, + secure=True, + httponly=True, + samesite=same_site, + path="/", + ) + response.headers["Cache-Control"] = "no-store" + return response + + @app.post("/auth/logout") + def registry_logout(): + try: + authorized_mutation() + except ReauthenticationRequired: + return error(ReauthenticationRequired.code, 401) + except CSRFError: + return error(CSRFError.code, 403) + result = sessions.logout(request.cookies[cookie_name]) + response = redirect(result.end_session_url or "/") + response.delete_cookie( + cookie_name, path="/", secure=True, httponly=True, samesite=same_site + ) + response.headers["Cache-Control"] = "no-store" + return response + + @app.post("/auth/switch") + def registry_switch(): + try: + authorized_mutation() + except ReauthenticationRequired: + return error(ReauthenticationRequired.code, 401) + except CSRFError: + return error(CSRFError.code, 403) + result = sessions.logout(request.cookies[cookie_name], switch=True) + response = ( + redirect(result.end_session_url) + if result.end_session_url is not None + else make_response( + jsonify({"code": "authentication.account-switch-unavailable"}), 409 + ) + ) + response.delete_cookie( + cookie_name, path="/", secure=True, httponly=True, samesite=same_site + ) + response.headers["Cache-Control"] = "no-store" + return response diff --git a/crates/registry-stack-client-py/python/registry_client/portal_flask.pyi b/crates/registry-stack-client-py/python/registry_client/portal_flask.pyi new file mode 100644 index 0000000000..1932436485 --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/portal_flask.pyi @@ -0,0 +1,14 @@ +from typing import Any, Callable + +from .portal import PortalContext, PortalSessions + +def install( + app: Any, + sessions: PortalSessions, + *, + origin: str, + persona: str, + person_factory: Callable[[PortalContext], Any], + request_seconds: float, + same_site: str = ..., +) -> None: ... diff --git a/crates/registry-stack-client-py/python/registry_client/portal_postgres.py b/crates/registry-stack-client-py/python/registry_client/portal_postgres.py new file mode 100644 index 0000000000..7e6a697d1d --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/portal_postgres.py @@ -0,0 +1,852 @@ +"""Encrypted PostgreSQL persistence for :mod:`registry_client.portal`. + +The caller resolves operator-managed encryption keys and supplies a connection +factory. Browser cookie secrets are deliberately not accepted. Migrations and +key rotation are explicit operator actions; ordinary reads and writes refuse a +missing or changed migration and coordinate on the database's active key. +""" + +from __future__ import annotations + +from collections.abc import Callable, Iterator, Mapping +from contextlib import contextmanager +import hashlib +import json +import math +from pathlib import Path +import secrets +from typing import Any + +from .portal import PendingGrant, PortalSession, VerifiedGrant + + +_FORMAT = 1 +_MAX_PLAINTEXT_BYTES = 1024 * 1024 +_MIGRATION_VERSION = 1 +_MIGRATION_PATH = Path(__file__).with_name("_sql") / "portal_postgres_v1.sql" +_PendingGrantConstructor: Any = PendingGrant +_PortalSessionConstructor: Any = PortalSession + + +class SessionStoreError(RuntimeError): + """The durable portal store could not safely complete an operation.""" + + code = "authentication.session-store-unavailable" + + def __init__(self, message: str = "portal session store is unavailable"): + super().__init__(message) + + +class SessionStateError(SessionStoreError): + """Persisted portal state or its migration cannot be trusted.""" + + code = "authentication.session-state-invalid" + + +class PortalEncryptionKeys: + """Operator-supplied AES-256-GCM keys with one intended rotation target.""" + + __slots__ = ("_ciphers", "_primary_key_id") + + def __init__(self, *, primary_key_id: str, keys: Mapping[str, bytes]): + try: + from cryptography.hazmat.primitives.ciphers.aead import AESGCM # pyright: ignore[reportMissingImports] + except ImportError: + raise RuntimeError( + "encrypted portal sessions require the cryptography package" + ) from None + if not _identifier(primary_key_id) or primary_key_id not in keys or not keys: + raise ValueError("portal encryption keys need a valid primary key id") + ciphers: dict[str, Any] = {} + for key_id, material in keys.items(): + if ( + not _identifier(key_id) + or not isinstance(material, bytes) + or len(material) != 32 + ): + raise ValueError( + "each portal encryption key must be 32 bytes with a valid id" + ) + ciphers[key_id] = AESGCM(material) + self._primary_key_id = primary_key_id + self._ciphers = ciphers + + @property + def primary_key_id(self) -> str: + return self._primary_key_id + + def __repr__(self) -> str: + return "PortalEncryptionKeys()" + + def _contains(self, key_id: str) -> bool: + return key_id in self._ciphers + + def _seal( + self, + key_id: str, + kind: str, + lookup_digest: bytes, + generation: int, + plaintext: bytes, + ) -> bytes: + cipher = self._ciphers.get(key_id) + if cipher is None: + raise SessionStateError("portal session encryption key is unavailable") + nonce = secrets.token_bytes(12) + return nonce + cipher.encrypt( + nonce, + plaintext, + _associated_data(kind, lookup_digest, generation), + ) + + def _open( + self, + key_id: str, + kind: str, + lookup_digest: bytes, + generation: int, + ciphertext: bytes, + ) -> bytes: + cipher = self._ciphers.get(key_id) + if cipher is None or len(ciphertext) < 29: + raise SessionStateError("portal session state is unreadable") + nonce, encrypted = ciphertext[:12], ciphertext[12:] + try: + plaintext = cipher.decrypt( + nonce, + encrypted, + _associated_data(kind, lookup_digest, generation), + ) + except Exception: + raise SessionStateError("portal session state is unreadable") from None + if len(plaintext) > _MAX_PLAINTEXT_BYTES: + raise SessionStateError("portal session state is unreadable") + return plaintext + + +class PostgresSessionStore: + """Cross-worker portal state with encrypted payloads and generation CAS.""" + + def __init__(self, connect: Callable[[], Any], keys: PortalEncryptionKeys): + if not callable(connect) or not isinstance(keys, PortalEncryptionKeys): + raise TypeError("PostgresSessionStore needs a connection factory and keys") + self._connect = connect + self._keys = keys + + def migrate(self) -> None: + """Apply schema v1 and bind a fresh store to the configured primary key.""" + sql, checksum = _migration() + try: + with self._connect() as connection: + with connection.cursor() as cursor: + cursor.execute(sql) + cursor.execute( + "SELECT version, checksum " + "FROM registry_client_portal.migrations " + "ORDER BY version FOR UPDATE" + ) + rows = cursor.fetchall() + if not rows: + cursor.execute( + "INSERT INTO registry_client_portal.migrations " + "(version, checksum) VALUES (%s, %s)", + (_MIGRATION_VERSION, checksum), + ) + elif rows != [(_MIGRATION_VERSION, checksum)]: + raise SessionStateError( + "portal session migration is not current" + ) + cursor.execute( + "INSERT INTO registry_client_portal.key_state " + "(singleton, active_key_id) VALUES (true, %s) " + "ON CONFLICT (singleton) DO NOTHING", + (self._keys.primary_key_id,), + ) + cursor.execute( + "SELECT active_key_id FROM registry_client_portal.key_state " + "WHERE singleton = true FOR UPDATE" + ) + key_row = cursor.fetchone() + if key_row is None or not self._keys._contains(key_row[0]): + raise SessionStateError( + "portal session encryption key is unavailable" + ) + except SessionStoreError: + raise + except Exception: + raise SessionStoreError("portal session migration failed") from None + + def check_ready(self) -> None: + with self._transaction() as cursor: + self._assert_ready(cursor) + + @contextmanager + def refresh_lock(self, session_id: str) -> Iterator[None]: + """Serialize one session's rotating refresh exchange across workers.""" + session_digest = _lookup_digest("session", session_id) + lock_keys = ( + int.from_bytes(session_digest[:4], "big", signed=True), + int.from_bytes(session_digest[4:8], "big", signed=True), + ) + entered_body = False + body_completed = False + try: + with self._connect() as connection: + with connection.cursor() as cursor: + try: + self._assert_ready(cursor) + cursor.execute( + "SELECT pg_advisory_xact_lock(%s, %s)", lock_keys + ) + except SessionStoreError: + raise + except Exception: + raise SessionStoreError() from None + entered_body = True + yield + body_completed = True + except SessionStoreError: + raise + except Exception: + if entered_body and not body_completed: + raise + raise SessionStoreError() from None + + def put_pending(self, pending: PendingGrant) -> bool: + plaintext = _encode_pending(pending) + state_digest = _lookup_digest("state", pending.state) + chain_digest = _lookup_digest("chain", pending.chain_id) + with self._transaction() as cursor: + active_key = self._assert_ready(cursor) + ciphertext = self._keys._seal( + active_key, "pending", state_digest, 0, plaintext + ) + cursor.execute( + "INSERT INTO registry_client_portal.chains " + "(chain_digest, closed) VALUES (%s, false) " + "ON CONFLICT (chain_digest) DO NOTHING", + (chain_digest,), + ) + cursor.execute( + "SELECT closed FROM registry_client_portal.chains " + "WHERE chain_digest = %s FOR UPDATE", + (chain_digest,), + ) + row = cursor.fetchone() + if row is None: + raise SessionStateError("portal session state is unreadable") + if row[0]: + return False + cursor.execute( + "INSERT INTO registry_client_portal.pending " + "(state_digest, chain_digest, expires_at, key_id, ciphertext) " + "VALUES (%s, %s, %s, %s, %s) " + "ON CONFLICT (state_digest) DO NOTHING RETURNING state_digest", + ( + state_digest, + chain_digest, + pending.expires_at, + active_key, + ciphertext, + ), + ) + return cursor.fetchone() is not None + + def consume_pending(self, state: str) -> PendingGrant | None: + state_digest = _lookup_digest("state", state) + row = None + with self._transaction() as cursor: + self._assert_ready(cursor) + cursor.execute( + "DELETE FROM registry_client_portal.pending " + "WHERE state_digest = %s RETURNING key_id, ciphertext", + (state_digest,), + ) + row = cursor.fetchone() + if row is None: + return None + plaintext = self._keys._open(row[0], "pending", state_digest, 0, bytes(row[1])) + result = _decode_pending(plaintext) + if result.state != state: + raise SessionStateError("portal session state is unreadable") + return result + + def close_chain(self, chain_id: str) -> None: + chain_digest = _lookup_digest("chain", chain_id) + with self._transaction() as cursor: + self._assert_ready(cursor) + cursor.execute( + "INSERT INTO registry_client_portal.chains " + "(chain_digest, closed) VALUES (%s, true) " + "ON CONFLICT (chain_digest) DO UPDATE " + "SET closed = true, updated_at = transaction_timestamp()", + (chain_digest,), + ) + cursor.execute( + "DELETE FROM registry_client_portal.pending WHERE chain_digest = %s", + (chain_digest,), + ) + + def create_session(self, chain_id: str, session: PortalSession) -> bool: + plaintext = _encode_session(session) + chain_digest = _lookup_digest("chain", chain_id) + session_digest = _lookup_digest("session", session.session_id) + with self._transaction() as cursor: + active_key = self._assert_ready(cursor) + cursor.execute( + "SELECT closed FROM registry_client_portal.chains " + "WHERE chain_digest = %s FOR UPDATE", + (chain_digest,), + ) + chain = cursor.fetchone() + if chain is None or chain[0]: + return False + ciphertext = self._keys._seal( + active_key, + "session", + session_digest, + session.generation, + plaintext, + ) + cursor.execute( + "INSERT INTO registry_client_portal.sessions " + "(session_digest, generation, expires_at, key_id, ciphertext) " + "VALUES (%s, %s, %s, %s, %s) " + "ON CONFLICT (session_digest) DO NOTHING RETURNING session_digest", + ( + session_digest, + session.generation, + session.expires_at, + active_key, + ciphertext, + ), + ) + if cursor.fetchone() is None: + return False + cursor.execute( + "UPDATE registry_client_portal.chains " + "SET closed = true, updated_at = transaction_timestamp() " + "WHERE chain_digest = %s", + (chain_digest,), + ) + cursor.execute( + "DELETE FROM registry_client_portal.pending WHERE chain_digest = %s", + (chain_digest,), + ) + return True + + def get_session(self, session_id: str) -> PortalSession | None: + session_digest = _lookup_digest("session", session_id) + row = None + with self._transaction() as cursor: + self._assert_ready(cursor) + cursor.execute( + "SELECT generation, key_id, ciphertext " + "FROM registry_client_portal.sessions WHERE session_digest = %s", + (session_digest,), + ) + row = cursor.fetchone() + if row is None: + return None + result = self._decrypt_session(session_digest, row) + if result.session_id != session_id: + raise SessionStateError("portal session state is unreadable") + return result + + def replace_session( + self, session_id: str, expected_generation: int, session: PortalSession + ) -> bool: + if ( + session.session_id != session_id + or expected_generation < 0 + or session.generation != expected_generation + 1 + ): + raise ValueError("replacement must advance the same portal session once") + plaintext = _encode_session(session) + session_digest = _lookup_digest("session", session_id) + with self._transaction() as cursor: + active_key = self._assert_ready(cursor) + ciphertext = self._keys._seal( + active_key, + "session", + session_digest, + session.generation, + plaintext, + ) + cursor.execute( + "UPDATE registry_client_portal.sessions " + "SET generation = %s, expires_at = %s, key_id = %s, ciphertext = %s " + "WHERE session_digest = %s AND generation = %s " + "RETURNING session_digest", + ( + session.generation, + session.expires_at, + active_key, + ciphertext, + session_digest, + expected_generation, + ), + ) + return cursor.fetchone() is not None + + def delete_session( + self, session_id: str, expected_generation: int | None = None + ) -> PortalSession | None: + if expected_generation is not None and expected_generation < 0: + raise ValueError("expected_generation must be nonnegative") + session_digest = _lookup_digest("session", session_id) + row = None + with self._transaction() as cursor: + self._assert_ready(cursor) + if expected_generation is None: + cursor.execute( + "DELETE FROM registry_client_portal.sessions " + "WHERE session_digest = %s " + "RETURNING generation, key_id, ciphertext", + (session_digest,), + ) + else: + cursor.execute( + "DELETE FROM registry_client_portal.sessions " + "WHERE session_digest = %s AND generation = %s " + "RETURNING generation, key_id, ciphertext", + (session_digest, expected_generation), + ) + row = cursor.fetchone() + if row is None: + return None + result = self._decrypt_session(session_digest, row) + if result.session_id != session_id: + raise SessionStateError("portal session state is unreadable") + return result + + def rotate_encryption(self) -> int: + """Atomically rewrite every payload and activate the configured primary. + + Deploy every worker with the new and previous keys before calling this. + The database key-state lock makes old-key-only workers fail closed after + activation. Remove the previous key only after this transaction passes. + """ + target = self._keys.primary_key_id + rewritten = 0 + with self._transaction() as cursor: + self._assert_ready(cursor, exclusive=True) + for table, kind, generation_expression in ( + ("pending", "pending", "0"), + ("sessions", "session", "generation"), + ): + digest_column = ( + "state_digest" if table == "pending" else "session_digest" + ) + cursor.execute( + f"SELECT {digest_column}, key_id, ciphertext, " + f"{generation_expression} FROM registry_client_portal.{table} " + "FOR UPDATE" + ) + for digest, key_id, ciphertext, generation in cursor.fetchall(): + plaintext = self._keys._open( + key_id, + kind, + bytes(digest), + generation, + bytes(ciphertext), + ) + if key_id == target: + continue + replacement = self._keys._seal( + target, kind, bytes(digest), generation, plaintext + ) + cursor.execute( + f"UPDATE registry_client_portal.{table} " + f"SET key_id = %s, ciphertext = %s WHERE {digest_column} = %s", + (target, replacement, digest), + ) + rewritten += 1 + cursor.execute( + "UPDATE registry_client_portal.key_state " + "SET active_key_id = %s, updated_at = transaction_timestamp() " + "WHERE singleton = true", + (target,), + ) + return rewritten + + def _decrypt_session(self, digest: bytes, row: Any) -> PortalSession: + generation, key_id, ciphertext = row + plaintext = self._keys._open( + key_id, "session", digest, generation, bytes(ciphertext) + ) + result = _decode_session(plaintext) + if result.generation != generation: + raise SessionStateError("portal session state is unreadable") + return result + + def _assert_ready(self, cursor: Any, *, exclusive: bool = False) -> str: + _, checksum = _migration() + lock = "FOR UPDATE" if exclusive else "FOR SHARE" + try: + cursor.execute( + "SELECT " + "to_regclass('registry_client_portal.migrations'), " + "to_regclass('registry_client_portal.key_state')" + ) + relations = cursor.fetchone() + if relations is None or None in relations: + raise SessionStateError("portal session migration is not current") + cursor.execute( + "SELECT version, checksum " + "FROM registry_client_portal.migrations " + f"ORDER BY version {lock}" + ) + migrations = cursor.fetchall() + cursor.execute( + "SELECT active_key_id FROM registry_client_portal.key_state " + f"WHERE singleton = true {lock}" + ) + key_state = cursor.fetchone() + except Exception: + raise SessionStateError("portal session migration is not current") from None + if migrations != [(_MIGRATION_VERSION, checksum)]: + raise SessionStateError("portal session migration is not current") + if key_state is None or not self._keys._contains(key_state[0]): + raise SessionStateError("portal session encryption key is unavailable") + return key_state[0] + + @contextmanager + def _transaction(self) -> Iterator[Any]: + try: + with self._connect() as connection: + with connection.cursor() as cursor: + yield cursor + except SessionStoreError: + raise + except Exception: + raise SessionStoreError() from None + + +def _migration() -> tuple[str, str]: + try: + data = _MIGRATION_PATH.read_bytes() + sql = data.decode("utf-8") + except (OSError, UnicodeError): + raise SessionStateError("portal session migration is not current") from None + return sql, hashlib.sha256(data).hexdigest() + + +def _associated_data(kind: str, lookup_digest: bytes, generation: int) -> bytes: + if kind not in {"pending", "session"} or len(lookup_digest) != 32: + raise SessionStateError("portal session state is unreadable") + return ( + b"registry-client-portal-v1\x00" + + kind.encode("ascii") + + b"\x00" + + lookup_digest + + generation.to_bytes(8, "big", signed=False) + ) + + +def _lookup_digest(kind: str, value: str) -> bytes: + if kind not in {"state", "chain", "session"} or not _bounded_text(value, 512): + raise ValueError("portal state identifier is invalid") + return hashlib.sha256( + b"registry-client-portal-lookup-v1\x00" + + kind.encode("ascii") + + b"\x00" + + value.encode("utf-8") + ).digest() + + +def _encode_pending(pending: PendingGrant) -> bytes: + return _encode( + { + "format": _FORMAT, + "kind": "pending", + "state": pending.state, + "chain_id": pending.chain_id, + "nonce": pending.nonce, + "code_verifier": pending.code_verifier, + "grant_index": pending.grant_index, + "created_at": pending.created_at, + "expires_at": pending.expires_at, + "return_to": pending.return_to, + "grants": [_grant_to_dict(grant) for grant in pending.grants], + } + ) + + +def _decode_pending(payload: bytes) -> PendingGrant: + value = _decode(payload) + _exact_keys( + value, + { + "format", + "kind", + "state", + "chain_id", + "nonce", + "code_verifier", + "grant_index", + "created_at", + "expires_at", + "return_to", + "grants", + }, + ) + if value["format"] != _FORMAT or value["kind"] != "pending": + raise SessionStateError("portal session state is unreadable") + grants = value["grants"] + if not isinstance(grants, list) or len(grants) > 16: + raise SessionStateError("portal session state is unreadable") + return _PendingGrantConstructor( + state=_string(value["state"]), + chain_id=_string(value["chain_id"]), + nonce=_string(value["nonce"]), + code_verifier=_string(value["code_verifier"]), + grant_index=_integer(value["grant_index"]), + created_at=_number(value["created_at"]), + expires_at=_number(value["expires_at"]), + return_to=_string(value["return_to"], maximum=4096), + grants=tuple(_grant_from_dict(item) for item in grants), + ) + + +def _encode_session(session: PortalSession) -> bytes: + return _encode( + { + "format": _FORMAT, + "kind": "session", + "session_id": session.session_id, + "subject": session.subject, + "principal": session.principal, + "persona": session.persona, + "grants": [_grant_to_dict(grant) for grant in session.grants], + "csrf_token": session.csrf_token, + "created_at": session.created_at, + "expires_at": session.expires_at, + "generation": session.generation, + } + ) + + +def _decode_session(payload: bytes) -> PortalSession: + value = _decode(payload) + _exact_keys( + value, + { + "format", + "kind", + "session_id", + "subject", + "principal", + "persona", + "grants", + "csrf_token", + "created_at", + "expires_at", + "generation", + }, + ) + if value["format"] != _FORMAT or value["kind"] != "session": + raise SessionStateError("portal session state is unreadable") + grants = value["grants"] + if not isinstance(grants, list) or not grants or len(grants) > 16: + raise SessionStateError("portal session state is unreadable") + return _PortalSessionConstructor( + session_id=_string(value["session_id"]), + subject=_string(value["subject"]), + principal=_string(value["principal"]), + persona=_string(value["persona"]), + grants=tuple(_grant_from_dict(item) for item in grants), + csrf_token=_string(value["csrf_token"]), + created_at=_number(value["created_at"]), + expires_at=_number(value["expires_at"]), + generation=_integer(value["generation"]), + ) + + +def _grant_to_dict(grant: VerifiedGrant) -> dict[str, Any]: + claims = dict(grant.claims) + if any( + not _bounded_text(name, 256) or not _bounded_text(value, 2048) + for name, value in claims.items() + ): + raise ValueError("verified portal claims must be bounded strings") + values = ( + grant.access_token, + grant.refresh_token, + grant.issuer, + grant.client_id, + grant.subject, + grant.principal, + grant.persona, + grant.resource, + grant.profile, + ) + if ( + any(not _bounded_text(value, 131072) for value in values) + or (grant.id_token is not None and not _bounded_text(grant.id_token, 131072)) + or not math.isfinite(grant.expires_at) + or len(grant.scopes) > 256 + or any(not _bounded_text(scope, 512) for scope in grant.scopes) + ): + raise ValueError("verified portal grant is not serializable") + return { + "access_token": grant.access_token, + "refresh_token": grant.refresh_token, + "id_token": grant.id_token, + "expires_at": grant.expires_at, + "issuer": grant.issuer, + "client_id": grant.client_id, + "subject": grant.subject, + "principal": grant.principal, + "persona": grant.persona, + "resource": grant.resource, + "profile": grant.profile, + "scopes": list(grant.scopes), + "claims": claims, + "authorized_party": grant.authorized_party, + "client_id_claim": grant.client_id_claim, + } + + +def _grant_from_dict(value: Any) -> VerifiedGrant: + if not isinstance(value, dict): + raise SessionStateError("portal session state is unreadable") + _exact_keys( + value, + { + "access_token", + "refresh_token", + "id_token", + "expires_at", + "issuer", + "client_id", + "subject", + "principal", + "persona", + "resource", + "profile", + "scopes", + "claims", + "authorized_party", + "client_id_claim", + }, + ) + scopes = value["scopes"] + claims = value["claims"] + if ( + not isinstance(scopes, list) + or len(scopes) > 256 + or not isinstance(claims, dict) + or len(claims) > 32 + ): + raise SessionStateError("portal session state is unreadable") + decoded_claims = { + _string(name, maximum=256): _string(claim, maximum=2048) + for name, claim in claims.items() + } + return VerifiedGrant( + access_token=_string(value["access_token"], maximum=131072), + refresh_token=_string(value["refresh_token"], maximum=131072), + id_token=_optional_string(value["id_token"], maximum=131072), + expires_at=_number(value["expires_at"]), + issuer=_string(value["issuer"], maximum=131072), + client_id=_string(value["client_id"]), + subject=_string(value["subject"]), + principal=_string(value["principal"]), + persona=_string(value["persona"]), + resource=_string(value["resource"], maximum=131072), + profile=_string(value["profile"]), + scopes=tuple(_string(scope, maximum=512) for scope in scopes), + claims=decoded_claims, + authorized_party=_optional_string(value["authorized_party"]), + client_id_claim=_optional_string(value["client_id_claim"]), + ) + + +def _encode(value: Mapping[str, Any]) -> bytes: + try: + payload = json.dumps( + value, + allow_nan=False, + ensure_ascii=False, + separators=(",", ":"), + sort_keys=True, + ).encode("utf-8") + except (TypeError, ValueError): + raise ValueError("portal session state is not serializable") from None + if len(payload) > _MAX_PLAINTEXT_BYTES: + raise ValueError("portal session state is too large") + return payload + + +def _decode(payload: bytes) -> dict[str, Any]: + if len(payload) > _MAX_PLAINTEXT_BYTES: + raise SessionStateError("portal session state is unreadable") + try: + value = json.loads( + payload, + object_pairs_hook=_unique_object, + parse_constant=lambda _value: (_ for _ in ()).throw(ValueError()), + ) + except (UnicodeError, ValueError, TypeError): + raise SessionStateError("portal session state is unreadable") from None + if not isinstance(value, dict): + raise SessionStateError("portal session state is unreadable") + return value + + +def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for name, value in pairs: + if name in result: + raise ValueError("duplicate member") + result[name] = value + return result + + +def _exact_keys(value: Mapping[str, Any], expected: set[str]) -> None: + if set(value) != expected: + raise SessionStateError("portal session state is unreadable") + + +def _string(value: Any, *, maximum: int = 512) -> str: + if not _bounded_text(value, maximum): + raise SessionStateError("portal session state is unreadable") + return value + + +def _optional_string(value: Any, *, maximum: int = 512) -> str | None: + if value is None: + return None + return _string(value, maximum=maximum) + + +def _number(value: Any) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise SessionStateError("portal session state is unreadable") + result = float(value) + if not math.isfinite(result): + raise SessionStateError("portal session state is unreadable") + return result + + +def _integer(value: Any) -> int: + if isinstance(value, bool) or not isinstance(value, int) or value < 0: + raise SessionStateError("portal session state is unreadable") + return value + + +def _identifier(value: Any) -> bool: + return bool( + _bounded_text(value, 128) + and not any(character.isspace() for character in value) + ) + + +def _bounded_text(value: Any, maximum: int) -> bool: + return bool( + isinstance(value, str) + and 1 <= len(value.encode("utf-8")) <= maximum + and value.strip() == value + and not any(ord(character) < 32 or ord(character) == 127 for character in value) + ) diff --git a/crates/registry-stack-client-py/python/registry_client/portal_postgres.pyi b/crates/registry-stack-client-py/python/registry_client/portal_postgres.pyi new file mode 100644 index 0000000000..9c5ce306b0 --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/portal_postgres.pyi @@ -0,0 +1,35 @@ +from collections.abc import Callable, Mapping +from typing import Any, ContextManager + +from .portal import PendingGrant, PortalSession, SessionStore + +class SessionStoreError(RuntimeError): + code: str + +class SessionStateError(SessionStoreError): + code: str + +class PortalEncryptionKeys: + def __init__(self, *, primary_key_id: str, keys: Mapping[str, bytes]) -> None: ... + @property + def primary_key_id(self) -> str: ... + +class PostgresSessionStore(SessionStore): + def __init__( + self, connect: Callable[[], Any], keys: PortalEncryptionKeys + ) -> None: ... + def migrate(self) -> None: ... + def check_ready(self) -> None: ... + def refresh_lock(self, session_id: str) -> ContextManager[None]: ... + def put_pending(self, pending: PendingGrant) -> bool: ... + def consume_pending(self, state: str) -> PendingGrant | None: ... + def close_chain(self, chain_id: str) -> None: ... + def create_session(self, chain_id: str, session: PortalSession) -> bool: ... + def get_session(self, session_id: str) -> PortalSession | None: ... + def replace_session( + self, session_id: str, expected_generation: int, session: PortalSession + ) -> bool: ... + def delete_session( + self, session_id: str, expected_generation: int | None = ... + ) -> PortalSession | None: ... + def rotate_encryption(self) -> int: ... diff --git a/crates/registry-stack-client-py/python/registry_client/portal_products.py b/crates/registry-stack-client-py/python/registry_client/portal_products.py new file mode 100644 index 0000000000..6f0c1065cb --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/portal_products.py @@ -0,0 +1,62 @@ +"""Construct request-local product clients from one complete person context.""" + +from __future__ import annotations + +from .portal import PortalContext, ReauthenticationRequired +from .workload_breg import BRegWorkload +from .workload_casework import CaseworkWorkload, HolderCaseworkWorkload + + +class PersonProducts: + """Product clients and non-secret identity facts for this one request.""" + + __slots__ = ("breg", "casework", "subject", "principal", "persona", "csrf_token") + + def __init__( + self, + breg: BRegWorkload, + casework: CaseworkWorkload | HolderCaseworkWorkload, + subject: str, + principal: str, + persona: str, + csrf_token: str, + ): + self.breg = breg + self.casework = casework + self.subject = subject + self.principal = principal + self.persona = persona + self.csrf_token = csrf_token + + +def bind_person( + context: PortalContext, + *, + persona: str, + breg_url: str, + casework_url: str, + casework_profile: str, +) -> PersonProducts: + """Make new native clients; no credential or caller state is retained globally.""" + if context.persona != persona: + raise ReauthenticationRequired() + breg_token = context._token_for("breg") + casework_token = context._token_for("casework") + from . import breg, casework + + return PersonProducts( + BRegWorkload( + breg.BaseRegistryClient( # pyright: ignore[reportAttributeAccessIssue] + breg_url, authorization={"static": breg_token} + ) + ), + (HolderCaseworkWorkload if persona == "holder" else CaseworkWorkload)( + casework.CaseworkClient(casework_url), # pyright: ignore[reportAttributeAccessIssue] + casework_token, + casework_profile, + ), + context.subject, + context.principal, + context.persona, + context.csrf_token, + ) diff --git a/crates/registry-stack-client-py/python/registry_client/portal_products.pyi b/crates/registry-stack-client-py/python/registry_client/portal_products.pyi new file mode 100644 index 0000000000..073f41e19e --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/portal_products.pyi @@ -0,0 +1,20 @@ +from .portal import PortalContext +from .workload_breg import BRegWorkload +from .workload_casework import CaseworkWorkload, HolderCaseworkWorkload + +class PersonProducts: + breg: BRegWorkload + casework: CaseworkWorkload | HolderCaseworkWorkload + subject: str + principal: str + persona: str + csrf_token: str + +def bind_person( + context: PortalContext, + *, + persona: str, + breg_url: str, + casework_url: str, + casework_profile: str, +) -> PersonProducts: ... diff --git a/crates/registry-stack-client-py/python/registry_client/portal_verifier.py b/crates/registry-stack-client-py/python/registry_client/portal_verifier.py new file mode 100644 index 0000000000..6e16db11a3 --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/portal_verifier.py @@ -0,0 +1,198 @@ +"""Turn native OIDC verification into one bounded personal product grant.""" + +from __future__ import annotations + +from typing import Any, Mapping, TypeGuard, cast + +from .portal import AdmissionError, GrantPolicy, VerifiedGrant + + +class NativeGrantVerifier: + """One issuer/client/persona and one native verifier per product resource.""" + + def __init__( + self, + *, + issuer: str, + client_id: str, + persona: str, + grants: Mapping[str, GrantPolicy], + verifiers: Mapping[str, Any], + principal_claim: str = "registry_principal", + actor_kind_claim: str = "registry_actor_kind", + ): + if ( + persona not in ("holder", "staff") + or not grants + or set(grants) != set(verifiers) + or any(name != policy.name for name, policy in grants.items()) + or not principal_claim + or not actor_kind_claim + ): + raise ValueError("native grant verifier needs exact per-resource policy") + self._issuer = issuer + self._client_id = client_id + self._persona = persona + self._grants = dict(grants) + self._verifiers = dict(verifiers) + self._principal_claim = principal_claim + self._actor_kind_claim = actor_kind_claim + + @classmethod + def from_native( + cls, + *, + issuer: str, + client_id: str, + persona: str, + grants: tuple[GrantPolicy, ...], + algorithm: str, + access_token_type: str = "at+jwt", + maximum_access_token_lifetime_seconds: int = 300, + maximum_id_token_lifetime_seconds: int = 3600, + jwks_uri: str | None = None, + allow_insecure_http: bool = False, + principal_claim: str = "registry_principal", + actor_kind_claim: str = "registry_actor_kind", + ) -> NativeGrantVerifier: + from .oidc import AccessTokenVerifier # pyright: ignore[reportMissingImports] + + verifiers = { + policy.name: AccessTokenVerifier( + issuer, + policy.resource, + client_id, + algorithm=algorithm, + access_token_type=access_token_type, + maximum_access_token_lifetime_seconds=maximum_access_token_lifetime_seconds, + maximum_id_token_lifetime_seconds=maximum_id_token_lifetime_seconds, + claim_names=tuple( + dict.fromkeys( + (principal_claim, actor_kind_claim, *policy.required_claims) + ) + ), + jwks_uri=jwks_uri, + allow_insecure_http=allow_insecure_http, + additional_audiences=( + (policy.forward_resource,) if policy.forward_resource else () + ), + ) + for policy in grants + } + return cls( + issuer=issuer, + client_id=client_id, + persona=persona, + grants={policy.name: policy for policy in grants}, + verifiers=verifiers, + principal_claim=principal_claim, + actor_kind_claim=actor_kind_claim, + ) + + def __call__( + self, + token_response: Mapping[str, Any], + expected_nonce: str | None, + policy: GrantPolicy, + current: VerifiedGrant | None, + ) -> VerifiedGrant: + if self._grants.get(policy.name) != policy or (expected_nonce is None) == ( + current is None + ): + raise AdmissionError() + access_token = token_response.get("access_token") + refresh_token = token_response.get("refresh_token") + id_token = token_response.get("id_token") + if ( + not _bearer(access_token) + or not _bearer(refresh_token) + or (expected_nonce is not None and not _bearer(id_token)) + ): + raise AdmissionError() + verifier = self._verifiers[policy.name] + try: + access = verifier.verify(access_token) + identity = ( + verifier.verify_id_token(id_token, expected_nonce) + if expected_nonce is not None + else None + ) + except Exception: + raise AdmissionError() from None + claims = access.claims + if ( + not isinstance(claims, Mapping) + or not isinstance(access.scopes, (tuple, list)) + or any(not isinstance(scope, str) for scope in access.scopes) + ): + raise AdmissionError() + principal = claims.get(self._principal_claim) + if ( + access.kind != "access" + or access.issuer != self._issuer + or not isinstance(access.audiences, (tuple, list)) + or any(not isinstance(value, str) for value in access.audiences) + or len(access.audiences) != len(policy.requested_resources) + or set(access.audiences) != set(policy.requested_resources) + or access.client_id != self._client_id + or not isinstance(access.subject, str) + or not access.subject + or not isinstance(principal, str) + or not principal + or claims.get(self._actor_kind_claim) != "human" + or not set(policy.scopes).issubset(access.scopes) + or any( + claims.get(name) != expected + for name, expected in policy.required_claims.items() + ) + ): + raise AdmissionError() + if identity is not None and ( + identity.kind != "id" + or identity.issuer != self._issuer + or identity.audiences != (self._client_id,) + or identity.client_id != self._client_id + or identity.subject != access.subject + ): + raise AdmissionError() + if current is not None and ( + current.issuer != access.issuer + or current.client_id != access.client_id + or current.subject != access.subject + or current.principal != principal + or current.persona != self._persona + or current.resource != policy.resource + or current.profile != policy.profile + ): + raise AdmissionError() + if identity is not None: + selected_id_token = id_token + else: + if current is None: + raise AdmissionError() + selected_id_token = current.id_token + return VerifiedGrant( + access_token=access_token, + refresh_token=refresh_token, + id_token=selected_id_token, + expires_at=access.expires_at, + issuer=access.issuer, + client_id=access.client_id, + subject=access.subject, + principal=principal, + persona=self._persona, + resource=policy.resource, + profile=policy.profile, + scopes=cast(tuple[str, ...], tuple(access.scopes)), + claims=claims, + authorized_party=access.client_id, + client_id_claim=access.client_id, + ) + + +def _bearer(value: Any) -> TypeGuard[str]: + return ( + isinstance(value, str) + and 1 <= len(value) <= 8192 + and not any(character.isspace() for character in value) + ) diff --git a/crates/registry-stack-client-py/python/registry_client/portal_verifier.pyi b/crates/registry-stack-client-py/python/registry_client/portal_verifier.pyi new file mode 100644 index 0000000000..0561f87684 --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/portal_verifier.pyi @@ -0,0 +1,40 @@ +from typing import Any, Mapping + +from .portal import GrantPolicy, VerifiedGrant + +class NativeGrantVerifier: + def __init__( + self, + *, + issuer: str, + client_id: str, + persona: str, + grants: Mapping[str, GrantPolicy], + verifiers: Mapping[str, Any], + principal_claim: str = ..., + actor_kind_claim: str = ..., + ) -> None: ... + @classmethod + def from_native( + cls, + *, + issuer: str, + client_id: str, + persona: str, + grants: tuple[GrantPolicy, ...], + algorithm: str, + access_token_type: str = ..., + maximum_access_token_lifetime_seconds: int = ..., + maximum_id_token_lifetime_seconds: int = ..., + jwks_uri: str | None = ..., + allow_insecure_http: bool = ..., + principal_claim: str = ..., + actor_kind_claim: str = ..., + ) -> NativeGrantVerifier: ... + def __call__( + self, + token_response: Mapping[str, Any], + expected_nonce: str | None, + policy: GrantPolicy, + current: VerifiedGrant | None, + ) -> VerifiedGrant: ... diff --git a/crates/registry-stack-client-py/python/registry_client/runner.py b/crates/registry-stack-client-py/python/registry_client/runner.py new file mode 100644 index 0000000000..1179c7660f --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/runner.py @@ -0,0 +1,143 @@ +"""Read a live runner's atomically rotated, run-bound workload credential.""" + +from __future__ import annotations + +import os +from pathlib import Path +import threading +import time +from typing import Any, Mapping + +from .connection import ConnectionError, _claims, _secret + + +TOKEN_VERSION = "id.registrystack.org/formats/platform/dev-workload-token/v1alpha1" +_STATE_FIELDS = frozenset(( + "apiVersion", "kind", "runId", "binding", "product", "issuer", "subject", "clientId", + "profile", "resource", "scopes", "claims", "generation", "issuedAt", "expiresAt", + "runExpiresAt", "token", +)) +_STOPPED_FIELDS = (_STATE_FIELDS - {"token"}) | {"status"} + + +def check_runner_document(state: Any, *, allow_stopped: bool = False) -> None: + """Check a runner envelope without granting it to a caller.""" + if (not isinstance(state, dict) + or state.get("apiVersion") != TOKEN_VERSION + or state.get("kind") != "PlatformDevWorkloadToken"): + raise ConnectionError("runner token state has an unsupported format") + stopped = state.get("status") == "stopped" + expected_fields = _STOPPED_FIELDS if stopped else _STATE_FIELDS + if set(state) != expected_fields or (stopped and not allow_stopped): + raise ConnectionError("runner token state is unavailable or malformed") + for field in ("runId", "binding", "product", "issuer", "subject", "clientId", "profile", "resource"): + if not isinstance(state[field], str) or not state[field]: + raise ConnectionError("runner token state has malformed authority") + scopes = state["scopes"] + if (not isinstance(scopes, list) or not scopes + or any(not isinstance(scope, str) or not scope or any(char.isspace() for char in scope) + for scope in scopes) + or len(set(scopes)) != len(scopes)): + raise ConnectionError("runner token state has malformed authority") + _claims(state["claims"], "runner token state.claims") + generation, issued, expires, run_expires = ( + state[field] for field in ("generation", "issuedAt", "expiresAt", "runExpiresAt") + ) + if (any(not isinstance(value, int) or isinstance(value, bool) + for value in (generation, issued, expires, run_expires)) + or generation < 1 or run_expires <= 0 or issued > run_expires + or (stopped and issued != expires) + or (not stopped and (issued > expires or expires - issued > 300 + or expires > run_expires or issued > int(time.time()) + 60))): + raise ConnectionError("runner token state has invalid generation or lifetime") + if stopped: + return + if int(time.time()) >= expires or int(time.time()) >= run_expires: + raise ConnectionError("runner token or development run expired; restart rstack dev") + token = state["token"] + if (not isinstance(token, str) or not token or len(token) > 8192 + or any(character.isspace() for character in token)): + raise ConnectionError("runner token state is malformed") + + +class RunnerTokenSource: + """One binding's finite run identity, checked at every protected call.""" + + def __init__(self, binding: Any, providers: Mapping[str, Any]): + self._binding = binding + self._providers = providers + self._lock = threading.Lock() + self._generation = 0 + self._token: str | None = None + + def current(self) -> tuple[int, str]: + with self._lock: + try: + contents = _secret(self._binding.credential["tokenRef"], self._providers).encode("utf-8") + except UnicodeError as exc: + raise ConnectionError("runner token state is unavailable or malformed") from exc + from .yaml import ConfigReadError, read_document # pyright: ignore[reportMissingImports] + + token_name = self._binding.credential["tokenRef"].split("/", 1)[1] + token_path = Path(self._providers["file"]["root"]) / token_name + try: + state = read_document( + contents, file=os.fspath(token_path), api_version=TOKEN_VERSION, + kind="PlatformDevWorkloadToken", + ) + except ConfigReadError as exc: + raise ConnectionError( + "runner token document was refused", diagnostics=exc.diagnostics + ) from None + check_runner_document(state) + credential = self._binding.credential + expected = { + "apiVersion": TOKEN_VERSION, + "kind": "PlatformDevWorkloadToken", + "runId": credential["runId"], + "binding": self._binding.name, + "product": self._binding.product, + "issuer": credential["issuer"], + "subject": credential["subject"], + "clientId": credential["clientId"], + "profile": credential["profile"], + "resource": credential["resource"], + "scopes": credential["scopes"], + "claims": credential["claims"], + "runExpiresAt": credential["runExpiresAt"], + } + if any(state.get(field) != value for field, value in expected.items()): + raise ConnectionError("runner token state does not match the declared authority") + generation = state["generation"] + token = state["token"] + if generation < self._generation: + raise ConnectionError("runner token generation moved backwards") + if generation == self._generation and token != self._token: + raise ConnectionError("runner token changed without a new generation") + self._generation = generation + self._token = token + return generation, token + + def bearer_token(self) -> str: + return self.current()[1] + + +class RotatingNativeBReg: + """Keep one public BReg handle while replacing a generation's static native client.""" + + def __init__(self, url: str, source: RunnerTokenSource): + self._url = url + self._source = source + self._lock = threading.Lock() + self._generation = 0 + self._client: Any = None + + def __getattr__(self, operation: str): + generation, token = self._source.current() + with self._lock: + if self._client is None or generation != self._generation: + from . import breg + client = breg.BaseRegistryClient(self._url, authorization={"static": token}) + self._client = client + self._generation = generation + return getattr(self._client, operation) diff --git a/crates/registry-stack-client-py/python/registry_client/web.py b/crates/registry-stack-client-py/python/registry_client/web.py new file mode 100644 index 0000000000..925412eae0 --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/web.py @@ -0,0 +1,46 @@ +"""Small shared web declarations; no framework is imported by the core.""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import TypeVar +from urllib.parse import parse_qs + + +_Function = TypeVar("_Function", bound=Callable) + + +def public(handler: _Function) -> _Function: + """Declare one route callable public before installing a framework adapter.""" + setattr(handler, "__registry_public__", True) + return handler + + +def is_public(handler: Callable | None) -> bool: + return bool(handler is not None and getattr(handler, "__registry_public__", False)) + + +def form_csrf_token( + *, content_type: str, content_length: int | None, body: bytes +) -> str: + """Read one bounded hidden CSRF field for a top-level browser form POST.""" + if ( + content_type.split(";", 1)[0].strip().lower() + != "application/x-www-form-urlencoded" + or content_length is None + or not 1 <= content_length <= 65_536 + or len(body) != content_length + ): + return "" + try: + fields = parse_qs( + body.decode("utf-8"), + keep_blank_values=True, + strict_parsing=True, + max_num_fields=64, + errors="strict", + ) + except (UnicodeDecodeError, ValueError): + return "" + tokens = fields.get("csrf_token", ()) + return tokens[0] if len(tokens) == 1 else "" diff --git a/crates/registry-stack-client-py/python/registry_client/web.pyi b/crates/registry-stack-client-py/python/registry_client/web.pyi new file mode 100644 index 0000000000..6f3de3ba39 --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/web.pyi @@ -0,0 +1,11 @@ +from collections.abc import Callable +from typing import ParamSpec, TypeVar + +_P = ParamSpec("_P") +_R = TypeVar("_R") + +def public(handler: Callable[_P, _R]) -> Callable[_P, _R]: ... +def is_public(handler: Callable | None) -> bool: ... +def form_csrf_token( + *, content_type: str, content_length: int | None, body: bytes +) -> str: ... diff --git a/crates/registry-stack-client-py/python/registry_client/workload.py b/crates/registry-stack-client-py/python/registry_client/workload.py new file mode 100644 index 0000000000..821dab9f43 --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/workload.py @@ -0,0 +1,110 @@ +"""Typed, token-free access to the supported workload product methods.""" + +from __future__ import annotations + +import asyncio +from contextlib import contextmanager +from contextvars import ContextVar +import math +import time +from typing import TYPE_CHECKING + +from .connection import UnsupportedOperationError + +if TYPE_CHECKING: + from . import messaging + from . import breg + + +_deadline: ContextVar[float | None] = ContextVar( + "registry_client_deadline", default=None +) + + +class RequestBudgetExceeded(TimeoutError): + """No new downstream work may begin within this request.""" + + +@contextmanager +def request_budget(seconds: float): + """Bound new work in this context; an inner budget cannot widen its parent.""" + if not math.isfinite(seconds) or seconds <= 0: + raise ValueError("request budget must be finite and positive") + deadline = time.monotonic() + seconds + prior = _deadline.get() + token = _deadline.set(min(prior, deadline) if prior is not None else deadline) + try: + yield + finally: + _deadline.reset(token) + + +def _require_sync() -> None: + deadline = _deadline.get() + if deadline is not None and time.monotonic() >= deadline: + raise RequestBudgetExceeded("request budget ended before a new downstream call") + try: + asyncio.get_running_loop() + except RuntimeError: + return + raise RuntimeError( + "Registry Stack native calls block the event-loop thread; use a synchronous " + "handler or explicitly offload the call to a worker thread" + ) + + +class MessagingWorkload: + """One Messaging target and one immutable workload token provider.""" + + __slots__ = ("_client", "_provider") + + def __init__(self, client: messaging.MessagingClient, provider: breg.PrivateKeyJwt): + self._client = client + self._provider = provider + + def __getattr__(self, operation: str): + raise UnsupportedOperationError("messaging", operation) + + def health(self) -> messaging.Complete[None]: + _require_sync() + return self._client.health() + + def ready(self) -> messaging.Complete[None]: + _require_sync() + return self._client.ready() + + def submit( + self, idempotency_key: str, request: messaging.SubmitMessageRequest + ) -> messaging.Complete[messaging.MessageReceipt]: + _require_sync() + return self._client.submit( + self._provider.bearer_token(), idempotency_key, request + ) + + def message_receipt( + self, idempotency_key: str, request: messaging.SubmitMessageRequest + ) -> messaging.Complete[messaging.MessageReceipt]: + _require_sync() + return self._client.message_receipt( + self._provider.bearer_token(), idempotency_key, request + ) + + def message( + self, message_id: messaging.MessageId + ) -> messaging.Complete[messaging.MessageView]: + _require_sync() + return self._client.message(self._provider.bearer_token(), message_id) + + def cancel( + self, message_id: messaging.MessageId + ) -> messaging.Complete[messaging.MessageView]: + _require_sync() + return self._client.cancel(self._provider.bearer_token(), message_id) + + def preview( + self, template_id: str, version: str, request: messaging.TemplatePreviewRequest + ) -> messaging.Complete[messaging.TemplatePreview]: + _require_sync() + return self._client.preview( + self._provider.bearer_token(), template_id, version, request + ) diff --git a/crates/registry-stack-client-py/python/registry_client/workload.pyi b/crates/registry-stack-client-py/python/registry_client/workload.pyi new file mode 100644 index 0000000000..026d1dc02b --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/workload.pyi @@ -0,0 +1,30 @@ +from typing import ContextManager + +from . import messaging as messaging +from . import breg as breg + +class RequestBudgetExceeded(TimeoutError): ... + +def request_budget(seconds: float) -> ContextManager[None]: ... + +class MessagingWorkload: + def __init__( + self, client: messaging.MessagingClient, provider: breg.PrivateKeyJwt + ) -> None: ... + def health(self) -> messaging.Complete[None]: ... + def ready(self) -> messaging.Complete[None]: ... + def submit( + self, idempotency_key: str, request: messaging.SubmitMessageRequest + ) -> messaging.Complete[messaging.MessageReceipt]: ... + def message_receipt( + self, idempotency_key: str, request: messaging.SubmitMessageRequest + ) -> messaging.Complete[messaging.MessageReceipt]: ... + def message( + self, message_id: messaging.MessageId + ) -> messaging.Complete[messaging.MessageView]: ... + def cancel( + self, message_id: messaging.MessageId + ) -> messaging.Complete[messaging.MessageView]: ... + def preview( + self, template_id: str, version: str, request: messaging.TemplatePreviewRequest + ) -> messaging.Complete[messaging.TemplatePreview]: ... diff --git a/crates/registry-stack-client-py/python/registry_client/workload_breg.py b/crates/registry-stack-client-py/python/registry_client/workload_breg.py new file mode 100644 index 0000000000..ef9f958526 --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/workload_breg.py @@ -0,0 +1,751 @@ +"""Complete token-free pass-through to one authorized native BReg client.""" + +from __future__ import annotations + +from typing import Any, Sequence, TYPE_CHECKING + +from .connection import UnsupportedOperationError +from .workload import _require_sync + +if TYPE_CHECKING: + from . import breg + + +class BRegWorkload: + """One immutable BReg target and workload authority.""" + + __slots__ = ("_client",) + + def __init__(self, client: breg.BaseRegistryClient): + self._client = client + + def __getattr__(self, operation: str): + raise UnsupportedOperationError("breg", operation) + + def get_proposal( + self, binding: breg.BRegProposalGetBinding, identifier: str + ) -> breg.BRegProposal: + _require_sync() + return self._client.get_proposal(binding, identifier) + + def start_proposal( + self, + binding: breg.BRegActionBinding, + inputs: dict[str, breg.JsonValue], + key: str, + ) -> breg.BRegProposal: + _require_sync() + return self._client.start_proposal(binding, inputs, key) + + def read_proposal(self, proposal: breg.BRegProposal) -> breg.BRegProposal: + _require_sync() + return self._client.read_proposal(proposal) + + def read_proposal_submission( + self, proposal: breg.BRegProposal, version: int + ) -> dict[str, Any]: + _require_sync() + return self._client.read_proposal_submission(proposal, version) + + def list_proposals( + self, collection: breg.BRegProposalCollection, query: dict[str, breg.JsonValue] + ) -> breg.BRegProposalPage: + _require_sync() + return self._client.list_proposals(collection, query) + + def prepare_proposal( + self, + proposal: breg.BRegProposal, + operation: breg.BRegProposalTransition, + body: dict[str, breg.JsonValue], + key: str, + ) -> breg.BRegPreparedProposal: + _require_sync() + return self._client.prepare_proposal(proposal, operation, body, key) + + def recover_proposal( + self, proposal: breg.BRegProposal, attempt: breg.BRegPreparedProposal + ) -> breg.BRegPreparedProposal: + _require_sync() + return self._client.recover_proposal(proposal, attempt) + + def execute_proposal(self, attempt: breg.BRegPreparedProposal) -> breg.BRegProposal: + _require_sync() + return self._client.execute_proposal(attempt) + + def health(self) -> dict[str, Any]: + _require_sync() + return self._client.health() + + def ready(self) -> dict[str, Any]: + _require_sync() + return self._client.ready() + + def openapi(self, access_profile: str | None = None) -> dict[str, Any]: + _require_sync() + return self._client.openapi(access_profile) + + def registry_metadata(self, access_profile: str | None = None) -> dict[str, Any]: + _require_sync() + return self._client.registry_metadata(access_profile) + + def event_record_creation_revision( + self, + record_route: str, + record_identifier: str, + *, + access_profile: str | None = None, + ) -> dict[str, str] | None: + _require_sync() + return self._client.event_record_creation_revision( + record_route, record_identifier, access_profile=access_profile + ) + + def statistics_live( + self, + dataset: str, + *, + from_period: str | None = None, + to_period: str | None = None, + access_profile: str | None = None, + format: breg.StatisticsFormat = "json", + ) -> dict[str, Any]: + _require_sync() + return self._client.statistics_live( + dataset, + from_period=from_period, + to_period=to_period, + access_profile=access_profile, + format=format, + ) + + def statistics_releases( + self, + dataset: str, + *, + top: int | None = None, + skip_token: str | None = None, + access_profile: str | None = None, + ) -> dict[str, Any]: + _require_sync() + return self._client.statistics_releases( + dataset, top=top, skip_token=skip_token, access_profile=access_profile + ) + + def statistics_latest_release( + self, + dataset: str, + period: str, + selection: breg.StatisticsReleaseSelection, + *, + access_profile: str | None = None, + format: breg.StatisticsFormat = "json", + ) -> dict[str, Any]: + _require_sync() + return self._client.statistics_latest_release( + dataset, period, selection, access_profile=access_profile, format=format + ) + + def statistics_release_version( + self, + dataset: str, + period: str, + version: int, + *, + access_profile: str | None = None, + format: breg.StatisticsFormat = "json", + ) -> dict[str, Any]: + _require_sync() + return self._client.statistics_release_version( + dataset, period, version, access_profile=access_profile, format=format + ) + + def statistics_release_series( + self, + dataset: str, + from_period: str, + to_period: str, + selection: breg.StatisticsReleaseSelection, + *, + access_profile: str | None = None, + format: breg.StatisticsFormat = "json", + ) -> dict[str, Any]: + _require_sync() + return self._client.statistics_release_series( + dataset, + from_period, + to_period, + selection, + access_profile=access_profile, + format=format, + ) + + def statistics_publish( + self, + dataset: str, + period: str, + status: breg.StatisticsReleaseStatus, + access_profile: str, + idempotency_key: str, + ) -> dict[str, Any]: + _require_sync() + return self._client.statistics_publish( + dataset, period, status, access_profile, idempotency_key + ) + + def statistics_withdraw( + self, + dataset: str, + period: str, + version: int, + reason: breg.StatisticsWithdrawalReason, + access_profile: str, + idempotency_key: str, + ) -> dict[str, Any]: + _require_sync() + return self._client.statistics_withdraw( + dataset, period, version, reason, access_profile, idempotency_key + ) + + def registry_contract(self, access_profile: str | None = None) -> breg.BRegMetadata: + _require_sync() + return self._client.registry_contract(access_profile) + + def record_schema( + self, record_type_identifier: str, access_profile: str | None = None + ) -> dict[str, Any]: + _require_sync() + return self._client.record_schema(record_type_identifier, access_profile) + + def get_record( + self, + record_route: str, + record_identifier: str, + *, + select: Sequence[str] | None = None, + access_profile: str | None = None, + format: breg.RecordFormat = "json", + ) -> dict[str, Any]: + _require_sync() + return self._client.get_record( + record_route, + record_identifier, + select=select, + access_profile=access_profile, + format=format, + ) + + def get_geojson_record( + self, + record_route: str, + record_identifier: str, + *, + select: Sequence[str] | None = None, + access_profile: str | None = None, + ) -> breg.GeoJsonCompleteOutcome: + _require_sync() + return self._client.get_geojson_record( + record_route, + record_identifier, + select=select, + access_profile=access_profile, + ) + + def list_geojson_records( + self, + record_route: str, + *, + top: int | None = None, + select: Sequence[str] | None = None, + access_profile: str | None = None, + filter: str | None = None, + orderby: str | None = None, + count: bool | None = None, + bbox: tuple[str, str, str, str] | None = None, + ) -> breg.GeoJsonPageOutcome: + _require_sync() + return self._client.list_geojson_records( + record_route, + top=top, + select=select, + access_profile=access_profile, + filter=filter, + orderby=orderby, + count=count, + bbox=bbox, + ) + + def continue_geojson_list( + self, continuation: dict[str, breg.JsonValue] + ) -> breg.GeoJsonPageOutcome: + _require_sync() + return self._client.continue_geojson_list(continuation) + + def record_revisions( + self, + record_route: str, + record_identifier: str, + access_profile: str | None = None, + ) -> dict[str, Any]: + _require_sync() + return self._client.record_revisions( + record_route, record_identifier, access_profile + ) + + def get_record_revision( + self, + record_route: str, + record_identifier: str, + revision: int, + *, + select: Sequence[str] | None = None, + access_profile: str | None = None, + format: breg.RecordFormat = "json", + ) -> dict[str, Any]: + _require_sync() + return self._client.get_record_revision( + record_route, + record_identifier, + revision, + select=select, + access_profile=access_profile, + format=format, + ) + + def list_records( + self, + record_route: str, + *, + top: int | None = None, + select: Sequence[str] | None = None, + access_profile: str | None = None, + format: breg.RecordFormat = "json", + filter: str | None = None, + orderby: str | None = None, + count: bool | None = None, + bbox: tuple[str, str, str, str] | None = None, + ) -> dict[str, Any]: + _require_sync() + return self._client.list_records( + record_route, + top=top, + select=select, + access_profile=access_profile, + format=format, + filter=filter, + orderby=orderby, + count=count, + bbox=bbox, + ) + + def list_current_records( + self, + record_route: str, + *, + top: int | None = None, + select: Sequence[str] | None = None, + access_profile: str | None = None, + format: breg.RecordFormat = "json", + filter: str | None = None, + orderby: str | None = None, + count: bool | None = None, + ) -> dict[str, Any]: + _require_sync() + return self._client.list_current_records( + record_route, + top=top, + select=select, + access_profile=access_profile, + format=format, + filter=filter, + orderby=orderby, + count=count, + ) + + def continue_current_list( + self, continuation: dict[str, breg.JsonValue] + ) -> dict[str, Any]: + _require_sync() + return self._client.continue_current_list(continuation) + + def list_records_as_of( + self, + record_route: str, + as_of: str, + *, + top: int | None = None, + select: Sequence[str] | None = None, + access_profile: str | None = None, + format: breg.RecordFormat = "json", + filter: str | None = None, + orderby: str | None = None, + count: bool | None = None, + ) -> dict[str, Any]: + _require_sync() + return self._client.list_records_as_of( + record_route, + as_of, + top=top, + select=select, + access_profile=access_profile, + format=format, + filter=filter, + orderby=orderby, + count=count, + ) + + def continue_as_of_list( + self, continuation: dict[str, breg.JsonValue] + ) -> dict[str, Any]: + _require_sync() + return self._client.continue_as_of_list(continuation) + + def list_snapshot_records( + self, + record_route: str, + *, + snapshot: str | None = None, + valid_at: str | None = None, + top: int | None = None, + select: Sequence[str] | None = None, + access_profile: str | None = None, + format: breg.RecordFormat = "json", + filter: str | None = None, + orderby: str | None = None, + count: bool | None = None, + ) -> dict[str, Any]: + _require_sync() + return self._client.list_snapshot_records( + record_route, + snapshot=snapshot, + valid_at=valid_at, + top=top, + select=select, + access_profile=access_profile, + format=format, + filter=filter, + orderby=orderby, + count=count, + ) + + def continue_snapshot_list( + self, continuation: dict[str, breg.JsonValue] + ) -> dict[str, Any]: + _require_sync() + return self._client.continue_snapshot_list(continuation) + + def list_relationship_records( + self, + record_route: str, + record_identifier: str, + path_route: str, + *, + top: int | None = None, + select: Sequence[str] | None = None, + access_profile: str | None = None, + format: breg.RecordFormat = "json", + filter: str | None = None, + orderby: str | None = None, + count: bool | None = None, + ) -> dict[str, Any]: + _require_sync() + return self._client.list_relationship_records( + record_route, + record_identifier, + path_route, + top=top, + select=select, + access_profile=access_profile, + format=format, + filter=filter, + orderby=orderby, + count=count, + ) + + def continue_relationship_list( + self, continuation: dict[str, breg.JsonValue] + ) -> dict[str, Any]: + _require_sync() + return self._client.continue_relationship_list(continuation) + + def continue_list(self, continuation: dict[str, breg.JsonValue]) -> dict[str, Any]: + _require_sync() + return self._client.continue_list(continuation) + + def lookup_record( + self, + record_route: str, + selector: str, + values: dict[str, breg.JsonValue] | None = None, + *, + select: Sequence[str] | None = None, + access_profile: str | None = None, + format: breg.RecordFormat = "json", + ) -> dict[str, Any]: + _require_sync() + return self._client.lookup_record( + record_route, + selector, + values, + select=select, + access_profile=access_profile, + format=format, + ) + + def create_record( + self, + binding: breg.BRegCreateBinding, + data: dict[str, breg.JsonValue], + idempotency_key: str, + *, + format: breg.RecordFormat = "json", + ) -> dict[str, Any]: + _require_sync() + return self._client.create_record(binding, data, idempotency_key, format=format) + + def prepare_create( + self, + binding: breg.BRegCreateBinding, + data: dict[str, breg.JsonValue], + idempotency_key: str, + *, + format: breg.RecordFormat = "json", + ) -> breg.BRegPreparedCreate: + _require_sync() + return self._client.prepare_create( + binding, data, idempotency_key, format=format + ) + + def recover_create( + self, binding: breg.BRegCreateBinding, prepared: breg.BRegPreparedCreate + ) -> breg.BRegRecoveredCreate: + _require_sync() + return self._client.recover_create(binding, prepared) + + def execute_recovered_create( + self, binding: breg.BRegCreateBinding, recovered: breg.BRegRecoveredCreate + ) -> dict[str, Any]: + _require_sync() + return self._client.execute_recovered_create(binding, recovered) + + def patch_record( + self, + binding: breg.BRegPatchBinding, + record_identifier: str, + etag: str, + operations: list[dict[str, breg.JsonValue]] + | tuple[dict[str, breg.JsonValue], ...], + idempotency_key: str, + *, + format: breg.RecordFormat = "json", + ) -> dict[str, Any]: + _require_sync() + return self._client.patch_record( + binding, record_identifier, etag, operations, idempotency_key, format=format + ) + + def action_target_conditions( + self, binding: breg.BRegActionBinding, inputs: dict[str, breg.JsonValue] + ) -> breg.BRegActionTargetConditions: + _require_sync() + return self._client.action_target_conditions(binding, inputs) + + def action_availability( + self, + binding: breg.BRegActionBinding, + target_input: str, + inputs: dict[str, breg.JsonValue], + ) -> breg.BRegActionAvailabilityOutcome: + _require_sync() + return self._client.action_availability(binding, target_input, inputs) + + def invoke_action( + self, + binding: breg.BRegActionBinding, + inputs: dict[str, breg.JsonValue], + idempotency_key: str, + conditions: breg.BRegActionTargetConditions | None = None, + ) -> dict[str, Any]: + _require_sync() + return self._client.invoke_action(binding, inputs, idempotency_key, conditions) + + def prepare_action( + self, + binding: breg.BRegActionBinding, + inputs: dict[str, breg.JsonValue], + idempotency_key: str, + conditions: breg.BRegActionTargetConditions | None = None, + ) -> breg.BRegPreparedAction: + _require_sync() + return self._client.prepare_action(binding, inputs, idempotency_key, conditions) + + def recover_action( + self, + binding: breg.BRegActionBinding, + prepared: breg.BRegPreparedAction, + inputs: dict[str, breg.JsonValue], + idempotency_key: str, + ) -> breg.BRegRecoveredAction: + _require_sync() + return self._client.recover_action(binding, prepared, inputs, idempotency_key) + + def execute_recovered_action( + self, binding: breg.BRegActionBinding, recovered: breg.BRegRecoveredAction + ) -> dict[str, Any]: + _require_sync() + return self._client.execute_recovered_action(binding, recovered) + + def execute_recovered_proposal_start( + self, binding: breg.BRegActionBinding, recovered: breg.BRegRecoveredAction + ) -> breg.BRegProposal: + _require_sync() + return self._client.execute_recovered_proposal_start(binding, recovered) + + def download_proposal_attachment( + self, proposal: breg.BRegProposal, slot: str + ) -> dict[str, Any]: + _require_sync() + return self._client.download_proposal_attachment(proposal, slot) + + def read_proposal_review_status( + self, proposal: breg.BRegProposal + ) -> dict[str, Any]: + _require_sync() + return self._client.read_proposal_review_status(proposal) + + def read_proposal_review_status_with_progress( + self, proposal: breg.BRegProposal + ) -> breg.BRegProposalReviewCompleteOutcome: + _require_sync() + return self._client.read_proposal_review_status_with_progress(proposal) + + def read_proposal_review_context( + self, proposal: breg.BRegProposal + ) -> dict[str, Any]: + _require_sync() + return self._client.read_proposal_review_context(proposal) + + def read_proposal_review_context_batch( + self, binding: breg.BRegProposalReviewBinding, ids: list[str] + ) -> dict[str, Any]: + _require_sync() + return self._client.read_proposal_review_context_batch(binding, ids) + + def read_proposal_review_by_id( + self, binding: breg.BRegProposalReviewBinding, identifier: str + ) -> dict[str, Any]: + _require_sync() + return self._client.read_proposal_review_by_id(binding, identifier) + + def download_proposal_review_document( + self, + binding: breg.BRegProposalReviewBinding, + context: dict[str, Any], + field: str, + ) -> dict[str, Any]: + _require_sync() + return self._client.download_proposal_review_document(binding, context, field) + + def upload_proposal_attachment( + self, + proposal: breg.BRegProposal, + slot: str, + content_type: str, + bytes: bytes, + key: str, + ) -> breg.BRegProposal: + _require_sync() + return self._client.upload_proposal_attachment( + proposal, slot, content_type, bytes, key + ) + + def delete_proposal_attachment( + self, proposal: breg.BRegProposal, slot: str, key: str + ) -> breg.BRegProposal: + _require_sync() + return self._client.delete_proposal_attachment(proposal, slot, key) + + def tombstone_record( + self, + binding: breg.BRegTombstoneBinding, + record_identifier: str, + etag: str, + idempotency_key: str, + *, + format: breg.RecordFormat = "json", + ) -> dict[str, Any]: + _require_sync() + return self._client.tombstone_record( + binding, record_identifier, etag, idempotency_key, format=format + ) + + def batch_records( + self, + binding: breg.BRegBatchBinding, + items: Sequence[dict[str, breg.JsonValue]], + idempotency_key: str, + *, + change_context: dict[str, breg.JsonValue] | None = None, + ) -> dict[str, Any]: + _require_sync() + return self._client.batch_records( + binding, items, idempotency_key, change_context=change_context + ) + + def create_ingestion_run( + self, record_route: str, request: dict[str, breg.JsonValue] + ) -> dict[str, Any]: + _require_sync() + return self._client.create_ingestion_run(record_route, request) + + def list_ingestion_runs( + self, + record_route: str, + *, + limit: int | None = None, + cursor: str | None = None, + status: breg.IngestionRunStatus | None = None, + input_digest: str | None = None, + access_profile: str | None = None, + ) -> dict[str, Any]: + _require_sync() + return self._client.list_ingestion_runs( + record_route, + limit=limit, + cursor=cursor, + status=status, + input_digest=input_digest, + access_profile=access_profile, + ) + + def read_ingestion_run( + self, record_route: str, run_id: str, access_profile: str | None = None + ) -> dict[str, Any]: + _require_sync() + return self._client.read_ingestion_run(record_route, run_id, access_profile) + + def submit_ingestion_chunk( + self, + record_route: str, + run_id: str, + chunk: breg.BRegIngestionChunk, + profile_id: str, + ) -> dict[str, Any]: + _require_sync() + return self._client.submit_ingestion_chunk( + record_route, run_id, chunk, profile_id + ) + + def cancel_ingestion_run( + self, record_route: str, run_id: str, access_profile: str | None = None + ) -> dict[str, Any]: + _require_sync() + return self._client.cancel_ingestion_run(record_route, run_id, access_profile) + + def ingestion_chunk_receipt( + self, record_route: str, run_id: str, chunk_index: int, profile_id: str + ) -> dict[str, Any]: + _require_sync() + return self._client.ingestion_chunk_receipt( + record_route, run_id, chunk_index, profile_id + ) diff --git a/crates/registry-stack-client-py/python/registry_client/workload_breg.pyi b/crates/registry-stack-client-py/python/registry_client/workload_breg.pyi new file mode 100644 index 0000000000..a97d2cf0d6 --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/workload_breg.pyi @@ -0,0 +1,406 @@ +from typing import Any, Never, Sequence + +from . import breg + +class BRegWorkload: + def __init__(self, client: breg.BaseRegistryClient) -> None: ... + def __getattr__(self, operation: str) -> Never: ... + def get_proposal( + self, binding: breg.BRegProposalGetBinding, identifier: str + ) -> breg.BRegProposal: ... + def start_proposal( + self, + binding: breg.BRegActionBinding, + inputs: dict[str, breg.JsonValue], + key: str, + ) -> breg.BRegProposal: ... + def read_proposal(self, proposal: breg.BRegProposal) -> breg.BRegProposal: ... + def read_proposal_submission( + self, proposal: breg.BRegProposal, version: int + ) -> dict[str, Any]: ... + def list_proposals( + self, collection: breg.BRegProposalCollection, query: dict[str, breg.JsonValue] + ) -> breg.BRegProposalPage: ... + def prepare_proposal( + self, + proposal: breg.BRegProposal, + operation: breg.BRegProposalTransition, + body: dict[str, breg.JsonValue], + key: str, + ) -> breg.BRegPreparedProposal: ... + def recover_proposal( + self, proposal: breg.BRegProposal, attempt: breg.BRegPreparedProposal + ) -> breg.BRegPreparedProposal: ... + def execute_proposal( + self, attempt: breg.BRegPreparedProposal + ) -> breg.BRegProposal: ... + def health(self) -> dict[str, Any]: ... + def ready(self) -> dict[str, Any]: ... + def openapi(self, access_profile: str | None = None) -> dict[str, Any]: ... + def registry_metadata( + self, access_profile: str | None = None + ) -> dict[str, Any]: ... + def event_record_creation_revision( + self, + record_route: str, + record_identifier: str, + *, + access_profile: str | None = None, + ) -> dict[str, str] | None: ... + def statistics_live( + self, + dataset: str, + *, + from_period: str | None = None, + to_period: str | None = None, + access_profile: str | None = None, + format: breg.StatisticsFormat = "json", + ) -> dict[str, Any]: ... + def statistics_releases( + self, + dataset: str, + *, + top: int | None = None, + skip_token: str | None = None, + access_profile: str | None = None, + ) -> dict[str, Any]: ... + def statistics_latest_release( + self, + dataset: str, + period: str, + selection: breg.StatisticsReleaseSelection, + *, + access_profile: str | None = None, + format: breg.StatisticsFormat = "json", + ) -> dict[str, Any]: ... + def statistics_release_version( + self, + dataset: str, + period: str, + version: int, + *, + access_profile: str | None = None, + format: breg.StatisticsFormat = "json", + ) -> dict[str, Any]: ... + def statistics_release_series( + self, + dataset: str, + from_period: str, + to_period: str, + selection: breg.StatisticsReleaseSelection, + *, + access_profile: str | None = None, + format: breg.StatisticsFormat = "json", + ) -> dict[str, Any]: ... + def statistics_publish( + self, + dataset: str, + period: str, + status: breg.StatisticsReleaseStatus, + access_profile: str, + idempotency_key: str, + ) -> dict[str, Any]: ... + def statistics_withdraw( + self, + dataset: str, + period: str, + version: int, + reason: breg.StatisticsWithdrawalReason, + access_profile: str, + idempotency_key: str, + ) -> dict[str, Any]: ... + def registry_contract( + self, access_profile: str | None = None + ) -> breg.BRegMetadata: ... + def record_schema( + self, record_type_identifier: str, access_profile: str | None = None + ) -> dict[str, Any]: ... + def get_record( + self, + record_route: str, + record_identifier: str, + *, + select: Sequence[str] | None = None, + access_profile: str | None = None, + format: breg.RecordFormat = "json", + ) -> dict[str, Any]: ... + def get_geojson_record( + self, + record_route: str, + record_identifier: str, + *, + select: Sequence[str] | None = None, + access_profile: str | None = None, + ) -> breg.GeoJsonCompleteOutcome: ... + def list_geojson_records( + self, + record_route: str, + *, + top: int | None = None, + select: Sequence[str] | None = None, + access_profile: str | None = None, + filter: str | None = None, + orderby: str | None = None, + count: bool | None = None, + bbox: tuple[str, str, str, str] | None = None, + ) -> breg.GeoJsonPageOutcome: ... + def continue_geojson_list( + self, continuation: dict[str, breg.JsonValue] + ) -> breg.GeoJsonPageOutcome: ... + def record_revisions( + self, + record_route: str, + record_identifier: str, + access_profile: str | None = None, + ) -> dict[str, Any]: ... + def get_record_revision( + self, + record_route: str, + record_identifier: str, + revision: int, + *, + select: Sequence[str] | None = None, + access_profile: str | None = None, + format: breg.RecordFormat = "json", + ) -> dict[str, Any]: ... + def list_records( + self, + record_route: str, + *, + top: int | None = None, + select: Sequence[str] | None = None, + access_profile: str | None = None, + format: breg.RecordFormat = "json", + filter: str | None = None, + orderby: str | None = None, + count: bool | None = None, + bbox: tuple[str, str, str, str] | None = None, + ) -> dict[str, Any]: ... + def list_current_records( + self, + record_route: str, + *, + top: int | None = None, + select: Sequence[str] | None = None, + access_profile: str | None = None, + format: breg.RecordFormat = "json", + filter: str | None = None, + orderby: str | None = None, + count: bool | None = None, + ) -> dict[str, Any]: ... + def continue_current_list( + self, continuation: dict[str, breg.JsonValue] + ) -> dict[str, Any]: ... + def list_records_as_of( + self, + record_route: str, + as_of: str, + *, + top: int | None = None, + select: Sequence[str] | None = None, + access_profile: str | None = None, + format: breg.RecordFormat = "json", + filter: str | None = None, + orderby: str | None = None, + count: bool | None = None, + ) -> dict[str, Any]: ... + def continue_as_of_list( + self, continuation: dict[str, breg.JsonValue] + ) -> dict[str, Any]: ... + def list_snapshot_records( + self, + record_route: str, + *, + snapshot: str | None = None, + valid_at: str | None = None, + top: int | None = None, + select: Sequence[str] | None = None, + access_profile: str | None = None, + format: breg.RecordFormat = "json", + filter: str | None = None, + orderby: str | None = None, + count: bool | None = None, + ) -> dict[str, Any]: ... + def continue_snapshot_list( + self, continuation: dict[str, breg.JsonValue] + ) -> dict[str, Any]: ... + def list_relationship_records( + self, + record_route: str, + record_identifier: str, + path_route: str, + *, + top: int | None = None, + select: Sequence[str] | None = None, + access_profile: str | None = None, + format: breg.RecordFormat = "json", + filter: str | None = None, + orderby: str | None = None, + count: bool | None = None, + ) -> dict[str, Any]: ... + def continue_relationship_list( + self, continuation: dict[str, breg.JsonValue] + ) -> dict[str, Any]: ... + def continue_list( + self, continuation: dict[str, breg.JsonValue] + ) -> dict[str, Any]: ... + def lookup_record( + self, + record_route: str, + selector: str, + values: dict[str, breg.JsonValue] | None = None, + *, + select: Sequence[str] | None = None, + access_profile: str | None = None, + format: breg.RecordFormat = "json", + ) -> dict[str, Any]: ... + def create_record( + self, + binding: breg.BRegCreateBinding, + data: dict[str, breg.JsonValue], + idempotency_key: str, + *, + format: breg.RecordFormat = "json", + ) -> dict[str, Any]: ... + def prepare_create( + self, + binding: breg.BRegCreateBinding, + data: dict[str, breg.JsonValue], + idempotency_key: str, + *, + format: breg.RecordFormat = "json", + ) -> breg.BRegPreparedCreate: ... + def recover_create( + self, binding: breg.BRegCreateBinding, prepared: breg.BRegPreparedCreate + ) -> breg.BRegRecoveredCreate: ... + def execute_recovered_create( + self, binding: breg.BRegCreateBinding, recovered: breg.BRegRecoveredCreate + ) -> dict[str, Any]: ... + def patch_record( + self, + binding: breg.BRegPatchBinding, + record_identifier: str, + etag: str, + operations: list[dict[str, breg.JsonValue]] + | tuple[dict[str, breg.JsonValue], ...], + idempotency_key: str, + *, + format: breg.RecordFormat = "json", + ) -> dict[str, Any]: ... + def action_target_conditions( + self, binding: breg.BRegActionBinding, inputs: dict[str, breg.JsonValue] + ) -> breg.BRegActionTargetConditions: ... + def action_availability( + self, + binding: breg.BRegActionBinding, + target_input: str, + inputs: dict[str, breg.JsonValue], + ) -> breg.BRegActionAvailabilityOutcome: ... + def invoke_action( + self, + binding: breg.BRegActionBinding, + inputs: dict[str, breg.JsonValue], + idempotency_key: str, + conditions: breg.BRegActionTargetConditions | None = None, + ) -> dict[str, Any]: ... + def prepare_action( + self, + binding: breg.BRegActionBinding, + inputs: dict[str, breg.JsonValue], + idempotency_key: str, + conditions: breg.BRegActionTargetConditions | None = None, + ) -> breg.BRegPreparedAction: ... + def recover_action( + self, + binding: breg.BRegActionBinding, + prepared: breg.BRegPreparedAction, + inputs: dict[str, breg.JsonValue], + idempotency_key: str, + ) -> breg.BRegRecoveredAction: ... + def execute_recovered_action( + self, binding: breg.BRegActionBinding, recovered: breg.BRegRecoveredAction + ) -> dict[str, Any]: ... + def execute_recovered_proposal_start( + self, binding: breg.BRegActionBinding, recovered: breg.BRegRecoveredAction + ) -> breg.BRegProposal: ... + def download_proposal_attachment( + self, proposal: breg.BRegProposal, slot: str + ) -> dict[str, Any]: ... + def read_proposal_review_status( + self, proposal: breg.BRegProposal + ) -> dict[str, Any]: ... + def read_proposal_review_status_with_progress( + self, proposal: breg.BRegProposal + ) -> breg.BRegProposalReviewCompleteOutcome: ... + def read_proposal_review_context( + self, proposal: breg.BRegProposal + ) -> dict[str, Any]: ... + def read_proposal_review_context_batch( + self, binding: breg.BRegProposalReviewBinding, ids: list[str] + ) -> dict[str, Any]: ... + def read_proposal_review_by_id( + self, binding: breg.BRegProposalReviewBinding, identifier: str + ) -> dict[str, Any]: ... + def download_proposal_review_document( + self, + binding: breg.BRegProposalReviewBinding, + context: dict[str, Any], + field: str, + ) -> dict[str, Any]: ... + def upload_proposal_attachment( + self, + proposal: breg.BRegProposal, + slot: str, + content_type: str, + bytes: bytes, + key: str, + ) -> breg.BRegProposal: ... + def delete_proposal_attachment( + self, proposal: breg.BRegProposal, slot: str, key: str + ) -> breg.BRegProposal: ... + def tombstone_record( + self, + binding: breg.BRegTombstoneBinding, + record_identifier: str, + etag: str, + idempotency_key: str, + *, + format: breg.RecordFormat = "json", + ) -> dict[str, Any]: ... + def batch_records( + self, + binding: breg.BRegBatchBinding, + items: Sequence[dict[str, breg.JsonValue]], + idempotency_key: str, + *, + change_context: dict[str, breg.JsonValue] | None = None, + ) -> dict[str, Any]: ... + def create_ingestion_run( + self, record_route: str, request: dict[str, breg.JsonValue] + ) -> dict[str, Any]: ... + def list_ingestion_runs( + self, + record_route: str, + *, + limit: int | None = None, + cursor: str | None = None, + status: breg.IngestionRunStatus | None = None, + input_digest: str | None = None, + access_profile: str | None = None, + ) -> dict[str, Any]: ... + def read_ingestion_run( + self, record_route: str, run_id: str, access_profile: str | None = None + ) -> dict[str, Any]: ... + def submit_ingestion_chunk( + self, + record_route: str, + run_id: str, + chunk: breg.BRegIngestionChunk, + profile_id: str, + ) -> dict[str, Any]: ... + def cancel_ingestion_run( + self, record_route: str, run_id: str, access_profile: str | None = None + ) -> dict[str, Any]: ... + def ingestion_chunk_receipt( + self, record_route: str, run_id: str, chunk_index: int, profile_id: str + ) -> dict[str, Any]: ... diff --git a/crates/registry-stack-client-py/python/registry_client/workload_casework.py b/crates/registry-stack-client-py/python/registry_client/workload_casework.py new file mode 100644 index 0000000000..1ca567d8a5 --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/workload_casework.py @@ -0,0 +1,183 @@ +"""Immutable, token-free access to the accepted staff Casework surface.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from .connection import UnsupportedOperationError +from .workload import _require_sync + +if TYPE_CHECKING: + from . import casework + + +class CaseworkWorkload: + """One Casework target with one immutable token and staff profile.""" + + __slots__ = ("__client", "__token", "__profile") + + def __init__( + self, client: casework.CaseworkClient, token: str, profile: str + ) -> None: + if not isinstance(token, str): + raise TypeError("token must be a string") + if not isinstance(profile, str): + raise TypeError("profile must be a string") + object.__setattr__(self, "_CaseworkWorkload__client", client) + object.__setattr__(self, "_CaseworkWorkload__token", token) + object.__setattr__(self, "_CaseworkWorkload__profile", profile) + + def __setattr__(self, name: str, value: object) -> None: + raise AttributeError("CaseworkWorkload is immutable") + + def __getattr__(self, operation: str): + raise UnsupportedOperationError("casework", operation) + + def description(self) -> casework.Complete[casework.Description]: + _require_sync() + return self.__client.description(self.__token, self.__profile) + + def review_policies( + self, + ) -> casework.Complete[list[casework.ReviewPolicyClosure]]: + _require_sync() + return self.__client.review_policies(self.__token, self.__profile) + + def review_policy( + self, policy_id: str + ) -> casework.Complete[casework.ReviewPolicyClosure]: + _require_sync() + return self.__client.review_policy(self.__token, self.__profile, policy_id) + + def review_tasks( + self, + query: casework.ReviewStaffingQuery | None = None, + source_profile: str | None = None, + ) -> casework.Complete[casework.ReviewTaskPage]: + _require_sync() + return self.__client.review_tasks( + self.__token, self.__profile, query, source_profile + ) + + def review_task( + self, + task_id: casework.Uuid, + source_profile: str | None = None, + ) -> casework.Complete[casework.ReviewTask]: + _require_sync() + return self.__client.review_task( + self.__token, self.__profile, task_id, source_profile + ) + + def review_task_context( + self, + task_id: casework.Uuid, + source_profile: str | None = None, + ) -> casework.Complete[casework.ReviewTaskContext]: + _require_sync() + return self.__client.review_task_context( + self.__token, self.__profile, task_id, source_profile + ) + + def claim_review_task( + self, + task_id: casework.Uuid, + expected_revision: casework.SafeInteger, + idempotency_key: str, + source_profile: str | None = None, + ) -> casework.Complete[casework.ReviewTask]: + _require_sync() + return self.__client.claim_review_task( + self.__token, + self.__profile, + task_id, + expected_revision, + idempotency_key, + source_profile, + ) + + def release_review_task( + self, + task_id: casework.Uuid, + expected_revision: casework.SafeInteger, + idempotency_key: str, + ) -> casework.Complete[casework.ReviewTask]: + _require_sync() + return self.__client.release_review_task( + self.__token, + self.__profile, + task_id, + expected_revision, + idempotency_key, + ) + + def decide_review_task( + self, + task_id: casework.Uuid, + expected_revision: casework.SafeInteger, + idempotency_key: str, + decision: casework.ReviewTaskDecisionRequest, + source_profile: str | None = None, + ) -> casework.Complete[None]: + _require_sync() + return self.__client.decide_review_task( + self.__token, + self.__profile, + task_id, + expected_revision, + idempotency_key, + decision, + source_profile, + ) + + def own_review_decisions( + self, + query: casework.OwnReviewDecisionQuery | None = None, + source_profile: str | None = None, + ) -> casework.Complete[casework.OwnReviewDecisionPage]: + _require_sync() + return self.__client.own_review_decisions( + self.__token, self.__profile, query, source_profile + ) + + def review_history( + self, + request_id: casework.Uuid, + query: casework.ReviewPageQuery | None = None, + source_profile: str | None = None, + ) -> casework.Complete[casework.ReviewHistoryPage]: + _require_sync() + return self.__client.review_history( + self.__token, self.__profile, request_id, query, source_profile + ) + + +class HolderCaseworkWorkload: + """Holder authority exposes only personal review history.""" + + __slots__ = ("__client", "__token", "__profile") + + def __init__( + self, client: casework.CaseworkClient, token: str, profile: str + ) -> None: + if not isinstance(token, str) or not isinstance(profile, str): + raise TypeError("token and profile must be strings") + object.__setattr__(self, "_HolderCaseworkWorkload__client", client) + object.__setattr__(self, "_HolderCaseworkWorkload__token", token) + object.__setattr__(self, "_HolderCaseworkWorkload__profile", profile) + + def __setattr__(self, name: str, value: object) -> None: + raise AttributeError("HolderCaseworkWorkload is immutable") + + def __getattr__(self, operation: str): + raise UnsupportedOperationError("casework", operation) + + def review_history( + self, + request_id: casework.Uuid, + query: casework.ReviewPageQuery | None = None, + ) -> casework.Complete[casework.ReviewHistoryPage]: + _require_sync() + return self.__client.review_history( + self.__token, self.__profile, request_id, query, None + ) diff --git a/crates/registry-stack-client-py/python/registry_client/workload_casework.pyi b/crates/registry-stack-client-py/python/registry_client/workload_casework.pyi new file mode 100644 index 0000000000..525c5e9c4f --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/workload_casework.pyi @@ -0,0 +1,76 @@ +from typing import Never + +from . import casework as casework + +class CaseworkWorkload: + def __init__( + self, client: casework.CaseworkClient, token: str, profile: str + ) -> None: ... + def __setattr__(self, name: str, value: object) -> None: ... + def __getattr__(self, operation: str) -> Never: ... + def description(self) -> casework.Complete[casework.Description]: ... + def review_policies( + self, + ) -> casework.Complete[list[casework.ReviewPolicyClosure]]: ... + def review_policy( + self, policy_id: str + ) -> casework.Complete[casework.ReviewPolicyClosure]: ... + def review_tasks( + self, + query: casework.ReviewStaffingQuery | None = None, + source_profile: str | None = None, + ) -> casework.Complete[casework.ReviewTaskPage]: ... + def review_task( + self, + task_id: casework.Uuid, + source_profile: str | None = None, + ) -> casework.Complete[casework.ReviewTask]: ... + def review_task_context( + self, + task_id: casework.Uuid, + source_profile: str | None = None, + ) -> casework.Complete[casework.ReviewTaskContext]: ... + def claim_review_task( + self, + task_id: casework.Uuid, + expected_revision: casework.SafeInteger, + idempotency_key: str, + source_profile: str | None = None, + ) -> casework.Complete[casework.ReviewTask]: ... + def release_review_task( + self, + task_id: casework.Uuid, + expected_revision: casework.SafeInteger, + idempotency_key: str, + ) -> casework.Complete[casework.ReviewTask]: ... + def decide_review_task( + self, + task_id: casework.Uuid, + expected_revision: casework.SafeInteger, + idempotency_key: str, + decision: casework.ReviewTaskDecisionRequest, + source_profile: str | None = None, + ) -> casework.Complete[None]: ... + def own_review_decisions( + self, + query: casework.OwnReviewDecisionQuery | None = None, + source_profile: str | None = None, + ) -> casework.Complete[casework.OwnReviewDecisionPage]: ... + def review_history( + self, + request_id: casework.Uuid, + query: casework.ReviewPageQuery | None = None, + source_profile: str | None = None, + ) -> casework.Complete[casework.ReviewHistoryPage]: ... + +class HolderCaseworkWorkload: + def __init__( + self, client: casework.CaseworkClient, token: str, profile: str + ) -> None: ... + def __setattr__(self, name: str, value: object) -> None: ... + def __getattr__(self, operation: str) -> Never: ... + def review_history( + self, + request_id: casework.Uuid, + query: casework.ReviewPageQuery | None = None, + ) -> casework.Complete[casework.ReviewHistoryPage]: ... diff --git a/crates/registry-stack-client-py/tests/test_breg_workload.py b/crates/registry-stack-client-py/tests/test_breg_workload.py new file mode 100644 index 0000000000..4630961d22 --- /dev/null +++ b/crates/registry-stack-client-py/tests/test_breg_workload.py @@ -0,0 +1,179 @@ +"""The workload facade preserves the complete native BReg client surface.""" + +from __future__ import annotations + +import ast +import asyncio +import copy +import importlib +import inspect +from pathlib import Path +import sys +import types +import unittest + + +ROOT = Path(__file__).resolve().parents[3] +FACADE_SOURCE = ROOT / "crates/registry-stack-client-py/python/registry_client" +NATIVE_STUB = ( + ROOT / "crates/registry-breg-client-py/python/registry_breg_client/__init__.pyi" +) +FACADE_RUNTIME = FACADE_SOURCE / "workload_breg.py" +FACADE_STUB = FACADE_SOURCE / "workload_breg.pyi" + + +def _load_facade(): + package_name = "_registry_client_breg_workload_test" + package = types.ModuleType(package_name) + package.__path__ = [str(FACADE_SOURCE)] + sys.modules[package_name] = package + return importlib.import_module(f"{package_name}.workload_breg") + + +workload_breg = _load_facade() +BRegWorkload = workload_breg.BRegWorkload +UnsupportedOperationError = importlib.import_module( + f"{BRegWorkload.__module__.rsplit('.', 1)[0]}.connection" +).UnsupportedOperationError + + +def _class(path: Path, name: str) -> ast.ClassDef: + module = ast.parse(path.read_text(encoding="utf-8")) + return next( + node + for node in module.body + if isinstance(node, ast.ClassDef) and node.name == name + ) + + +def _methods(node: ast.ClassDef) -> dict[str, ast.FunctionDef]: + return { + member.name: member + for member in node.body + if isinstance(member, ast.FunctionDef) + and member.name not in {"__init__", "__getattr__"} + } + + +class _UnqualifyBReg(ast.NodeTransformer): + def visit_Attribute(self, node: ast.Attribute): + node = self.generic_visit(node) + if isinstance(node.value, ast.Name) and node.value.id == "breg": + return ast.copy_location(ast.Name(id=node.attr, ctx=node.ctx), node) + return node + + +def _signature(node: ast.FunctionDef) -> tuple[str, str]: + arguments = _UnqualifyBReg().visit(copy.deepcopy(node.args)) + returns = ( + _UnqualifyBReg().visit(copy.deepcopy(node.returns)) + if node.returns is not None + else None + ) + return ( + ast.dump(arguments, include_attributes=False), + ast.dump(returns, include_attributes=False), + ) + + +class RecordingClient: + def __init__(self) -> None: + self.calls: list[tuple[str, tuple[object, ...], dict[str, object]]] = [] + self.results: dict[str, object] = {} + self.failures: dict[str, BaseException] = {} + + def __getattr__(self, name: str): + def call(*args: object, **kwargs: object): + self.calls.append((name, args, kwargs)) + if name in self.failures: + raise self.failures[name] + return self.results.setdefault(name, object()) + + return call + + +class BRegWorkloadTests(unittest.TestCase): + def test_runtime_and_stub_declare_exactly_the_native_method_set(self) -> None: + native = _methods(_class(NATIVE_STUB, "BaseRegistryClient")) + runtime = _methods(_class(FACADE_RUNTIME, "BRegWorkload")) + facade = _methods(_class(FACADE_STUB, "BRegWorkload")) + + self.assertEqual(len(native), 68) + self.assertEqual(set(runtime), set(native)) + self.assertEqual(set(facade), set(native)) + + def test_runtime_and_stub_preserve_every_native_signature(self) -> None: + native = _methods(_class(NATIVE_STUB, "BaseRegistryClient")) + runtime = _methods(_class(FACADE_RUNTIME, "BRegWorkload")) + facade = _methods(_class(FACADE_STUB, "BRegWorkload")) + + for name, native_method in native.items(): + with self.subTest(method=name): + expected = _signature(native_method) + self.assertEqual(_signature(runtime[name]), expected) + self.assertEqual(_signature(facade[name]), expected) + + def test_every_method_forwards_all_arguments_and_result_identity(self) -> None: + native = RecordingClient() + client = BRegWorkload(native) + method_names = sorted(_methods(_class(NATIVE_STUB, "BaseRegistryClient"))) + + for name in method_names: + with self.subTest(method=name): + signature = inspect.signature(getattr(BRegWorkload, name)) + positional: list[object] = [] + keywords: dict[str, object] = {} + for parameter in signature.parameters.values(): + if parameter.name == "self": + continue + value = object() + if parameter.kind in ( + inspect.Parameter.POSITIONAL_ONLY, + inspect.Parameter.POSITIONAL_OR_KEYWORD, + ): + positional.append(value) + elif parameter.kind == inspect.Parameter.KEYWORD_ONLY: + keywords[parameter.name] = value + else: + self.fail(f"unexpected variadic parameter on {name}") + expected = native.results.setdefault(name, object()) + actual = getattr(client, name)(*positional, **keywords) + self.assertIs(actual, expected) + self.assertEqual(native.calls[-1], (name, tuple(positional), keywords)) + + def test_native_errors_pass_through_unchanged(self) -> None: + native = RecordingClient() + failure = RuntimeError("native refusal") + native.failures["health"] = failure + + with self.assertRaises(RuntimeError) as raised: + BRegWorkload(native).health() + + self.assertIs(raised.exception, failure) + + def test_unknown_operation_uses_the_closed_public_error(self) -> None: + native = RecordingClient() + client = BRegWorkload(native) + + with self.assertRaises(UnsupportedOperationError) as raised: + getattr(client, "bearer_token") + + self.assertEqual(raised.exception.code, "client.operation-not-supported") + self.assertEqual(raised.exception.product, "breg") + self.assertEqual(raised.exception.operation, "bearer_token") + self.assertEqual(native.calls, []) + + def test_direct_event_loop_call_is_refused_before_the_native_client(self) -> None: + native = RecordingClient() + client = BRegWorkload(native) + + async def invoke() -> None: + with self.assertRaisesRegex(RuntimeError, "event-loop thread"): + client.health() + + asyncio.run(invoke()) + self.assertEqual(native.calls, []) + + +if __name__ == "__main__": + unittest.main() diff --git a/crates/registry-stack-client-py/tests/test_casework_workload.py b/crates/registry-stack-client-py/tests/test_casework_workload.py new file mode 100644 index 0000000000..f3cecb05ab --- /dev/null +++ b/crates/registry-stack-client-py/tests/test_casework_workload.py @@ -0,0 +1,244 @@ +"""The staff workload facade preserves the accepted L4 Casework surface.""" + +from __future__ import annotations + +import ast +import asyncio +import copy +import importlib +import inspect +from pathlib import Path +import sys +import types +import unittest + + +ROOT = Path(__file__).resolve().parents[3] +FACADE_SOURCE = ROOT / "crates/registry-stack-client-py/python/registry_client" +NATIVE_STUB = ( + ROOT + / "crates/registry-casework-client-py/python/registry_casework_client/__init__.pyi" +) +FACADE_RUNTIME = FACADE_SOURCE / "workload_casework.py" +FACADE_STUB = FACADE_SOURCE / "workload_casework.pyi" +L4_METHODS = { + "description", + "review_policies", + "review_policy", + "review_tasks", + "review_task", + "review_task_context", + "claim_review_task", + "release_review_task", + "decide_review_task", + "own_review_decisions", + "review_history", +} + + +def _load_facade(): + package_name = "_registry_client_casework_workload_test" + package = types.ModuleType(package_name) + package.__path__ = [str(FACADE_SOURCE)] + sys.modules[package_name] = package + return importlib.import_module(f"{package_name}.workload_casework") + + +workload_casework = _load_facade() +CaseworkWorkload = workload_casework.CaseworkWorkload +UnsupportedOperationError = importlib.import_module( + f"{CaseworkWorkload.__module__.rsplit('.', 1)[0]}.connection" +).UnsupportedOperationError + + +def _class(path: Path, name: str) -> ast.ClassDef: + module = ast.parse(path.read_text(encoding="utf-8")) + return next( + node + for node in module.body + if isinstance(node, ast.ClassDef) and node.name == name + ) + + +def _methods(node: ast.ClassDef) -> dict[str, ast.FunctionDef]: + return { + member.name: member + for member in node.body + if isinstance(member, ast.FunctionDef) + and member.name not in {"__init__", "__getattr__", "__setattr__"} + } + + +class _UnqualifyCasework(ast.NodeTransformer): + def visit_Attribute(self, node: ast.Attribute): + node = self.generic_visit(node) + if isinstance(node.value, ast.Name) and node.value.id == "casework": + return ast.copy_location(ast.Name(id=node.attr, ctx=node.ctx), node) + return node + + +def _signature(node: ast.FunctionDef, *, remove_auth: bool = False) -> tuple[str, str]: + arguments = copy.deepcopy(node.args) + if remove_auth: + self_arg, token_arg, profile_arg, *remaining = arguments.args + if ( + self_arg.arg != "self" + or token_arg.arg != "token" + or profile_arg.arg != "profile" + ): + raise AssertionError( + f"unexpected native authentication prefix on {node.name}" + ) + arguments.args = [self_arg, *remaining] + arguments = _UnqualifyCasework().visit(arguments) + returns = ( + _UnqualifyCasework().visit(copy.deepcopy(node.returns)) + if node.returns is not None + else None + ) + return ( + ast.dump(arguments, include_attributes=False), + ast.dump(returns, include_attributes=False), + ) + + +class RecordingClient: + def __init__(self) -> None: + self.calls: list[tuple[str, tuple[object, ...], dict[str, object]]] = [] + self.results: dict[str, object] = {} + self.failures: dict[str, BaseException] = {} + + def __getattr__(self, name: str): + def call(*args: object, **kwargs: object): + self.calls.append((name, args, kwargs)) + if name in self.failures: + raise self.failures[name] + return self.results.setdefault(name, object()) + + return call + + +class TokenProviderCanary: + def __init__(self) -> None: + self.calls = 0 + + def bearer_token(self) -> str: + self.calls += 1 + return "late-token" + + +class CaseworkWorkloadTests(unittest.TestCase): + def test_runtime_and_stub_declare_exactly_the_l4_method_set(self) -> None: + native = _methods(_class(NATIVE_STUB, "CaseworkClient")) + runtime = _methods(_class(FACADE_RUNTIME, "CaseworkWorkload")) + facade = _methods(_class(FACADE_STUB, "CaseworkWorkload")) + + self.assertTrue(L4_METHODS <= set(native)) + self.assertEqual(len(L4_METHODS), 11) + self.assertEqual(set(runtime), L4_METHODS) + self.assertEqual(set(facade), L4_METHODS) + + def test_runtime_and_stub_preserve_native_signatures_without_auth(self) -> None: + native = _methods(_class(NATIVE_STUB, "CaseworkClient")) + runtime = _methods(_class(FACADE_RUNTIME, "CaseworkWorkload")) + facade = _methods(_class(FACADE_STUB, "CaseworkWorkload")) + + for name in L4_METHODS: + with self.subTest(method=name): + expected = _signature(native[name], remove_auth=True) + self.assertEqual(_signature(runtime[name]), expected) + self.assertEqual(_signature(facade[name]), expected) + + def test_every_method_supplies_bound_auth_and_forwards_remaining_arguments( + self, + ) -> None: + native = RecordingClient() + token = "secret-token-canary" + profile = "reviewer-profile" + client = CaseworkWorkload(native, token, profile) + + for name in sorted(L4_METHODS): + with self.subTest(method=name): + signature = inspect.signature(getattr(CaseworkWorkload, name)) + positional: list[object] = [] + keywords: dict[str, object] = {} + for parameter in signature.parameters.values(): + if parameter.name == "self": + continue + value = object() + if parameter.kind in ( + inspect.Parameter.POSITIONAL_ONLY, + inspect.Parameter.POSITIONAL_OR_KEYWORD, + ): + positional.append(value) + elif parameter.kind == inspect.Parameter.KEYWORD_ONLY: + keywords[parameter.name] = value + else: + self.fail(f"unexpected variadic parameter on {name}") + expected = native.results.setdefault(name, object()) + actual = getattr(client, name)(*positional, **keywords) + self.assertIs(actual, expected) + self.assertEqual( + native.calls[-1], + (name, (token, profile, *positional), keywords), + ) + + def test_native_errors_pass_through_unchanged(self) -> None: + native = RecordingClient() + failure = RuntimeError("native refusal") + native.failures["description"] = failure + + with self.assertRaises(RuntimeError) as raised: + CaseworkWorkload(native, "token", "profile").description() + + self.assertIs(raised.exception, failure) + + def test_unknown_operation_uses_the_closed_public_error(self) -> None: + native = RecordingClient() + client = CaseworkWorkload(native, "secret-token-canary", "profile") + + with self.assertRaises(UnsupportedOperationError) as raised: + getattr(client, "create_or_recover_review_request") + + self.assertEqual(raised.exception.code, "client.operation-not-supported") + self.assertEqual(raised.exception.product, "casework") + self.assertEqual(raised.exception.operation, "create_or_recover_review_request") + self.assertEqual(native.calls, []) + + def test_auth_is_a_secret_safe_immutable_snapshot_not_a_callback(self) -> None: + provider = TokenProviderCanary() + with self.assertRaisesRegex(TypeError, "token must be a string"): + CaseworkWorkload(RecordingClient(), provider, "profile") + self.assertEqual(provider.calls, 0) + + with self.assertRaisesRegex(TypeError, "profile must be a string"): + CaseworkWorkload(RecordingClient(), "token", object()) + + native = RecordingClient() + client = CaseworkWorkload(native, "secret-token-canary", "profile") + self.assertNotIn("secret-token-canary", repr(client)) + with self.assertRaisesRegex(AttributeError, "immutable"): + client._token = "replacement" + with self.assertRaisesRegex(AttributeError, "immutable"): + client._profile = "replacement" + + client.description() + self.assertEqual( + native.calls[-1], + ("description", ("secret-token-canary", "profile"), {}), + ) + + def test_direct_event_loop_call_is_refused_before_the_native_client(self) -> None: + native = RecordingClient() + client = CaseworkWorkload(native, "token", "profile") + + async def invoke() -> None: + with self.assertRaisesRegex(RuntimeError, "event-loop thread"): + client.description() + + asyncio.run(invoke()) + self.assertEqual(native.calls, []) + + +if __name__ == "__main__": + unittest.main() diff --git a/crates/registry-stack-client-py/tests/test_connection.py b/crates/registry-stack-client-py/tests/test_connection.py new file mode 100644 index 0000000000..4e24ae5f09 --- /dev/null +++ b/crates/registry-stack-client-py/tests/test_connection.py @@ -0,0 +1,665 @@ +"""Connection validation keeps workload authority explicit and bounded.""" + +from contextlib import redirect_stderr +import importlib +from io import StringIO +import json +import os +from pathlib import Path +import sys +import tempfile +import threading +import time +import types +import unittest +from unittest.mock import patch + + +class ConnectionTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + class NativeClient: + def __init__(self, *args, **kwargs): + self.args = args + self.kwargs = kwargs + + def submit(self, *args): + return args + + def message_receipt(self, *args): + return args + + def health(self): + return "healthy" + + def bearer_token(self): + return "test-bearer" + + def registry_metadata(self, access_profile=None): + return self.kwargs["authorization"] + + cls.NativeClient = NativeClient + + modules = {} + for product in ( + "breg", + "casework", + "discovery", + "evidence", + "messaging", + "scheduling", + "coordinator", + "render", + ): + module = types.ModuleType(f"registry_client.{product}") + module.PrivateKeyJwt = NativeClient + module.BaseRegistryClient = NativeClient + module.MessagingClient = NativeClient + modules[module.__name__] = module + yaml_module = types.ModuleType("registry_client.yaml") + + class ConfigReadError(ValueError): + def __init__(self, message, *, diagnostics=None): + super().__init__(message) + self.diagnostics = diagnostics or ({"code": "configuration.refused"},) + + def read_document(contents, *, file, api_version, kind): + def unique_pairs(pairs): + result = {} + for name, value in pairs: + if name in result: + raise ConfigReadError("duplicate mapping key") + result[name] = value + return result + + try: + value = json.loads(contents, object_pairs_hook=unique_pairs) + except (UnicodeError, json.JSONDecodeError): + raise ConfigReadError("invalid document") from None + if not isinstance(value, dict): + raise ConfigReadError("wrong envelope") + if value.get("kind") != kind: + raise ConfigReadError( + "wrong kind", diagnostics=({"code": "config.wrong-kind"},) + ) + if value.get("apiVersion") != api_version: + raise ConfigReadError( + "wrong version", + diagnostics=({"code": "config.unsupported-api-version"},), + ) + return value + + yaml_module.ConfigReadError = ConfigReadError + yaml_module.read_document = read_document + modules[yaml_module.__name__] = yaml_module + cls.module_patch = patch.dict(sys.modules, modules) + cls.module_patch.start() + cls.path_patch = patch.object( + sys, + "path", + [str(Path(__file__).resolve().parents[1] / "python"), *sys.path], + ) + cls.path_patch.start() + cls.client = importlib.import_module("registry_client.connection") + + @classmethod + def tearDownClass(cls): + for name in ( + "registry_client.connection", + "registry_client.auth", + "registry_client", + ): + sys.modules.pop(name, None) + cls.path_patch.stop() + cls.module_patch.stop() + + def setUp(self): + self.ConnectionError = self.client.ConnectionError + self.connect = self.client.connect + self.temporary = tempfile.TemporaryDirectory() + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + (self.root / "key").write_text('{"kty":"EC"}', encoding="utf-8") + (self.root / "key").chmod(0o600) + + def connection(self, bindings): + path = self.root / "connection.json" + path.write_text( + json.dumps( + { + "apiVersion": "id.registrystack.org/formats/platform/python-connection/v1alpha1", + "kind": "PlatformPythonConnection", + "service": "test-service", + "audience": "service", + "secretProviders": {"file": {"root": str(self.root)}}, + "bindings": bindings, + } + ), + encoding="utf-8", + ) + return path + + def binding(self, name="registry", product="breg", default=True): + return { + "name": name, + "product": product, + "url": "https://example.invalid/", + "default": default, + "credential": { + "type": "private-key-jwt", + "issuer": "https://issuer.example.invalid/", + "subject": "test-workload", + "tokenEndpoint": "https://issuer.example.invalid/token", + "clientId": "test-client", + "profile": "test-profile", + "clientKeyRef": "secret:file/key", + "resource": "https://example.invalid/", + "scopes": ["registry.read"], + "claims": { + "application_reference": "application-001", + "registry_actor_kind": "service", + }, + }, + } + + def test_authority_fingerprint_tracks_identity_not_alias_or_secret(self): + primary = self.binding(product="messaging") + alias = self.binding(name="renamed", product="messaging", default=False) + alias["url"] = "https://moved.example.invalid/" + alias["credential"]["tokenEndpoint"] = ( + "https://issuer.example.invalid/other-token-endpoint" + ) + alias["credential"]["clientKeyRef"] = "secret:file/other-key" + alias["credential"]["claims"] = { + "registry_actor_kind": "service", + "application_reference": "application-001", + } + (self.root / "other-key").write_text('{"kty":"EC"}', encoding="utf-8") + (self.root / "other-key").chmod(0o600) + + stack = self.connect(path=self.connection([primary, alias])) + default = stack.authority("messaging") + renamed = stack.using("renamed").authority + + self.assertEqual(default, renamed) + self.assertEqual(default.product, "messaging") + self.assertEqual(default.issuer, "https://issuer.example.invalid/") + self.assertEqual(default.subject, "test-workload") + self.assertEqual(default.client_id, "test-client") + self.assertEqual(default.profile, "test-profile") + self.assertEqual(default.resource, "https://example.invalid/") + self.assertEqual(default.scopes, ("registry.read",)) + self.assertEqual( + default.claims, + { + "application_reference": "application-001", + "registry_actor_kind": "service", + }, + ) + self.assertRegex(default.fingerprint, r"\A[0-9a-f]{64}\Z") + self.assertNotIn("other-key", repr(default)) + self.assertNotIn("application-001", repr(default)) + self.assertNotIn("test-workload", repr(default)) + with self.assertRaises(TypeError): + default.claims["registry_actor_kind"] = "human" + + for field, value in ( + ("issuer", "https://other-issuer.example.invalid/"), + ("subject", "other-workload"), + ("clientId", "other-client"), + ("profile", "other-profile"), + ("resource", "urn:registry:messaging:other"), + ("scopes", ["registry.read", "registry.write"]), + ( + "claims", + { + "application_reference": "application-002", + "registry_actor_kind": "service", + }, + ), + ): + with self.subTest(field=field): + changed = self.binding( + name="changed", product="messaging", default=False + ) + changed["credential"][field] = value + changed_stack = self.connect(path=self.connection([primary, changed])) + self.assertNotEqual( + default.fingerprint, + changed_stack.using("changed").authority.fingerprint, + ) + + reordered = self.binding( + name="reordered", product="messaging", default=False + ) + primary["credential"]["scopes"] = ["registry.write", "registry.read"] + reordered["credential"]["scopes"] = ["registry.read", "registry.write"] + reordered_stack = self.connect(path=self.connection([primary, reordered])) + self.assertEqual( + reordered_stack.authority("messaging").fingerprint, + reordered_stack.using("reordered").authority.fingerprint, + ) + + def test_private_key_authority_requires_complete_identity_metadata(self): + for field in ("issuer", "subject", "profile", "claims"): + with self.subTest(field=field): + binding = self.binding() + del binding["credential"][field] + with self.assertRaisesRegex(self.ConnectionError, f"{field}.*required"): + self.connect(path=self.connection([binding])) + + def test_declared_claims_cannot_replace_protocol_identity(self): + binding = self.binding() + binding["credential"]["claims"]["sub"] = "other-workload" + with self.assertRaisesRegex(self.ConnectionError, "claim name"): + self.connect(path=self.connection([binding])) + + def test_missing_default_refuses_without_selecting_another_binding(self): + path = self.connection([self.binding(default=False)]) + with self.assertRaisesRegex(self.ConnectionError, "default.*breg"): + self.connect(path=path) + + def test_connect_is_the_public_core_entry_point(self): + from registry_client import WorkloadAuthority, connect + + self.assertIs(connect, self.connect) + self.assertIs(WorkloadAuthority, self.client.WorkloadAuthority) + + def test_duplicate_default_refuses(self): + path = self.connection([self.binding(), self.binding(name="other")]) + with self.assertRaisesRegex(self.ConnectionError, "default.*breg"): + self.connect(path=path) + + def test_connection_kind_is_required_and_exact(self): + path = self.connection([self.binding()]) + document = json.loads(path.read_text(encoding="utf-8")) + document["kind"] = "PlatformOtherConnection" + path.write_text(json.dumps(document), encoding="utf-8") + with self.assertRaises(self.ConnectionError) as caught: + self.connect(path=path) + self.assertEqual(caught.exception.diagnostics[0]["code"], "config.wrong-kind") + + def test_duplicate_mapping_key_is_refused_with_bounded_diagnostics(self): + path = self.connection([self.binding()]) + raw = path.read_text(encoding="utf-8") + path.write_text(raw.replace('"service": "test-service",', + '"service": "test-service", "service": "other",'), + encoding="utf-8") + with self.assertRaises(self.ConnectionError) as caught: + self.connect(path=path) + self.assertEqual(caught.exception.diagnostics[0]["code"], "configuration.refused") + + def test_unknown_binding_and_product_refuse_with_named_errors(self): + path = self.connection([self.binding()]) + stack = self.connect(path=path) + with self.assertRaisesRegex(self.ConnectionError, "unknown.*binding"): + stack.using("missing") + with self.assertRaisesRegex(self.ConnectionError, "messaging"): + _ = stack.messaging + + def test_inline_credential_and_malformed_reference_refuse_without_leak(self): + binding = self.binding() + binding["credential"]["token"] = "secret-canary" + path = self.connection([binding]) + with self.assertRaises(self.ConnectionError) as caught: + self.connect(path=path) + self.assertNotIn("secret-canary", str(caught.exception)) + del binding["credential"]["token"] + binding["credential"]["clientKeyRef"] = "secret:file/../key" + path = self.connection([binding]) + with self.assertRaisesRegex(self.ConnectionError, "clientKeyRef"): + self.connect(path=path) + + def test_unsupported_audience_refuses(self): + path = self.connection([self.binding()]) + document = json.loads(path.read_text(encoding="utf-8")) + document["audience"] = "all" + path.write_text(json.dumps(document), encoding="utf-8") + with self.assertRaisesRegex(self.ConnectionError, "audience"): + self.connect(path=path) + + def test_breg_uses_native_provider_and_named_binding_is_immutable(self): + from registry_client.workload_breg import BRegWorkload + + path = self.connection( + [self.binding(), self.binding(name="other", default=False)] + ) + stack = self.connect(path=path) + default = stack.breg + named = stack.using("other").breg + self.assertIsInstance(default, BRegWorkload) + self.assertIs(default, stack.breg) + self.assertIsNot(default, named) + self.assertIn("private_key_jwt", default._client.kwargs["authorization"]) + self.assertEqual( + stack.breg._client.kwargs["authorization"]["private_key_jwt"]["client_id"], + "test-client", + ) + + def test_messaging_supplies_token_for_every_protected_call(self): + path = self.connection([self.binding(product="messaging")]) + stack = self.connect(path=path) + self.assertEqual(stack.messaging.health(), "healthy") + self.assertEqual( + stack.messaging.submit("key", {"message": "test"}), + ("test-bearer", "key", {"message": "test"}), + ) + self.assertEqual( + stack.messaging.message_receipt("key", {"message": "test"}), + ("test-bearer", "key", {"message": "test"}), + ) + with self.assertRaisesRegex( + AttributeError, "client.operation-not-supported.*messaging.*bearer_token" + ): + _ = stack.messaging.bearer_token + + def test_urn_resource_and_local_runner_http_are_valid(self): + binding = self.binding() + binding["url"] = "http://127.0.0.1:8123/registry" + binding["credential"]["tokenEndpoint"] = "http://localhost:8124/oauth/token" + binding["credential"]["resource"] = "urn:registry:breg:test" + stack = self.connect(path=self.connection([binding])) + self.assertEqual(stack.breg._client.args[0], binding["url"]) + + def test_nonloopback_http_is_refused(self): + binding = self.binding() + binding["url"] = "http://registry.example.invalid/" + with self.assertRaisesRegex(self.ConnectionError, "url"): + self.connect(path=self.connection([binding])) + + def test_concurrent_selection_constructs_one_native_client(self): + path = self.connection([self.binding()]) + stack = self.connect(path=path) + constructed = [] + original = self.NativeClient.__init__ + + def initialize(instance, *args, **kwargs): + time.sleep(0.01) + constructed.append(instance) + original(instance, *args, **kwargs) + + results = [] + with patch.object(self.NativeClient, "__init__", initialize): + threads = [ + threading.Thread(target=lambda: results.append(stack.breg)) + for _ in range(8) + ] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + self.assertEqual(len(constructed), 1) + self.assertTrue(all(result is results[0] for result in results)) + + def test_file_secret_must_be_private_and_owned(self): + stack = self.connect(path=self.connection([self.binding()])) + (self.root / "key").chmod(0o644) + with self.assertRaisesRegex(self.ConnectionError, "private regular file"): + _ = stack.breg + + def test_file_secret_rejects_a_shared_root_and_symlink(self): + path = self.connection([self.binding()]) + self.root.chmod(0o755) + with self.assertRaisesRegex(self.ConnectionError, "private directory"): + _ = self.connect(path=path).breg + self.root.chmod(0o700) + (self.root / "key").rename(self.root / "original") + (self.root / "key").symlink_to(self.root / "original") + with self.assertRaisesRegex(self.ConnectionError, "private regular file"): + _ = self.connect(path=path).breg + + def test_offline_checker_reads_secret_refs_without_native_construction(self): + from registry_client.check_connection import check_file + + path = self.connection([self.binding()]) + with patch.object(self.NativeClient, "__init__", side_effect=AssertionError("native")): + check_file(path) + (self.root / "key").write_text("not-json", encoding="utf-8") + with self.assertRaisesRegex(self.ConnectionError, "client key"): + check_file(path) + + def test_offline_checker_cli_prints_bounded_structured_diagnostics(self): + checker = importlib.import_module("registry_client.check_connection") + diagnostics = tuple( + { + "code": "config.unknown-key", + "path": f"/bindings/{index}/unexpected", + "message": "value-canary must not be printed", + "source": { + "file": "connection.json", + "line": index + 1, + "column": 7, + }, + } + for index in range(12) + ) + failure = self.ConnectionError("the read-back document was refused", diagnostics=diagnostics) + stderr = StringIO() + with ( + patch.object(checker, "check_file", side_effect=failure), + patch.object(sys, "argv", ["registry-client-check", "connection.json"]), + redirect_stderr(stderr), + self.assertRaises(SystemExit) as caught, + ): + checker.main() + self.assertEqual(caught.exception.code, 2) + output = stderr.getvalue() + self.assertIn("config.unknown-key at /bindings/0/unexpected", output) + self.assertIn("connection.json:1:7", output) + self.assertIn("2 additional diagnostics omitted", output) + self.assertNotIn("/bindings/10/unexpected", output) + self.assertNotIn("value-canary", output) + + def test_expired_budget_refuses_new_native_work(self): + from registry_client.workload import RequestBudgetExceeded, request_budget + + stack = self.connect(path=self.connection([self.binding()])) + native = stack.breg._client + with patch.object(native, "health", wraps=native.health) as health: + with request_budget(0.001): + time.sleep(0.005) + with self.assertRaises(RequestBudgetExceeded): + stack.breg.health() + health.assert_not_called() + + def test_nested_budget_cannot_extend_the_outer_limit(self): + from registry_client.workload import RequestBudgetExceeded, request_budget + + stack = self.connect(path=self.connection([self.binding()])) + with request_budget(0.001): + with request_budget(60): + time.sleep(0.005) + with self.assertRaises(RequestBudgetExceeded): + stack.breg.health() + + def runner_binding(self, product="breg"): + binding = self.binding(product=product) + binding["credential"] = { + "type": "runner-token", + "tokenRef": "secret:file/workload-registry.json", + "runId": "run-one", + "binding": "registry", + "issuer": "https://issuer.example.invalid/", + "subject": "test-workload", + "clientId": "test-client", + "profile": "test-profile", + "resource": "urn:registry:breg:test", + "scopes": ["registry.read"], + "claims": {"registry_actor_kind": "service"}, + "runExpiresAt": int(time.time()) + 900, + } + return binding + + def write_runner_state(self, binding, generation, *, token=None, issuer=None): + credential = binding["credential"] + now = int(time.time()) + state = { + "apiVersion": "id.registrystack.org/formats/platform/dev-workload-token/v1alpha1", + "kind": "PlatformDevWorkloadToken", + "runId": credential["runId"], + "binding": binding["name"], + "product": binding["product"], + "issuer": issuer or credential["issuer"], + "subject": credential["subject"], + "clientId": credential["clientId"], + "profile": credential["profile"], + "resource": credential["resource"], + "scopes": credential["scopes"], + "claims": credential["claims"], + "generation": generation, + "issuedAt": now, + "expiresAt": now + 300, + "runExpiresAt": credential["runExpiresAt"], + "token": token or f"synthetic-token-{generation}", + } + temporary = self.root / "next-token.json" + temporary.write_text(json.dumps(state), encoding="utf-8") + temporary.chmod(0o600) + os.replace(temporary, self.root / "workload-registry.json") + + def test_runner_token_rotation_updates_breg_without_changing_handle(self): + binding = self.runner_binding() + self.write_runner_state(binding, 1) + stack = self.connect(path=self.connection([binding])) + handle = stack.breg + self.assertEqual(handle.registry_metadata(), {"static": "synthetic-token-1"}) + self.write_runner_state(binding, 2) + self.assertIs(stack.breg, handle) + self.assertEqual(handle.registry_metadata(), {"static": "synthetic-token-2"}) + + def test_runner_token_kind_cannot_cross_format_boundary(self): + binding = self.runner_binding() + self.write_runner_state(binding, 1) + state_path = self.root / "workload-registry.json" + state = json.loads(state_path.read_text(encoding="utf-8")) + state["kind"] = "PlatformPythonConnection" + state_path.write_text(json.dumps(state), encoding="utf-8") + state_path.chmod(0o600) + stack = self.connect(path=self.connection([binding])) + with self.assertRaisesRegex(self.ConnectionError, "runner token"): + stack.breg.registry_metadata() + + def test_offline_checker_validates_standalone_runner_state(self): + from registry_client.check_connection import check_file + + binding = self.runner_binding() + self.write_runner_state(binding, 1) + state_path = self.root / "workload-registry.json" + check_file(state_path) + state = json.loads(state_path.read_text(encoding="utf-8")) + state["expiresAt"] = 0 + state_path.write_text(json.dumps(state), encoding="utf-8") + state_path.chmod(0o600) + with self.assertRaisesRegex(self.ConnectionError, "lifetime"): + check_file(state_path) + + def test_offline_checker_accepts_stopped_envelope_but_consumer_refuses(self): + from registry_client.check_connection import check_file + + binding = self.runner_binding() + self.write_runner_state(binding, 1) + state_path = self.root / "workload-registry.json" + state = json.loads(state_path.read_text(encoding="utf-8")) + state["status"] = "stopped" + state["expiresAt"] = state["issuedAt"] + del state["token"] + state_path.write_text(json.dumps(state), encoding="utf-8") + state_path.chmod(0o600) + check_file(state_path) + stack = self.connect(path=self.connection([binding])) + with self.assertRaisesRegex(self.ConnectionError, "runner token state"): + stack.breg.registry_metadata() + + def test_runner_token_rejects_identity_change_and_generation_rollback(self): + binding = self.runner_binding() + self.write_runner_state(binding, 2) + stack = self.connect(path=self.connection([binding])) + self.assertEqual(stack.breg.registry_metadata(), {"static": "synthetic-token-2"}) + self.write_runner_state(binding, 3, issuer="https://other.example.invalid/") + with self.assertRaisesRegex(self.ConnectionError, "runner"): + stack.breg.registry_metadata() + self.write_runner_state(binding, 3) + state_path = self.root / "workload-registry.json" + state = json.loads(state_path.read_text(encoding="utf-8")) + state["claims"]["registry_actor_kind"] = "human" + state_path.write_text(json.dumps(state), encoding="utf-8") + state_path.chmod(0o600) + with self.assertRaisesRegex(self.ConnectionError, "authority"): + stack.breg.registry_metadata() + self.write_runner_state(binding, 1) + with self.assertRaisesRegex(self.ConnectionError, "generation"): + stack.breg.registry_metadata() + + def test_runner_token_stop_refuses_without_using_cached_bearer(self): + binding = self.runner_binding(product="messaging") + self.write_runner_state(binding, 1) + stack = self.connect(path=self.connection([binding])) + self.assertEqual(stack.messaging.submit("key", {}), ("synthetic-token-1", "key", {})) + (self.root / "workload-registry.json").unlink() + with self.assertRaises(self.ConnectionError): + stack.messaging.submit("key", {}) + + def admission_config(self): + return { + "issuer": "https://issuer.example.invalid/", + "resource": "urn:registry:python:test", + "clientId": "coordinator-client", + "profile": "coordinator-invoker", + "requiredScopes": ["python.invoke"], + "requiredClaims": {"registry_actor_kind": "machine"}, + "algorithm": "RS256", + "accessTokenType": "at+jwt", + "maximumAccessTokenLifetimeSeconds": 300, + } + + def test_connection_admits_only_its_exact_service_invoker(self): + path = self.connection([self.binding()]) + document = json.loads(path.read_text(encoding="utf-8")) + document["admission"] = self.admission_config() + path.write_text(json.dumps(document), encoding="utf-8") + + class Verifier: + def __init__(self, *args, **kwargs): + self.args = args + self.options = kwargs + + def verify(self, token): + return types.SimpleNamespace( + kind="access", + issuer="https://issuer.example.invalid/", + audiences=("urn:registry:python:test",), + subject="coordinator", + client_id="coordinator-client", + scopes=("python.invoke",), + claims={"registry_actor_kind": "machine"}, + ) + + native = types.ModuleType("registry_client.oidc") + native.AccessTokenVerifier = Verifier + with patch.dict(sys.modules, {"registry_client.oidc": native}): + stack = self.connect(path=path) + context = stack.admit({"authorization": ["Bearer synthetic"]}) + self.assertEqual(context.client_id, "coordinator-client") + self.assertEqual(context.profile, "coordinator-invoker") + + def test_admission_configuration_is_service_only(self): + path = self.connection([self.binding()]) + document = json.loads(path.read_text(encoding="utf-8")) + document["admission"] = self.admission_config() + document["audience"] = "holder" + path.write_text(json.dumps(document), encoding="utf-8") + with self.assertRaisesRegex(self.ConnectionError, "admission"): + self.connect(path=path) + + def test_malformed_machine_scope_is_a_named_configuration_error(self): + path = self.connection([self.binding()]) + document = json.loads(path.read_text(encoding="utf-8")) + document["admission"] = self.admission_config() + document["admission"]["requiredScopes"] = [{"invalid": "scope"}] + path.write_text(json.dumps(document), encoding="utf-8") + with self.assertRaisesRegex(self.ConnectionError, "requiredScopes"): + self.connect(path=path) + + +if __name__ == "__main__": + unittest.main() diff --git a/crates/registry-stack-client-py/tests/test_dev_picker.py b/crates/registry-stack-client-py/tests/test_dev_picker.py new file mode 100644 index 0000000000..5e1956f6d6 --- /dev/null +++ b/crates/registry-stack-client-py/tests/test_dev_picker.py @@ -0,0 +1,555 @@ +"""The local picker accepts only one live runner's complete development authority.""" + +from __future__ import annotations + +import asyncio +import base64 +import fcntl +import importlib +import json +from pathlib import Path +import re +import sys +import tempfile +import time +import types +import unittest + +from fastapi import FastAPI, Request +from flask import Flask, g, jsonify +import httpx + + +SOURCE = Path(__file__).resolve().parents[1] / "python" / "registry_client" +PACKAGE = "_registry_client_dev_picker_test" +package = types.ModuleType(PACKAGE) +package.__path__ = [str(SOURCE)] +sys.modules[PACKAGE] = package +yaml_module = types.ModuleType(f"{PACKAGE}.yaml") + + +class ConfigReadError(ValueError): + def __init__(self, message, *, diagnostics=()): + super().__init__(message) + self.diagnostics = diagnostics + + +def read_document(contents, *, file, api_version, kind): + try: + value = json.loads(contents) + except (UnicodeError, json.JSONDecodeError): + raise ConfigReadError("invalid document") from None + if value.get("apiVersion") != api_version or value.get("kind") != kind: + raise ConfigReadError("wrong envelope") + return value + + +yaml_module.ConfigReadError = ConfigReadError +yaml_module.read_document = read_document +sys.modules[yaml_module.__name__] = yaml_module +portal = importlib.import_module(f"{PACKAGE}.portal") +dev_picker = importlib.import_module(f"{PACKAGE}.dev_picker") + + +RUN_ID = "0123456789abcdef0123456789abcdef" + + +def _segment(value): + return base64.urlsafe_b64encode( + json.dumps(value, separators=(",", ":")).encode() + ).rstrip(b"=").decode() + + +def _token(*, product, persona, generation, issued, expires, **changes): + audience = f"urn:test:{product}" + claims = { + "iss": "https://issuer.example.test", + "aud": audience, + "sub": "person-one", + "client_id": "portal-client", + "scope": f"{product}:read", + "registry_principal": "person-one", + "registry_dev_persona": persona, + "iat": issued, + "exp": expires, + "jti": f"generation-{generation}-{product}", + } + claims.update(changes) + return f"{_segment({'typ': 'at+jwt'})}.{_segment(claims)}.signature" + + +class LivePicker: + def __init__(self): + self.scratch = tempfile.TemporaryDirectory() + self.root = Path(self.scratch.name) / RUN_ID + self.root.mkdir(mode=0o700) + self.lock_path = self.root / "worker.lock" + self.lock_path.write_bytes(b"") + self.lock_path.chmod(0o600) + self.lock = self.lock_path.open("rb") + fcntl.flock(self.lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + self.now = int(time.time()) + self.expires = self.now + 600 + self.origin = "http://127.0.0.1:43891" + self.persona = "holder" + self.namespace = "run-namespace-canary" + self.picker_root = self.root / "python-picker" / self.persona + self.picker_root.mkdir(parents=True, mode=0o700) + self.picker_root.parent.chmod(0o700) + self.workload_root = self.root / "python-workload" + self.workload_root.mkdir(mode=0o700) + self.descriptor_path = self.picker_root / "picker.json" + self.selector = "opaque-selector-canary" + self._write_report("ready") + self._write_connection() + self.write_generation(1) + self.write_token("breg", 1) + self.write_token("casework", 1) + self.write_descriptor() + + def close(self): + self.lock.close() + self.scratch.cleanup() + + def _write_json(self, path, value): + path.write_text(json.dumps(value), encoding="utf-8") + path.chmod(0o600) + + def _write_report(self, status): + self._write_json( + self.root / "report.json", + { + "schema_version": "registry.rstack.dev.v1", + "run_id": RUN_ID, + "status": status, + "expires_at": self.expires, + }, + ) + + def _write_connection( + self, + *, + endpoint="http://127.0.0.1:49201", + credential_type="runner-token", + run_id=RUN_ID, + ): + credential = { + "type": credential_type, + "tokenRef": "secret:file/workload-notices.json", + "runId": run_id, + "binding": "notices", + "issuer": "https://issuer.example.test", + "subject": "notice-service", + "clientId": "notice-client", + "profile": "service-sender", + "resource": "urn:test:messaging", + "scopes": ["messaging:send"], + "claims": {"registry_actor_kind": "service"}, + "runExpiresAt": self.expires, + } + if credential_type != "runner-token": + credential = { + "type": "private-key-jwt", + "issuer": "https://production.example.test/", + "subject": "production-service", + "tokenEndpoint": "https://production.example.test/token", + "clientId": "production", + "profile": "service-sender", + "clientKeyRef": "secret:env/PRODUCTION_KEY", + "resource": "urn:test:messaging", + "scopes": ["messaging:send"], + "claims": {"registry_actor_kind": "service"}, + } + self._write_json( + self.workload_root / "python-connection.json", + { + "apiVersion": "id.registrystack.org/formats/platform/python-connection/v1alpha1", + "kind": "PlatformPythonConnection", + "service": f"rstack-dev-{RUN_ID}", + "audience": "service", + "secretProviders": {"file": {"root": str(self.workload_root.resolve())}}, + "bindings": [{ + "name": "notices", + "product": "messaging", + "url": endpoint, + "default": True, + "credential": credential, + }], + }, + ) + + def write_descriptor(self, **changes): + descriptor = { + "apiVersion": "id.registrystack.org/formats/platform/dev-person-picker/v1alpha1", + "kind": "PlatformDevPersonPicker", + "runId": RUN_ID, + "persona": self.persona, + "origin": self.origin, + "sessionNamespace": self.namespace, + "issuedAt": self.now, + "expiresAt": self.expires, + "generationRef": "generation.json", + "products": { + "breg": {"url": "http://127.0.0.1:49199", "resource": "urn:test:breg"}, + "casework": {"url": "http://127.0.0.1:49200", "resource": "urn:test:casework"}, + "messaging": {"url": "http://127.0.0.1:49201", "resource": "urn:test:messaging"}, + }, + "people": [{ + "selector": self.selector, + "label": "Applicant One", + "subject": "person-one", + "principal": "person-one", + "clientId": "portal-client", + "credentials": { + product: { + "tokenRef": f"person-one-{product}.json", + "profile": "applicant" if product == "breg" else "requester", + "resource": f"urn:test:{product}", + "audiences": [f"urn:test:{product}"], + "scopes": [f"{product}:read"], + "principalClaim": "registry_principal", + } + for product in ("breg", "casework") + }, + }], + "workloadConnectionRef": "../../python-workload/python-connection.json", + "workloads": [{ + "name": "notices", + "product": "messaging", + "default": True, + "url": "http://127.0.0.1:49201", + "issuer": "https://issuer.example.test", + "subject": "notice-service", + "clientId": "notice-client", + "profile": "service-sender", + "resource": "urn:test:messaging", + "scopes": ["messaging:send"], + "claims": {"registry_actor_kind": "service"}, + }], + } + descriptor.update(changes) + self._write_json(self.descriptor_path, descriptor) + + def write_generation(self, generation, *, status="ready", run_id=RUN_ID): + self._write_json( + self.picker_root / "generation.json", + { + "apiVersion": "id.registrystack.org/formats/platform/dev-person-generation/v1alpha1", + "kind": "PlatformDevPersonGeneration", + "status": status, + "runId": run_id, + "picker": self.persona, + "generation": generation, + "runExpiresAt": self.expires, + }, + ) + + def write_token(self, product, generation, **changes): + state = { + "apiVersion": "id.registrystack.org/formats/platform/dev-person-token/v1alpha1", + "kind": "PlatformDevPersonToken", + "runId": RUN_ID, + "picker": self.persona, + "persona": self.persona, + "selector": self.selector, + "product": product, + "issuer": "https://issuer.example.test", + "subject": "person-one", + "principal": "person-one", + "clientId": "portal-client", + "profile": "applicant" if product == "breg" else "requester", + "resource": f"urn:test:{product}", + "audiences": [f"urn:test:{product}"], + "scopes": [f"{product}:read"], + "principalClaim": "registry_principal", + "generation": generation, + "issuedAt": self.now, + "expiresAt": min(self.now + 300, self.expires), + "runExpiresAt": self.expires, + "token": _token( + product=product, + persona=self.persona, + generation=generation, + issued=self.now, + expires=min(self.now + 300, self.expires), + ), + } + state.update(changes) + self._write_json(self.picker_root / f"person-one-{product}.json", state) + + +class DevelopmentPickerTests(unittest.TestCase): + def setUp(self): + self.live = LivePicker() + + def tearDown(self): + self.live.close() + + def picker(self): + return dev_picker.DevelopmentPicker.from_descriptor(self.live.descriptor_path) + + def select(self, picker=None): + picker = picker or self.picker() + form = picker.begin() + session = picker.select( + form.pending_id, + selector=self.live.selector, + origin=self.live.origin, + host="127.0.0.1:43891", + csrf_token=form.csrf_token, + ) + return picker, session + + def test_only_a_private_live_runner_descriptor_mounts(self): + picker = self.picker() + self.assertEqual(picker.origin, self.live.origin) + self.assertEqual(picker.persona, "holder") + self.assertIn(self.live.namespace, picker.session_cookie) + self.assertEqual( + [(choice.label, choice.selector) for choice in picker.choices()], + [("Applicant One", self.live.selector)], + ) + self.assertNotIn("person-one", repr(picker)) + self.live.lock.close() + with self.assertRaisesRegex(dev_picker.PickerUnavailable, "live development run"): + dev_picker.DevelopmentPicker.from_descriptor(self.live.descriptor_path) + + def test_nonloopback_wrong_run_stopped_expired_and_copied_descriptors_are_refused(self): + cases = ( + {"origin": "https://portal.example.test"}, + {"runId": "f" * 32}, + {"expiresAt": self.live.now - 1}, + ) + for changes in cases: + with self.subTest(changes=changes): + self.live.write_descriptor(**changes) + with self.assertRaises(dev_picker.PickerUnavailable): + dev_picker.DevelopmentPicker.from_descriptor(self.live.descriptor_path) + self.live.write_descriptor() + self.live._write_report("stopping") + with self.assertRaises(dev_picker.PickerUnavailable): + dev_picker.DevelopmentPicker.from_descriptor(self.live.descriptor_path) + self.live._write_report("ready") + copied = self.live.root / "copied.json" + copied.write_bytes(self.live.descriptor_path.read_bytes()) + copied.chmod(0o600) + with self.assertRaises(dev_picker.PickerUnavailable): + dev_picker.DevelopmentPicker.from_descriptor(copied) + + def test_selection_is_opaque_csrf_bound_and_all_or_nothing(self): + picker = self.picker() + form = picker.begin() + for selector, origin, host, csrf in ( + ("person-one", self.live.origin, "127.0.0.1:43891", form.csrf_token), + (self.live.selector, "http://127.0.0.1:1", "127.0.0.1:43891", form.csrf_token), + (self.live.selector, self.live.origin, "127.0.0.1:1", form.csrf_token), + (self.live.selector, self.live.origin, "127.0.0.1:43891", "wrong"), + ): + with self.subTest(selector=selector, origin=origin, host=host, csrf=csrf): + with self.assertRaises(dev_picker.PickerAdmissionError): + picker.select( + form.pending_id, + selector=selector, + origin=origin, + host=host, + csrf_token=csrf, + ) + self.assertEqual(picker.session_count(), 0) + self.live.write_token("casework", 1, persona="staff") + with self.assertRaises(dev_picker.PickerAdmissionError): + picker.select( + form.pending_id, + selector=self.live.selector, + origin=self.live.origin, + host="127.0.0.1:43891", + csrf_token=form.csrf_token, + ) + self.assertEqual(picker.session_count(), 0) + + def test_complete_session_tracks_rotation_and_refuses_mismatch_stop_or_old_run(self): + picker, session = self.select() + context = picker.context(session.session_id) + self.assertEqual(context.subject, "person-one") + self.assertEqual(context.persona, "holder") + self.assertNotIn("canary", repr(context)) + + self.live.write_token("breg", 2) + with self.assertRaises(dev_picker.PickerUnavailable): + picker.context(session.session_id) + self.live.write_token("casework", 2) + self.live.write_generation(2) + rotated = picker.context(session.session_id) + self.assertEqual(rotated.session_id, session.session_id) + + self.live.write_generation(3, status="stopped") + with self.assertRaises(portal.ReauthenticationRequired): + picker.context(session.session_id) + self.assertEqual(picker.session_count(), 0) + + def test_person_clients_are_bound_to_descriptor_endpoints(self): + class NativeBReg: + def __init__(self, *args, **kwargs): + self.args = args + self.kwargs = kwargs + + class NativeCasework: + def __init__(self, *args, **kwargs): + self.args = args + self.kwargs = kwargs + + breg_module = types.ModuleType(f"{PACKAGE}.breg") + breg_module.BaseRegistryClient = NativeBReg + casework_module = types.ModuleType(f"{PACKAGE}.casework") + casework_module.CaseworkClient = NativeCasework + sys.modules[breg_module.__name__] = breg_module + sys.modules[casework_module.__name__] = casework_module + setattr(package, "breg", breg_module) + setattr(package, "casework", casework_module) + + picker, session = self.select() + person = picker.context(session.session_id) + self.assertEqual(person.breg._client.args[0], "http://127.0.0.1:49199") + self.assertEqual( + person.breg._client.kwargs["authorization"]["static"], + person._context._token_for("breg"), + ) + casework = person.casework + self.assertEqual( + casework._CaseworkWorkload__client.args[0], "http://127.0.0.1:49200" + ) + self.assertEqual(casework._CaseworkWorkload__profile, "requester") + self.assertNotIn("http", repr(person)) + + def test_tampered_identity_audience_client_or_missing_product_opens_no_session(self): + mutations = ( + ("breg", {"subject": "other"}), + ("breg", {"clientId": "other-client"}), + ("breg", {"audiences": ["urn:other"]}), + ("casework", {"resource": "urn:other"}), + ) + for product, changes in mutations: + with self.subTest(product=product, changes=changes): + self.live.write_token(product, 1, **changes) + picker = self.picker() + form = picker.begin() + with self.assertRaises(dev_picker.PickerAdmissionError): + picker.select( + form.pending_id, + selector=self.live.selector, + origin=self.live.origin, + host="127.0.0.1:43891", + csrf_token=form.csrf_token, + ) + self.assertEqual(picker.session_count(), 0) + self.live.write_token(product, 1) + (self.live.picker_root / "person-one-casework.json").unlink() + with self.assertRaises(dev_picker.PickerUnavailable): + self.picker() + + def test_workload_connection_is_same_run_runner_only_and_endpoint_bound(self): + picker = self.picker() + connection = picker.workloads + self.assertEqual(connection.using("notices")._binding.product, "messaging") + + self.live._write_connection(endpoint="http://127.0.0.1:49999") + with self.assertRaisesRegex(dev_picker.PickerUnavailable, "workload"): + self.picker().workloads + self.live._write_connection(credential_type="private-key-jwt") + with self.assertRaisesRegex(dev_picker.PickerUnavailable, "workload"): + self.picker().workloads + self.live._write_connection(run_id="f" * 32) + with self.assertRaisesRegex(dev_picker.PickerUnavailable, "workload"): + self.picker().workloads + self.live._write_connection() + connection_path = self.live.workload_root / "python-connection.json" + connection = json.loads(connection_path.read_text(encoding="utf-8")) + connection["bindings"][0]["credential"]["claims"] = { + "registry_actor_kind": "human" + } + self.live._write_json(connection_path, connection) + with self.assertRaisesRegex(dev_picker.PickerUnavailable, "workload"): + self.picker().workloads + + +class FrameworkPickerTests(unittest.TestCase): + def setUp(self): + self.live = LivePicker() + + def tearDown(self): + self.live.close() + + @staticmethod + def _form(body): + values = {} + for name in ("pending_id", "selector", "csrf_token"): + pattern = ( + rb' + + +
+ + +
+ + + diff --git a/products/platform/examples/python-portal/portal.js b/products/platform/examples/python-portal/portal.js new file mode 100644 index 0000000000..a0652a8401 --- /dev/null +++ b/products/platform/examples/python-portal/portal.js @@ -0,0 +1,25 @@ +"use strict"; + +async function loadDashboard() { + const element = document.getElementById("registry-dashboard"); + const initial = JSON.parse(element.textContent); + if (initial !== null) { + return initial; + } + const response = await fetch("/api/dashboard", { + credentials: "same-origin", + headers: {Accept: "application/json"}, + }); + if (!response.ok) { + throw new Error("dashboard request failed"); + } + return response.json(); +} + +loadDashboard() + .then((value) => { + document.getElementById("dashboard").textContent = JSON.stringify(value, null, 2); + }) + .catch(() => { + document.getElementById("dashboard").textContent = "Sign in again to continue."; + }); diff --git a/products/platform/examples/python-portal/portal_example.py b/products/platform/examples/python-portal/portal_example.py new file mode 100644 index 0000000000..744c6f87ee --- /dev/null +++ b/products/platform/examples/python-portal/portal_example.py @@ -0,0 +1,1073 @@ +"""Shared configuration, business calls, and framework factories for a portal.""" + +import base64 +import binascii +from dataclasses import dataclass +import html +import json +import math +import os +from pathlib import Path +import re +import tomllib +from types import MappingProxyType +from typing import Any, Callable, Mapping +from urllib.parse import urlsplit +import uuid + +from registry_client import portal_fastapi, portal_flask +from registry_client.portal import ( + AuthlibOIDCClient, + GrantPolicy, + PortalConfig, + PortalSessions, +) +from registry_client.portal_postgres import PortalEncryptionKeys, PostgresSessionStore +from registry_client.portal_products import bind_person +from registry_client.portal_verifier import NativeGrantVerifier + + +_ENV = re.compile(r"[A-Z][A-Z0-9_]{0,127}\Z") +_TOKEN = re.compile(r"[A-Za-z][A-Za-z0-9:+._-]{0,255}\Z") +_ROOT = Path(__file__).resolve().parent + + +@dataclass(frozen=True) +class GrantSettings: + name: str + resource: str + scopes: tuple[str, ...] + profile: str + required_claims: Mapping[str, str] + forward_resource: str | None = None + + +@dataclass(frozen=True) +class ServiceSettings: + persona: str + client_id: str + client_secret_env: str + origin: str + redirect_uri: str + switch_redirect_uri: str + breg_profile: str + casework_profile: str + session_seconds: float + pending_seconds: float + request_seconds: float + same_site: str + grants: tuple[GrantSettings, ...] + + +@dataclass(frozen=True) +class OperatorConfig: + issuer: Mapping[str, Any] + products: Mapping[str, Any] + session_store: Mapping[str, Any] + services: Mapping[str, ServiceSettings] + + +@dataclass(frozen=True) +class Runtime: + service: ServiceSettings + sessions: Any + store: Any + person_factory: Callable[[Any], Any] + + +def _obj(value: Any, path: str, fields: set[str]) -> dict[str, Any]: + if not isinstance(value, dict) or set(value) != fields: + raise ValueError(f"{path} must contain exactly the documented fields") + return value + + +def _text(value: Any, path: str) -> str: + if ( + not isinstance(value, str) + or not value + or value.strip() != value + or any(ord(char) < 32 or ord(char) == 127 for char in value) + ): + raise ValueError(f"{path} must be bounded text") + return value + + +def _token(value: Any, path: str) -> str: + value = _text(value, path) + if not _TOKEN.fullmatch(value): + raise ValueError(f"{path} must be a token") + return value + + +def _url(value: Any, path: str) -> str: + value = _text(value, path) + try: + parsed = urlsplit(value) + parsed.port + except ValueError as error: + raise ValueError(f"{path} must be an HTTPS URL") from error + if ( + parsed.scheme != "https" + or not parsed.hostname + or parsed.username is not None + or parsed.password is not None + or parsed.query + or parsed.fragment + ): + raise ValueError(f"{path} must be an HTTPS URL") + return value + + +def _origin(value: Any, path: str) -> str: + value = _url(value, path) + if urlsplit(value).path or value.endswith("/"): + raise ValueError(f"{path} must be an HTTPS origin without a trailing slash") + return value + + +def _resource(value: Any, path: str) -> str: + value = _text(value, path) + parsed = urlsplit(value) + if ( + not parsed.scheme + or not parsed.path + or parsed.fragment + or parsed.username is not None + or parsed.password is not None + or any(char.isspace() for char in value) + ): + raise ValueError(f"{path} must be an absolute resource URI") + return value + + +def _env(value: Any, path: str) -> str: + value = _text(value, path) + if not _ENV.fullmatch(value): + raise ValueError(f"{path} must name an environment variable") + return value + + +def _duration(value: Any, path: str) -> float: + if ( + not isinstance(value, (int, float)) + or isinstance(value, bool) + or not math.isfinite(value) + or value <= 0 + ): + raise ValueError(f"{path} must be finite and positive") + return float(value) + + +def _positive_integer(value: Any, path: str) -> int: + if not isinstance(value, int) or isinstance(value, bool) or value <= 0: + raise ValueError(f"{path} must be a positive integer") + return value + + +def _grant(name: str, value: Any, path: str) -> GrantSettings: + if ( + not isinstance(value, dict) + or not {"resource", "scopes", "profile", "requiredClaims"} <= set(value) + or set(value) + - {"resource", "scopes", "profile", "requiredClaims", "forwardResource"} + ): + raise ValueError(f"{path} has incomplete or unsupported fields") + scopes = value["scopes"] + if ( + not isinstance(scopes, list) + or not scopes + or len(scopes) > 32 + or len(set(scopes)) != len(scopes) + ): + raise ValueError(f"{path}.scopes must be distinct scope tokens") + claims = value["requiredClaims"] + if not isinstance(claims, dict) or not claims: + raise ValueError(f"{path}.requiredClaims must name exact claims") + return GrantSettings( + name, + _resource(value["resource"], f"{path}.resource"), + tuple(_token(scope, f"{path}.scopes") for scope in scopes), + _token(value["profile"], f"{path}.profile"), + MappingProxyType( + { + _token(claim, f"{path}.requiredClaims"): _text( + expected, f"{path}.requiredClaims" + ) + for claim, expected in claims.items() + } + ), + _resource(value["forwardResource"], f"{path}.forwardResource") + if "forwardResource" in value + else None, + ) + + +def _service(persona: str, value: Any) -> ServiceSettings: + path = f"services.{persona}" + value = _obj( + value, + path, + { + "clientId", + "clientSecretEnv", + "origin", + "redirectUri", + "switchRedirectUri", + "bregProfile", + "caseworkProfile", + "sessionSeconds", + "pendingSeconds", + "requestSeconds", + "sameSite", + "grants", + }, + ) + raw_grants = _obj(value["grants"], f"{path}.grants", {"breg", "casework"}) + grants = tuple( + _grant(name, raw_grants[name], f"{path}.grants.{name}") + for name in ("breg", "casework") + ) + origin = _origin(value["origin"], f"{path}.origin") + redirect_uri = _url(value["redirectUri"], f"{path}.redirectUri") + switch_uri = _url(value["switchRedirectUri"], f"{path}.switchRedirectUri") + if ( + urlsplit(redirect_uri).path != "/auth/callback" + or urlsplit(switch_uri).path != "/auth/login" + or not redirect_uri.startswith(f"{origin}/") + or not switch_uri.startswith(f"{origin}/") + ): + raise ValueError(f"{path} redirects must use the registered auth routes") + breg_profile = _token(value["bregProfile"], f"{path}.bregProfile") + casework_profile = _token(value["caseworkProfile"], f"{path}.caseworkProfile") + if grants[0].profile != breg_profile or grants[1].profile != casework_profile: + raise ValueError(f"{path} profiles must match their grant profiles") + if ( + grants[0].forward_resource is not None + or (persona == "holder" and grants[1].forward_resource is not None) + or ( + persona == "staff" + and ( + grants[1].forward_resource != grants[0].resource + or not set(grants[0].scopes).issubset(grants[1].scopes) + or any( + grants[1].required_claims.get(name) != expected + for name, expected in grants[0].required_claims.items() + ) + ) + ) + ): + raise ValueError(f"{path} forwarded Casework grant must include BReg authority") + if value["sameSite"] not in ("Lax", "Strict"): + raise ValueError(f"{path}.sameSite is unsupported") + return ServiceSettings( + persona, + _token(value["clientId"], f"{path}.clientId"), + _env(value["clientSecretEnv"], f"{path}.clientSecretEnv"), + origin, + redirect_uri, + switch_uri, + breg_profile, + casework_profile, + _duration(value["sessionSeconds"], f"{path}.sessionSeconds"), + _duration(value["pendingSeconds"], f"{path}.pendingSeconds"), + _duration(value["requestSeconds"], f"{path}.requestSeconds"), + value["sameSite"], + grants, + ) + + +def load_config(path: str | Path) -> OperatorConfig: + selected = Path(path) + try: + contents = selected.read_bytes() + except OSError as error: + raise ValueError("operator configuration is unavailable") from error + if len(contents) > 1_048_576: + raise ValueError("operator configuration exceeds the size limit") + try: + document = tomllib.loads(contents.decode("utf-8")) + except (UnicodeDecodeError, tomllib.TOMLDecodeError) as error: + raise ValueError("operator configuration is invalid TOML") from error + return _parse_config(document) + + +def _parse_config(document: Any) -> OperatorConfig: + document = _obj( + document, + "configuration", + { + "issuer", + "products", + "sessionStore", + "services", + }, + ) + issuer = _obj( + document["issuer"], + "issuer", + { + "url", + "authorizationEndpoint", + "tokenEndpoint", + "endSessionEndpoint", + "jwksUri", + "algorithm", + "accessTokenType", + "maximumAccessTokenLifetimeSeconds", + "maximumIdTokenLifetimeSeconds", + }, + ) + issuer = MappingProxyType( + { + "url": _url(issuer["url"], "issuer.url"), + "authorization_endpoint": _url( + issuer["authorizationEndpoint"], "issuer.authorizationEndpoint" + ), + "token_endpoint": _url(issuer["tokenEndpoint"], "issuer.tokenEndpoint"), + "end_session_endpoint": _url( + issuer["endSessionEndpoint"], "issuer.endSessionEndpoint" + ), + "jwks_uri": _url(issuer["jwksUri"], "issuer.jwksUri"), + "algorithm": _token(issuer["algorithm"], "issuer.algorithm"), + "access_token_type": _token( + issuer["accessTokenType"], "issuer.accessTokenType" + ), + "maximum_access_token_lifetime_seconds": _positive_integer( + issuer["maximumAccessTokenLifetimeSeconds"], + "issuer.maximumAccessTokenLifetimeSeconds", + ), + "maximum_id_token_lifetime_seconds": _positive_integer( + issuer["maximumIdTokenLifetimeSeconds"], + "issuer.maximumIdTokenLifetimeSeconds", + ), + } + ) + products = _obj( + document["products"], + "products", + { + "recordsUrl", + "reviewsUrl", + "recordRoute", + "recordFields", + "reviewQueue", + "reviewActionId", + "reviewRecordInput", + "reviewSubjectSource", + "reviewSubjectType", + }, + ) + fields = products["recordFields"] + if ( + not isinstance(fields, list) + or not fields + or len(fields) > 32 + or len(set(fields)) != len(fields) + ): + raise ValueError("products.recordFields must be distinct field identifiers") + products = MappingProxyType( + { + "records_url": _url(products["recordsUrl"], "products.recordsUrl"), + "reviews_url": _url(products["reviewsUrl"], "products.reviewsUrl"), + "record_route": _token(products["recordRoute"], "products.recordRoute"), + "record_fields": tuple( + _token(field, "products.recordFields") for field in fields + ), + "review_queue": _token(products["reviewQueue"], "products.reviewQueue"), + "review_action_id": _token( + products["reviewActionId"], "products.reviewActionId" + ), + "review_record_input": _token( + products["reviewRecordInput"], "products.reviewRecordInput" + ), + "review_subject_source": _token( + products["reviewSubjectSource"], "products.reviewSubjectSource" + ), + "review_subject_type": _token( + products["reviewSubjectType"], "products.reviewSubjectType" + ), + } + ) + store = _obj( + document["sessionStore"], + "sessionStore", + {"databaseUrlEnv", "primaryKeyId", "encryptionKeyEnvs"}, + ) + key_envs = store["encryptionKeyEnvs"] + if not isinstance(key_envs, dict) or not key_envs: + raise ValueError("sessionStore.encryptionKeyEnvs must not be empty") + store = MappingProxyType( + { + "database_url_env": _env( + store["databaseUrlEnv"], "sessionStore.databaseUrlEnv" + ), + "primary_key_id": _token( + store["primaryKeyId"], "sessionStore.primaryKeyId" + ), + "key_envs": MappingProxyType( + { + _token(key_id, "sessionStore.encryptionKeyEnvs"): _env( + env_name, "sessionStore.encryptionKeyEnvs" + ) + for key_id, env_name in key_envs.items() + } + ), + } + ) + if store["primary_key_id"] not in store["key_envs"]: + raise ValueError("sessionStore.primaryKeyId needs a declared key reference") + raw_services = _obj(document["services"], "services", {"holder", "staff"}) + services = { + persona: _service(persona, raw_services[persona]) + for persona in ("holder", "staff") + } + if ( + services["holder"].client_id == services["staff"].client_id + or services["holder"].origin == services["staff"].origin + or services["holder"].client_secret_env == services["staff"].client_secret_env + ): + raise ValueError("holder and staff need distinct service registrations") + return OperatorConfig(issuer, products, store, MappingProxyType(services)) + + +def _environment(name: str) -> str: + value = os.environ.get(name) + if not value: + raise RuntimeError(f"required operator secret {name} is unavailable") + return value + + +def build_store(config: OperatorConfig) -> PostgresSessionStore: + keys = {} + for key_id, environment_name in config.session_store["key_envs"].items(): + try: + material = base64.b64decode(_environment(environment_name), validate=True) + except (ValueError, binascii.Error): + raise RuntimeError( + f"operator encryption key {environment_name} is invalid" + ) from None + if len(material) != 32: + raise RuntimeError(f"operator encryption key {environment_name} is invalid") + keys[key_id] = material + encryption = PortalEncryptionKeys( + primary_key_id=config.session_store["primary_key_id"], keys=keys + ) + database_url = _environment(config.session_store["database_url_env"]) + import psycopg + + return PostgresSessionStore(lambda: psycopg.connect(database_url), encryption) + + +def build_runtime( + config: OperatorConfig, persona: str, *, store: Any | None = None +) -> Runtime: + try: + service = config.services[persona] + except KeyError: + raise ValueError("persona must be holder or staff") from None + grants = tuple( + GrantPolicy( + grant.name, + grant.resource, + grant.scopes, + grant.profile, + grant.required_claims, + grant.forward_resource, + ) + for grant in service.grants + ) + verifier = NativeGrantVerifier.from_native( + issuer=config.issuer["url"], + client_id=service.client_id, + persona=service.persona, + grants=grants, + algorithm=config.issuer["algorithm"], + access_token_type=config.issuer["access_token_type"], + maximum_access_token_lifetime_seconds=config.issuer[ + "maximum_access_token_lifetime_seconds" + ], + maximum_id_token_lifetime_seconds=config.issuer[ + "maximum_id_token_lifetime_seconds" + ], + jwks_uri=config.issuer["jwks_uri"], + ) + oidc = AuthlibOIDCClient( + client_id=service.client_id, + client_secret=_environment(service.client_secret_env), + redirect_uri=service.redirect_uri, + authorization_endpoint=config.issuer["authorization_endpoint"], + token_endpoint=config.issuer["token_endpoint"], + end_session_endpoint=config.issuer["end_session_endpoint"], + switch_redirect_uri=service.switch_redirect_uri, + verify_token=verifier, + ) + portal_config = PortalConfig( + issuer=config.issuer["url"], + client_id=service.client_id, + redirect_uri=service.redirect_uri, + origin=service.origin, + persona=service.persona, + grants=grants, + session_seconds=service.session_seconds, + pending_seconds=service.pending_seconds, + ) + selected_store = store if store is not None else build_store(config) + sessions = PortalSessions(portal_config, oidc, selected_store) + + def person_factory(context): + return bind_person( + context, + persona=service.persona, + breg_url=config.products["records_url"], + casework_url=config.products["reviews_url"], + casework_profile=service.casework_profile, + ) + + return Runtime(service, sessions, selected_store, person_factory) + + +def _complete(result: Any, operation: str) -> Any: + if ( + not isinstance(result, dict) + or result.get("kind") != "complete" + or "value" not in result + ): + raise RuntimeError(f"{operation} did not return a complete result") + return result["value"] + + +def _person_service( + person: Any, config: OperatorConfig, persona: str +) -> ServiceSettings: + service = config.services.get(person.persona) + if service is None or service.persona != persona: + raise PermissionError(f"this operation requires the {persona} service") + return service + + +def _uuid_identifier(value: Any, name: str) -> str: + if not isinstance(value, str): + raise ValueError(f"{name} must be a canonical UUID") + try: + parsed = uuid.UUID(value) + except ValueError: + raise ValueError(f"{name} must be a canonical UUID") from None + if str(parsed) != value: + raise ValueError(f"{name} must be a canonical UUID") + return value + + +def _idempotency_key(value: Any) -> str: + value = _token(value, "idempotencyKey") + if len(value.encode("utf-8")) > 180: + raise ValueError("idempotencyKey is too long") + return value + + +def _revision(value: Any) -> int: + if ( + not isinstance(value, int) + or isinstance(value, bool) + or value < 0 + or value > 9_007_199_254_740_991 + ): + raise ValueError("revision must be a non-negative safe integer") + return value + + +def _request_object(value: Any, name: str) -> dict[str, Any]: + if not isinstance(value, dict): + raise ValueError(f"{name} must be an object") + return value + + +def dashboard(person: Any, config: OperatorConfig) -> dict[str, Any]: + service = config.services.get(person.persona) + if service is None: + raise RuntimeError("the signed-in persona is not configured") + if service.persona == "holder": + applications = _complete( + person.breg.list_records( + config.products["record_route"], + top=10, + select=list(config.products["record_fields"]), + access_profile=service.breg_profile, + ), + "record list", + ) + reviews = [] + else: + applications = [] + reviews = _complete( + person.casework.review_tasks( + {"queue": config.products["review_queue"]}, + source_profile=service.breg_profile, + ), + "review task list", + ) + return { + "persona": person.persona, + "subject": person.subject, + "principal": person.principal, + "csrfToken": person.csrf_token, + "applications": applications, + "reviews": reviews, + } + + +def holder_submit_review( + person: Any, + config: OperatorConfig, + record_identifier: str, + inputs: dict[str, Any], + idempotency_key: str, +) -> dict[str, Any]: + service = _person_service(person, config, "holder") + record_identifier = _uuid_identifier(record_identifier, "record identifier") + inputs = dict(_request_object(inputs, "inputs")) + record_input = config.products["review_record_input"] + if inputs.get(record_input) != record_identifier: + raise ValueError("inputs must bind the selected record") + if inputs.get("status") != "submitted": + raise ValueError("inputs.status must be submitted") + key = _idempotency_key(idempotency_key) + record = _complete( + person.breg.get_record( + config.products["record_route"], + record_identifier, + select=list(config.products["record_fields"]), + access_profile=service.breg_profile, + ), + "record read", + ) + metadata = person.breg.registry_contract(service.breg_profile) + binding = metadata.select_action( + config.products["review_action_id"], service.breg_profile + ) + draft = person.breg.start_proposal(binding, inputs, f"{key}:draft") + prepared = person.breg.prepare_proposal(draft, "submit", {}, f"{key}:submit") + submitted = person.breg.execute_proposal(prepared) + return {"record": record, "proposal": submitted.document} + + +def holder_review_history( + person: Any, config: OperatorConfig, request_identifier: str +) -> Any: + _person_service(person, config, "holder") + request_identifier = _uuid_identifier( + request_identifier, "review request identifier" + ) + return _complete( + person.casework.review_history(request_identifier), "review history" + ) + + +def staff_review_task( + person: Any, config: OperatorConfig, task_identifier: str +) -> dict[str, Any]: + service = _person_service(person, config, "staff") + task_identifier = _uuid_identifier(task_identifier, "task identifier") + task = _complete( + person.casework.review_task( + task_identifier, source_profile=service.breg_profile + ), + "review task", + ) + context = _complete( + person.casework.review_task_context( + task_identifier, source_profile=service.breg_profile + ), + "review task context", + ) + subject = task.get("subject") if isinstance(task, dict) else None + if ( + not isinstance(subject, dict) + or subject.get("source") != config.products["review_subject_source"] + or subject.get("type") != config.products["review_subject_type"] + ): + raise RuntimeError("review task does not identify the configured source") + source_identifier = _uuid_identifier(subject.get("id"), "review subject identifier") + metadata = person.breg.registry_contract(service.breg_profile) + binding = metadata.select_proposal_review_context( + service.breg_profile, config.products["review_action_id"] + ) + source = _complete( + person.breg.read_proposal_review_by_id(binding, source_identifier), + "review source read", + ) + if ( + not isinstance(source, dict) + or source.get("id") != source_identifier + or source.get("actionId") != config.products["review_action_id"] + or source.get("effectDigest") != subject.get("digest") + ): + raise RuntimeError("review source does not match the Casework task") + return {"task": task, "context": context, "source": source} + + +def staff_claim_task( + person: Any, + config: OperatorConfig, + task_identifier: str, + revision: int, + idempotency_key: str, +) -> Any: + service = _person_service(person, config, "staff") + return _complete( + person.casework.claim_review_task( + _uuid_identifier(task_identifier, "task identifier"), + _revision(revision), + _idempotency_key(idempotency_key), + source_profile=service.breg_profile, + ), + "review task claim", + ) + + +def staff_release_task( + person: Any, + config: OperatorConfig, + task_identifier: str, + revision: int, + idempotency_key: str, +) -> Any: + _person_service(person, config, "staff") + return _complete( + person.casework.release_review_task( + _uuid_identifier(task_identifier, "task identifier"), + _revision(revision), + _idempotency_key(idempotency_key), + ), + "review task release", + ) + + +def staff_decide_task( + person: Any, + config: OperatorConfig, + task_identifier: str, + revision: int, + idempotency_key: str, + decision: dict[str, Any], +) -> dict[str, str]: + service = _person_service(person, config, "staff") + _complete( + person.casework.decide_review_task( + _uuid_identifier(task_identifier, "task identifier"), + _revision(revision), + _idempotency_key(idempotency_key), + _request_object(decision, "decision"), + source_profile=service.breg_profile, + ), + "review task decision", + ) + return {"status": "accepted"} + + +def staff_own_decisions( + person: Any, config: OperatorConfig, query: dict[str, Any] +) -> Any: + service = _person_service(person, config, "staff") + return _complete( + person.casework.own_review_decisions( + _request_object(query, "decision query"), + source_profile=service.breg_profile, + ), + "own review decisions", + ) + + +def staff_review_history( + person: Any, config: OperatorConfig, request_identifier: str +) -> Any: + service = _person_service(person, config, "staff") + return _complete( + person.casework.review_history( + _uuid_identifier(request_identifier, "review request identifier"), + source_profile=service.breg_profile, + ), + "review history", + ) + + +def _frontend(csrf_token: str, initial: Any) -> str: + template = (_ROOT / "frontend.html").read_text(encoding="utf-8") + payload = json.dumps(initial, sort_keys=True, separators=(",", ":")) + payload = payload.replace("<", "\\u003c").replace(">", "\\u003e") + return template.replace( + "__REGISTRY_CSRF__", html.escape(csrf_token, quote=True) + ).replace("__REGISTRY_DASHBOARD__", payload) + + +def _headers(content_type: str) -> dict[str, str]: + return { + "Cache-Control": "no-store", + "Content-Security-Policy": ( + "default-src 'self'; base-uri 'none'; frame-ancestors 'none'" + ), + "Content-Type": content_type, + "X-Content-Type-Options": "nosniff", + } + + +def create_flask_app(config: OperatorConfig, runtime: Runtime): + from flask import Flask, Response, g, jsonify, request + + app = Flask(__name__) + + @app.get("/") + def index(): + person = g.registry_person + return Response( + _frontend(person.csrf_token, dashboard(person, config)), + headers=_headers("text/html; charset=utf-8"), + ) + + @app.get("/portal.js") + def script(): + return Response( + (_ROOT / "portal.js").read_text(encoding="utf-8"), + headers=_headers("text/javascript; charset=utf-8"), + ) + + @app.get("/reviews/") + def review_page(identifier: str): + person = g.registry_person + if person.persona == "holder": + value = holder_review_history(person, config, identifier) + else: + value = staff_review_task(person, config, identifier) + return Response( + _frontend(person.csrf_token, {"review": value}), + headers=_headers("text/html; charset=utf-8"), + ) + + def api_response(value: Any): + response = jsonify(value) + response.headers.update(_headers("application/json")) + return response + + @app.errorhandler(ValueError) + def invalid_request(_error): + return api_response({"code": "request.invalid"}), 400 + + @app.errorhandler(PermissionError) + def wrong_persona(_error): + return api_response({"code": "authorization.persona-refused"}), 403 + + @app.post("/api/applications//reviews") + def submit_review(identifier: str): + body = _request_object(request.get_json(), "request body") + return api_response( + holder_submit_review( + g.registry_person, + config, + identifier, + body.get("inputs"), + body.get("idempotencyKey"), + ) + ) + + @app.get("/api/review-requests//history") + def review_history(identifier: str): + person = g.registry_person + if person.persona == "holder": + value = holder_review_history(person, config, identifier) + else: + value = staff_review_history(person, config, identifier) + return api_response(value) + + @app.get("/api/tasks/") + def task(identifier: str): + return api_response(staff_review_task(g.registry_person, config, identifier)) + + @app.post("/api/tasks//claim") + def claim_task(identifier: str): + body = _request_object(request.get_json(), "request body") + return api_response( + staff_claim_task( + g.registry_person, + config, + identifier, + body.get("revision"), + body.get("idempotencyKey"), + ) + ) + + @app.post("/api/tasks//release") + def release_task(identifier: str): + body = _request_object(request.get_json(), "request body") + return api_response( + staff_release_task( + g.registry_person, + config, + identifier, + body.get("revision"), + body.get("idempotencyKey"), + ) + ) + + @app.post("/api/tasks//decisions") + def decide_task(identifier: str): + body = _request_object(request.get_json(), "request body") + return api_response( + staff_decide_task( + g.registry_person, + config, + identifier, + body.get("revision"), + body.get("idempotencyKey"), + {"decision": body.get("decision")}, + ) + ) + + @app.get("/api/decisions") + def decisions(): + limit = request.args.get("limit", default=10, type=int) + return api_response( + staff_own_decisions(g.registry_person, config, {"limit": limit}) + ) + + portal_flask.install( + app, + runtime.sessions, + origin=runtime.service.origin, + persona=runtime.service.persona, + person_factory=runtime.person_factory, + request_seconds=runtime.service.request_seconds, + same_site=runtime.service.same_site, + ) + return app + + +def create_fastapi_app(config: OperatorConfig, runtime: Runtime): + from fastapi import FastAPI, Request + from fastapi.responses import HTMLResponse, JSONResponse, Response + + app = FastAPI() + + @app.exception_handler(ValueError) + async def invalid_request(_request: Request, _error: ValueError): + return JSONResponse( + {"code": "request.invalid"}, + status_code=400, + headers=_headers("application/json"), + ) + + @app.exception_handler(PermissionError) + async def wrong_persona(_request: Request, _error: PermissionError): + return JSONResponse( + {"code": "authorization.persona-refused"}, + status_code=403, + headers=_headers("application/json"), + ) + + @app.get("/") + def index(request: Request): + return HTMLResponse( + _frontend(request.state.registry_person.csrf_token, None), + headers=_headers("text/html; charset=utf-8"), + ) + + @app.get("/portal.js") + def script(): + return Response( + (_ROOT / "portal.js").read_text(encoding="utf-8"), + headers=_headers("text/javascript; charset=utf-8"), + ) + + @app.get("/api/dashboard") + def api_dashboard(request: Request): + return JSONResponse( + dashboard(request.state.registry_person, config), + headers=_headers("application/json"), + ) + + @app.post("/api/applications/{identifier}/reviews") + def submit_review(identifier: str, body: dict[str, Any], request: Request): + return JSONResponse( + holder_submit_review( + request.state.registry_person, + config, + identifier, + body.get("inputs"), + body.get("idempotencyKey"), + ), + headers=_headers("application/json"), + ) + + @app.get("/api/review-requests/{identifier}/history") + def review_history(identifier: str, request: Request): + person = request.state.registry_person + if person.persona == "holder": + value = holder_review_history(person, config, identifier) + else: + value = staff_review_history(person, config, identifier) + return JSONResponse(value, headers=_headers("application/json")) + + @app.get("/api/tasks/{identifier}") + def task(identifier: str, request: Request): + return JSONResponse( + staff_review_task(request.state.registry_person, config, identifier), + headers=_headers("application/json"), + ) + + @app.post("/api/tasks/{identifier}/claim") + def claim_task(identifier: str, body: dict[str, Any], request: Request): + return JSONResponse( + staff_claim_task( + request.state.registry_person, + config, + identifier, + body.get("revision"), + body.get("idempotencyKey"), + ), + headers=_headers("application/json"), + ) + + @app.post("/api/tasks/{identifier}/release") + def release_task(identifier: str, body: dict[str, Any], request: Request): + return JSONResponse( + staff_release_task( + request.state.registry_person, + config, + identifier, + body.get("revision"), + body.get("idempotencyKey"), + ), + headers=_headers("application/json"), + ) + + @app.post("/api/tasks/{identifier}/decisions") + def decide_task(identifier: str, body: dict[str, Any], request: Request): + return JSONResponse( + staff_decide_task( + request.state.registry_person, + config, + identifier, + body.get("revision"), + body.get("idempotencyKey"), + {"decision": body.get("decision")}, + ), + headers=_headers("application/json"), + ) + + @app.get("/api/decisions") + def decisions(request: Request, limit: int = 10): + return JSONResponse( + staff_own_decisions( + request.state.registry_person, config, {"limit": limit} + ), + headers=_headers("application/json"), + ) + + portal_fastapi.install( + app, + runtime.sessions, + origin=runtime.service.origin, + persona=runtime.service.persona, + person_factory=runtime.person_factory, + request_seconds=runtime.service.request_seconds, + same_site=runtime.service.same_site, + ) + return app diff --git a/products/platform/examples/python-portal/pyproject.toml b/products/platform/examples/python-portal/pyproject.toml new file mode 100644 index 0000000000..2913fbe6f8 --- /dev/null +++ b/products/platform/examples/python-portal/pyproject.toml @@ -0,0 +1,24 @@ +[project] +name = "registry-python-portal-example" +version = "0.1.0" +description = "Prepared Flask and FastAPI person portal for Registry Stack" +requires-python = ">=3.11" +dependencies = [ + "Authlib>=1.9.5,<2", + "cryptography>=50.0.2,<51", + "fastapi>=0.115,<1", + "Flask>=3.1,<4", + "gunicorn>=23,<24", + "psycopg[binary]>=3.3.6,<4", + "requests>=2.31,<3", + "uvicorn>=0.34,<1", +] + +[dependency-groups] +dev = [ + "httpx>=0.28,<1", + "ruff==0.14.3", +] + +[tool.uv] +package = false diff --git a/products/platform/examples/python-portal/service.py b/products/platform/examples/python-portal/service.py new file mode 100644 index 0000000000..31daea896b --- /dev/null +++ b/products/platform/examples/python-portal/service.py @@ -0,0 +1,65 @@ +"""Application factories and explicit encrypted-session store lifecycle commands.""" + +import argparse +import json +import os + +from portal_example import ( + build_runtime, + build_store, + create_fastapi_app, + create_flask_app, + load_config, +) + + +def _environment(name: str) -> str: + value = os.environ.get(name) + if not value: + raise RuntimeError(f"set {name} before constructing a portal worker") + return value + + +def _configured_runtime(): + config = load_config(_environment("PORTAL_CONFIG")) + runtime = build_runtime(config, _environment("PORTAL_PERSONA")) + runtime.store.check_ready() + return config, runtime + + +def create_flask(): + config, runtime = _configured_runtime() + return create_flask_app(config, runtime) + + +def create_fastapi(): + config, runtime = _configured_runtime() + return create_fastapi_app(config, runtime) + + +def main(arguments: list[str] | None = None) -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "action", choices=("migrate", "check-store", "rotate-encryption") + ) + parser.add_argument("--config", required=True) + options = parser.parse_args(arguments) + store = build_store(load_config(options.config)) + if options.action == "migrate": + store.migrate() + result = {"action": options.action, "status": "complete"} + elif options.action == "check-store": + store.check_ready() + result = {"action": options.action, "status": "ready"} + else: + rewritten = store.rotate_encryption() + result = { + "action": options.action, + "status": "complete", + "rewritten": rewritten, + } + print(json.dumps(result, sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/products/platform/examples/python-portal/tests/test_portal_example.py b/products/platform/examples/python-portal/tests/test_portal_example.py new file mode 100644 index 0000000000..ac7a6fa2e4 --- /dev/null +++ b/products/platform/examples/python-portal/tests/test_portal_example.py @@ -0,0 +1,825 @@ +import asyncio +import base64 +import contextlib +import importlib.util +import io +import json +import os +from pathlib import Path +import sys +import types +import unittest +from unittest import mock + +from flask import g +import httpx + + +ROOT = Path(__file__).resolve().parents[1] +RECORD_ID = "11111111-1111-4111-8111-111111111111" +REQUEST_ID = "22222222-2222-4222-8222-222222222222" +TASK_ID = "33333333-3333-4333-8333-333333333333" +PROPOSAL_ID = "44444444-4444-4444-8444-444444444444" + + +class GrantPolicy: + def __init__( + self, name, resource, scopes, profile, required_claims, forward_resource=None + ): + self.name = name + self.resource = resource + self.scopes = scopes + self.profile = profile + self.required_claims = required_claims + self.forward_resource = forward_resource + + +class Recorder: + calls = [] + + @classmethod + def reset(cls): + cls.calls = [] + + +class NativeGrantVerifier(Recorder): + @classmethod + def from_native(cls, **kwargs): + cls.calls.append(kwargs) + return ("native-verifier", kwargs) + + +class AuthlibOIDCClient(Recorder): + def __init__(self, **kwargs): + self.configuration = kwargs + self.calls.append(kwargs) + + +class PortalConfig(Recorder): + def __init__(self, **kwargs): + self.__dict__.update(kwargs) + self.calls.append(kwargs) + + +class PortalSessions(Recorder): + def __init__(self, config, oidc, store): + self.config = config + self.oidc = oidc + self.store = store + self.calls.append((config, oidc, store)) + + +class PortalEncryptionKeys: + def __init__(self, *, primary_key_id, keys): + self.primary_key_id = primary_key_id + self.keys = keys + + +class PostgresSessionStore: + def __init__(self, connect, keys): + self.connect = connect + self.keys = keys + self.actions = [] + + def migrate(self): + self.actions.append("migrate") + + def check_ready(self): + self.actions.append("check_ready") + + def rotate_encryption(self): + self.actions.append("rotate_encryption") + return 3 + + +class Proposal: + def __init__(self, identifier, document): + self.identifier = identifier + self.document = document + + +class Metadata: + def __init__(self): + self.select_action = mock.Mock(return_value="submit-application-binding") + self.select_proposal_review_context = mock.Mock( + return_value="review-context-binding" + ) + + +class Person: + def __init__(self, persona="holder"): + self.persona = persona + self.subject = f"{persona}-subject" + self.principal = f"{persona}-principal" + self.csrf_token = f"{persona}-csrf" + self.metadata = Metadata() + self.draft = Proposal("proposal-1", {"id": "proposal-1", "state": "draft"}) + self.prepared = object() + self.submitted = Proposal( + "proposal-1", + { + "id": "proposal-1", + "state": "review", + "requestId": REQUEST_ID, + }, + ) + self.breg = types.SimpleNamespace( + list_records=mock.Mock( + return_value={ + "kind": "complete", + "value": [{"data": {"reference": "application-001"}}], + } + ), + get_record=mock.Mock( + return_value={ + "kind": "complete", + "value": { + "data": { + "recordIdentifier": RECORD_ID, + "revisionIdentifier": "1", + "domainData": { + "reference": "application-001", + "profession": "Surveyor", + "status": "submitted", + }, + }, + "meta": { + "registryIdentifier": "licensing", + "datasetIdentifier": "licensing", + "recordTypeIdentifier": "application", + }, + }, + } + ), + registry_contract=mock.Mock(return_value=self.metadata), + read_proposal_review_by_id=mock.Mock( + return_value={ + "kind": "complete", + "value": { + "id": PROPOSAL_ID, + "actionId": "submit-application", + "effectDigest": "sha256:" + "a" * 64, + "context": {"reference": "application-001"}, + }, + } + ), + start_proposal=mock.Mock(return_value=self.draft), + prepare_proposal=mock.Mock(return_value=self.prepared), + execute_proposal=mock.Mock(return_value=self.submitted), + ) + self.casework = types.SimpleNamespace( + review_policies=mock.Mock( + return_value={ + "kind": "complete", + "value": [{"id": "licensing-approval"}], + } + ), + review_tasks=mock.Mock( + return_value={ + "kind": "complete", + "value": {"items": [{"taskId": "task-1"}]}, + } + ), + review_history=mock.Mock( + return_value={ + "kind": "complete", + "value": {"items": [{"status": "approved"}]}, + } + ), + review_task=mock.Mock( + return_value={ + "kind": "complete", + "value": { + "taskId": TASK_ID, + "requestId": REQUEST_ID, + "revision": 4, + "subject": { + "source": "licensing", + "type": "proposal", + "id": PROPOSAL_ID, + "version": "1", + "digest": "sha256:" + "a" * 64, + }, + }, + } + ), + review_task_context=mock.Mock( + return_value={ + "kind": "complete", + "value": {"context": {"reference": "application-001"}}, + } + ), + claim_review_task=mock.Mock( + return_value={ + "kind": "complete", + "value": {"taskId": TASK_ID, "revision": 5}, + } + ), + release_review_task=mock.Mock( + return_value={ + "kind": "complete", + "value": {"taskId": TASK_ID, "revision": 6}, + } + ), + decide_review_task=mock.Mock( + return_value={"kind": "complete", "value": None} + ), + own_review_decisions=mock.Mock( + return_value={ + "kind": "complete", + "value": {"items": [{"requestId": REQUEST_ID}]}, + } + ), + ) + + +def install_modules(): + package = types.ModuleType("registry_client") + package.__path__ = [] + portal = types.ModuleType("registry_client.portal") + portal.GrantPolicy = GrantPolicy + portal.PortalConfig = PortalConfig + portal.AuthlibOIDCClient = AuthlibOIDCClient + portal.PortalSessions = PortalSessions + portal_flask = types.ModuleType("registry_client.portal_flask") + portal_fastapi = types.ModuleType("registry_client.portal_fastapi") + portal_postgres = types.ModuleType("registry_client.portal_postgres") + portal_postgres.PortalEncryptionKeys = PortalEncryptionKeys + portal_postgres.PostgresSessionStore = PostgresSessionStore + portal_products = types.ModuleType("registry_client.portal_products") + portal_products.bind_person = mock.Mock(return_value="bound-person") + portal_verifier = types.ModuleType("registry_client.portal_verifier") + portal_verifier.NativeGrantVerifier = NativeGrantVerifier + package.portal_flask = portal_flask + package.portal_fastapi = portal_fastapi + modules = { + "registry_client": package, + "registry_client.portal": portal, + "registry_client.portal_flask": portal_flask, + "registry_client.portal_fastapi": portal_fastapi, + "registry_client.portal_postgres": portal_postgres, + "registry_client.portal_products": portal_products, + "registry_client.portal_verifier": portal_verifier, + } + sys.modules.update(modules) + return portal_flask, portal_fastapi, portal_products + + +def load_example(): + portal_flask, portal_fastapi, portal_products = install_modules() + spec = importlib.util.spec_from_file_location( + "registry_python_portal_example", ROOT / "portal_example.py" + ) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + spec.loader.exec_module(module) + return module, portal_flask, portal_fastapi, portal_products + + +def load_service(example): + previous = sys.modules.get("portal_example") + sys.modules["portal_example"] = example + spec = importlib.util.spec_from_file_location( + "registry_python_portal_service", ROOT / "service.py" + ) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + try: + spec.loader.exec_module(module) + finally: + if previous is None: + del sys.modules["portal_example"] + else: + sys.modules["portal_example"] = previous + return module + + +def document(): + grant_claims = {"registry_actor_kind": "human"} + return { + "issuer": { + "url": "https://identity.example.test", + "authorizationEndpoint": "https://identity.example.test/authorize", + "tokenEndpoint": "https://identity.example.test/token", + "endSessionEndpoint": "https://identity.example.test/logout", + "jwksUri": "https://identity.example.test/jwks.json", + "algorithm": "ES256", + "accessTokenType": "at+jwt", + "maximumAccessTokenLifetimeSeconds": 300, + "maximumIdTokenLifetimeSeconds": 3600, + }, + "products": { + "recordsUrl": "https://records.example.test", + "reviewsUrl": "https://reviews.example.test", + "recordRoute": "applications", + "recordFields": ["reference", "profession", "status"], + "reviewQueue": "applications", + "reviewActionId": "submit-application", + "reviewRecordInput": "application", + "reviewSubjectSource": "licensing", + "reviewSubjectType": "application", + }, + "sessionStore": { + "databaseUrlEnv": "PORTAL_DATABASE_URL", + "primaryKeyId": "current", + "encryptionKeyEnvs": {"current": "PORTAL_SESSION_KEY_CURRENT"}, + }, + "services": { + "holder": { + "clientId": "applicant-portal", + "clientSecretEnv": "PORTAL_HOLDER_CLIENT_SECRET", + "origin": "https://holder.example.test", + "redirectUri": "https://holder.example.test/auth/callback", + "switchRedirectUri": "https://holder.example.test/auth/login", + "bregProfile": "applicant", + "caseworkProfile": "applicant", + "sessionSeconds": 900, + "pendingSeconds": 300, + "requestSeconds": 10, + "sameSite": "Lax", + "grants": { + "breg": { + "resource": "urn:example:licensing:registry", + "scopes": ["licensing:apply"], + "profile": "applicant", + "requiredClaims": grant_claims, + }, + "casework": { + "resource": "urn:example:licensing:review", + "scopes": ["casework:history"], + "profile": "applicant", + "requiredClaims": grant_claims, + }, + }, + }, + "staff": { + "clientId": "licensing-auditor", + "clientSecretEnv": "PORTAL_STAFF_CLIENT_SECRET", + "origin": "https://staff.example.test", + "redirectUri": "https://staff.example.test/auth/callback", + "switchRedirectUri": "https://staff.example.test/auth/login", + "bregProfile": "auditor", + "caseworkProfile": "reviewer", + "sessionSeconds": 900, + "pendingSeconds": 300, + "requestSeconds": 10, + "sameSite": "Lax", + "grants": { + "breg": { + "resource": "urn:example:licensing:registry", + "scopes": ["licensing:audit"], + "profile": "auditor", + "requiredClaims": grant_claims, + }, + "casework": { + "resource": "urn:example:licensing:review", + "forwardResource": "urn:example:licensing:registry", + "scopes": ["casework:review", "licensing:audit"], + "profile": "reviewer", + "requiredClaims": grant_claims, + }, + }, + }, + }, + } + + +class PortalExampleTests(unittest.TestCase): + def setUp(self): + for recorder in ( + NativeGrantVerifier, + AuthlibOIDCClient, + PortalConfig, + PortalSessions, + ): + recorder.reset() + + def test_config_requires_distinct_holder_and_staff_registrations(self): + module, _, _, _ = load_example() + config = module.load_config(ROOT / "config.example.toml") + + self.assertEqual(set(config.services), {"holder", "staff"}) + self.assertNotEqual( + config.services["holder"].client_id, + config.services["staff"].client_id, + ) + self.assertEqual( + config.services["holder"].grants[1].resource, + "urn:example:licensing:review", + ) + self.assertEqual(config.services["holder"].casework_profile, "applicant") + + invalid = document() + invalid["services"]["staff"]["clientId"] = invalid["services"]["holder"][ + "clientId" + ] + with self.assertRaises(ValueError): + module._parse_config(invalid) + + def test_staff_current_source_bridge_cannot_be_omitted(self): + module, _, _, _ = load_example() + invalid = document() + del invalid["services"]["staff"]["grants"]["casework"]["forwardResource"] + with self.assertRaisesRegex(ValueError, "forwarded Casework grant"): + module._parse_config(invalid) + + def test_operator_example_matches_the_licensing_resource_contract(self): + module, _, _, _ = load_example() + config = module.load_config(ROOT / "config.example.toml") + + self.assertEqual(config.services["holder"].client_id, "applicant-portal") + self.assertEqual(config.services["staff"].client_id, "licensing-auditor") + for service in config.services.values(): + self.assertEqual( + [grant.resource for grant in service.grants], + ["urn:example:licensing:registry", "urn:example:licensing:review"], + ) + self.assertEqual(config.services["holder"].casework_profile, "applicant") + invalid = document() + invalid["services"]["holder"]["grants"]["breg"]["resource"] = "/records" + with self.assertRaises(ValueError): + module._parse_config(invalid) + + def test_runtime_binds_exact_native_grants_and_request_local_person_clients(self): + module, _, _, portal_products = load_example() + config = module.load_config(ROOT / "config.example.toml") + store = object() + environment = {"PORTAL_HOLDER_CLIENT_SECRET": "client-secret-canary"} + + with mock.patch.dict(os.environ, environment, clear=False): + runtime = module.build_runtime(config, "holder", store=store) + + verifier = NativeGrantVerifier.calls[0] + self.assertEqual(verifier["persona"], "holder") + self.assertEqual(verifier["client_id"], "applicant-portal") + self.assertEqual( + [grant.name for grant in verifier["grants"]], ["breg", "casework"] + ) + self.assertEqual( + [grant.resource for grant in verifier["grants"]], + [ + "urn:example:licensing:registry", + "urn:example:licensing:review", + ], + ) + self.assertEqual( + AuthlibOIDCClient.calls[0]["client_secret"], "client-secret-canary" + ) + self.assertEqual( + AuthlibOIDCClient.calls[0]["switch_redirect_uri"], + "https://holder.example.test/auth/login", + ) + + with mock.patch.dict( + os.environ, + {"PORTAL_STAFF_CLIENT_SECRET": "client-secret-canary"}, + clear=False, + ): + module.build_runtime(config, "staff", store=store) + staff = NativeGrantVerifier.calls[-1]["grants"] + self.assertEqual(staff[1].forward_resource, staff[0].resource) + self.assertTrue(set(staff[0].scopes).issubset(staff[1].scopes)) + self.assertEqual(PortalSessions.calls[0][2], store) + + context = object() + self.assertEqual(runtime.person_factory(context), "bound-person") + portal_products.bind_person.assert_called_once_with( + context, + persona="holder", + breg_url="https://records.licensing.example.test", + casework_url="https://reviews.licensing.example.test", + casework_profile="applicant", + ) + + def test_postgres_store_resolves_key_and_database_references_without_logging_values( + self, + ): + module, _, _, _ = load_example() + config = module.load_config(ROOT / "config.example.toml") + connections = [] + psycopg = types.ModuleType("psycopg") + psycopg.connect = lambda value: connections.append(value) or "connection" + key = base64.b64encode(b"k" * 32).decode("ascii") + environment = { + "PORTAL_DATABASE_URL": "postgresql://portal-secret-canary", + "PORTAL_SESSION_KEY_CURRENT": key, + } + + with mock.patch.dict(sys.modules, {"psycopg": psycopg}): + with mock.patch.dict(os.environ, environment, clear=False): + store = module.build_store(config) + + self.assertEqual(store.keys.primary_key_id, "current") + self.assertEqual(store.keys.keys, {"current": b"k" * 32}) + self.assertEqual(store.connect(), "connection") + self.assertEqual(connections, ["postgresql://portal-secret-canary"]) + + def test_holder_reads_own_record_submits_review_and_reads_history(self): + module, _, _, _ = load_example() + config = module.load_config(ROOT / "config.example.toml") + holder = Person("holder") + + submitted = module.holder_submit_review( + holder, + config, + RECORD_ID, + {"application": RECORD_ID, "status": "submitted"}, + "holder-review-001", + ) + history = module.holder_review_history(holder, config, REQUEST_ID) + + holder.breg.get_record.assert_called_once_with( + "applications", + RECORD_ID, + select=["reference", "profession", "status"], + access_profile="applicant", + ) + holder.breg.registry_contract.assert_called_once_with("applicant") + holder.metadata.select_action.assert_called_once_with( + "submit-application", "applicant" + ) + holder.breg.start_proposal.assert_called_once_with( + "submit-application-binding", + {"application": RECORD_ID, "status": "submitted"}, + "holder-review-001:draft", + ) + holder.breg.prepare_proposal.assert_called_once_with( + holder.draft, "submit", {}, "holder-review-001:submit" + ) + holder.breg.execute_proposal.assert_called_once_with(holder.prepared) + holder.casework.review_history.assert_called_once_with(REQUEST_ID) + self.assertEqual(submitted["proposal"]["requestId"], REQUEST_ID) + self.assertEqual(history["items"][0]["status"], "approved") + + def test_staff_uses_exact_task_context_mutation_and_outcome_methods(self): + module, _, _, _ = load_example() + config = module.load_config(ROOT / "config.example.toml") + staff = Person("staff") + + staff_dashboard = module.dashboard(staff, config) + detail = module.staff_review_task(staff, config, TASK_ID) + claimed = module.staff_claim_task(staff, config, TASK_ID, 4, "staff-claim-001") + released = module.staff_release_task( + staff, config, TASK_ID, 5, "staff-release-001" + ) + decided = module.staff_decide_task( + staff, + config, + TASK_ID, + 5, + "staff-decision-001", + {"decision": {"type": "approve", "outcome": "approved"}}, + ) + decisions = module.staff_own_decisions(staff, config, {"limit": 10}) + history = module.staff_review_history(staff, config, REQUEST_ID) + + staff.breg.list_records.assert_not_called() + staff.casework.review_tasks.assert_called_once_with( + {"queue": "applications"}, source_profile="auditor" + ) + staff.casework.review_task.assert_called_once_with( + TASK_ID, source_profile="auditor" + ) + staff.casework.review_task_context.assert_called_once_with( + TASK_ID, source_profile="auditor" + ) + staff.metadata.select_proposal_review_context.assert_called_once_with( + "auditor", "submit-application" + ) + staff.breg.read_proposal_review_by_id.assert_called_once_with( + "review-context-binding", PROPOSAL_ID + ) + staff.breg.get_record.assert_not_called() + staff.casework.claim_review_task.assert_called_once_with( + TASK_ID, 4, "staff-claim-001", source_profile="auditor" + ) + staff.casework.release_review_task.assert_called_once_with( + TASK_ID, 5, "staff-release-001" + ) + staff.casework.decide_review_task.assert_called_once_with( + TASK_ID, + 5, + "staff-decision-001", + {"decision": {"type": "approve", "outcome": "approved"}}, + source_profile="auditor", + ) + staff.casework.own_review_decisions.assert_called_once_with( + {"limit": 10}, source_profile="auditor" + ) + staff.casework.review_history.assert_called_once_with( + REQUEST_ID, source_profile="auditor" + ) + self.assertEqual(staff_dashboard["applications"], []) + self.assertEqual(detail["task"]["taskId"], TASK_ID) + self.assertEqual(detail["source"]["id"], PROPOSAL_ID) + self.assertEqual(claimed["revision"], 5) + self.assertEqual(released["revision"], 6) + self.assertEqual(decided, {"status": "accepted"}) + self.assertEqual(decisions["items"][0]["requestId"], REQUEST_ID) + self.assertEqual(history["items"][0]["status"], "approved") + + def test_mutations_refuse_changed_binding_or_revision_before_product_calls(self): + module, _, _, _ = load_example() + config = module.load_config(ROOT / "config.example.toml") + holder = Person("holder") + staff = Person("staff") + + with self.assertRaises(ValueError): + module.holder_submit_review( + holder, + config, + RECORD_ID, + {"application": TASK_ID, "status": "submitted"}, + "holder-review-002", + ) + holder.breg.get_record.assert_not_called() + holder.breg.start_proposal.assert_not_called() + + with self.assertRaises(ValueError): + module.staff_claim_task(staff, config, TASK_ID, -1, "staff-claim-refused") + staff.casework.claim_review_task.assert_not_called() + + with self.assertRaises(PermissionError): + module.staff_decide_task( + holder, + config, + TASK_ID, + 4, + "wrong-persona-decision", + {"decision": {"type": "approve", "outcome": "approved"}}, + ) + holder.casework.decide_review_task.assert_not_called() + + def test_flask_html_and_fastapi_frontend_share_the_business_functions(self): + module, portal_flask, portal_fastapi, _ = load_example() + config = module.load_config(ROOT / "config.example.toml") + + holder = Person("holder") + + def install_flask(app, sessions, **kwargs): + @app.before_request + def person(): + g.registry_person = holder + + portal_flask.install = mock.Mock(side_effect=install_flask) + holder_runtime = module.Runtime( + config.services["holder"], object(), object(), lambda _: holder + ) + flask_app = module.create_flask_app(config, holder_runtime) + client = flask_app.test_client() + page = client.get("/", base_url="https://holder.example.test") + self.assertEqual(page.status_code, 200) + self.assertIn(b"holder-subject", page.data) + self.assertIn(b"holder-csrf", page.data) + self.assertIn(b'action="/auth/logout"', page.data) + self.assertIn(b'action="/auth/switch"', page.data) + self.assertEqual(page.data.count(b'name="csrf_token"'), 2) + self.assertEqual(page.headers["Cache-Control"], "no-store") + submitted = client.post( + f"/api/applications/{RECORD_ID}/reviews", + base_url="https://holder.example.test", + headers={ + "Origin": "https://holder.example.test", + "X-CSRF-Token": "holder-csrf", + }, + json={ + "idempotencyKey": "holder-review-route-001", + "inputs": {"application": RECORD_ID, "status": "submitted"}, + }, + ) + self.assertEqual(submitted.status_code, 200) + self.assertEqual(submitted.json["proposal"]["requestId"], REQUEST_ID) + refused = client.post( + f"/api/applications/{RECORD_ID}/reviews", + base_url="https://holder.example.test", + headers={ + "Origin": "https://holder.example.test", + "X-CSRF-Token": "holder-csrf", + }, + json={ + "idempotencyKey": "holder-review-route-refused", + "inputs": {"application": TASK_ID, "status": "submitted"}, + }, + ) + self.assertEqual(refused.status_code, 400) + self.assertEqual(refused.json, {"code": "request.invalid"}) + history = client.get( + f"/api/review-requests/{REQUEST_ID}/history", + base_url="https://holder.example.test", + ) + self.assertEqual(history.status_code, 200) + self.assertEqual(history.json["items"][0]["status"], "approved") + + staff = Person("staff") + + def install_fastapi(app, sessions, **kwargs): + @app.middleware("http") + async def person(request, call_next): + request.state.registry_person = staff + return await call_next(request) + + portal_fastapi.install = mock.Mock(side_effect=install_fastapi) + staff_runtime = module.Runtime( + config.services["staff"], object(), object(), lambda _: staff + ) + fastapi_app = module.create_fastapi_app(config, staff_runtime) + + async def check_fastapi(): + transport = httpx.ASGITransport(app=fastapi_app) + async with httpx.AsyncClient( + transport=transport, base_url="https://staff.example.test" + ) as client: + page = await client.get("/") + self.assertEqual(page.status_code, 200) + self.assertIn("staff-csrf", page.text) + self.assertIn('action="/auth/logout"', page.text) + self.assertIn('action="/auth/switch"', page.text) + self.assertEqual(page.text.count('name="csrf_token"'), 2) + dashboard = await client.get("/api/dashboard") + self.assertEqual(dashboard.status_code, 200) + self.assertEqual(dashboard.json()["persona"], "staff") + task = await client.get(f"/api/tasks/{TASK_ID}") + self.assertEqual(task.json()["task"]["taskId"], TASK_ID) + claim = await client.post( + f"/api/tasks/{TASK_ID}/claim", + headers={ + "Origin": "https://staff.example.test", + "X-CSRF-Token": "staff-csrf", + }, + json={"revision": 4, "idempotencyKey": "route-claim-001"}, + ) + self.assertEqual(claim.json()["revision"], 5) + release = await client.post( + f"/api/tasks/{TASK_ID}/release", + headers={ + "Origin": "https://staff.example.test", + "X-CSRF-Token": "staff-csrf", + }, + json={"revision": 5, "idempotencyKey": "route-release-001"}, + ) + self.assertEqual(release.json()["revision"], 6) + decision = await client.post( + f"/api/tasks/{TASK_ID}/decisions", + headers={ + "Origin": "https://staff.example.test", + "X-CSRF-Token": "staff-csrf", + }, + json={ + "revision": 5, + "idempotencyKey": "route-decision-001", + "decision": {"type": "approve", "outcome": "approved"}, + }, + ) + self.assertEqual(decision.json(), {"status": "accepted"}) + decisions = await client.get("/api/decisions?limit=10") + self.assertEqual(decisions.json()["items"][0]["requestId"], REQUEST_ID) + history = await client.get(f"/api/review-requests/{REQUEST_ID}/history") + self.assertEqual(history.json()["items"][0]["status"], "approved") + refused = await client.post( + f"/api/applications/{RECORD_ID}/reviews", + headers={ + "Origin": "https://staff.example.test", + "X-CSRF-Token": "staff-csrf", + }, + json={ + "idempotencyKey": "staff-holder-route-refused", + "inputs": { + "application": RECORD_ID, + "status": "submitted", + }, + }, + ) + self.assertEqual(refused.status_code, 403) + self.assertEqual( + refused.json(), {"code": "authorization.persona-refused"} + ) + + asyncio.run(check_fastapi()) + + def test_store_lifecycle_cli_reports_only_bounded_results(self): + example, _, _, _ = load_example() + service = load_service(example) + store = PostgresSessionStore( + lambda: None, + PortalEncryptionKeys(primary_key_id="current", keys={"current": b"k" * 32}), + ) + service.load_config = mock.Mock(return_value="configuration") + service.build_store = mock.Mock(return_value=store) + + for action, expected in ( + ("migrate", {"action": "migrate", "status": "complete"}), + ("check-store", {"action": "check-store", "status": "ready"}), + ( + "rotate-encryption", + {"action": "rotate-encryption", "status": "complete", "rewritten": 3}, + ), + ): + output = io.StringIO() + with self.subTest(action=action), contextlib.redirect_stdout(output): + service.main([action, "--config", "operator.toml"]) + self.assertEqual(json.loads(output.getvalue()), expected) + self.assertEqual(store.actions, ["migrate", "check_ready", "rotate_encryption"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/products/platform/examples/python-portal/uv.lock b/products/platform/examples/python-portal/uv.lock new file mode 100644 index 0000000000..19a5712c60 --- /dev/null +++ b/products/platform/examples/python-portal/uv.lock @@ -0,0 +1,1060 @@ +version = 1 +revision = 3 +requires-python = ">=3.11" + +[[package]] +name = "annotated-doc" +version = "0.0.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/0f/6e/a61e86e43bb6039b31a33a8f5fba76fe1cdacf3661e7b9756d4ff1b28cdc/annotated_doc-0.0.6.tar.gz", hash = "sha256:7969bb69912085b2285849c0dcac0b4b374fd180c13cf10a87f284ffcf347bbf", size = 10767, upload-time = "2026-11-10T18:17:11.28Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cd/f5/3dd85d583e55be76cd02b1fc9bbec771b12d63124b01661d9535ccf8721f/annotated_doc-0.0.6-py3-none-any.whl", hash = "sha256:361ca0950cc7082f53fa69e9328409f40a62c61e57e0a47e1825a08078a58a53", size = 5293, upload-time = "2026-11-10T18:17:10.249Z" }, +] + +[[package]] +name = "annotated-types" +version = "0.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/5f/56/a8120250d128bed162cd73c76d45f6ef9991f3e068f62a8ee060afa3104a/annotated_types-0.8.0.tar.gz", hash = "sha256:13b2beaad985e05e2d6407ee4c4f35590b11f8d693a258a561055cac8f64cab7", size = 15893, upload-time = "2026-07-23T20:16:13.995Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/99/91/8acff4f5e50511b911bbccb72b8628a49c68ce14148cd9f6431094859a90/annotated_types-0.8.0-py3-none-any.whl", hash = "sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0", size = 13427, upload-time = "2026-07-23T20:16:12.938Z" }, +] + +[[package]] +name = "anyio" +version = "4.16.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "idna" }, + { name = "typing-extensions", marker = "python_full_version < '3.15'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a1/98/7e457a3b014976887a050561955c0b76e1e7e2d6e27b78ecef2ef80518f2/anyio-4.16.0.tar.gz", hash = "sha256:59bb03251907983d1603d27c3087ddb1e93299ea2163adcdba37899a4fb12ffb", size = 310971, upload-time = "2026-11-01T11:20:07.282Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a9/16/7757fb84c819accc7d7e9af5291b261e4abb8627ee040f99e7d35ef2457a/anyio-4.16.0-py3-none-any.whl", hash = "sha256:c66ae634e0b8228396b801741beb3294326d4b6102f7bba4041c0dfb58c29026", size = 134521, upload-time = "2026-11-01T11:20:05.59Z" }, +] + +[[package]] +name = "authlib" +version = "1.9.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cryptography" }, + { name = "joserfc" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/04/96/6e7ed72bb49762a9b65d51c4cb235d793f0485cd8d6f7e9404ce955a4808/authlib-1.9.5.tar.gz", hash = "sha256:3f031d5e9b6486089e91e8f7f1b68f36275f3151c66460d650fc90d420545fd7", size = 183564, upload-time = "2026-11-05T16:13:18.409Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/58/d7/d384e7a639dd1d018767ba0fe39601b61cded066bb7af38db31ec998252d/authlib-1.9.5-py2.py3-none-any.whl", hash = "sha256:e32a63e3d869196b61816b2602231862179a2ffc29358c009d1f022c8b86a8b2", size = 267074, upload-time = "2026-11-05T16:13:16.766Z" }, +] + +[[package]] +name = "blinker" +version = "1.9.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/21/28/9b3f50ce0e048515135495f198351908d99540d69bfdc8c1d15b73dc55ce/blinker-1.9.0.tar.gz", hash = "sha256:b4ce2265a7abece45e7cc896e98dbebe6cead56bcf805a3d23136d145f5445bf", size = 22460, upload-time = "2024-11-08T17:25:47.436Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/10/cb/f2ad4230dc2eb1a74edf38f1a38b9b52277f75bef262d8908e60d957e13c/blinker-1.9.0-py3-none-any.whl", hash = "sha256:ba0efaa9080b619ff2f3459d1d500c57bddea4a6b424b60a91141db6fd2f08bc", size = 8458, upload-time = "2024-11-08T17:25:46.184Z" }, +] + +[[package]] +name = "certifi" +version = "2026.10.23" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, +] + +[[package]] +name = "cffi" +version = "2.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pycparser", marker = "implementation_name != 'PyPy'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9e/ef/008a1939e372c06329a3fce4279c02f328488f3526744906eeec3da7ad5f/cffi-2.1.1.tar.gz", hash = "sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be", size = 530807, upload-time = "2026-08-03T21:21:18.939Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/70/d2/16d99a0c4948febc0ebd133a13b2f688ff7f8cb04da971e1128872ce0c03/cffi-2.1.1-cp311-cp311-macosx_10_15_x86_64.whl", hash = "sha256:c8d2c9fd1f2d16f780d15127abb050d13d1a76c03a4bd87d7e4980e45e511e12", size = 183838, upload-time = "2026-08-03T21:19:29.637Z" }, + { url = "https://files.pythonhosted.org/packages/cd/95/31b535a9f0220ae9f357de4a08d57ce89cb417653c2fd9f075f50822a388/cffi-2.1.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:398aff33cee2767e3e781d2554c54bd0dff386bb437581e0d8011fde1a942ec1", size = 184168, upload-time = "2026-08-03T21:19:30.764Z" }, + { url = "https://files.pythonhosted.org/packages/ad/5a/4707a0dc1f203f5dde5a907b0d4e3c25d71120241048bd5bc6f1bb9d4e71/cffi-2.1.1-cp311-cp311-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:154852545011f779917b11c78db2358d095da62a9a172b78ad0a583ee5adc0d0", size = 211805, upload-time = "2026-08-03T21:19:31.867Z" }, + { url = "https://files.pythonhosted.org/packages/ad/66/c19feabb28485b6e0bbaaafa90837a1ef5d302e90f2178bd33f17a49879b/cffi-2.1.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:3311ed60d36f83378794e1009ac6258bafbf81f7888b4caa7b35a521e3f95813", size = 218716, upload-time = "2026-08-03T21:19:32.896Z" }, + { url = "https://files.pythonhosted.org/packages/a7/92/500760486c8baab49a7a8a58ba7fc3355ec3974b454b8a09e528efde9e1d/cffi-2.1.1-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:6e192623c49c94421616a5778fba35cf0d5a8d000650c1967ef4448ee5cdd990", size = 205569, upload-time = "2026-08-03T21:19:34.142Z" }, + { url = "https://files.pythonhosted.org/packages/a5/a7/a67c733254d6e7373f7822f8082d8d6beade791e0cf12a7611f376fa61c7/cffi-2.1.1-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a6e721d4b0e45d5b65e87534470e67b18dcd092c83f68fba09f152b9cbc061af", size = 204907, upload-time = "2026-08-03T21:19:35.174Z" }, + { url = "https://files.pythonhosted.org/packages/f7/a4/4399daaf8f7dfee9d7c3327fdb0426ee041cc63edc358b93911ceb2bfc7a/cffi-2.1.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:34e261f78cb6ceaaa36f42f2613f4380d94d9c759a9c73c769ee6e0247364632", size = 217807, upload-time = "2026-08-03T21:19:36.286Z" }, + { url = "https://files.pythonhosted.org/packages/28/f7/dabe6da2466ecbd82dc62e7342dc6b1065dad990c06f00f0ede9ebf2a0ed/cffi-2.1.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:7225e4514edb64eb6740324353e0da0711954fd8d7da4576755b1c6e09b697cd", size = 221252, upload-time = "2026-08-03T21:19:37.416Z" }, + { url = "https://files.pythonhosted.org/packages/ce/87/616202d8e51342c07d2534c510111c4cc37201775ce8f60802c9335d1edd/cffi-2.1.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:df913725b79db7bcf03448f36b7bf8815363417d5b58deecf9305e3e30f0f21a", size = 214214, upload-time = "2026-08-03T21:19:38.507Z" }, + { url = "https://files.pythonhosted.org/packages/b4/c6/ab025d75d2c26c19b087c0124e75ee31cb65032f4fe345d356d8c507ab97/cffi-2.1.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f5cfbc5fe74540d335175b656c725d74d90e3730c626d92575eea35029d9afaa", size = 219408, upload-time = "2026-08-03T21:19:39.809Z" }, + { url = "https://files.pythonhosted.org/packages/db/e2/7e8109f65445bdc673a7b54f02c677de462db75674220fd1335efc8eb598/cffi-2.1.1-cp311-cp311-win32.whl", hash = "sha256:f8ec5e643a9a937f64e1999eb9f75d072263751912dc5cd06d3c85f8f44be7c3", size = 174470, upload-time = "2026-08-03T21:19:41.246Z" }, + { url = "https://files.pythonhosted.org/packages/73/c0/77ba02423c2f7d7091143c45cd49e0e6575c4c1967394bb542bd923a9b74/cffi-2.1.1-cp311-cp311-win_amd64.whl", hash = "sha256:42f6930c31dc7f50732c9ae793c2786c7b6b044195967bbdde40bb9be81c4cc0", size = 185096, upload-time = "2026-08-03T21:19:42.615Z" }, + { url = "https://files.pythonhosted.org/packages/7c/47/9f1f85f9672ceda4984dc6c4f8824e8558992a2972c3d3c81fb8eb28d4ba/cffi-2.1.1-cp311-cp311-win_arm64.whl", hash = "sha256:c7659f22557c5a0bc4855cd635f55edec690cc008a40768527762cb9fb263455", size = 179941, upload-time = "2026-08-03T21:19:43.747Z" }, + { url = "https://files.pythonhosted.org/packages/10/69/43965eccfdead3b9220015fd1320e117be8c6ed01a62ffab76eeb752f5d5/cffi-2.1.1-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:c8c69575568085ba0b1b10c0249d779a214aea6f6522e949a0fc9fb0fcb449d0", size = 184821, upload-time = "2026-08-03T21:19:44.887Z" }, + { url = "https://files.pythonhosted.org/packages/54/7d/16e5a096677b5e313ca80cd5e5170efa3ea44624a82bb111925522da64b1/cffi-2.1.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f81b3b8f3d4e343550fa4baa0e479bba9f2d29ce9c2e9b51d1ce1718d7442fcf", size = 184719, upload-time = "2026-08-03T21:19:46.129Z" }, + { url = "https://files.pythonhosted.org/packages/56/e6/8941622732edec876dd17d0453dce07317ae96db34f2ec1436c9d3785986/cffi-2.1.1-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a", size = 214799, upload-time = "2026-08-03T21:19:47.218Z" }, + { url = "https://files.pythonhosted.org/packages/44/de/f98430906df1545ffde0d543dd124a7a439bc2cd32b36b9c53f805df7333/cffi-2.1.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890", size = 222389, upload-time = "2026-08-03T21:19:48.331Z" }, + { url = "https://files.pythonhosted.org/packages/6a/5b/717f1526b9957b34456313c31645c5b82b8fb5c3fe9e4752999be7128bfc/cffi-2.1.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50", size = 210249, upload-time = "2026-08-03T21:19:49.543Z" }, + { url = "https://files.pythonhosted.org/packages/64/b3/f8aa4f3e34986c7e4ec45072d1b1b9dd295b6b18007b45518d79726dd725/cffi-2.1.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e", size = 208775, upload-time = "2026-08-03T21:19:50.918Z" }, + { url = "https://files.pythonhosted.org/packages/b1/db/dceb9dd5b231e1da801793f8acc9f3c52a7e1afe40bb1aae37e02b0faad5/cffi-2.1.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf", size = 221822, upload-time = "2026-08-03T21:19:52.054Z" }, + { url = "https://files.pythonhosted.org/packages/a0/d2/6cd24ae3be000a634109c247d1475d62e5616d0dc78c82770942ec384248/cffi-2.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517", size = 225232, upload-time = "2026-08-03T21:19:53.109Z" }, + { url = "https://files.pythonhosted.org/packages/cb/52/3fa190537004dd7f0ab860a6dc7c0175b8667f68d1e618a46f5498d30250/cffi-2.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735", size = 223597, upload-time = "2026-08-03T21:19:54.515Z" }, + { url = "https://files.pythonhosted.org/packages/80/fb/0bb75b7039588c074b37ae99f40d9bfddf990ecb2fbc346ebccd2e56b9be/cffi-2.1.1-cp312-cp312-win32.whl", hash = "sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e", size = 175292, upload-time = "2026-08-03T21:19:55.566Z" }, + { url = "https://files.pythonhosted.org/packages/d9/79/615cc094e2fb508cade7de88d3b4f6c4ec2bab695c97bce9153dc65aadf5/cffi-2.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a", size = 185919, upload-time = "2026-08-03T21:19:56.89Z" }, + { url = "https://files.pythonhosted.org/packages/70/c6/d0ea84713fe46b243a436a18fcd47d639732747e21635c8a27191b06dc30/cffi-2.1.1-cp312-cp312-win_arm64.whl", hash = "sha256:7bde5e4cc5c10140859842b9d383af292b22639a4dffb725314baf45968cef80", size = 180093, upload-time = "2026-08-03T21:19:58.155Z" }, + { url = "https://files.pythonhosted.org/packages/9d/f4/035513d4117049066b4779dc3b7c0c0fdad175fa13731c9f4003f1cd1478/cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:b5bdfd1c873d4e093aabc0ca84c4ca6dbc4f752afb5c86f146d9742580c9da2e", size = 194248, upload-time = "2026-08-03T21:19:59.399Z" }, + { url = "https://files.pythonhosted.org/packages/76/af/2aeb4dbb5fc41a04161ae9ff1518de7cec08e164f44a8ce6a4cf7fd2cd1d/cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:31348097ff5bbe827ccc41795d4dd099d9f0625e7def00ee653c137a490c2a6c", size = 196908, upload-time = "2026-08-03T21:20:00.746Z" }, + { url = "https://files.pythonhosted.org/packages/a7/46/2e5fdde8555706dd98139a910ca11be02809f3f605ce956f655d0214e100/cffi-2.1.1-cp313-cp313-macosx_10_15_x86_64.whl", hash = "sha256:9d2055050ea716bd38b7f7f1579c275386646b4894c155a3e2f3cd62ed41b7c6", size = 184805, upload-time = "2026-08-03T21:20:02.02Z" }, + { url = "https://files.pythonhosted.org/packages/55/41/4c7042f317b9217502988f0873af87e16ad606dc20f84e546e3e6ce9764c/cffi-2.1.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:19ee6127ee34de7d83ce3d371ebc5ed91addbdcc39f9ab15ce4eb35a4e534971", size = 184764, upload-time = "2026-08-03T21:20:03.141Z" }, + { url = "https://files.pythonhosted.org/packages/43/1f/1c3d90d91811c8f86ced9ed637956c54bfe5b79ca98fe976d7f8c8979f6b/cffi-2.1.1-cp313-cp313-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:6a8dddef476fab96d066d578fc88526767b836ab5ab21754e1d5bf3879c31c7c", size = 214722, upload-time = "2026-08-03T21:20:04.377Z" }, + { url = "https://files.pythonhosted.org/packages/37/6f/3b5ce4c3b2192d250f04908f2bfd91ef34552ec8f7716a5d4abdb8d67bb2/cffi-2.1.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f16c709686a78c727bbbf059f92b0bf41c6fc60deec706d2dc19f529175a6125", size = 222369, upload-time = "2026-08-03T21:20:05.544Z" }, + { url = "https://files.pythonhosted.org/packages/02/10/4b3c75dde3d9663c9e02ba05c2668b954f671d4bbe346413ca8c696b295a/cffi-2.1.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:fcd22650c908d7b7da162bbfaab594a1227a15d1643a98c68b122ac642fa2264", size = 210175, upload-time = "2026-08-03T21:20:06.75Z" }, + { url = "https://files.pythonhosted.org/packages/df/62/14f74b9543e605d17701dc797b815958b8bb70b7624ce1b832ddad48ed6c/cffi-2.1.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:aa9511c62d14da7aacc9b4bf51f3f697a621e83b2d6919008243c3aad168eea3", size = 208670, upload-time = "2026-08-03T21:20:08.04Z" }, + { url = "https://files.pythonhosted.org/packages/95/95/86342356ff5953b3fb06f7ef7c5bee212d45e770abc7218d451b9148313c/cffi-2.1.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a931079504ecc49efed7744c476a5c343a92fabf66dec2db95edb1b2fdc770e2", size = 221824, upload-time = "2026-08-03T21:20:09.274Z" }, + { url = "https://files.pythonhosted.org/packages/eb/ff/7b3429ff53aafe931ed8a5fc69f481bbef7ba6de87ddcbb63d08f483f613/cffi-2.1.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a2d7755bef5a12ed488f4ef1f1b69ee9191d7396083b755a5d2295f6edb4768b", size = 225148, upload-time = "2026-08-03T21:20:10.7Z" }, + { url = "https://files.pythonhosted.org/packages/34/34/a95870b9221e09cf4f2ce3178b1a210abdfe63a1bd357da940418d7b8d15/cffi-2.1.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e0bcb7e0f677f543555d2adff3bf19c05f66cdb4796e5ff602442ab2fe3c4ef7", size = 223564, upload-time = "2026-08-03T21:20:12.165Z" }, + { url = "https://files.pythonhosted.org/packages/70/ea/839b50531021a647fb5e929f72cf97bc1ff702b5472166164b5b6e76b851/cffi-2.1.1-cp313-cp313-win32.whl", hash = "sha256:334644fbac4eff73d985a17a91226df55d0f394160c4cfb880e084c8f7161cac", size = 175263, upload-time = "2026-08-03T21:20:13.559Z" }, + { url = "https://files.pythonhosted.org/packages/60/a6/8b149b2c3f2e11aaa1618ef64500b45f50f22c57a977a4dff1aff1f91042/cffi-2.1.1-cp313-cp313-win_amd64.whl", hash = "sha256:1aa5645c30469b09530c4ebca77ebf8f17618293c58f8549cb1a543a50236e7d", size = 185688, upload-time = "2026-08-03T21:20:14.69Z" }, + { url = "https://files.pythonhosted.org/packages/01/9a/11f687cb39d6a3504060d5242f04f48c735afb4d3d533958a20594890cb2/cffi-2.1.1-cp313-cp313-win_arm64.whl", hash = "sha256:63bbfd5ded17c4840ac07cd8f1c21ba9d9708141f840b324f422f41b207e3973", size = 180078, upload-time = "2026-08-03T21:20:15.917Z" }, + { url = "https://files.pythonhosted.org/packages/d3/7b/d6bbf82b8b96e7391438898c42f5bd96dd02030fd5b64937d248220003e2/cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:7dbb61fe3a7699468030f71bbe5f8a0e326a151daa91beb11a6fc1f980c55e1c", size = 194064, upload-time = "2026-08-03T21:20:17.148Z" }, + { url = "https://files.pythonhosted.org/packages/94/e6/bcc91b283be94735e268487a054004f0aa19947b6348fa367db53230abc8/cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:f24fb43132a4c6b4cb4eb029492919b2db645be6808d738f244fd146c03c32cb", size = 196720, upload-time = "2026-08-03T21:20:18.268Z" }, + { url = "https://files.pythonhosted.org/packages/d9/99/c4b0c17cacdc9c3b8f280026286a9826d6a208c0f047591a3c3ce99b91fd/cffi-2.1.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:d28630f5854ab07ab1fd4aba756de52326c82e6be15d414b12793f1975048b54", size = 184964, upload-time = "2026-08-03T21:20:19.708Z" }, + { url = "https://files.pythonhosted.org/packages/b3/a9/9db617d05d7367c1ad0ab00b3aa6e6f9281edd689b4ee9ea0e5a84e89c97/cffi-2.1.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:661c298b4821edebead0c91edd2b00374d67ad7c5a1f7a91d4442633b79d6a72", size = 184962, upload-time = "2026-08-03T21:20:20.833Z" }, + { url = "https://files.pythonhosted.org/packages/67/b8/b42132ca113dc567d37684437b46ca1dafc885902b02a110a02d5b511857/cffi-2.1.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:58acb8ab8e295e6c5ea12f888cbb13cf21511ef2a3303a23f4325c29d17fe5c1", size = 222328, upload-time = "2026-08-03T21:20:22.118Z" }, + { url = "https://files.pythonhosted.org/packages/80/10/c5c0cbf0a657aecf59ef511409734230bf556f05a0d6c9eed7aa5c0a0166/cffi-2.1.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:456a61fa52d579ebf9df2e9552ead5129855dbaff6c1e5a9b1bc408809bdc062", size = 209985, upload-time = "2026-08-03T21:20:23.401Z" }, + { url = "https://files.pythonhosted.org/packages/d5/6c/bfa0b87b03b9238148beca990292843c9396ba069b54496596594173de7b/cffi-2.1.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a4f00aa42f75d6e4595e8866e748cc1705adc0cddfeb2ca86d0d03993d63ba03", size = 208530, upload-time = "2026-08-03T21:20:24.628Z" }, + { url = "https://files.pythonhosted.org/packages/e9/02/4e7d553a7ac4b4238b38b3c1b80d486e9d4436f8d2acbf87a0997fe3f402/cffi-2.1.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b0431303acaea1089ad4b3e9ce4e6518193def1118d4073ca848635ee4ea2e96", size = 221525, upload-time = "2026-08-03T21:20:25.758Z" }, + { url = "https://files.pythonhosted.org/packages/82/1d/a4aaf9babd75acb4d5f223bff71533bee748dd770a382619a798960ee9ba/cffi-2.1.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:64faea20f4e2613363a1a9b9c7dd73058f3ecd00133a511e72ad7c511658f527", size = 225053, upload-time = "2026-08-03T21:20:26.985Z" }, + { url = "https://files.pythonhosted.org/packages/81/10/5dc0e7bdd18e22107054288283380fc97a06ae3f1656a106908d666a3c88/cffi-2.1.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5c58fe613dc5e5336357eff555824a314d8e43282600435c8d1cb6a7a2fedd13", size = 223213, upload-time = "2026-08-03T21:20:28.277Z" }, + { url = "https://files.pythonhosted.org/packages/0b/e9/d0061c364cde06ee43168a0d076ac1da512cbc380d44767b844ba34fe2b6/cffi-2.1.1-cp314-cp314-win32.whl", hash = "sha256:1a18a57b58cfb21fc28d72e876acf10eaed67a1ed96226f92af4df681d571c4c", size = 177682, upload-time = "2026-08-03T21:20:44.288Z" }, + { url = "https://files.pythonhosted.org/packages/a7/06/1c3e01e3ba14c39f6d10bfbac52753b7e22259e38088e5cfe1d704918690/cffi-2.1.1-cp314-cp314-win_amd64.whl", hash = "sha256:3222ba5d678f80a030e6afbcc33dc1ae5cb45facabb61cee2c7016b8432fde48", size = 187949, upload-time = "2026-08-03T21:20:45.623Z" }, + { url = "https://files.pythonhosted.org/packages/87/5b/da4e39efe18eeb89cf580ea9cfc66b6a7c3eadb808fc0cc1d3a295cb5a5d/cffi-2.1.1-cp314-cp314-win_arm64.whl", hash = "sha256:ab36d55f9ed2d067327667c2fea18dda018eb628dd6347aa01dda6cf1f5d3836", size = 182947, upload-time = "2026-08-03T21:20:46.955Z" }, + { url = "https://files.pythonhosted.org/packages/23/59/40338bf421c5accea1d45158170c87006ef1cd371b05c077e76476949728/cffi-2.1.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:7750c6449dff7864bb9bb27ddfb0267756189201a3afc911d82b3caacd70dfc3", size = 188504, upload-time = "2026-08-03T21:20:29.495Z" }, + { url = "https://files.pythonhosted.org/packages/7d/47/5ecf1023850036e674c77ec4de86182d309ae344e39e7cba984b7df5d647/cffi-2.1.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:0beceaabe56af686895136a2de78db54ecd8e4046b236b8fd6d6cb61389e9bf2", size = 188259, upload-time = "2026-08-03T21:20:31.291Z" }, + { url = "https://files.pythonhosted.org/packages/2a/9c/92934c3bea9f785b23eba304538c0b4d37a2a96d2431eb3a1bc87a11aa19/cffi-2.1.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:49cbc70e6542d4ccccb936558d1064a8012541e78f821f955cff24e357776c94", size = 223864, upload-time = "2026-08-03T21:20:32.571Z" }, + { url = "https://files.pythonhosted.org/packages/4d/45/ba4c93527bc38616a8bd36488acb69a2212d60486794f0c1f318949bbb76/cffi-2.1.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:e2d65b31f36619cda3999b78b2aa9632e76b78448e7a56fc4240824200e7c4fc", size = 211538, upload-time = "2026-08-03T21:20:33.808Z" }, + { url = "https://files.pythonhosted.org/packages/80/e9/b6ef565e452acb932fb0cb5443f44a78efbd1233e566f02b5a83855e9115/cffi-2.1.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:28907ab9bfb6aa13184cfc17c6b8e1023c5ab6fd7076d8c20a35e59fe04f8f29", size = 210688, upload-time = "2026-08-03T21:20:34.974Z" }, + { url = "https://files.pythonhosted.org/packages/9a/95/eff5f0cee78d2eabc7eebffec40d3fc1876b5f3c95582e018bb4b99601f2/cffi-2.1.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:51b31d1c98274844cfd7838ce00bfc27c7423a4dc00fc0772fc3331c2cc90676", size = 223803, upload-time = "2026-08-03T21:20:36.564Z" }, + { url = "https://files.pythonhosted.org/packages/fa/01/579d39fb8bef00a335a23d83757b44feb24cd6345a2c451b64cb67b9c362/cffi-2.1.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:5e7cecbaadb83884793e05828cee59b210b24583b9c7425d0ba6a754fe22eb4e", size = 226763, upload-time = "2026-08-03T21:20:37.816Z" }, + { url = "https://files.pythonhosted.org/packages/8d/b0/0b44f47c60b01b57b6e2bbd92343f13a85a1d93bc46ccf6e47e244acd99c/cffi-2.1.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:25792eac27877609e7bb06d42ff88278a6624fff2ba9bbb523c09616b117e80f", size = 225688, upload-time = "2026-08-03T21:20:38.959Z" }, + { url = "https://files.pythonhosted.org/packages/eb/d2/3b7176cb570a1d3e27faf67b72f591af508036e0d8b2be2ef9af9e8c84bb/cffi-2.1.1-cp314-cp314t-win32.whl", hash = "sha256:8ef53b2de9bcb9197d31854256575d59dbac0cba72ac627bb291ef5eceb74be4", size = 182868, upload-time = "2026-08-03T21:20:40.388Z" }, + { url = "https://files.pythonhosted.org/packages/56/78/31f00c1bcd97c9bbf55f1bfdf5bc809a5de8887473e90bb9960dca825e80/cffi-2.1.1-cp314-cp314t-win_amd64.whl", hash = "sha256:616f097f2fe415bc92a247f02e11f634e1f9e9a83d327e3c915c15089c87869e", size = 194104, upload-time = "2026-08-03T21:20:41.725Z" }, + { url = "https://files.pythonhosted.org/packages/7b/1b/58496f2ed0a35de575250c02a43ab3cc2c04d494a88fed31c1cabc0fd176/cffi-2.1.1-cp314-cp314t-win_arm64.whl", hash = "sha256:ad2c86c495b899d862ea0f4b42891b8713a3bd45dd4105c7fd51c2a72f39f3a5", size = 186402, upload-time = "2026-08-03T21:20:43.042Z" }, + { url = "https://files.pythonhosted.org/packages/c1/8f/9ebe220eab48a093d1a5a5e339ab0dc7316eef3bb04d63c42f0251b61f50/cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:dddad92b554513a31f272570678ba307fb9f618f05e3d4a5eacafff9eae03e1d", size = 194043, upload-time = "2026-08-03T21:20:48.179Z" }, + { url = "https://files.pythonhosted.org/packages/ff/69/844bad3ece306c4782c2ecb93597035b6690d48704b803914c199da1e8b3/cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:da0e573f9f97159390c89d9f1a9e41908b66d408cc5b58d08cf3847d844c531b", size = 196737, upload-time = "2026-08-03T21:20:49.457Z" }, + { url = "https://files.pythonhosted.org/packages/1b/8a/af668013284634733f02d683458a0728739c7d6ddb5e14cb0c20832266fe/cffi-2.1.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:fb92203a88b3d3053034db775110081c49d28be6551923805e039924093761e4", size = 184933, upload-time = "2026-08-03T21:20:50.639Z" }, + { url = "https://files.pythonhosted.org/packages/0c/75/2f5207ff6d1a613133b23a5203cc0c2a628313b5eb3974d7956ae3c57950/cffi-2.1.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:2ae64be792b8966f2c69538199728b290e34726562896df1e5dc8ffd8d8188e8", size = 185002, upload-time = "2026-08-03T21:20:52.173Z" }, + { url = "https://files.pythonhosted.org/packages/e2/31/9e1313b0a6e30e91b3b3d3fff51ae99c857c07738e3afcce1f7334e1b7ab/cffi-2.1.1-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:507a24c282e0f42f8ed737cf048572cbf580468da5555764a8331735e9c736b6", size = 222271, upload-time = "2026-08-03T21:20:53.462Z" }, + { url = "https://files.pythonhosted.org/packages/50/e3/f6234a833e6e08c7007003074723c406559eecf9b48dfc97471e5a8eb7a0/cffi-2.1.1-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:246fa40ce8645a614ff682e0b70f37134e460eaf93a775e0cbe3cca585a67a80", size = 209919, upload-time = "2026-08-03T21:20:54.783Z" }, + { url = "https://files.pythonhosted.org/packages/0d/fc/5f74e293fced6edb51af3a46c4ccf6c23c9943774ecb375ddbd522c76add/cffi-2.1.1-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:471cee653ae88de62096552e6d24ccb4a5adb8c8c9f10b5054d0122c15bf2779", size = 208529, upload-time = "2026-08-03T21:20:56.066Z" }, + { url = "https://files.pythonhosted.org/packages/44/16/29e6d01b388bef055ecd6ca8244b3f4d336bd09e92d5d892187b9601084e/cffi-2.1.1-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:aeae0e330c9f6acd681f647d46cefd30c29f93e3392882e792e82080c9691399", size = 221630, upload-time = "2026-08-03T21:20:57.336Z" }, + { url = "https://files.pythonhosted.org/packages/a4/18/fa7f1f6857d5eb88a4ca99ffcbfb7c387a287ccc154c64a73e86314745d7/cffi-2.1.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:42a494cee34437f05546455144f2b5d9ac09b1face62bcfce597d2e521066688", size = 225134, upload-time = "2026-08-03T21:20:58.675Z" }, + { url = "https://files.pythonhosted.org/packages/e0/9f/e8e3dfa04a1b4c241f8c91faacad872b4d4efd051d49764ad4e2fd4b9fea/cffi-2.1.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:cc572dace3f60ef98d7b12ff411d20f5362feb31a0439eab0085bbfd349982d7", size = 223197, upload-time = "2026-08-03T21:20:59.968Z" }, + { url = "https://files.pythonhosted.org/packages/f8/7e/8debeb04f1ab9fe2a6963964cd6f1aaf7192627b83926586a6a4e089c9fa/cffi-2.1.1-cp315-cp315-win32.whl", hash = "sha256:4f42141fc14250de6dde5ee7ea4432be017252d91f19c5ad043c084cea629cac", size = 177683, upload-time = "2026-08-03T21:21:14.901Z" }, + { url = "https://files.pythonhosted.org/packages/e0/31/5158704cc474ab65c1647932e88be78dc0873f47130e253be38bcaf13d01/cffi-2.1.1-cp315-cp315-win_amd64.whl", hash = "sha256:e6e8cff14d6fb0be70a09c0bdc58096f501952d04624ebf867e0e56da2df8960", size = 187897, upload-time = "2026-08-03T21:21:16.108Z" }, + { url = "https://files.pythonhosted.org/packages/cc/4b/b3a2da8570c704ffc0f9762cdc3ec0f02c8573798e0b5cf7f11c82bbb70f/cffi-2.1.1-cp315-cp315-win_arm64.whl", hash = "sha256:27350daa11d4f10c540e6e89dada4c54feb7256ad03e9a4dc075ebad7ba360d1", size = 182935, upload-time = "2026-08-03T21:21:17.271Z" }, + { url = "https://files.pythonhosted.org/packages/d0/ef/5443574510a1207e6f6bc38ba6e1f1de36cb48fef07b2728bb896a21f430/cffi-2.1.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:c26608d2222fb1e94487e4a387d85f13eb55d5ed725cb25a0c589ac4ee60e7bc", size = 188464, upload-time = "2026-08-03T21:21:01.163Z" }, + { url = "https://files.pythonhosted.org/packages/7e/ae/a56fa8c4686ad50e148fcbc8d3ae0d03915ff5c30d795058988c24118cef/cffi-2.1.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:4be96343e422f2dfcd12ab5c9f5aebe03f82f737c6bffeca6830b3875cb44aab", size = 188262, upload-time = "2026-08-03T21:21:02.382Z" }, + { url = "https://files.pythonhosted.org/packages/53/b2/6187f46f2912276a3ae284076109cc5c8680482f11f766ccf26db4a86427/cffi-2.1.1-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:937c0052c05a31ca1daf18de3158eed4dbfcb9cc107adbea227728d647be701e", size = 223779, upload-time = "2026-08-03T21:21:03.553Z" }, + { url = "https://files.pythonhosted.org/packages/8a/f6/c3ad28bd19f77047a03084424fbd4cbe997303267c14423737324be0385d/cffi-2.1.1-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:df423d40ee8654634421812bc3b196da3f9bd7d32929da813f8394c4348a5358", size = 211520, upload-time = "2026-08-03T21:21:04.863Z" }, + { url = "https://files.pythonhosted.org/packages/a0/cd/ccac9013a5bd9fd764de118674ab9c805b5ca10c19270d90ee273f8b2240/cffi-2.1.1-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a730a083190634c65cca36ba5f489531576ebd79bcd5c8e172130f6453127231", size = 210673, upload-time = "2026-08-03T21:21:06.223Z" }, + { url = "https://files.pythonhosted.org/packages/52/86/2976131c639aead931c5bee5aba67e4b09fbeb8018b6f282f70803f923a7/cffi-2.1.1-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:363e05fa78e15116c3c32c210ee36884fd6b9afa6d440e47112c3bd511d64cb6", size = 223835, upload-time = "2026-08-03T21:21:07.539Z" }, + { url = "https://files.pythonhosted.org/packages/ac/0c/33a7aeab2f9c76918c52e084beb39c570db3588133412929e8ec06fab90b/cffi-2.1.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:770de9db11e84213beec501cfcaa013b019820ca881e03344dea5844f7876d94", size = 226705, upload-time = "2026-08-03T21:21:08.774Z" }, + { url = "https://files.pythonhosted.org/packages/e3/26/2cde30fdde421130bfc18f70395731a6e6b2053c6a1978a5258ff04e72fa/cffi-2.1.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:7da0c5eff80f0197f3b3d1232ec5a682a9325f4ae9016a78f5f5ca35f9ced1f5", size = 225539, upload-time = "2026-08-03T21:21:09.911Z" }, + { url = "https://files.pythonhosted.org/packages/6d/cd/a361394c94b2129d604bb846f624a8e88255a3ee33129c434a00d715e64f/cffi-2.1.1-cp315-cp315t-win32.whl", hash = "sha256:06c72bb76605a4b0cd0aad6930b69d4baf7dd5d806cfc409b824191099700e66", size = 182707, upload-time = "2026-08-03T21:21:11.226Z" }, + { url = "https://files.pythonhosted.org/packages/9b/b5/ba2b299993c26577d529b6ae29841f9e15b9fcf004d65f423f4fcf94ade9/cffi-2.1.1-cp315-cp315t-win_amd64.whl", hash = "sha256:d9c275eaacd24aa73f94ffd6de08fc3f932424d8b6c376f4bed7cde376fe7bc3", size = 193772, upload-time = "2026-08-03T21:21:12.39Z" }, + { url = "https://files.pythonhosted.org/packages/aa/29/35e016098c814cd93de9cd320c66b5bfba14dc6ecedd3cb518fa7c408c69/cffi-2.1.1-cp315-cp315t-win_arm64.whl", hash = "sha256:d18e5ac0f2f03f4f518d3e23db0f0cad7faa1da8620e9c09461d443bbf6e6692", size = 186360, upload-time = "2026-08-03T21:21:13.636Z" }, +] + +[[package]] +name = "charset-normalizer" +version = "3.5.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/33/1c/f41d4e74c28ab327ff3acd36053f7ea506c55872d7a90b0fa71aa3ab0c89/charset_normalizer-3.5.2.tar.gz", hash = "sha256:39de2a259fc954455c57274dc94c79d5842774e1247a016aff30bc0efed0f4ef", size = 172659, upload-time = "2026-09-30T04:39:23.398Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/22/67/6a0b94a7960d5e1b5eacd2fb529f3fccc47db4644f7f0a7cfdcfc3be578a/charset_normalizer-3.5.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:3d21b8b13c7592db2ac5e544a6d83187b995257472b0c9e8351b6d507ae37ed6", size = 370642, upload-time = "2026-09-30T04:35:06.91Z" }, + { url = "https://files.pythonhosted.org/packages/fb/94/01009e13b94041599004edf32e56e382c24e570f60f79bab8efe45cfe1eb/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d760fe2a4d7c3b226cb9026d6a842868d52a7901bd98420e1baf14e80da85cf5", size = 259280, upload-time = "2026-09-30T04:35:08.448Z" }, + { url = "https://files.pythonhosted.org/packages/66/85/3b5358f60a13210f0b67d3755c168ef758701b021e655d88d4da28554467/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c9790464842f85f437dbbb54417eda1e0e6bfc52dd8d22d6fd1c994b73b2dc74", size = 245335, upload-time = "2026-09-30T04:35:10.104Z" }, + { url = "https://files.pythonhosted.org/packages/74/75/77c1c479b09ecd751d1e767b251ea5c14d4d50ff757bf404afab2692f600/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4685902cf26edf013ed7a3da0f426ebba7a00ebb9541386d835afbf002c11cab", size = 291707, upload-time = "2026-09-30T04:35:11.575Z" }, + { url = "https://files.pythonhosted.org/packages/0b/0d/363f78cacb70f58f15f4b083961bbd9d292f335d3f5c66fc4f1cfe69cb90/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4495c5002a7b28557e7e222e77e0b661183e432b7d6d2e788101e3f240e05b8c", size = 286747, upload-time = "2026-09-30T04:35:13.022Z" }, + { url = "https://files.pythonhosted.org/packages/e4/ed/cf505d3011ffceb12c2067a7a5d3cfe92b875d4d44bb0ff0d69375e2c184/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:211d5a3eb6af8f513b8d4ca19a8c1b7accab1b5f0d3175f9826b03c1a920dc1f", size = 269972, upload-time = "2026-09-30T04:35:14.606Z" }, + { url = "https://files.pythonhosted.org/packages/15/d8/f0a93a431d170e7ca681d4f6650fee3de934d18560e474e7267eb4b0f987/charset_normalizer-3.5.2-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:ef4fcbf3327382cd4c9f540babd61248208af7b93eec4de397b4d5f58a09e288", size = 269339, upload-time = "2026-09-30T04:35:16.087Z" }, + { url = "https://files.pythonhosted.org/packages/86/bd/9b2bd1c5b7af02462c9752d33994834ff972a96b4c483eefde9e594488e2/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:bd16aabe4a02a297c23417aa17ac6299dbd8c49f673bcd645b4929b11f5a4400", size = 261683, upload-time = "2026-09-30T04:35:17.488Z" }, + { url = "https://files.pythonhosted.org/packages/76/a5/cac540ab0fd61f3fec88ad3dbb64509e71424593d73cfdfff5ab3e4db279/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:fb9e68df06293761f9fe66ade60a9bc6d0f5e42b8acf2939a9158af86ab0e5bd", size = 248143, upload-time = "2026-09-30T04:35:18.849Z" }, + { url = "https://files.pythonhosted.org/packages/71/7a/ff467301deef2089fad87f72df9e000a26a78fec7acbb18e1999371b8369/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:59f63901b0031c3136cf64704dcb21de0bbae62ce2c9529bc39d27665463de37", size = 292358, upload-time = "2026-09-30T04:35:20.326Z" }, + { url = "https://files.pythonhosted.org/packages/ad/77/22d7e785d1e210afc2e2f58600dd1799d17a35665faf84383f002826c5f8/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:304d5463e65a35d7bb0850550e0780395395f6fcf452f04db7d5ca7cecc425ac", size = 268766, upload-time = "2026-09-30T04:35:21.72Z" }, + { url = "https://files.pythonhosted.org/packages/ae/91/e8e946267f1c2d9e2bd651726e2fbd2addf02c4d36cea5069e32ca9d7bb5/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:9cf9b1a857e25c4baceeb3624e92a56df3668f398c4acba74e174d81fb4d1d3a", size = 287432, upload-time = "2026-09-30T04:35:23.273Z" }, + { url = "https://files.pythonhosted.org/packages/4e/88/7561d8a88d555e7df6623abe7c0070b4baf47549b9408783a2ae0a1a6cf7/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:114e4d0c92d618409ed82a99e22b5c5e768fe995f2973f78265f4524f49d4640", size = 272470, upload-time = "2026-09-30T04:35:24.655Z" }, + { url = "https://files.pythonhosted.org/packages/35/7e/578c702301ec036f01455f30744a08d2b42f6ab35b9b2d4bf8cae0ef2a80/charset_normalizer-3.5.2-cp311-cp311-win32.whl", hash = "sha256:2625388c6c754520c37abaf3b41eb34d1cc4a373f457898f08606c8e362b891d", size = 186688, upload-time = "2026-09-30T04:35:26.225Z" }, + { url = "https://files.pythonhosted.org/packages/e8/fc/fdf8cf52ff21cd5bf158f20978991cf985325842f74283eb6df26c8a39d8/charset_normalizer-3.5.2-cp311-cp311-win_amd64.whl", hash = "sha256:87e50a3e7cb90af586b6c5faf23e302a970415ac73bd7bd90a515a04b427ef96", size = 214932, upload-time = "2026-09-30T04:35:27.796Z" }, + { url = "https://files.pythonhosted.org/packages/97/66/3e45a506d8110b632541faf9a9470185aa9878f1ed44020f31346c1c5e5b/charset_normalizer-3.5.2-cp311-cp311-win_arm64.whl", hash = "sha256:254eb48b9fa5ee9898a3c445825a1f340fe53712a098904b39b0bddba8ea3cb1", size = 202828, upload-time = "2026-09-30T04:35:29.259Z" }, + { url = "https://files.pythonhosted.org/packages/e7/c8/693809898870237d82785a03f3b2b58fe4c9f14669f84a7d4e623c92a59e/charset_normalizer-3.5.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:ed2a239c0ea213acc1908150a3037257083c7c083128f1a4cec2ec4b97dca491", size = 367780, upload-time = "2026-09-30T04:35:30.888Z" }, + { url = "https://files.pythonhosted.org/packages/c9/87/2fea8c13dc24b3ca9c6f803a5b2dfdeae73eb4f9e12c7885ed908ff0433c/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b91363207bd9dc966a691e959bb47f64b30f7ac4b072be9968b366982f7db77c", size = 246730, upload-time = "2026-09-30T04:35:32.286Z" }, + { url = "https://files.pythonhosted.org/packages/a8/9e/09efac30b937722f46d3110ba30b875b24b2e3a266ed746cc4e376a94d80/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:38a873987f3be698494da8b2e3085e29da02da7b633dce73e79c699a113d7bf0", size = 237707, upload-time = "2026-09-30T04:35:33.709Z" }, + { url = "https://files.pythonhosted.org/packages/9e/18/70d76670b13686237863a379928d60bd10e021f17d243ab3d7014c4a5f4e/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:355ad8011081dec5412240c087a9a0c9d4d5039f3ed11a3f13e18c2b29b56c51", size = 273050, upload-time = "2026-09-30T04:35:35.138Z" }, + { url = "https://files.pythonhosted.org/packages/54/e2/77a8b09d5adc013ed07b95b01b8b8fa5441c4e810e83ee7e4aae2fa4d91a/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:ee21e28f0430bd6dc9086c6e525d5e818a44a5ad19720c8a0ef766792f3eb5e5", size = 270345, upload-time = "2026-09-30T04:35:36.502Z" }, + { url = "https://files.pythonhosted.org/packages/7f/c5/38806a25ab5e65fc178f39affeda20858efafede2fce1ffc2556cfc9fe73/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3d31298449090ab8d47b7b1b2a555ff73cac7ed438a08b7ac160980c7ebed649", size = 257601, upload-time = "2026-09-30T04:35:37.919Z" }, + { url = "https://files.pythonhosted.org/packages/ae/8d/213565184708fdb263ae55e2c04ee1ff748129dd65d48ed0e3502da9c85a/charset_normalizer-3.5.2-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:5cde776b7cc66e4f6c99612cea4aa7269aa65863f7a15841b2c264f103822f4e", size = 252222, upload-time = "2026-09-30T04:35:39.544Z" }, + { url = "https://files.pythonhosted.org/packages/7e/24/76d2cefc25472531e4c5c7dfff68865eb1c39b78482f0fdc15b46f047830/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:ae4f5fea5b8b8ccff88238cc8569303e5ee95efae67fa62922a311397a71f346", size = 248482, upload-time = "2026-09-30T04:35:41.088Z" }, + { url = "https://files.pythonhosted.org/packages/7d/dc/65a801b66ab4c197e22c433ab25e7ac24324ac6f45a2269aca42cce309bf/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:f7d486c83842422badd511868fd8a9a20e9407ace71564b6af47ce7e60a336c1", size = 241206, upload-time = "2026-09-30T04:35:42.59Z" }, + { url = "https://files.pythonhosted.org/packages/a7/95/ca9b5eabde673002c6f1e7ada1b223916fe18f6d661da7aabd4d643718f1/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:11a4d68a6ecda3292cb1e50239e111543ba5d709bb62a6b4ea1afcfa729d8875", size = 273190, upload-time = "2026-09-30T04:35:44.347Z" }, + { url = "https://files.pythonhosted.org/packages/2d/8b/803b4d2a3f6e1740f63f1e87b04d14b42f3d4fdfe6ed7d4db2d34102b14f/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:d6734d2ef8a50fbf8445c139477da401f50d62a0606bf00e20ec6d87773fefb1", size = 253527, upload-time = "2026-09-30T04:35:45.915Z" }, + { url = "https://files.pythonhosted.org/packages/a9/55/93c0e5dbd085ae0471346026abbe7e0db9ea2d6fea74e51f0b5a46f233a7/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:a815775b6c38d4e0ff7bcffbeba67feded90202bb6a226b8dd35f1c855217413", size = 271285, upload-time = "2026-09-30T04:35:47.49Z" }, + { url = "https://files.pythonhosted.org/packages/95/69/0dbd0e0b9b16cfa816cdfcb3e2e3854a1f680dc07fb1245ea125e7448060/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:23851fb4e1b85ed3f6c2a27b777cdfe2e19fb5b38429a8faf38c7542b7665869", size = 260010, upload-time = "2026-09-30T04:35:48.996Z" }, + { url = "https://files.pythonhosted.org/packages/58/9d/e7b88e7b1bf403590c3b573277b5e1e488c68c7a6fbacca310a2c324e90c/charset_normalizer-3.5.2-cp312-cp312-win32.whl", hash = "sha256:db19d07e2e0129e974a0e65d0064fc222a446cd5122c2fd4184d2af9fc734a9e", size = 184125, upload-time = "2026-09-30T04:35:50.777Z" }, + { url = "https://files.pythonhosted.org/packages/eb/e6/e6e083884cbcfd49c64865af05027fe7011be7b2d9179524f099a1b611f3/charset_normalizer-3.5.2-cp312-cp312-win_amd64.whl", hash = "sha256:780fbe7cab297b81dad9fb8dc5eb003c0468ffb0d9e5f65068c53a34661a96bc", size = 207486, upload-time = "2026-09-30T04:35:52.194Z" }, + { url = "https://files.pythonhosted.org/packages/c4/e3/017aea0911ada7405a825c7d937eb3a13009664e2f5b38e8c4bbf2abf894/charset_normalizer-3.5.2-cp312-cp312-win_arm64.whl", hash = "sha256:e2af3aad578aa6bd1384bcf4750fc285e5a9de53f40b7d41e5a0bf748edeb2b3", size = 196734, upload-time = "2026-09-30T04:35:53.636Z" }, + { url = "https://files.pythonhosted.org/packages/c5/34/68292d68512768591aaff07c59bb53ee31341c87759433a859c4641a50c2/charset_normalizer-3.5.2-cp313-cp313-android_24_arm64_v8a.whl", hash = "sha256:ed905975ab14056a2e5eb1c376cb2e1ebc5396baf84163939c518556fccde9f5", size = 225946, upload-time = "2026-09-30T04:35:55.313Z" }, + { url = "https://files.pythonhosted.org/packages/e3/80/bee0b01b90ccd5322ae1d0abb33fab1bd95b7c2eadaf02aeccf22e04ee83/charset_normalizer-3.5.2-cp313-cp313-android_24_x86_64.whl", hash = "sha256:a66c3bc5ab1f0ff2164fc9965ddd611ff0802173f4b9d24554c563f6ab7e1d6e", size = 238619, upload-time = "2026-09-30T04:35:56.863Z" }, + { url = "https://files.pythonhosted.org/packages/78/6e/60ce52a85a7fd631ae8482ae6d74521014ca2f255892679484dc04d7ef56/charset_normalizer-3.5.2-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:d2374b62878abb00cd8309b32af6c0b715cd02dec0ca74ef12e5069bdc64144a", size = 206701, upload-time = "2026-09-30T04:35:58.639Z" }, + { url = "https://files.pythonhosted.org/packages/36/8c/71aafad23f971afc84c2b295bc0c560739ce1dac558aad9fec22e39f3639/charset_normalizer-3.5.2-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:d376bbd28b3a8999db1a103b3b388aee6f1ddeb3e51bc2172993efdcd86e064d", size = 210506, upload-time = "2026-09-30T04:36:00.147Z" }, + { url = "https://files.pythonhosted.org/packages/91/da/3c5a7798c046df7d2d68ad653cf5b6c5a8bfee225055a843c6f2f42aac1a/charset_normalizer-3.5.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:6045373d5a89a5ec71afde535db987ca28e76dfa276c2d4c818265b375d4b055", size = 366626, upload-time = "2026-09-30T04:36:01.77Z" }, + { url = "https://files.pythonhosted.org/packages/e1/16/710ac3de2ee354e2bd1a9c94efe45a2d27b5c6ad39b2d6a905be2c094b6c/charset_normalizer-3.5.2-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:849df64e889b2e17230d58410a03dba311a65b163508fd33679b2b737d4b7858", size = 244624, upload-time = "2026-09-30T04:36:03.389Z" }, + { url = "https://files.pythonhosted.org/packages/d6/39/45c7439f5b63d24f7d5b2a1d760f34af7628782d7144b4cc8ded45c2d4bc/charset_normalizer-3.5.2-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:15c44f7edfd477b06f517a5cc317fc1707edb9de2c865f43d4b6513907473234", size = 235731, upload-time = "2026-09-30T04:36:04.987Z" }, + { url = "https://files.pythonhosted.org/packages/4d/34/38f3154785ce92e9f56eb226f4d35bdfae6b008480dd055f58837a89c810/charset_normalizer-3.5.2-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a89012d6d5476ee112d20d998570ed58df2260a852afb1758809cd6900411d21", size = 270352, upload-time = "2026-09-30T04:36:06.412Z" }, + { url = "https://files.pythonhosted.org/packages/04/f3/859f74e7babc977705026b30593b3be04049632a522fb7000f83c033d747/charset_normalizer-3.5.2-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:0c951d5e6dd9c2ff60609476752bee49da4206adde960ebc247766937f72e718", size = 267393, upload-time = "2026-09-30T04:36:07.865Z" }, + { url = "https://files.pythonhosted.org/packages/4b/85/41d27f234b82e47c167a5f6c0f62501dc0c640585ff4aba79e08a390336a/charset_normalizer-3.5.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7218e8f32b0956cfcd048fd42d9d5779809745ca1d86113ca56f66e7ae1549c4", size = 254660, upload-time = "2026-09-30T04:36:09.248Z" }, + { url = "https://files.pythonhosted.org/packages/58/ca/5d1a997587febe5b26d8daffe363b5c1a091cece19828eec6502fd09c5ef/charset_normalizer-3.5.2-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a19a731138fc27d5682277d3b9df22855cea1239bce7fcec5f78f42ef2d1f3c3", size = 249996, upload-time = "2026-09-30T04:36:10.73Z" }, + { url = "https://files.pythonhosted.org/packages/b3/1f/d1e78246f7ed60c8c8d606b4ac27f66ce49cc3e95f24893ccbeba9f77302/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:62603db9a7caa0802eaa28c1c46fecd7b3a263a774069c24c3c28c302448721c", size = 247028, upload-time = "2026-09-30T04:36:12.294Z" }, + { url = "https://files.pythonhosted.org/packages/8e/37/eba316edd4f0c4d3a5d945924c4eeeae59abac4056aa815d8a4268f863a2/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:b6856554c4f44d79fc2307d5768854310a8f0096e501c75637542c82292b0429", size = 240562, upload-time = "2026-09-30T04:36:13.887Z" }, + { url = "https://files.pythonhosted.org/packages/c8/8e/aaa037d40ca9ef045977f1a661048b1aa33f223adfce3452fe9be9f79d14/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:1bc0baf5ef96b6ede57d47f4b8fe4d9d84019c3bfcbeb20a41edc6a6ee341f1f", size = 271699, upload-time = "2026-09-30T04:36:15.41Z" }, + { url = "https://files.pythonhosted.org/packages/26/19/1c1c9f75974adf523b87f34b8a2adc5a435cd65916812bcbd0dfa45f9a29/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:56bc200a365efb37383b7852e4cc5898d3b2da5987289b543956cf8cad71018a", size = 252030, upload-time = "2026-09-30T04:36:16.839Z" }, + { url = "https://files.pythonhosted.org/packages/bc/90/0660ef18e18df0a4d2a1a0edff7dfbba42d4e50ef2425557a5bb7051f77b/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:2c9ad19a6cfcd5ea5c0d41161d22f9df1dcc277e9bef2751391334546a314c00", size = 268565, upload-time = "2026-09-30T04:36:18.468Z" }, + { url = "https://files.pythonhosted.org/packages/79/ba/57adc269824e8658f1a0f97a9e514c247445a9632b3419b97e0ba37f16dc/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e243bd13217235fc7290c621941c3f5cc8b66e4872495be821d7436ba2fb838d", size = 257627, upload-time = "2026-09-30T04:36:19.938Z" }, + { url = "https://files.pythonhosted.org/packages/9a/85/33abd4315c052d3d4f54c92b1ee49bfbc0dc7115a981e462a793b6d2ab87/charset_normalizer-3.5.2-cp313-cp313-pyemscripten_2025_0_wasm32.whl", hash = "sha256:a090bb2c68df85450502e3e20d665e3a5af9c65a84d6508ed477badd49166fd3", size = 143407, upload-time = "2026-09-30T04:36:21.376Z" }, + { url = "https://files.pythonhosted.org/packages/4f/de/6435e18d1aaa5d910b896d551411c96af1f42a0c56c29afc2016c61ccc2e/charset_normalizer-3.5.2-cp313-cp313-win32.whl", hash = "sha256:2b7b3bbfb4fe8ef40600792d762fbaa9057559f9d3fad209525b7a22b99e91fd", size = 183207, upload-time = "2026-09-30T04:36:22.776Z" }, + { url = "https://files.pythonhosted.org/packages/9c/76/b8ec57f4e9ee3253541abf95e4a462c0175fe8032dcd070f1f2421240942/charset_normalizer-3.5.2-cp313-cp313-win_amd64.whl", hash = "sha256:78456a747de8dc58360ffa581f30a002baf5aa28cb262536545e91f113ed7639", size = 206489, upload-time = "2026-09-30T04:36:24.306Z" }, + { url = "https://files.pythonhosted.org/packages/3e/60/c647c6ae47480221e875ea5d743ff94946f7416e3c69415ab772928e8d32/charset_normalizer-3.5.2-cp313-cp313-win_arm64.whl", hash = "sha256:11912e4bb14baae7c5d8791aa55ba0a3a03ec6729073307b0f57270abaa713d3", size = 195501, upload-time = "2026-09-30T04:36:25.846Z" }, + { url = "https://files.pythonhosted.org/packages/58/ca/7aa91362a2f77ac8e9e28a9b902a74f7d0e11a851ef0d27a74308da8cd90/charset_normalizer-3.5.2-cp314-cp314-android_24_arm64_v8a.whl", hash = "sha256:1afb975bd5d68d5ce9f6b6d44fdf2f7e34b895a35e95708a7a91b20a3b51d187", size = 226010, upload-time = "2026-09-30T04:36:27.669Z" }, + { url = "https://files.pythonhosted.org/packages/a8/cf/ac8878d0322cf88a1aad4c7b147db32ca0bd806eb0060957b2e31486dbe6/charset_normalizer-3.5.2-cp314-cp314-android_24_x86_64.whl", hash = "sha256:bbbfc8e28816f19d7c0f1816664980c0a9875d01b27cdf8eedddb639d9e108ad", size = 239266, upload-time = "2026-09-30T04:36:29.434Z" }, + { url = "https://files.pythonhosted.org/packages/c9/6d/9a08d7e0b29b7208e2c6c01dc56c8e0520e7c7beadbbfb024b58fd69c8a5/charset_normalizer-3.5.2-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:7967d08cf06dee78443b874f98c98036f624f3a4e73e11f9f64f5be4d25393cf", size = 206783, upload-time = "2026-09-30T04:36:30.872Z" }, + { url = "https://files.pythonhosted.org/packages/82/44/b0aa350280e6ff5a5492d17cf10460dd39d5ee848f872f7ba2df10607f60/charset_normalizer-3.5.2-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:4c2b5031f63e331e3839b40aed2dd6f191e9c07edbde303e7876846ea1946995", size = 210449, upload-time = "2026-09-30T04:36:32.625Z" }, + { url = "https://files.pythonhosted.org/packages/7c/8a/40db9aa9f5907bb0e6f8b6d64064bf8852fb33d4b813ff9414911df7647c/charset_normalizer-3.5.2-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:fcff63213e8e6e47770541a4607175404f47cbb3ebea7b6058cc82d524a0e424", size = 367815, upload-time = "2026-09-30T04:36:34.197Z" }, + { url = "https://files.pythonhosted.org/packages/7f/72/9c5e7707b57c8ddfa9ddf7b0b1d009d7fbab9e9e887d5b721060f37e307d/charset_normalizer-3.5.2-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8d86d6fc60743dc916eb79e2eb1ec4818e21e427731543af40a3021851174a13", size = 247095, upload-time = "2026-09-30T04:36:35.803Z" }, + { url = "https://files.pythonhosted.org/packages/83/09/71e453691e927de4ddf792770cfaab3f49d494e222f66ea5e404bbd5e39c/charset_normalizer-3.5.2-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:7a881931aa470808df94a8c380eed2bbbc76cd9dc622310f99665658c821eb6d", size = 233942, upload-time = "2026-09-30T04:36:37.407Z" }, + { url = "https://files.pythonhosted.org/packages/9f/86/85c84e4da8b27dd409577d9437926ff581c5f9d3c66038dc68c1a526de51/charset_normalizer-3.5.2-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8024d00c3faf3fc0c16e07a69f4405e8eac7cc0ab15f65fe6cf43827c4cf72b4", size = 273762, upload-time = "2026-09-30T04:36:38.904Z" }, + { url = "https://files.pythonhosted.org/packages/92/08/564955a4b5f2ccb410ab480bbe8c6a18063ff27f2d35458731c4a5335df9/charset_normalizer-3.5.2-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4d48f2d08b9de5864e2c8744d4461b862fb149a18274abc8b698c45975573438", size = 269514, upload-time = "2026-09-30T04:36:40.469Z" }, + { url = "https://files.pythonhosted.org/packages/18/24/bad3ac4271589df29cf5ce2f5ae490518a5739358052bd0d61209e6fea54/charset_normalizer-3.5.2-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:34276fd796040bf0993ab33a369aa572e6979c7aab225a88893667ad8eac8f7a", size = 255056, upload-time = "2026-09-30T04:36:42.02Z" }, + { url = "https://files.pythonhosted.org/packages/d6/3e/350d89ad49916b86554d6f5f2d03ec1152148f87e5ff735106c6a03b1a36/charset_normalizer-3.5.2-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0521c5665880b33d603717defa76c094048900010897909952397feb3039da56", size = 251311, upload-time = "2026-09-30T04:36:43.577Z" }, + { url = "https://files.pythonhosted.org/packages/56/5b/4970a2d154df502e133402906dd04e3ae7cada7b3011283c88d0479a2585/charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:eff0ac9dbe711a4aee69bf04a83896aa9b85f19641264053a9f6d48573abb7dd", size = 250190, upload-time = "2026-09-30T04:36:45.185Z" }, + { url = "https://files.pythonhosted.org/packages/88/8c/f1a91bddc8fb47c2889e29ea7ea49a194eb0d9868675d786806519c00d76/charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:1503bccbeb36d5527790c3930327704c39af22de3112f1b1666a9f3ce15ee204", size = 237098, upload-time = "2026-09-30T04:36:46.689Z" }, + { url = "https://files.pythonhosted.org/packages/24/0e/bb5dace3cc7e79068425386a6589c19b5a2ab5fefc2a46abea6919683332/charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:52aa6992700996af31f375de0c6bacd402b0097fe40b53c426b9f51a90ebabc7", size = 274228, upload-time = "2026-09-30T04:36:48.31Z" }, + { url = "https://files.pythonhosted.org/packages/9d/79/b849ad523017ea9f5a45581bbebed91439e0cf42fd2860a6f64e358eb5a6/charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:e09a3942ecbdee5cce73ea9d42da82b81b72ac1bf031ce069b93b5adf4eac8cd", size = 252401, upload-time = "2026-09-30T04:36:50.091Z" }, + { url = "https://files.pythonhosted.org/packages/89/8c/75469d690cf47200bce8f6cad7655724fc23148e147abfc5ce78b5f65863/charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:c7c9ab723cde841fefb34efbad91e87f00a674b1fe1cd0784fde742bf2c154dc", size = 271846, upload-time = "2026-09-30T04:36:51.719Z" }, + { url = "https://files.pythonhosted.org/packages/26/cd/6d52d3c7437cdcf2e310ce9f28f282e733d4ef60ed19105d1819c356255f/charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:ddc7dacc8ece3a182e7f15cb862d1fd616b46d076cb1ae9dd232b2c38b655874", size = 258151, upload-time = "2026-09-30T04:36:53.234Z" }, + { url = "https://files.pythonhosted.org/packages/f7/4c/070b38bdb5f49a70199fce923ec0726a49536a63ab262abbfcaaf351110b/charset_normalizer-3.5.2-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:ee43c17b173d46a3212baa6ead3ae258eeabdae48c263a01ccf0218c366dd655", size = 143570, upload-time = "2026-09-30T04:36:54.816Z" }, + { url = "https://files.pythonhosted.org/packages/81/84/9ebfc8ed6c8c4fcd8e726ff6bf220cc8deb3966e31dce9be8dd8aa017e64/charset_normalizer-3.5.2-cp314-cp314-win32.whl", hash = "sha256:4f87960d57feabfb618e4e0af6e7371645fa26a277860739d6e5d6e0012c92f0", size = 186412, upload-time = "2026-09-30T04:36:56.643Z" }, + { url = "https://files.pythonhosted.org/packages/d1/78/5ed86f743d4bc350db307e7636419a0a5ee1d91806d30c7f667bd5c80dae/charset_normalizer-3.5.2-cp314-cp314-win_amd64.whl", hash = "sha256:e4e81e09c1578b8df602e3db08b0b3ea0a6947ad612f52bf8dc5ea8d47691f0c", size = 210965, upload-time = "2026-09-30T04:36:58.205Z" }, + { url = "https://files.pythonhosted.org/packages/53/94/a3a7698e9b1a395e1eb99ccd9a324be9347973bff4e72db2a06496d7cd27/charset_normalizer-3.5.2-cp314-cp314-win_arm64.whl", hash = "sha256:80d02b6f04e92601a081dd97b23d3128033098bff5d35d392ddcc0476ea11253", size = 200406, upload-time = "2026-09-30T04:36:59.764Z" }, + { url = "https://files.pythonhosted.org/packages/c1/48/c5dd00d5ef7791f02666de250a5bb6071e29b7e133cf4b835800b6d3bc27/charset_normalizer-3.5.2-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:dca9ab98072a5a54ebacebdc45f53e645336b320c667410b061be1ca588ae709", size = 396871, upload-time = "2026-09-30T04:37:01.543Z" }, + { url = "https://files.pythonhosted.org/packages/12/c8/8379554b42e8368161d898476686947a0fdbd3e8865170d7909dcabfdee8/charset_normalizer-3.5.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f0aa869112ef88429ae17820d99c3dd9504c9e9c671d3c246f3d7442cb051084", size = 249711, upload-time = "2026-09-30T04:37:03.111Z" }, + { url = "https://files.pythonhosted.org/packages/4a/eb/2ddb1035d17320caa9f41682935123a9a250277b261c3efc86b2d2a21343/charset_normalizer-3.5.2-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c0afc6800ba57ccc350374c5bd6150419915d95ce93cdbab2d783d75eaf30ecb", size = 231146, upload-time = "2026-09-30T04:37:04.721Z" }, + { url = "https://files.pythonhosted.org/packages/4a/24/2ecb4bde104322cd7859d6594fcfa74649f8d90b3221c9feecbef149875b/charset_normalizer-3.5.2-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:7dcd882da75ef9adf94903b1e3b9419e8aa8fb4c7396822b834b9ef7fb96954f", size = 271552, upload-time = "2026-09-30T04:37:06.295Z" }, + { url = "https://files.pythonhosted.org/packages/3f/98/9d5f6ebc3aee9fef5d30b4aff11fb2ab7a1222b4064f8ef2c7c87cde217a/charset_normalizer-3.5.2-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2e06a3a98f916dd41d27f3105e02e7a40181c98c94b9158733d03a6f80506c09", size = 269810, upload-time = "2026-09-30T04:37:07.905Z" }, + { url = "https://files.pythonhosted.org/packages/09/e1/a3b06a10461b1b7628853c934c644e03bc28e42767116afb52f19a56519b/charset_normalizer-3.5.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6bd128f206a7752ae1f2ab6c61bf8a24ba28913a10df8b14c2637b973ff97a80", size = 259845, upload-time = "2026-09-30T04:37:09.554Z" }, + { url = "https://files.pythonhosted.org/packages/fd/d3/6f561f74a296cf27d61775a1dc665ad13f3bff6a798810ca05907f37a7c4/charset_normalizer-3.5.2-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c8f3d67aeaf55f017982b73683f0e7342ba2f6635a78f69ce89ebb26aa411e5c", size = 252825, upload-time = "2026-09-30T04:37:11.274Z" }, + { url = "https://files.pythonhosted.org/packages/26/9f/69e13ca3b18f43e0eafcd34c04a45b732ae22a43b54a5fc9e119103356eb/charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:fe9753dfee015c570d73df76f899f18444d41388bffcde097deba51c4fadbb9f", size = 252659, upload-time = "2026-09-30T04:37:12.941Z" }, + { url = "https://files.pythonhosted.org/packages/73/a9/ace29806a0dae18939919c76ba526472d83214afa101105fabff2cf30625/charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:92888bb3187c5ba50500b00b3b310c9f2c651709d28036077680cb5255450a03", size = 238819, upload-time = "2026-09-30T04:37:14.659Z" }, + { url = "https://files.pythonhosted.org/packages/f8/c1/6116d52a2e3311ec80f21f5fb5e17b27405f10b9608af8f6e69516841a1b/charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:d008d90a7f2471519aef0c90dfbe73b3e6e4d5e66ac48e19154c17e89e98b604", size = 272973, upload-time = "2026-09-30T04:37:16.346Z" }, + { url = "https://files.pythonhosted.org/packages/19/aa/9955c7e93bba10a9c7e8f7a5031b7ced66f3a1883a55c00712b8d5850ff3/charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:31f3930700408d211f13378ccbe1c40845d8da54bd0681fac3a9b5aae81c7aa8", size = 253692, upload-time = "2026-09-30T04:37:18.212Z" }, + { url = "https://files.pythonhosted.org/packages/bb/33/2a6ae7fdc1b10cb581cef91addd8cdfc5f40d50abb5702309369d5834579/charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:2a925889534b3748302dae5dead07cc13480de1dac3aea80a941b729b471ef93", size = 268757, upload-time = "2026-09-30T04:37:19.877Z" }, + { url = "https://files.pythonhosted.org/packages/a2/22/80992720a0282cd39bba1db35868e6b9c22f41281160143a836544bc1d8a/charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:f5ec61164adcec446f8969a3358ec3f9b26bbda3b9213e5586d219afa8df2915", size = 262220, upload-time = "2026-09-30T04:37:21.583Z" }, + { url = "https://files.pythonhosted.org/packages/92/9f/181fd07e1bffea1d95cd80c84ac537354f50699c22cfc4d3c02b6fc16208/charset_normalizer-3.5.2-cp314-cp314t-win32.whl", hash = "sha256:598a11a2c7ebaa5334bf698bf29568c9c390abac6a154d8170fedecd1cea38c5", size = 197797, upload-time = "2026-09-30T04:37:23.235Z" }, + { url = "https://files.pythonhosted.org/packages/49/1c/25d8415ec1c4f2f41f1680435e4c87cfb378ff2f677d950946f2a45d0632/charset_normalizer-3.5.2-cp314-cp314t-win_amd64.whl", hash = "sha256:7fdde2c9fd9e3eca40631e024664cf2584272cc8f96308cbe5fdfc930f51d8bc", size = 222765, upload-time = "2026-09-30T04:37:24.891Z" }, + { url = "https://files.pythonhosted.org/packages/3e/b4/46b48f013dadfc0d0d33b375438e31bdf5a989dc68389c6bf627054d4df9/charset_normalizer-3.5.2-cp314-cp314t-win_arm64.whl", hash = "sha256:d1befeed746d247c81127bb14de9dc3d30edb6e5976d34f83f86ed262b1d9105", size = 210985, upload-time = "2026-09-30T04:37:26.634Z" }, + { url = "https://files.pythonhosted.org/packages/ca/e9/34e597dee616d0b8ee4b34d29399e85c2204ade174157a48505d42baa4ff/charset_normalizer-3.5.2-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:87475fabc8d9996fd9c27debb395e642e8c838d78a00b6e932227a0e06b81e26", size = 367676, upload-time = "2026-09-30T04:37:28.329Z" }, + { url = "https://files.pythonhosted.org/packages/60/9f/a5d1c91c0263745e2cd344c5a4415d787c575501ab1d449f1148ac6b495d/charset_normalizer-3.5.2-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9409a8bf35cf78353942504b24a57de3d75b708997a1e4bd8db71ac8633ce364", size = 248414, upload-time = "2026-09-30T04:37:30.167Z" }, + { url = "https://files.pythonhosted.org/packages/26/79/e697f77464748a3ee3cf490c83d592459400d4898380d66c38366b03080c/charset_normalizer-3.5.2-cp315-cp315-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:498dc3188ca05a68231ac3fdbfc7f57eb67e1343c30e0fea17f8218c1599b253", size = 244775, upload-time = "2026-09-30T04:37:31.964Z" }, + { url = "https://files.pythonhosted.org/packages/ca/87/3d42a42e18ea066e2513936fd678a00696e77878b5ae04528976abdbcb83/charset_normalizer-3.5.2-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e242bb1c5e76e97dfa9e7f209a71e93a01d7f19ffdd5cfbb2e2d55b4f08f8ab0", size = 273877, upload-time = "2026-09-30T04:37:33.661Z" }, + { url = "https://files.pythonhosted.org/packages/c3/76/8a28136f3938ba9836f84280ce0c4d61ed1cf15a036b2034900c62634162/charset_normalizer-3.5.2-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:def79fa35ef0cef8d2accec024f4fdc7ead3012ff02f5215c783f39f03ef8cfc", size = 269455, upload-time = "2026-09-30T04:37:35.573Z" }, + { url = "https://files.pythonhosted.org/packages/a0/a1/4fbf5d0f0f1b2a080474c1cf9a2f12c4c6531bb0e8ba591055e846d2b4e9/charset_normalizer-3.5.2-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3df041de8887954562c9b261cba85ca0e9ded74048daf125f45edcfaa4832229", size = 257336, upload-time = "2026-09-30T04:37:37.397Z" }, + { url = "https://files.pythonhosted.org/packages/ba/a2/8b50aa320adb880ad579518e6f718f24944804b42a88b83d267d5d444125/charset_normalizer-3.5.2-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:04851f73ae72b8413dddadb16a49dfee95263553741fd42d546f7d66907e6be5", size = 257584, upload-time = "2026-09-30T04:37:39.522Z" }, + { url = "https://files.pythonhosted.org/packages/a5/57/50e3fed84e175f40349bd0da7a4fce94c87f0378f52d74f511d89e0bdc20/charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:183b88127acdb4fabe59d951ab424faf1af7b63cdbb5f776186c1ea2ffcaed98", size = 251854, upload-time = "2026-09-30T04:37:41.23Z" }, + { url = "https://files.pythonhosted.org/packages/d6/54/f7fbb3493c9f49091213b9c2d6dd65800696f1ce1a3f196a4205f50417b1/charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_armv7l.whl", hash = "sha256:16fa0eccf81304b79c5cd87f9271c3b85dd9dd99245e4422ae9c0dd45e0f99d3", size = 248767, upload-time = "2026-09-30T04:37:42.883Z" }, + { url = "https://files.pythonhosted.org/packages/d9/37/b3a6385acc5a1e45b39ae9c90bfb9cf838a09b9dd37ef2740ab4c6b4a2eb/charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:7441d755b7ab94f8d4eb3e43ec05482d760842fd263d003a99102d742cd835e2", size = 274479, upload-time = "2026-09-30T04:37:44.658Z" }, + { url = "https://files.pythonhosted.org/packages/89/44/809913e2cfd279e635a9294fdbbfb1b1dc62a8189d473d561f649fce98d8/charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:ca403d7e4798f525fdfc78e258820419cbbd0f0ecbab9de7840e3c017cf6b8cf", size = 258310, upload-time = "2026-09-30T04:37:46.529Z" }, + { url = "https://files.pythonhosted.org/packages/af/a2/f28400ab13359d91bd39179df8e149376b9bf36588e739a3a4f9de2b84b2/charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_s390x.whl", hash = "sha256:df29a0a7107f7011e77f4eebdddec4c7331e24d787a0b21a46d63bdf7445da95", size = 271100, upload-time = "2026-09-30T04:37:48.399Z" }, + { url = "https://files.pythonhosted.org/packages/e9/89/9bab37955edf0adb3b66f8a3a6617d9f2f487e0d56f295a6a286cb640aa6/charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:f3c96f633825733f735c5a9cf21d21a257d8e1edf0b1cee0a064b9c424ca0f7d", size = 259936, upload-time = "2026-09-30T04:37:50.023Z" }, + { url = "https://files.pythonhosted.org/packages/23/b5/4459e08d45a679f903d50fea08bc52cfa728cca4d7bd02c757b5e5abda2e/charset_normalizer-3.5.2-cp315-cp315-win32.whl", hash = "sha256:281cb91036248400f4cc957495cccd44c275c2e0c5854f7e45ac5cf7dc193847", size = 186301, upload-time = "2026-09-30T04:37:51.722Z" }, + { url = "https://files.pythonhosted.org/packages/98/e8/55d5fd3935b4bce6da4fe0df61898e8c82653e317e677bd58aceb9c60f13/charset_normalizer-3.5.2-cp315-cp315-win_amd64.whl", hash = "sha256:89b53f3cda69831909888e0494f4fa0bcd3537e3e138dabeb620bd6ad946bae8", size = 210858, upload-time = "2026-09-30T04:37:53.427Z" }, + { url = "https://files.pythonhosted.org/packages/a9/5b/974423c2fd8e524c7a7f64318c1e02240ef954912fa2b4d70344107b9c68/charset_normalizer-3.5.2-cp315-cp315-win_arm64.whl", hash = "sha256:6be488a102b8cf28d0391d8c4ba7748938ae28b78ad901f8585520fca33ead1a", size = 200309, upload-time = "2026-09-30T04:37:55.015Z" }, + { url = "https://files.pythonhosted.org/packages/ee/f9/00ee0195db1013d8f7c416fd770fbeb560bb46eb2e36b054d05cb56f6cfa/charset_normalizer-3.5.2-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:915563965d418f986e7e145accc592eae9e1a1be3566ff98a05d7a9ec42a76e1", size = 395343, upload-time = "2026-09-30T04:37:56.743Z" }, + { url = "https://files.pythonhosted.org/packages/04/3a/c00b50e94c964cf934c7899cd47c97952fc11dad71cc5884b3c61795b09b/charset_normalizer-3.5.2-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:65cd72beeeca9d3aaea1201e5923859f308f952f9c71de93f06063c79f0f7a3b", size = 250114, upload-time = "2026-09-30T04:37:58.607Z" }, + { url = "https://files.pythonhosted.org/packages/50/27/d102dc880bbcffd0479ab64dfc1fb96777a854355a55e2bda72a71efadcb/charset_normalizer-3.5.2-cp315-cp315t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:b7fd005a73d9e657273b7a10dc71a9e03c8fb9ee6999798d6918ce095b81ac7f", size = 239997, upload-time = "2026-09-30T04:38:00.511Z" }, + { url = "https://files.pythonhosted.org/packages/a5/4a/bf7ef45794dd293fab5f98a9309817977fbb845b9998f171b8cc5d8437a3/charset_normalizer-3.5.2-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e54da4baf05720032d527874d40b65fa4d7e5c6c6a43d0c3adbeffcaf275a2b3", size = 272313, upload-time = "2026-09-30T04:38:02.509Z" }, + { url = "https://files.pythonhosted.org/packages/e8/ee/008a2837737991474c5754bb3191010007663860979701990982a502cbaf/charset_normalizer-3.5.2-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:124fbf1a8ff966d87ae05bb8bd45a71f966055ed8bba320d0c7cf450bc5f4d0e", size = 269986, upload-time = "2026-09-30T04:38:04.435Z" }, + { url = "https://files.pythonhosted.org/packages/93/ad/bd74a283940dc910c5b14f8e4f80a248082bc9c0fcbe1f54530cb6d9cc5e/charset_normalizer-3.5.2-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:28b4f0d66fb834ff90f28209ac7bce77868c45d8c93e26f906709d9b7c2e1af9", size = 260202, upload-time = "2026-09-30T04:38:06.549Z" }, + { url = "https://files.pythonhosted.org/packages/8a/7b/ed341c66f69f688723501fac752be3d63c7159ca0d0d4174fc611e5710bb/charset_normalizer-3.5.2-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:58ca3755ee7ff7f59b57789ec9833c9de9ea275405cdd240eda1f193112e398a", size = 259083, upload-time = "2026-09-30T04:38:08.311Z" }, + { url = "https://files.pythonhosted.org/packages/cc/9d/e41588b777965e5031a43128a1e96173ebb35ac75fc53ec3b517e7c21cd4/charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:443eae2bf318abeaf6f15d785138f71fd6de770e99a92158b8b814265e079115", size = 253081, upload-time = "2026-09-30T04:38:10.402Z" }, + { url = "https://files.pythonhosted.org/packages/81/35/b761eb6d8c1eb218b9b42b9b4d5ac902afdc399fb6dac6f9a9aac7bda589/charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_armv7l.whl", hash = "sha256:58f361dcbab699cf8f42db3f47c8e7fd1036f138c23a5d08de9fde5f425a730c", size = 248712, upload-time = "2026-09-30T04:38:12.317Z" }, + { url = "https://files.pythonhosted.org/packages/4d/2c/147169a041b747759f37405c0a97157e8e92de967968373101ff14915cba/charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:1b4cbc7c3491ccb4aa17fcd8165649d01cf39f76de1696da8631b5f71b85401d", size = 274176, upload-time = "2026-09-30T04:38:14.138Z" }, + { url = "https://files.pythonhosted.org/packages/f0/2d/0ff8db0d373ba8538db686db11cd7e8912031490b9e4f383b41912e8d594/charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:ba0b1d2620edf869789c3879223f52bf2afc5d31b3cb47cc57b3a12c05e2aa9d", size = 259413, upload-time = "2026-09-30T04:38:15.841Z" }, + { url = "https://files.pythonhosted.org/packages/8a/8e/b4a085fb47c9d3a7e43576a4784fdd8fe23f907514a972de8086edaf7a48/charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_s390x.whl", hash = "sha256:5e2b6b57e9733d39f0c9fd3185efa6b8e29652c4cd8fe94180272cf6ed9a78c4", size = 269434, upload-time = "2026-09-30T04:38:17.626Z" }, + { url = "https://files.pythonhosted.org/packages/83/1c/d8d8d7322a7c3eecdf3237a4a419cf41d2eaad8e006ce7dfdd9d4c8fa2eb/charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:51cf45226a9b588d0d2b4880c62d686934b63ab0bd79ca23ab0e9762eb27441b", size = 262716, upload-time = "2026-09-30T04:38:19.214Z" }, + { url = "https://files.pythonhosted.org/packages/a0/16/0e4c6ba9b44e97a2da150e52d331e8f9c968b21b358fbffa6c856cebcd89/charset_normalizer-3.5.2-cp315-cp315t-win32.whl", hash = "sha256:5fb29fb8cd1a46c27a1bf9613ad5ec2599310d46b4025d9556404a6b6a292800", size = 197159, upload-time = "2026-09-30T04:38:21.037Z" }, + { url = "https://files.pythonhosted.org/packages/be/33/e90bc2b1374f7f36ef106f56620de5a783907e19ca857efe2277e31cac3e/charset_normalizer-3.5.2-cp315-cp315t-win_amd64.whl", hash = "sha256:a192e2c40070d92c3ccf777e3a5c4ff515573cd2bb7ed0c537fdadbbec5bbf21", size = 221322, upload-time = "2026-09-30T04:38:22.886Z" }, + { url = "https://files.pythonhosted.org/packages/66/89/dfa6dcb08c200b7830ab56439e8c1890f2971d51aafbb3937894a2e7fcfc/charset_normalizer-3.5.2-cp315-cp315t-win_arm64.whl", hash = "sha256:749e97e1b32313717a565abbe321bc2190bc8b35f1a67e4cdbc7c56c8d8ffe58", size = 209192, upload-time = "2026-09-30T04:38:24.648Z" }, + { url = "https://files.pythonhosted.org/packages/8c/ab/176fbfd5b64939c55d652366aa5b9ef1d767af207a3aa6ebeb0d226c484d/charset_normalizer-3.5.2-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:4275811936e2f06feff5e598fb42a1b7ae852da8e39605211892b56b81a34efd", size = 331815, upload-time = "2026-09-30T04:38:26.216Z" }, + { url = "https://files.pythonhosted.org/packages/7e/84/371eac6b30bdbcbf2d632a1a01809103459216fcaae61b8b8d922c1bfb8a/charset_normalizer-3.5.2-cp37-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:1c50fe28bbc2ced33386f298650d91218076c05420e6cbd790b913adc41659e7", size = 253276, upload-time = "2026-09-30T04:38:28.032Z" }, + { url = "https://files.pythonhosted.org/packages/43/6f/c4fbae58febff71709c51bc7e18fdfa55341dc382704740f9f0cbf03817b/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d19fbd981a488e22cd04883659ca6b08f50b5974f9fd7c95655ef6a043e5893f", size = 241239, upload-time = "2026-09-30T04:38:29.732Z" }, + { url = "https://files.pythonhosted.org/packages/61/71/458c3f42164a07d0c5210798e9e704b39e540a6793b05aba67f3a35243a9/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:0fed1d06615f022ee3b13caf5e8b180cfea32bb2c5aded8a9d44277afc040f93", size = 231121, upload-time = "2026-09-30T04:38:31.462Z" }, + { url = "https://files.pythonhosted.org/packages/09/54/ab9e89367076f6331bb6c65c4bf14a5361fa5191cb6561bf534f18504e1b/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:838dcc90063569a0448120554591a1d6c4a4ffe11babf048908793154ab86ade", size = 260350, upload-time = "2026-09-30T04:38:33.239Z" }, + { url = "https://files.pythonhosted.org/packages/7c/c1/061431ecc688d9d76602502cb57cc01e691e682c18f1beb45f9673b5bbd2/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2ce45c6627b22c47e390bc91a41c3d13032192e699fa0bea96e9671b373d69b0", size = 255430, upload-time = "2026-09-30T04:38:34.865Z" }, + { url = "https://files.pythonhosted.org/packages/8d/1f/20c8949f0676f7ab811abdeb7f4d7f1cbc6e61ff20bef08b44edeb092bc8/charset_normalizer-3.5.2-cp37-abi3-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0774bf9bf620249fee3e0b8b9fd3065de213be30f3aa94ce2494b3b638949e26", size = 250612, upload-time = "2026-09-30T04:38:36.649Z" }, + { url = "https://files.pythonhosted.org/packages/2b/9e/46f2fa4c431fc98c4ae76a8cb5bdca54e0341e3cfc3fcfd8e82740250818/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:1db38f4c5496827c1a501846d64d14c3b80c7e6714e406cd7dc36a9899fa1011", size = 242083, upload-time = "2026-09-30T04:38:38.26Z" }, + { url = "https://files.pythonhosted.org/packages/bd/39/559be29a0c0f086e0bba6922babd38916cc5e0b58ced4de13ee01ea05508/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:304d8e4d493af723536393eee0c689eb7813f4a474c8b479dee63f1fdd98f621", size = 232738, upload-time = "2026-09-30T04:38:39.81Z" }, + { url = "https://files.pythonhosted.org/packages/ff/6c/387b0e4f756a282831c1d9fc6aeb6c51ca4507ca202767c8de15ce9b12e2/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:9b7f416ff0978e2f2249330527f0ad6fa02f4932e6199692d3b52da2048c19e4", size = 260703, upload-time = "2026-09-30T04:38:41.346Z" }, + { url = "https://files.pythonhosted.org/packages/96/92/1fdf015f09ef449f50d3ac4b67c90887c9c318b727daa95cc4f866e6521d/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:01077390b03f7988f11d700a2194e69b119741a86b1a638b1db88891e3eced8e", size = 247622, upload-time = "2026-09-30T04:38:42.937Z" }, + { url = "https://files.pythonhosted.org/packages/dc/3c/8e7b8a5671ad5d433669fb2a76f1a0164df2d9b1718b0206bc2a16d840cc/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_s390x.whl", hash = "sha256:7e841fb9010836c992c9f12fcbd43a831de93a5f726fc1ccd8ca1d0268c5014c", size = 257500, upload-time = "2026-09-30T04:38:44.604Z" }, + { url = "https://files.pythonhosted.org/packages/b4/f0/45b579df5cabc1d5d53ea1cc35e8437d3ca768c0acccc7041517cb6fbb32/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:9cae88599c7219005d879f98e5ed53341e9a122af585e1091200358a3003d2a0", size = 255100, upload-time = "2026-09-30T04:38:46.289Z" }, + { url = "https://files.pythonhosted.org/packages/31/68/fdec18a343f5fb3f310588dd478b09ac4799e0b187dbade3a8cd776f03ef/charset_normalizer-3.5.2-cp37-abi3-win32.whl", hash = "sha256:01b0c0d2262a9e28e8484a278c7e1b5d650e3ac8cf2683d2967e25899f208bdf", size = 174499, upload-time = "2026-09-30T04:38:47.999Z" }, + { url = "https://files.pythonhosted.org/packages/9d/8a/b618149cc5207943a0242068d7a27897f56a62947b5a039085f2a22029f8/charset_normalizer-3.5.2-cp37-abi3-win_amd64.whl", hash = "sha256:9f56f72050826f63dcee7a7f55b0a77168cb3bfc553fd405e7f8f9ece75a4036", size = 200092, upload-time = "2026-09-30T04:38:49.707Z" }, + { url = "https://files.pythonhosted.org/packages/03/cf/4c66866fa9e2b1c78e3c911516d1de497a677b7ac60f1eceda74ce777ca3/charset_normalizer-3.5.2-cp37-abi3-win_arm64.whl", hash = "sha256:40ab6bffa02ae10a0581e6c198be7d2d8ca5c2a0c64e4ed3465d766df457573e", size = 294363, upload-time = "2026-09-30T04:38:51.312Z" }, + { url = "https://files.pythonhosted.org/packages/fc/ad/d07d7862a62ffa6d79d68074d14823243dd235a77c45262acbf6adeb28bf/charset_normalizer-3.5.2-py3-none-any.whl", hash = "sha256:b6b751274acb69d77b3323d6b7dbaa3c7fdfc1eb829b7eb61d262f32e1af9685", size = 68872, upload-time = "2026-09-30T04:39:21.828Z" }, +] + +[[package]] +name = "click" +version = "8.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/45/37/edbf1b0707709013c0cf2e8317e03d97ed29bf4cac709fe328904ae92a38/click-8.5.1.tar.gz", hash = "sha256:9bbfada76703fd1d784b83eea012e3e8c6a001a876543ef104fa56aaaeb072b4", size = 399151, upload-time = "2026-11-06T17:37:01.021Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/31/7d/164b7ffc8624fe9efb4221bf9af485d5c1e41b9ae118045d2b6dc5457d8b/click-8.5.1-py3-none-any.whl", hash = "sha256:8bb5376d2006950386f8c6427613334a2acadc5f559cb80e638d00b4df957e37", size = 126163, upload-time = "2026-11-06T17:36:59.287Z" }, +] + +[[package]] +name = "cryptography" +version = "50.0.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cffi", marker = "platform_python_implementation != 'PyPy'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9d/af/182eb91b0df3fe75c4d9f26fe70684569566745f6ba7e5c9c73a862c5252/cryptography-50.0.2.tar.gz", hash = "sha256:7b46165bb56eb4704e2eaaf86f3c940d19154535d9b0ca7d6d590b04060e00d5", size = 880623, upload-time = "2026-09-30T15:30:04.884Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e5/56/d194340cc4a57535e82e1bee9e89667ac4b7c13b5d3f59686deae3094dd5/cryptography-50.0.2-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:fa8f5efb344d6908a1ce62f4a24e2e5780f825d6f53f5f50ec5ffacac72936cb", size = 3914904, upload-time = "2026-09-30T14:43:44.339Z" }, + { url = "https://files.pythonhosted.org/packages/d9/69/c9bd862c3bf43d6399c433caf002df16e2dffd4be49bdf515cda38038711/cryptography-50.0.2-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:79def8d059362e7831389ed3be0ecdf58a89386e1271e35dd9f5af84e81bffd0", size = 4731146, upload-time = "2026-09-30T14:43:47.113Z" }, + { url = "https://files.pythonhosted.org/packages/21/69/64cef1f702bf6657e0cc186ed1a2891d50d29fb41586b254e1c07adea261/cryptography-50.0.2-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:630ebfea3bf689d075f82316324ff7433dc447fe6bc1bfc76524b74b4a9567d2", size = 4719841, upload-time = "2026-09-30T14:43:49.01Z" }, + { url = "https://files.pythonhosted.org/packages/38/6b/61a3f8d8c5e1e49a6cddccafc4015cc1c0021360ab0acb4080e7a423644a/cryptography-50.0.2-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:f9f6143a8c75945eb960d9eb98905a441394abfa24afaae239d514ffb2586480", size = 4738340, upload-time = "2026-09-30T14:43:50.932Z" }, + { url = "https://files.pythonhosted.org/packages/7b/2e/7212ca32fd43dc91f2f41db20160b268098874b4c9a0e7be94d6835f5b2e/cryptography-50.0.2-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:a582ab2ae1d34f67112cadc86702774c9ea4374df6bca6afe672817203c99134", size = 5367029, upload-time = "2026-09-30T14:43:52.911Z" }, + { url = "https://files.pythonhosted.org/packages/1a/f1/b474e930c4d910328780e3940da76f5aa5cbc48ce1fc14e44d239d9ea9db/cryptography-50.0.2-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:4061c0079120205fb760c58acab6443e217307dcf05e3702cf970e0689972856", size = 4753050, upload-time = "2026-09-30T14:43:55.272Z" }, + { url = "https://files.pythonhosted.org/packages/7c/52/9af10e80ac16b0fcc2123f9cbd5e7afbd0fd5075bb7a607c592258a39cda/cryptography-50.0.2-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:ac9ed99d81760c62fe89d5f0815cdfa1ba9a35141cf30f1c2d044f04b4803d2e", size = 4376724, upload-time = "2026-09-30T14:43:57.24Z" }, + { url = "https://files.pythonhosted.org/packages/71/37/6202e488cc1eb625ea110c292c6bda92823176e023f427d8d5660ce8d632/cryptography-50.0.2-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:87e9ce85beb6b328ba370cc6e6aea483c92617b4c95b1d33a49297eb662bfb04", size = 4737859, upload-time = "2026-09-30T14:43:59.541Z" }, + { url = "https://files.pythonhosted.org/packages/8f/30/e86d7d518489b0ae2497091a35287abcb1a2ce4037837a34afbe9b1d6964/cryptography-50.0.2-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:f265528741e048bce55c3463ed721fb0aa45a5888d8add8cfeccb3035451bbdc", size = 5324103, upload-time = "2026-09-30T14:44:01.901Z" }, + { url = "https://files.pythonhosted.org/packages/d3/69/2c833a049475e0a3444e94c7d0aca0aa51d166374a449b09e92ac98138de/cryptography-50.0.2-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:9dab55f57c74c3cad24c323bacbbd04be4705ba6eb0d92e920b1fc4837ed5079", size = 4752576, upload-time = "2026-09-30T14:44:04.545Z" }, + { url = "https://files.pythonhosted.org/packages/6c/5d/906970b83bbfc1f5bbfb677a143c181f2801f23b6a7204a3b47c42c97e65/cryptography-50.0.2-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:25784ce8b9621c90c643efb9e1e2162ab3b0224cae446ad5e70e7fcb1ce18b51", size = 4870819, upload-time = "2026-09-30T14:44:06.884Z" }, + { url = "https://files.pythonhosted.org/packages/68/e3/f2298d3bb55e0c4a91841ec4d01b3f020ba8c5fbf15ccdcc6dcf03f97025/cryptography-50.0.2-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:85d0d9a31b9098e98534226d5686b47264b95e62ce459dc2e62fdfc809f9fe93", size = 5030152, upload-time = "2026-09-30T14:44:09.443Z" }, + { url = "https://files.pythonhosted.org/packages/9a/4f/adfc442765721292fff86d314ce385d3249d22db42295c0dd057727b60f3/cryptography-50.0.2-cp311-abi3-win_amd64.whl", hash = "sha256:7afa5a6602a9f29af1f3a2965f831bae7c9d5d597b7cbb716d41ab3b7d89879c", size = 3824692, upload-time = "2026-09-30T14:44:11.671Z" }, + { url = "https://files.pythonhosted.org/packages/ce/cb/52eb3770c0d0be2702a98c6e96065ddc0a2877cf0845aa9c23397c142cd4/cryptography-50.0.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:f785f6161f202ab04d8ca194158968798e480ca058943907972da5f12e2881e8", size = 3892731, upload-time = "2026-09-30T14:44:13.485Z" }, + { url = "https://files.pythonhosted.org/packages/19/8e/aa1fc533d4546b127b45de8aa024eb5933d23eff9debfe25931e56861095/cryptography-50.0.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:0ecbc5652bdb6fc9eaf89a7d196e20941adfe812f43bc4ca05d9150496821047", size = 4710431, upload-time = "2026-09-30T14:44:15.427Z" }, + { url = "https://files.pythonhosted.org/packages/6a/64/72bc3f75176e7e406b748a3e3830432b8c51297b38368713df04dc04898a/cryptography-50.0.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ab50ee449bf968271e820086f10a33d101dd060370abc10bcd22279be2656539", size = 4694824, upload-time = "2026-09-30T14:44:17.69Z" }, + { url = "https://files.pythonhosted.org/packages/4e/c6/62c77550edfa5ca3f14bf44a1e6739b9fa09d6e998a11d97ed8213bccc98/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:a9f7355e6fab51f6c369b86fb7571cffa05edee2c2121e0380a37fb9ac1cd5c1", size = 4716967, upload-time = "2026-09-30T14:44:19.661Z" }, + { url = "https://files.pythonhosted.org/packages/f4/37/cce70f150c432914460157a6ecc161752e053aa5ec0ef3b3f7dc6e31039a/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_ppc64le.whl", hash = "sha256:94e5e9f108ee10471288214d3d233fbfbb492840a8457eb85178d643ddeb32c7", size = 5328676, upload-time = "2026-09-30T14:44:21.744Z" }, + { url = "https://files.pythonhosted.org/packages/aa/9a/6f2f0304d634ceafdeaf23e84537336664ac419b5d07611675c2ad3f6b7a/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:241449bf940a5d27309bd317e6f9a2af6932113818bb2b8f5c59ddc7ef16da18", size = 4727698, upload-time = "2026-09-30T14:44:24.178Z" }, + { url = "https://files.pythonhosted.org/packages/1d/de/66bcf9244d118663b2e1aaded8990f4640e3d7b7411870a5765f252074d2/cryptography-50.0.2-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:d8947001be83df1394050758ce0e745dd74fb134eef0a4b5124208dfc3a68c37", size = 4354821, upload-time = "2026-09-30T14:44:26.263Z" }, + { url = "https://files.pythonhosted.org/packages/bd/e6/db28a28c7b6c676addce89136de3d8db49ea825a8c863472e36e42ead4ad/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_aarch64.whl", hash = "sha256:4a20ce1e5cb4284a86692fdcba7cb8754185c6b2e5c56fcef3751cf451d3cdc2", size = 4716748, upload-time = "2026-09-30T14:44:28.447Z" }, + { url = "https://files.pythonhosted.org/packages/30/96/01546c7f69ea0e2ab790a2e4f0934a4052fb9b388147fbf83c2fd72f1e57/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_ppc64le.whl", hash = "sha256:84f964e537f916e2cc85199e5a88742e964939b575ac8598b3f9d6cc416cdaf1", size = 5285085, upload-time = "2026-09-30T14:44:30.704Z" }, + { url = "https://files.pythonhosted.org/packages/6c/01/03263395f74d50b071e9e66daace3f8bef80493e5d410726f2ba8554736b/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:828d49b0ff5a0e3975865571c5d91dbbdd0d38d8289b249a163e9425413a5e05", size = 4727268, upload-time = "2026-09-30T14:44:32.92Z" }, + { url = "https://files.pythonhosted.org/packages/eb/94/2bfe8f29ec0cc9c0d99359c4161adf32858e4934b72c6d100d2ac0bbe962/cryptography-50.0.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:deb9fde5c60e437ee4821bc9bc39ff31b42135c27e1dc61ef0a629389c1de62e", size = 4849503, upload-time = "2026-09-30T14:44:34.969Z" }, + { url = "https://files.pythonhosted.org/packages/54/44/e80651ecbf0e42b62e2bb5f5768916e07eea72e1297338956a61df361f88/cryptography-50.0.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:8c71ba2cd31fc93748c38e1b613200ff1c2665cbfd5341fe3a61cfde35a1430e", size = 5004057, upload-time = "2026-09-30T14:44:37.064Z" }, + { url = "https://files.pythonhosted.org/packages/f8/cc/1d33befb3cd7ea7e77d2d73f43f2066471da1b21f24a6156efcaabf6d2e8/cryptography-50.0.2-cp314-cp314t-win_amd64.whl", hash = "sha256:78198641e5be9521beea5aa782bb551a58068d10e6eb04c9c680c1b69f2e7d45", size = 3795868, upload-time = "2026-09-30T14:44:39.71Z" }, + { url = "https://files.pythonhosted.org/packages/2d/49/93f6a6e7a87c9aa68d44d3e1cdb5fe8f60c90d5d2f46acae9a56892816b8/cryptography-50.0.2-cp315-abi3.abi3t-macosx_11_0_arm64.whl", hash = "sha256:edc3342adf8f697fc5f59c887a304356f147b397809440ed64e2fa6af2f50f37", size = 4133708, upload-time = "2026-09-30T14:44:41.807Z" }, + { url = "https://files.pythonhosted.org/packages/8c/75/32ac2a56243d778805c16ca6a32b8f74fb757df7e28d7ecb560afafb59cf/cryptography-50.0.2-cp315-abi3.abi3t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d370b8d1dfcdf7130178137f6fbee6140774a1acc6cacefc4b42643ec11d0a3a", size = 4956267, upload-time = "2026-09-30T14:44:43.693Z" }, + { url = "https://files.pythonhosted.org/packages/aa/a4/2c8d734e43d97f0842ee9f1b7b4bfb3d0cf5e19edebf43c2afe6675c2320/cryptography-50.0.2-cp315-abi3.abi3t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f2f9bd7f90c64fe89253f0a2c05e3c4856072660429ce8831b4235bf29403a67", size = 4966465, upload-time = "2026-09-30T14:44:45.769Z" }, + { url = "https://files.pythonhosted.org/packages/c2/58/ee288c829a6f41f6235ae9dd33d82fd19b45442b65b4c8a3da36963d9f7a/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_aarch64.whl", hash = "sha256:e275096ea1e60cc595cda2836fd4a6c725d1125108b868be17f53684d164e2cc", size = 4959356, upload-time = "2026-09-30T14:44:48.211Z" }, + { url = "https://files.pythonhosted.org/packages/92/20/9ded6d51ddd9897f6b6e81fb9ebea7951d7cc5d6c890b0ed8abf77a51a80/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_ppc64le.whl", hash = "sha256:b13478603dcd0a2479ff8e87e2c19a7d525734686fe3c49542472293a204212d", size = 5548822, upload-time = "2026-09-30T14:44:50.86Z" }, + { url = "https://files.pythonhosted.org/packages/02/a8/8df951850d6b31d2a00218f19e2b3f999523437ed7a819df7fa427942fca/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_x86_64.whl", hash = "sha256:58a0c478eeca76fe5e07993c5a0703def34a6dc6a0cda4f5564639b33112ffe7", size = 5001199, upload-time = "2026-09-30T14:44:53.379Z" }, + { url = "https://files.pythonhosted.org/packages/8b/f9/36b3022218ce75b7cdf068fb95f809f9bd0d820e4955ef43b90c255cc7ac/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_31_armv7l.whl", hash = "sha256:d38cdff612d06fa6a32840d5e1b1f7a27cee4a349aa9085d94a67789d6bfd408", size = 4629333, upload-time = "2026-09-30T14:44:55.635Z" }, + { url = "https://files.pythonhosted.org/packages/8c/72/20f99a219f6af47cdd1cbd978c243b92d71496e168a746138af44ded4f29/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_aarch64.whl", hash = "sha256:fdd28f912fccfec1846a94e2e1e8f9b0012f557f0c46fe4f3eb0d7a87afcf90b", size = 4958822, upload-time = "2026-09-30T14:44:59.639Z" }, + { url = "https://files.pythonhosted.org/packages/f2/20/196f112617fb08eb4d608a2a6c422373d46f9cc2857f38fc0667033c0899/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_ppc64le.whl", hash = "sha256:cbc8738fd8526d80f35cb3a40d41f41a2e7030bb3b18b09a6778ef63d291c2fd", size = 5506351, upload-time = "2026-09-30T14:45:02.267Z" }, + { url = "https://files.pythonhosted.org/packages/24/95/83378121ef3eaaaf71d4b781577ff794acb39b9e1b87a3f156898c8497ed/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_x86_64.whl", hash = "sha256:e105ab60406787da31fccc883fc0f733af1efd78f0136a4599692c4083a73d0c", size = 5000859, upload-time = "2026-09-30T14:45:05.009Z" }, + { url = "https://files.pythonhosted.org/packages/22/f7/70fd7ae4d1dbfa7ba29b02e1b9068771519a86027756510b700ce81086a8/cryptography-50.0.2-cp315-abi3.abi3t-musllinux_1_2_aarch64.whl", hash = "sha256:6f8700550aa1474a91e5dc07049c46f98b423b5b1ddd0483e0b51362eeeaf5be", size = 5092151, upload-time = "2026-09-30T15:29:15.932Z" }, + { url = "https://files.pythonhosted.org/packages/d4/be/688367b74de86984bd58d8efacfc7c9e68b89a6a22ced0fb4f38db50254a/cryptography-50.0.2-cp315-abi3.abi3t-musllinux_1_2_x86_64.whl", hash = "sha256:c71be1cbfa5cd9a41ee452acf1eccd82b2c05950358b106ec8ceb83411d1a020", size = 5286120, upload-time = "2026-09-30T15:29:18.309Z" }, + { url = "https://files.pythonhosted.org/packages/39/d1/55f8a3f2ef5d1529e16835ef10cf0fe3d559ce237b46dddc440c0bba3649/cryptography-50.0.2-cp315-abi3.abi3t-win_amd64.whl", hash = "sha256:c423ab384a46c4dff7217b2ea5ba2e11cffdeab6441acd04cf65a369caf0366c", size = 4111557, upload-time = "2026-09-30T15:29:20.155Z" }, + { url = "https://files.pythonhosted.org/packages/23/ad/ac987755d00e1e64273760228d2635ae38dae2be83e3c6e0d3289d91dec3/cryptography-50.0.2-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:0ec5f09541743261e66e291b4a0cbf0fb2997aeaab6d9e9c740b9dba1b58d1c2", size = 3943588, upload-time = "2026-09-30T15:29:22.265Z" }, + { url = "https://files.pythonhosted.org/packages/d5/8d/6d585339bedf85d45044c85d8412dac53f2bb6f918e8b7777efba1787844/cryptography-50.0.2-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:c5e67125c7dca78d199ec4e116aa93dbb83494808ecbb8211a2cb09b1bf41dbd", size = 4756166, upload-time = "2026-09-30T15:29:24.58Z" }, + { url = "https://files.pythonhosted.org/packages/bf/f1/1c1f6874e8550cfddd4b688ceb38cefb6ed15ceed224d56f133f3d88c214/cryptography-50.0.2-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ee247f5c245c9a2fe7c8e2214e295918838e44e00a45a6718451e4004219e767", size = 4749145, upload-time = "2026-09-30T15:29:26.807Z" }, + { url = "https://files.pythonhosted.org/packages/c1/63/61b15dc1a8de03fe0adbe3fd7608b3ad5c73bf50993bbcb1faaa930afe33/cryptography-50.0.2-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:dfe9763530994147d9af1def057a5b9658b00e8f8fe8743d144d1e0911c2e454", size = 4763638, upload-time = "2026-09-30T15:29:28.588Z" }, + { url = "https://files.pythonhosted.org/packages/fc/35/b345bdfa40c9126df1a9d33236aa98418367931b8725f84fc3ae2b98dc59/cryptography-50.0.2-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:58ddb5a8e3179d12f19e4ea34d2d32e9d63a4baa142c875c1eb59f41b7243acd", size = 5382217, upload-time = "2026-09-30T15:29:30.589Z" }, + { url = "https://files.pythonhosted.org/packages/4f/87/ef344a9e616871f2519c22d6afcda79ddd5d35e9592d95eb6e677608d055/cryptography-50.0.2-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:f21e8a22c8605750c7af886bab299a363721264061b4ac0a30efb73cfd58efc5", size = 4781387, upload-time = "2026-09-30T15:29:32.605Z" }, + { url = "https://files.pythonhosted.org/packages/90/5b/f2fdb13cd0b96f6f932c8627bb292a45f11c64d21620a8e120aee9a3b848/cryptography-50.0.2-cp39-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:9c8402a82ea0dc4ceeab793db05f0fafa8ca139ca34fcde5df0f596103c74107", size = 4403790, upload-time = "2026-09-30T15:29:34.374Z" }, + { url = "https://files.pythonhosted.org/packages/bc/ce/7e4f662b1e3c393513569e402cfc85ac7da0bd3d5435e122a3140219eb2d/cryptography-50.0.2-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:0ddc924c04591c2811ca024d62ecad4f7f6f08af8939c211438f48a16bd23602", size = 4764319, upload-time = "2026-09-30T15:29:36.149Z" }, + { url = "https://files.pythonhosted.org/packages/3c/3f/86ff33ce34cc0de6847fb96e035a1a760d81652e38643f617c02ad32ef7a/cryptography-50.0.2-cp39-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:a6557e5f38e065ca9fbdaf7cfc7435ecb1d113aa81a022d1b51921ee7432e227", size = 5338560, upload-time = "2026-09-30T15:29:39.053Z" }, + { url = "https://files.pythonhosted.org/packages/40/cf/6b5c8e2fd9202d98988ab7cb5cc5c991704c4ad55f492ff408e4969f83f1/cryptography-50.0.2-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:1981f1db4630889b9ef7803fadef12b056f428cb6b85c27ba57b774793b6093c", size = 4780973, upload-time = "2026-09-30T15:29:41.251Z" }, + { url = "https://files.pythonhosted.org/packages/10/bf/8d6ebc7dded797bd0f0160d52188021211f011a2b164ef0ae1dac4587465/cryptography-50.0.2-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:7a8701d6b584d76e909e3d305b7d126b41439876a5aaf76cddc67fc230eafa2e", size = 4897738, upload-time = "2026-09-30T15:29:43.106Z" }, + { url = "https://files.pythonhosted.org/packages/d4/aa/f3f6e0de7e6253b8baa8b2d8fb9d50924fa75cee3d4624bd4bc1208ee923/cryptography-50.0.2-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:ce47f66801c20ec6c6632453bb5960fe38939e9306970b48b3a5a26de7745d94", size = 5058280, upload-time = "2026-09-30T15:29:44.827Z" }, + { url = "https://files.pythonhosted.org/packages/f6/b6/a1faf3a27ae9405fb34b1713cc73b2d8a26b04d5c561578fa2e6ef3e5bb9/cryptography-50.0.2-cp39-abi3-win_amd64.whl", hash = "sha256:4e81d95e5bafc2d6e34e4bed780e53e4d5b9a2f928573428aa4d35fbec1eb0de", size = 3854095, upload-time = "2026-09-30T15:29:46.782Z" }, + { url = "https://files.pythonhosted.org/packages/1d/7a/f08d34ce09d60f89ebd391e2ebc6ba2b995e6dd7552f41820f8085f94e53/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:92e665960f25fcdc73725b9cec7a3824f279ba97a98653afe9ffac2e43668f67", size = 4716035, upload-time = "2026-09-30T15:29:48.681Z" }, + { url = "https://files.pythonhosted.org/packages/45/67/e18fb65592451a2acb76e9f2fbe14e0f47a8318b4c5430f1633851d03daa/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:eef4c2f3423810b3070ab391f85436d2f8bbfcb286ac15cbc73190b3563b1f1a", size = 4726917, upload-time = "2026-09-30T15:29:50.608Z" }, + { url = "https://files.pythonhosted.org/packages/83/28/38fdce17e60f6b825e69fc3b7f75e70a6612759980704697e1de4cbfaf6e/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_34_aarch64.whl", hash = "sha256:7c6d0330c472d96f6a6afe24d80dfdf15176c33096f0a4397ae4c60f3dd3be48", size = 4715341, upload-time = "2026-09-30T15:29:52.522Z" }, + { url = "https://files.pythonhosted.org/packages/b6/b1/d9121a717e0f893c64bd6ca7702614778d7df2a5c309128a002421788516/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_34_x86_64.whl", hash = "sha256:1ba34f04897fcdaa73f74145c25f3ec146fbd56593853e88adc2e811303c5f42", size = 4726322, upload-time = "2026-09-30T15:29:54.263Z" }, + { url = "https://files.pythonhosted.org/packages/36/8b/e6d153808bf353e152abd2fd4d8f09670d956ac78379ac46e60d7efbf04c/cryptography-50.0.2-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:3dc4fd8058cea1644971207d530e1a03a184a805ffc8ebdddf0599d78a331b81", size = 3873097, upload-time = "2026-09-30T15:29:56.097Z" }, + { url = "https://files.pythonhosted.org/packages/ca/1d/1271f287ff7170ddafc2aad36260c4eec20ccd2fea70f38455e9d56d427b/cryptography-50.0.2-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:7b75de3c8b3be1cdb1052747c929440c3eea46c1bc2cb8a6e3a48388e9b7b452", size = 3805376, upload-time = "2026-09-30T15:29:58.729Z" }, +] + +[[package]] +name = "fastapi" +version = "0.162.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "annotated-doc" }, + { name = "anyio" }, + { name = "opentelemetry-api" }, + { name = "pydantic" }, + { name = "starlette" }, + { name = "typing-extensions" }, + { name = "typing-inspection" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/4e/7b/ae546e10f153fcf9a6afd8b9fe4730bdfeb8fdcb93178d54122973ef3f4c/fastapi-0.162.5.tar.gz", hash = "sha256:1ca37f64f61c99cebd38636e67525fb721c5e8c1169f07f2a35d73b0a63265d4", size = 531785, upload-time = "2026-11-11T22:29:53.177Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/10/19/5b9abfa67a29b862e509911eef40f4901f78aa48de32ad1f939b5c2b165e/fastapi-0.162.5-py3-none-any.whl", hash = "sha256:5303c67415fde762889ca337db79d27b755b8bd09cef314fa7a4340bb30bfd2b", size = 151782, upload-time = "2026-11-11T22:29:51.47Z" }, +] + +[[package]] +name = "flask" +version = "3.1.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "blinker" }, + { name = "click" }, + { name = "itsdangerous" }, + { name = "jinja2" }, + { name = "markupsafe" }, + { name = "werkzeug" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz", hash = "sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb", size = 759004, upload-time = "2026-02-19T05:00:57.678Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7f/9c/34f6962f9b9e9c71f6e5ed806e0d0ff03c9d1b0b2340088a0cf4bce09b18/flask-3.1.3-py3-none-any.whl", hash = "sha256:f4bcbefc124291925f1a26446da31a5178f9483862233b23c0c96a20701f670c", size = 103424, upload-time = "2026-02-19T05:00:56.027Z" }, +] + +[[package]] +name = "gunicorn" +version = "23.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "packaging" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/34/72/9614c465dc206155d93eff0ca20d42e1e35afc533971379482de953521a4/gunicorn-23.0.0.tar.gz", hash = "sha256:f014447a0101dc57e294f6c18ca6b40227a4c90e9bdb586042628030cba004ec", size = 375031, upload-time = "2024-08-10T20:25:27.378Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cb/7d/6dac2a6e1eba33ee43f318edbed4ff29151a49b5d37f080aad1e6469bca4/gunicorn-23.0.0-py3-none-any.whl", hash = "sha256:ec400d38950de4dfd418cff8328b2c8faed0edb0d517d3394e457c317908ca4d", size = 85029, upload-time = "2024-08-10T20:25:24.996Z" }, +] + +[[package]] +name = "h11" +version = "0.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/01/ee/02a2c011bdab74c6fb3c75474d40b3052059d95df7e73351460c8588d963/h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1", size = 101250, upload-time = "2025-04-24T03:35:25.427Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" }, +] + +[[package]] +name = "httpcore" +version = "1.0.9" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "h11" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484, upload-time = "2025-04-24T22:06:22.219Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" }, +] + +[[package]] +name = "httpx" +version = "0.28.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "certifi" }, + { name = "httpcore" }, + { name = "idna" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406, upload-time = "2024-12-06T15:37:23.222Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" }, +] + +[[package]] +name = "idna" +version = "3.20" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f5/08/8eea9d4b8302028f3abb2c0813953f7aec26d33b7a8960ed760e65ff29fa/idna-3.20.tar.gz", hash = "sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44", size = 216463, upload-time = "2026-09-17T14:11:04.752Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl", hash = "sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c", size = 69583, upload-time = "2026-09-17T14:11:03.168Z" }, +] + +[[package]] +name = "itsdangerous" +version = "2.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9c/cb/8ac0172223afbccb63986cc25049b154ecfb5e85932587206f42317be31d/itsdangerous-2.2.0.tar.gz", hash = "sha256:e0050c0b7da1eea53ffaf149c0cfbb5c6e2e2b69c4bef22c81fa6eb73e5f6173", size = 54410, upload-time = "2024-04-16T21:28:15.614Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/04/96/92447566d16df59b2a776c0fb82dbc4d9e07cd95062562af01e408583fc4/itsdangerous-2.2.0-py3-none-any.whl", hash = "sha256:c6242fc49e35958c8b15141343aa660db5fc54d4f13a1db01a3f5891b98700ef", size = 16234, upload-time = "2024-04-16T21:28:14.499Z" }, +] + +[[package]] +name = "jinja2" +version = "3.1.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markupsafe" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/df/bf/f7da0350254c0ed7c72f3e33cef02e048281fec7ecec5f032d4aac52226b/jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d", size = 245115, upload-time = "2025-03-05T20:05:02.478Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", size = 134899, upload-time = "2025-03-05T20:05:00.369Z" }, +] + +[[package]] +name = "joserfc" +version = "1.8.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cryptography" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/74/31/5c3f27e82c92a7bbe1f028033ff19e0251540395c9be244c01a50de42bdb/joserfc-1.8.0.tar.gz", hash = "sha256:cbf03cb2c6db8cc5289f1ef8718842e53dba244b4c0de5fefa0c0eaee4bde8db", size = 241023, upload-time = "2026-11-03T10:45:57.948Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5e/7e/7ffaae13415e8f51c8e8d5d1845f2de7a27ebf2717e97a38d7e7446d6030/joserfc-1.8.0-py3-none-any.whl", hash = "sha256:176b836ac7ed9a46a88629e24076314b475f33a75d0bad7f26146e572eed7c79", size = 73147, upload-time = "2026-11-03T10:45:56.531Z" }, +] + +[[package]] +name = "markupsafe" +version = "3.0.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/38/9b/e422a865e1d5d57d0e509b4e0bf1c1a70a7f6382c29a5aa428df994c8bc8/markupsafe-3.0.4.tar.gz", hash = "sha256:2e9ad7dd851bf45fab9f75cbff4cb493fee9979e8d8c7c9c3ee119022518edd6", size = 153777, upload-time = "2026-10-02T23:07:22.29Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/55/18dbb4778b30ada5ce071608503cc3edc9e14e13d868c17a6d178fc30f7a/markupsafe-3.0.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:9e25feb9e330b63edb0278a0acdf85e50d0cb0fbf49c3084abbe4e24ae195346", size = 11520, upload-time = "2026-10-02T23:04:36.299Z" }, + { url = "https://files.pythonhosted.org/packages/6c/14/0b05f79b4733e264a18d08fe08fa1df7347630ff32a6cb82180d9dccec55/markupsafe-3.0.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:7d3391b2188d18737cb2fa147028b1096236eaa7e156446c650a489fa2cadc91", size = 12063, upload-time = "2026-10-02T23:04:37.291Z" }, + { url = "https://files.pythonhosted.org/packages/ca/3a/63ba10b6c1463216b3e4df669a9f0e5a3b0c3071557d2e8229e3968c79fb/markupsafe-3.0.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:849dd2bb0e5e4ab2b71c7191726a4a8d5aa8a610daa584728cbee0b710ddc4ef", size = 24321, upload-time = "2026-10-02T23:04:38.262Z" }, + { url = "https://files.pythonhosted.org/packages/1a/2e/5f015261b76ad633d187ef6f388b413aedd64a8773c4df59e530a0be5525/markupsafe-3.0.4-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:befb4158af32106b9a93db8d6d1d1cbbd418c0d5aca0cabb7b1780abf0c89169", size = 28845, upload-time = "2026-10-02T23:04:39.295Z" }, + { url = "https://files.pythonhosted.org/packages/33/cf/26e594b26be40c2f1fec63ccf8a8b99d0335a5b2cbe84835c7d82a994375/markupsafe-3.0.4-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:71f88e749ea29f67f21f3b36433c1dc54c7729ed2a6d9e2da2e0d9e0d7b224eb", size = 24701, upload-time = "2026-10-02T23:04:40.348Z" }, + { url = "https://files.pythonhosted.org/packages/81/a5/a513b76c139a3915b43404324e55c0b7979ae4f0d39eb6f075b0282e90a8/markupsafe-3.0.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6da83a088f8ef93b2d483a8232a4dbf4d69d3d8496b568a03c56becac43e1808", size = 22961, upload-time = "2026-10-02T23:04:41.372Z" }, + { url = "https://files.pythonhosted.org/packages/46/cf/4c66192c100b4542bcbe392ae06696b670f66927be3ac38a213234778ff9/markupsafe-3.0.4-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:8f0fac8b13d14bb06c68195f849371924ae53dd7b1c00fed24650f704383b692", size = 21920, upload-time = "2026-10-02T23:04:42.429Z" }, + { url = "https://files.pythonhosted.org/packages/cb/17/ac3662678bfbad649893117ada2ba44dc30bf56884e84f13154a792b10f1/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:4a7cdc2a420ca01058182da4253329764d4bfa055564d1eced90e6ba1e8b1d3d", size = 23726, upload-time = "2026-10-02T23:04:43.531Z" }, + { url = "https://files.pythonhosted.org/packages/f7/af/fe47cee339180a69ebca3c57fb3483d0f5cbd1e8337d1871fb1d9c1aebee/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:83b3944fea42a8400edf92fd1770fb8d0d4f7de651353bd2d8525a92dba69a21", size = 22539, upload-time = "2026-10-02T23:04:44.618Z" }, + { url = "https://files.pythonhosted.org/packages/12/32/d55440ba140442800e02d799c9cb5ab597bf6ebdb1177b5ea39a11f797bd/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:8138eb83940ec7299024d92d4dee45f601b9e6c5ffde9d25f4e35e326203c707", size = 23963, upload-time = "2026-10-02T23:04:45.656Z" }, + { url = "https://files.pythonhosted.org/packages/50/9d/9c86042cb364c2ad4c971e6d1247929effd25f714cd7ee11b05e6316445b/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:811d02d5122171c1941357efd8f9bf4ffe907b7f0a1a4e729a880e4be3f46e3e", size = 21506, upload-time = "2026-10-02T23:04:46.671Z" }, + { url = "https://files.pythonhosted.org/packages/75/ef/5b824f03ba40c3b3652b6272d083d2fc4fcdd440de519a3a39ba2c3e7262/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:50b5bedc9ed8a94fc8857a42ef4f84a81ea88f8d4f05dc8705fb23ee6d8dcca7", size = 22955, upload-time = "2026-10-02T23:04:47.698Z" }, + { url = "https://files.pythonhosted.org/packages/1e/e8/44cfcb5ea40e5e43cec7793ef90704ed0c475280839076c4345757eb8e59/markupsafe-3.0.4-cp311-cp311-win32.whl", hash = "sha256:2e5a7cd7fdd14fcb1ae5d7d8bf23d24fbd1daefd1fbca2580132e1ea75f098b5", size = 14094, upload-time = "2026-10-02T23:04:48.788Z" }, + { url = "https://files.pythonhosted.org/packages/91/89/f2b509f7bf79352e40117824c1070dbeafd4df67031d3fa98165a3134228/markupsafe-3.0.4-cp311-cp311-win_amd64.whl", hash = "sha256:fdb4ca07ab75ffadab4a8b135ad59cdbb3156b99310f3d565370da74a15d6bd3", size = 14328, upload-time = "2026-10-02T23:04:49.801Z" }, + { url = "https://files.pythonhosted.org/packages/2b/5a/ccf22672a0f64dc682306e288f0dabcb06c7a201f3bb6e6cbf86d9e8ad03/markupsafe-3.0.4-cp311-cp311-win_arm64.whl", hash = "sha256:569d65055d367e3dcdf30c3f41119467b73d9ee9faf332bdf40402644f5ac08e", size = 14188, upload-time = "2026-10-02T23:04:50.847Z" }, + { url = "https://files.pythonhosted.org/packages/81/09/4c59d56b8461ae8eb0d8ba34bb25b7e618547044679d58a82ef9b2479fc1/markupsafe-3.0.4-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:61631e08084be9e21a8967ec3139c7616ed7c5e9368e05c86d1b39562c8a57b6", size = 11658, upload-time = "2026-10-02T23:04:51.876Z" }, + { url = "https://files.pythonhosted.org/packages/a2/f0/d6613774d86fbf6d145751d43c59875e47a6f9f17daee0aef173bd36d90e/markupsafe-3.0.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:0930db9bdc62d22944e10b066448bb65dc9abe9112880c7cab8da54db4284d5f", size = 12050, upload-time = "2026-10-02T23:04:52.931Z" }, + { url = "https://files.pythonhosted.org/packages/0d/f2/8f18e0b806eb13c1f8d07d917a720831ead54253a6dec011fbc78098a6f8/markupsafe-3.0.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6a45c3d514f2436064db00d7fc8778d888f0236ebfed649b53d13a59e69ad51b", size = 24363, upload-time = "2026-10-02T23:04:53.895Z" }, + { url = "https://files.pythonhosted.org/packages/60/ce/fa07dbe8a5675558fa36dea033e19995bc783de2dec5f540ccb9030b06aa/markupsafe-3.0.4-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:1e1451fab512d1bcc3dc26988ec1edb0b82c2db909132872cd9356070a6b63df", size = 28525, upload-time = "2026-10-02T23:04:54.905Z" }, + { url = "https://files.pythonhosted.org/packages/85/40/be87c01f3868ec217f8a2015089d71c22c8c5a75324822e5ed1cdd87210d/markupsafe-3.0.4-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:bd3ce56ae2cbae3ba82b683bc425cd7e48d2ed8b10f3e818186b6f5646d9271c", size = 24733, upload-time = "2026-10-02T23:04:56.229Z" }, + { url = "https://files.pythonhosted.org/packages/4f/a7/aeedb5140afa41fc74c225e9184ab96723a6e873b6ee1c9fede7283456d8/markupsafe-3.0.4-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8e124f974786f831d6043728e38296969d3579db8896fe004682f5758e613581", size = 22985, upload-time = "2026-10-02T23:04:57.521Z" }, + { url = "https://files.pythonhosted.org/packages/c3/fc/e91352bb08c6a59da3ef0909d457bf95a5f5908fbf151b30a06d9dbcfbb4/markupsafe-3.0.4-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c02e8f18bdedba082cef725942ac823b9b60656db07f7e265cb31618dfd00d77", size = 22001, upload-time = "2026-10-02T23:04:58.597Z" }, + { url = "https://files.pythonhosted.org/packages/5d/f8/bffee5e7d2a3deb59748a797650a48af7e672025cf641a79344a771ad106/markupsafe-3.0.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:9f098115c247e11d138ab83a28fa0323c77015007ea2df73ba5fd714dfefd67c", size = 23793, upload-time = "2026-10-02T23:04:59.686Z" }, + { url = "https://files.pythonhosted.org/packages/ed/59/b853d6628ecb4d658e1d637224846d5e9bb4adf4f8df97f3be9f29dce2ec/markupsafe-3.0.4-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:d5f93ebbeb8032d47e349328ec8662d973d9b05a70b3c35df1f91fe419b84749", size = 22640, upload-time = "2026-10-02T23:05:00.768Z" }, + { url = "https://files.pythonhosted.org/packages/09/b2/1506df394f0f075797c418d0301498f49e43be194e3ffcb49e6fe6ccf022/markupsafe-3.0.4-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:64511c54db4e4987aef4c41923235927428729e8174c5dba488429be70a998ed", size = 24074, upload-time = "2026-10-02T23:05:01.813Z" }, + { url = "https://files.pythonhosted.org/packages/c7/81/5ed69cda630ac69ef60d06c09ba5a7f84ff66a2e28cf986fd5614ab3c6e6/markupsafe-3.0.4-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:e1a622f13970d81f95d0c72f9dc090dce9085fccfa4c9f2174377ee32bd15786", size = 21563, upload-time = "2026-10-02T23:05:03.239Z" }, + { url = "https://files.pythonhosted.org/packages/0c/fe/fb1e79be0fea60aa32602ebefc9c35a82bb42b4df157285ab7dfec12341a/markupsafe-3.0.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:c9a7f43c0b202b334cc9184af09bb8f21d3a209e038efaf106936fb69e6b026e", size = 23048, upload-time = "2026-10-02T23:05:04.479Z" }, + { url = "https://files.pythonhosted.org/packages/c8/52/7632a53360671a9b750cdbabaf9cdd89f18b42248b8e4cb42c0b0296e459/markupsafe-3.0.4-cp312-cp312-win32.whl", hash = "sha256:f0ec3b750b59375eab5b0fb2b9254810c00a3375be6d789899f1055a1d556237", size = 14108, upload-time = "2026-10-02T23:05:05.513Z" }, + { url = "https://files.pythonhosted.org/packages/3f/bf/62495e180b7000aaf30000fff849e933f74264638057176cf46852500adc/markupsafe-3.0.4-cp312-cp312-win_amd64.whl", hash = "sha256:11935df9bf455ed0c04eb87bcd720f02b1fe5e02128a9430f23aed6f93336fc7", size = 14303, upload-time = "2026-10-02T23:05:06.538Z" }, + { url = "https://files.pythonhosted.org/packages/c5/8e/4c24208776a65878d656996945aacfbfe010d3720d1a98fc0eb8491fc03b/markupsafe-3.0.4-cp312-cp312-win_arm64.whl", hash = "sha256:a4bbd2d87dd233b9fc5812160c3d0ffbe42edc22a26ce0469f58479ede633fe9", size = 14174, upload-time = "2026-10-02T23:05:07.617Z" }, + { url = "https://files.pythonhosted.org/packages/6d/18/4bc5ba32499e87bb2b0ef5b3a9bb9c00a131fa961ddf0be548cb550f548b/markupsafe-3.0.4-cp313-cp313-android_24_arm64_v8a.whl", hash = "sha256:de8b364c423ef0a4bad9069657d617f9a5d2b2062457a89b1fa16ee199c399c1", size = 12786, upload-time = "2026-10-02T23:05:08.709Z" }, + { url = "https://files.pythonhosted.org/packages/4e/6f/17f0c099bf25f3e31e63cc19244d9f6af861a9a4ab778c203997903cfdd0/markupsafe-3.0.4-cp313-cp313-android_24_x86_64.whl", hash = "sha256:34bdde374c5932765d7dc685c4a1d191a3207852d67e8e0a9eb6ea85156181f1", size = 12510, upload-time = "2026-10-02T23:05:09.93Z" }, + { url = "https://files.pythonhosted.org/packages/11/af/1a141081b905036ee904ec4bd945e1f70b4e1b32d33c4e59e8cf1d58b247/markupsafe-3.0.4-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:6bd9e1788e15bfcf6a9082de42e30387e7b85d211ab21e57a939bb8cfaaf8d96", size = 11583, upload-time = "2026-10-02T23:05:10.884Z" }, + { url = "https://files.pythonhosted.org/packages/e7/0a/a89385ae590232622a03e091805cff12f24fabe6c11e0e8bae096cece81c/markupsafe-3.0.4-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:5066b244f576f91afc8ee3ba029a89f99d39c79b1853fe9d39bea9f0afbec148", size = 11801, upload-time = "2026-10-02T23:05:11.913Z" }, + { url = "https://files.pythonhosted.org/packages/ed/85/ea548dc013962eb73653124bc595635fbf9e0fa41d1f181a967ccb784dfb/markupsafe-3.0.4-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:7a83aa6e4805df46fed18e989d3d16f86ef60cb50bbc8d9ce3a6be89165fbf6e", size = 11443, upload-time = "2026-10-02T23:05:12.887Z" }, + { url = "https://files.pythonhosted.org/packages/cc/72/15f2e5ec9cf2eb00d5cdfe968d94e4156a7bd7303832c3f3b2c403a36839/markupsafe-3.0.4-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:2d1b7d9308288661f56672b1b157d75fc536714d3638487bbea17b6318a78248", size = 11665, upload-time = "2026-10-02T23:05:13.829Z" }, + { url = "https://files.pythonhosted.org/packages/ca/e0/4030bea613677e333c8a2c901fd405055f657f9d06acba5b7357984b6ef7/markupsafe-3.0.4-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:73e77980c7207854f00fc4e71fb1626868d5740ab4012623d55c7a99ad122a72", size = 12061, upload-time = "2026-10-02T23:05:14.807Z" }, + { url = "https://files.pythonhosted.org/packages/f3/a5/28b76a7449eb702966b88bef599e2360b411fbb3afeee8fe560939be06ec/markupsafe-3.0.4-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7018d4af1cd272e847aa5917983ab5e83e4f6579f9dbfecd4a79c0ca80b144c2", size = 24395, upload-time = "2026-10-02T23:05:15.909Z" }, + { url = "https://files.pythonhosted.org/packages/07/6c/21232811afc3a063b5e934b1ae2efda52f46154ec382f585149c020e61fe/markupsafe-3.0.4-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c90d5b3d4e944e065a301d741b3c1d784f6bd1f503aa68b4967e32b2ba313d85", size = 27183, upload-time = "2026-10-02T23:05:16.976Z" }, + { url = "https://files.pythonhosted.org/packages/14/38/6ccdfa5b59049cb36fb80cbc80aee9cf1fc9bb77d1335ad435f2070b08cf/markupsafe-3.0.4-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:18a801868a884f216e784d7d14db2a4077143ce7610440aee2ce8f734e7cfcde", size = 24772, upload-time = "2026-10-02T23:05:18.209Z" }, + { url = "https://files.pythonhosted.org/packages/63/e0/cec6865dfe88cb48fedd4b20aed6af5158e41092adcbf3e028bcc6ec2108/markupsafe-3.0.4-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:434139499bb20b502ed3baa1f169e618f924a97e7a777fea1a49446d80106cf6", size = 23017, upload-time = "2026-10-02T23:05:19.286Z" }, + { url = "https://files.pythonhosted.org/packages/ee/76/6ed4940bb7648a9aac457c14f870cfdd5105f139a0fb1f29cd61fafa47d1/markupsafe-3.0.4-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:9e227f3dbe6bde7491cf0a9965d00b88c6b1a4a95d11480ddf88bb96d397c19f", size = 22036, upload-time = "2026-10-02T23:05:20.352Z" }, + { url = "https://files.pythonhosted.org/packages/a1/4f/ed476226d4fe46a09090a36025bf319296810028df55eb12f1253b540f3a/markupsafe-3.0.4-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:b8cd1f918b26fd7b1832ece557cc18f2d8747309ff8b3f0ef9d4250c5ad67a39", size = 23786, upload-time = "2026-10-02T23:05:21.576Z" }, + { url = "https://files.pythonhosted.org/packages/9a/35/66ff30450e35ef5fba9ebc930c9411747e537fd9447b65e44f5007e2b84d/markupsafe-3.0.4-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:a5fcffb37e602b0b3c1638a97746b9b96125caa9bcf6fa41d337a9261de231ee", size = 22672, upload-time = "2026-10-02T23:05:22.922Z" }, + { url = "https://files.pythonhosted.org/packages/32/0b/72f45ce4b4efcbca4b80cf1b06703eff0be8d37e82abb78f66c85a7ead1e/markupsafe-3.0.4-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:5989cb26b2e1efc6a42216a9f6b5ee495ce5ace2e5b352a9af489976b32d1ee2", size = 24107, upload-time = "2026-10-02T23:05:24.175Z" }, + { url = "https://files.pythonhosted.org/packages/d2/03/71776e5fdcba04614b384cc102e8a4198208579d896fd1394cb7cb9aa900/markupsafe-3.0.4-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:add96447a86d205ab616665d53b2950ee81083757f56e6ea833c8b2917646b46", size = 21615, upload-time = "2026-10-02T23:05:25.215Z" }, + { url = "https://files.pythonhosted.org/packages/ab/5f/801ce02a02e7aee0f784b1ec7843026178f6adeb9c93ac67eb1992a9a84d/markupsafe-3.0.4-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:2628d3a8cb648ecebb3c5d6b0a1052d400e4d8b7ac0fb786be8d285b50040d17", size = 23076, upload-time = "2026-10-02T23:05:26.423Z" }, + { url = "https://files.pythonhosted.org/packages/4a/85/c43776625428f3bb4a61e8633940400e3efe6409e3c6f5bff26de5e45618/markupsafe-3.0.4-cp313-cp313-win32.whl", hash = "sha256:672d207103e6b16ca098611b0f9efad6bc00afd47c03d6ef62186495ca677dc0", size = 14118, upload-time = "2026-10-02T23:05:27.716Z" }, + { url = "https://files.pythonhosted.org/packages/6f/36/163da64de88a13db79214ef75fa041be7fa13bdb42261cf5b7484de14bfb/markupsafe-3.0.4-cp313-cp313-win_amd64.whl", hash = "sha256:1f1f9477e174582b0a1b583d60b66e1f2cf5d3fe12cee985e4aedf44766600e5", size = 14313, upload-time = "2026-10-02T23:05:28.749Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a8/9b662783ffaa1149221432a923cee562f78b9cbbb8baa3df9b3753e63e1e/markupsafe-3.0.4-cp313-cp313-win_arm64.whl", hash = "sha256:06de8ef6331f6e822c28d577dc8bf43fe398800477c49498f38fc38b67ff33fc", size = 14189, upload-time = "2026-10-02T23:05:29.917Z" }, + { url = "https://files.pythonhosted.org/packages/5c/c3/a944f3b0df22bd129e96915b9f4e98d2eeca6516687d7618304a966c3c74/markupsafe-3.0.4-cp314-cp314-android_24_arm64_v8a.whl", hash = "sha256:4ed644d75aa94a2baf7ec3a96eaa160ea58c742eb9d27c6506053c5c40fc84ed", size = 12787, upload-time = "2026-10-02T23:05:30.971Z" }, + { url = "https://files.pythonhosted.org/packages/d4/d6/a44863f69d88b6c7e27889108f70d47aed259edf89d5df3c5fca1eac87d6/markupsafe-3.0.4-cp314-cp314-android_24_x86_64.whl", hash = "sha256:6d2a9efe686f9de00d0d1ea32a4a5a86d558a2277501bd78d964214eab625e59", size = 12525, upload-time = "2026-10-02T23:05:32.263Z" }, + { url = "https://files.pythonhosted.org/packages/17/8f/168ba80e532dd6a93f96f8f706f1ad41d7990b6e1aeedc1cc0d211a33497/markupsafe-3.0.4-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:8781a792a070cf2bd1b86d3aa943894115faaba6e88122a7bf32d62072742453", size = 11589, upload-time = "2026-10-02T23:05:33.251Z" }, + { url = "https://files.pythonhosted.org/packages/32/b3/aa2c95a574d3af39403a469b295886eb9b6d448da568cbebb5a2cbfdc2e5/markupsafe-3.0.4-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:971a3bbb75d97ae4e2e8f7d4834236f86f85f0c85e04ab2e191db1123b04f80b", size = 11801, upload-time = "2026-10-02T23:05:34.315Z" }, + { url = "https://files.pythonhosted.org/packages/60/d0/34b810107d83840e768bf485de795893ebbae35b26ab061b487adfa0a692/markupsafe-3.0.4-cp314-cp314-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:8909c2f1c6dd65e054ac4b573a91c8384d1492281e55d82d159d653f7a13adf6", size = 11447, upload-time = "2026-10-02T23:05:35.302Z" }, + { url = "https://files.pythonhosted.org/packages/6c/ab/2f8488f0f817a39fca068d2b17daf446bf5cdb3eae28c3720af534d873b4/markupsafe-3.0.4-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:4cf3468d5ec187ffffcaca8e61929a37448f215dafc1386a12c750a72fe53634", size = 11722, upload-time = "2026-10-02T23:05:36.363Z" }, + { url = "https://files.pythonhosted.org/packages/ad/40/e2d117b048d47282ade906fbfd92814cbee5647afc13fda88a3406039372/markupsafe-3.0.4-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:52704c5d36eb6dda8866493decd61111fff86244c9b1ad225ca01b9e91e5970f", size = 12061, upload-time = "2026-10-02T23:05:37.397Z" }, + { url = "https://files.pythonhosted.org/packages/9a/a8/73a81135e85ba66217f5af7facb03bbb386807e1a729ab64532e4c802652/markupsafe-3.0.4-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1caa2fa5a6184fb233153b35f654e6687bd555476f6170f29d8ee9be1a8b0af9", size = 24434, upload-time = "2026-10-02T23:05:38.407Z" }, + { url = "https://files.pythonhosted.org/packages/ac/ca/fa9216dd01efee2dfdacafe7df32b4d0170fbac694b0c258a193d6e53999/markupsafe-3.0.4-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:387d8cd30e69b3f0a72877b9ae717033396404e19095b17fe89753a981fda44f", size = 27183, upload-time = "2026-10-02T23:05:39.581Z" }, + { url = "https://files.pythonhosted.org/packages/fa/4e/a469509e538d37af51103b17b073126973f2b1cbf197ff32c7ddf025cfe5/markupsafe-3.0.4-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:051417f74bcaaefa316276e0ff723f541616ca51043d070da00249d9bddd3e3c", size = 24813, upload-time = "2026-10-02T23:05:40.671Z" }, + { url = "https://files.pythonhosted.org/packages/8f/db/d7282caf7ab03af44d5d6fdbaa019b35c7d7f1c90588b839c07cba640d6a/markupsafe-3.0.4-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a8e9f292fcda89b324f2f5c91d13f1424a153e40fc2756f38ee23b15835ff300", size = 23049, upload-time = "2026-10-02T23:05:41.864Z" }, + { url = "https://files.pythonhosted.org/packages/30/f3/b6a425206e6964efda6acee544d0eb01d1501784d0b8e2dcc74986f33b17/markupsafe-3.0.4-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:df1ae86ff54725a01fa1a0510b914ca53a161b7050be74f6204e24aded5971d0", size = 22088, upload-time = "2026-10-02T23:05:43.014Z" }, + { url = "https://files.pythonhosted.org/packages/ea/8a/84d3582fc1f0d5bd466cdf2eebf175e172158a6e70701aacec1de1b35430/markupsafe-3.0.4-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:8965520ac587c94a4ac48b729be3d8b8de00af39699b17585dfb599babe77977", size = 23846, upload-time = "2026-10-02T23:05:44.098Z" }, + { url = "https://files.pythonhosted.org/packages/1c/65/db101cce51b7ba4864ac491a9859d297dd1adf0e55b103fee9db9c47c527/markupsafe-3.0.4-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:340cbb1957ba99929cbf19a75626d36ba1ae21d1730b287d1cf7f824a20c4fc7", size = 22674, upload-time = "2026-10-02T23:05:45.23Z" }, + { url = "https://files.pythonhosted.org/packages/e0/49/ddee9813d71db0c7a5c9d97c832125e6758a0c844777f1cf076569bb0e22/markupsafe-3.0.4-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:3a93d9616ddecfb393727a0041a562cf0b15a244e20f2bd25efc7949be4c4f17", size = 24104, upload-time = "2026-10-02T23:05:46.398Z" }, + { url = "https://files.pythonhosted.org/packages/aa/0e/7d8518d726726870a2399d69fd30d0fa36c5e57a2132c336b58d7c491073/markupsafe-3.0.4-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:d2e56fd3b00222722abfb3f5f0759ddbae4b90811b5ad4343c64030ad1bde70c", size = 21637, upload-time = "2026-10-02T23:05:47.48Z" }, + { url = "https://files.pythonhosted.org/packages/b4/b0/b505e8a361ba557dbf3b3aa7331ea39b00d2022a26e925ff8463b9714bb3/markupsafe-3.0.4-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:0d9c47709875fdb321452056622e930c52afbc07a7d780762fbb8b4d91ce6fa4", size = 23081, upload-time = "2026-10-02T23:05:48.611Z" }, + { url = "https://files.pythonhosted.org/packages/1c/ea/9cc3cea873f980c75cbdb6f4277ce30ee955de38be0b3d02f14c108e0698/markupsafe-3.0.4-cp314-cp314-win32.whl", hash = "sha256:38fc55594dab834470b6733dead2ee9e3f657fb0608c769dcafa0ba5ab52f45c", size = 14272, upload-time = "2026-10-02T23:05:49.707Z" }, + { url = "https://files.pythonhosted.org/packages/80/f0/5792ff768a410f93ee3f84fc19345295ffc352d2c936b424cb37e514714c/markupsafe-3.0.4-cp314-cp314-win_amd64.whl", hash = "sha256:c1bc67752d5f21013cfe430df4062441714eab79f65a6a05e01505957e9c35fe", size = 14501, upload-time = "2026-10-02T23:05:50.788Z" }, + { url = "https://files.pythonhosted.org/packages/5f/cf/3d074a8edffcc6899355232ff2543ae8d929733239596423b7db79698bc9/markupsafe-3.0.4-cp314-cp314-win_arm64.whl", hash = "sha256:7e1636da3d8dfc220b6dd10264db5f2b165e4888c4518594898fbe381049af8a", size = 14364, upload-time = "2026-10-02T23:05:51.857Z" }, + { url = "https://files.pythonhosted.org/packages/d9/31/87ce42159aae2163cf3bbbd0c44bc87780510eecab1ea3859099aed95dcb/markupsafe-3.0.4-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:805c8b84534fa10891890f0e4be39f3a99e94615d93e8836bf9fa1fdca2feeb2", size = 11759, upload-time = "2026-10-02T23:05:52.951Z" }, + { url = "https://files.pythonhosted.org/packages/5f/53/b047207eeb7752e960aca3eb1df5fb7eefa7dd4c62ac49bb156456c8a702/markupsafe-3.0.4-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:fa95848c929b6a75f6848d3c9793e59db365ee436776e57db835cdbfa79ba977", size = 12096, upload-time = "2026-10-02T23:05:54.066Z" }, + { url = "https://files.pythonhosted.org/packages/ee/51/4326c88a13c7b755657d44b4bb986f8c3d9843ecba7e22d98661d87f9a57/markupsafe-3.0.4-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e916035e3e9930cbdfdd10abf48861340221857f45509565898e012263f7b289", size = 25699, upload-time = "2026-10-02T23:05:55.15Z" }, + { url = "https://files.pythonhosted.org/packages/f2/bb/990581b7474bfcf2cf34bed6ba5ea23bd87adb9d671213d68e88620e7a6b/markupsafe-3.0.4-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:b4d12837e0203bbace818ff4a7461afdcd78bcd782351cea148139180d7bcffe", size = 27804, upload-time = "2026-10-02T23:05:56.29Z" }, + { url = "https://files.pythonhosted.org/packages/6b/89/89491878c28e8291f5aa2fffe2c2d57230d10ae366d55dd810b840513d78/markupsafe-3.0.4-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5086f9975abb1ab531ee6afca1761e4b59a19b446f3f6522ed776963228cfe5a", size = 25912, upload-time = "2026-10-02T23:05:57.416Z" }, + { url = "https://files.pythonhosted.org/packages/30/77/680998b54efdea06fc114565cd739b6d059f826a0279219b218dfa750d29/markupsafe-3.0.4-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b4a635a0487774f841cb1fb62e907e7195cc95bc761e053184b8acc3ceb20733", size = 23623, upload-time = "2026-10-02T23:05:58.557Z" }, + { url = "https://files.pythonhosted.org/packages/ae/75/2709f5ac5de9467b40b10e2bb8f89cc63dfb74582e09aa734b1124a217de/markupsafe-3.0.4-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:cb96e6e088d6cf71c1ea977510948320234824cf226e32f6f6e044f7a9c82b34", size = 23301, upload-time = "2026-10-02T23:05:59.94Z" }, + { url = "https://files.pythonhosted.org/packages/a0/c8/39eadc6c5b14c9c7679bfb98f4d4c6a97863b5beb91839aca4d2d6e16e55/markupsafe-3.0.4-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:8b5d563170ff8ba3181caa967c99a3c804d1dedb702c7cb93a6a7c32247da978", size = 24950, upload-time = "2026-10-02T23:06:01.289Z" }, + { url = "https://files.pythonhosted.org/packages/1a/5e/01037f8a43e8ccb0bffb4fbdc5212db05bf080fdd7286cd392332d58128a/markupsafe-3.0.4-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:396ec4e65cc889f69786b3b89478b471cee5a3bcf468b9d9bb03e1a30fb291fc", size = 23330, upload-time = "2026-10-02T23:06:02.441Z" }, + { url = "https://files.pythonhosted.org/packages/d4/f4/23e83ce0596bb0cbe670502d31df8f757bbd01a392aa486fa3b40d1ed399/markupsafe-3.0.4-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:15ba9e28640feef770374b116a6f019c21f52404aeabe516aa7f800587b98cfc", size = 25239, upload-time = "2026-10-02T23:06:03.579Z" }, + { url = "https://files.pythonhosted.org/packages/88/5b/3708897368073cc683d524750474f41a77d2986152c380dcc55b20fdf340/markupsafe-3.0.4-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:d920abdfa61279ba1a2ef9484aab07bf03331f8c08a10120fa332353d06e6932", size = 22767, upload-time = "2026-10-02T23:06:04.699Z" }, + { url = "https://files.pythonhosted.org/packages/c6/61/ebda1307864b409e6b3115757a3d4a09cca46cfb6cc65191b5de226b424b/markupsafe-3.0.4-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:a9f54054101545a9a9cccefddf54316aa6e4491611fcbef9e91b3b6bebec04f6", size = 23668, upload-time = "2026-10-02T23:06:05.9Z" }, + { url = "https://files.pythonhosted.org/packages/09/15/98075cceac3b5ba0dbb8e4762a847be967d2befc349a2cf2d0ac77f62c9d/markupsafe-3.0.4-cp314-cp314t-win32.whl", hash = "sha256:12a606a492de952afcb43b59a14aaaaad120e708d3663dd0fdf2d738d427a691", size = 14301, upload-time = "2026-10-02T23:06:07.109Z" }, + { url = "https://files.pythonhosted.org/packages/0b/a3/768b560fcc4156685cb563d922b217810cfa7bc135773367f62f1f9d2078/markupsafe-3.0.4-cp314-cp314t-win_amd64.whl", hash = "sha256:a18f38cafc329bac5e3c2b96c765b4c96d3d103421ed22ab7988c1e3fce27464", size = 14526, upload-time = "2026-10-02T23:06:08.276Z" }, + { url = "https://files.pythonhosted.org/packages/93/63/da554b4c97a6b0ea3229ca7fe8cbfb620be81613d517f482e85958550537/markupsafe-3.0.4-cp314-cp314t-win_arm64.whl", hash = "sha256:eba154571c16e032112afac0dc2dfe9e63c2ceb7aedd07bb7eecf2ce26d4dd4c", size = 14421, upload-time = "2026-10-02T23:06:09.402Z" }, + { url = "https://files.pythonhosted.org/packages/a9/30/54d11c8ca027114898cab97421fb39e4ffd9ddf47cdbc44df2ec76722da9/markupsafe-3.0.4-cp315-cp315-android_24_arm64_v8a.whl", hash = "sha256:737c9c3981998eba27f11786f84fddcbabc74068b72a4a1f454ea02094b57b65", size = 12791, upload-time = "2026-10-02T23:06:10.485Z" }, + { url = "https://files.pythonhosted.org/packages/10/6d/97c913e253a14bd3cd0e15a5c56d13203b823fa7ee32498342896a072dc4/markupsafe-3.0.4-cp315-cp315-android_24_x86_64.whl", hash = "sha256:489505b03f692c3f376394e49194fa7a7f9e8558d6e293a7056a0032b0c38163", size = 12527, upload-time = "2026-10-02T23:06:11.834Z" }, + { url = "https://files.pythonhosted.org/packages/26/f9/b86d032042a4d597d9e1997f0e5f63a3eedaf11258e0a05760b0a0a826ea/markupsafe-3.0.4-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:077293e425f28ec737dbcad442a71752e28f8ae27cde3d68acd1fb212091cd92", size = 11602, upload-time = "2026-10-02T23:06:13.122Z" }, + { url = "https://files.pythonhosted.org/packages/f2/dc/73c14c1eedf0ac5fa3292ba43435e6c49d2c2050f33cebde541f8f4807f1/markupsafe-3.0.4-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:9348cbb300d224fe3b89793262cb093504d4ae927004468463f745188a193e4a", size = 11817, upload-time = "2026-10-02T23:06:14.227Z" }, + { url = "https://files.pythonhosted.org/packages/8f/69/2c2fcaa5fcee22d72c7819c0d536fd181c74a688e6143845419579cd2863/markupsafe-3.0.4-cp315-cp315-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:b807e598953730f82e4eae3bd30f6a122cf6b31c398c6b504c0e04c13c170429", size = 11446, upload-time = "2026-10-02T23:06:15.574Z" }, + { url = "https://files.pythonhosted.org/packages/88/54/9e5ec76c62e6e2834d5a93623018c943e8b3bb41d663e3fd4c03303b9b85/markupsafe-3.0.4-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:799c39bdf5e2f1292fedd3009f7b3c9e760f10b2420cb9638d56920840ff6db8", size = 11719, upload-time = "2026-10-02T23:06:16.701Z" }, + { url = "https://files.pythonhosted.org/packages/96/24/3ec292b44064c16229e064d770b2625bd8ea941aa61f44905a9fa44942c0/markupsafe-3.0.4-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:ae9dcb8fbe244cb82f8a6458b455b927a03685e383d9bacf1ea5ce180b96dc97", size = 12075, upload-time = "2026-10-02T23:06:17.855Z" }, + { url = "https://files.pythonhosted.org/packages/aa/85/b64fdb1f304848518742136983c24e96d967bfb59a0ea160e92736901ab0/markupsafe-3.0.4-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4bced6e2a6dba6a28f7dd3c6ce14df1b2dd495923f16ea484cad03decd463b2b", size = 24656, upload-time = "2026-10-02T23:06:18.963Z" }, + { url = "https://files.pythonhosted.org/packages/9c/18/23997d4c65b355da6390d61cd56e0ab3befd6ba8dda25cb40c602bd0fa6b/markupsafe-3.0.4-cp315-cp315-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3882fb412298575bae3b9c46868251f15cc69307359f87bb1b382e53d6e5a2c9", size = 27737, upload-time = "2026-10-02T23:06:20.117Z" }, + { url = "https://files.pythonhosted.org/packages/d4/36/35998dead3c6af88c38265a56e58100211f036234ab88eb2283fd4cbce44/markupsafe-3.0.4-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:04e7902ba80ee4bac1d50a549606527a1dcf0476cd81403db41099d3b60ec653", size = 25003, upload-time = "2026-10-02T23:06:21.284Z" }, + { url = "https://files.pythonhosted.org/packages/82/96/ef49135ce260db4ca4a12b119ed468449cd248db6b1468e2112b546d7a2e/markupsafe-3.0.4-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:925f929d6b59a8b3f8b8c6ac363cd0af7eecc81efb3071770b3c6717c450a369", size = 23111, upload-time = "2026-10-02T23:06:22.524Z" }, + { url = "https://files.pythonhosted.org/packages/50/7d/83126e338bd88c17a220668235368ad719fd4638e426739858cbb8508f77/markupsafe-3.0.4-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f68edfc67aabac33708941f26f22a7b8e9f81429bc0cf249fcf7d66b23af8d19", size = 22403, upload-time = "2026-10-02T23:06:23.785Z" }, + { url = "https://files.pythonhosted.org/packages/83/dd/daf7e420de23c8206c365204e7b85e1251d8e19d34196a56336f316e5ed2/markupsafe-3.0.4-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:e5c802729725bd07e2bc3ab7b76dc7e0bbfc53129d8f1eb1c002c24cf774717e", size = 24083, upload-time = "2026-10-02T23:06:25.037Z" }, + { url = "https://files.pythonhosted.org/packages/19/3c/11eecdc06bc44ad5570350085b572ebf049e8f9a38d1ece6d76640b739cd/markupsafe-3.0.4-cp315-cp315-musllinux_1_2_armv7l.whl", hash = "sha256:55ffd6ce583d97dc71dc92e930324c8c0d25aea7e3ade6ae54ef77cedb096811", size = 22931, upload-time = "2026-10-02T23:06:26.328Z" }, + { url = "https://files.pythonhosted.org/packages/0d/9e/ac0fd77f2a726e56ecc3ca0235d095feace1358d1b822406c2a2ef26a4dc/markupsafe-3.0.4-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:2cb3dd71fc6be918ad4264346a8ed69485f9b7ed7bf35495d8e22807cd6b8bea", size = 24299, upload-time = "2026-10-02T23:06:27.742Z" }, + { url = "https://files.pythonhosted.org/packages/d7/09/c6bd842ad58ff5b3bc76eeed7e9a42a6f11adc5d090ec697b72c9672731e/markupsafe-3.0.4-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:94f5407f7bc64fa6463906b896f9904beeeb7dd8dc116ee8e9056c8714ff9916", size = 21948, upload-time = "2026-10-02T23:06:29.274Z" }, + { url = "https://files.pythonhosted.org/packages/a3/46/82f586711fed61e86faa1ee1bc317d68cd45a10c8bdbe3f7d1fdf9026ad8/markupsafe-3.0.4-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:2dad610540cb2e6272855c178f08ae9a1c7ac258a7fb71660553a5f104b42741", size = 23150, upload-time = "2026-10-02T23:06:30.583Z" }, + { url = "https://files.pythonhosted.org/packages/19/2d/2dfdce99318abbfa26925195fbc17db188c46a1ec6457be121b6f9cfeb42/markupsafe-3.0.4-cp315-cp315-win32.whl", hash = "sha256:03470d1a8268e692ecf79ecd565593e59d44219377a7ead61f1f1b94c1f7ff6b", size = 14269, upload-time = "2026-10-02T23:06:31.949Z" }, + { url = "https://files.pythonhosted.org/packages/5b/ec/6000fd82e8791e58fcd0456ec20f098957e2b03d5ed02eb73241a577c0ba/markupsafe-3.0.4-cp315-cp315-win_amd64.whl", hash = "sha256:d882a373d8093c2941e01291b7ced96e9cbe4781da9a7751ca7e6c70385e5214", size = 14496, upload-time = "2026-10-02T23:06:33.258Z" }, + { url = "https://files.pythonhosted.org/packages/bc/66/e73bd5016421d5d6e2fb6de7dd609f9de020942ac8c626526bd8c6eeaf82/markupsafe-3.0.4-cp315-cp315-win_arm64.whl", hash = "sha256:353bd63081912ab8cfa6a0c7d185934cdf8426f04c618bba6bc4b394f2069b67", size = 14361, upload-time = "2026-10-02T23:06:34.539Z" }, + { url = "https://files.pythonhosted.org/packages/90/df/cb8c3dc98d313a951df2f8968f44e4cb5643df6d3cab749a530ce2f7d972/markupsafe-3.0.4-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:c61750fadcd119d0825bcb7d7d675dd264dcc89cc05292aab5be68ebdbb374ad", size = 11760, upload-time = "2026-10-02T23:06:35.807Z" }, + { url = "https://files.pythonhosted.org/packages/d6/bb/4af9b3ca0753d654ac75f9531d5bd741bb77ca6e696f36807c475ffc099a/markupsafe-3.0.4-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:1c0df495a977d10460a94941799c72d5b5ab03d3858d949b55b5a66c8f371c99", size = 12108, upload-time = "2026-10-02T23:06:37.089Z" }, + { url = "https://files.pythonhosted.org/packages/3f/d4/b56429313aee5fd59b079c3df5615299959e25e7113eb6d8caadbdd7d38a/markupsafe-3.0.4-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:02fa4acbc6a3fc5c693c34d4dd8c1130b7fe99cc915181b0ddd6f72aeb296002", size = 25762, upload-time = "2026-10-02T23:06:38.419Z" }, + { url = "https://files.pythonhosted.org/packages/65/f5/34c181e891aa4f7d59c918584672e0c5eb7fffe76c1387d1246008bf4081/markupsafe-3.0.4-cp315-cp315t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:05295589e619b9bed252a86b532b8e27350abc372d18ba89b59375325e91ec1e", size = 28400, upload-time = "2026-10-02T23:06:39.819Z" }, + { url = "https://files.pythonhosted.org/packages/ce/b5/ad14694fd0ac9a5ce30bc6498f2999378f418583dd1679cca5a1b512957e/markupsafe-3.0.4-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:be6cb0c799abb0e2ba3e618e6d28ddddf7e485f6c2ce938dfa237daf3905072c", size = 25946, upload-time = "2026-10-02T23:06:41.381Z" }, + { url = "https://files.pythonhosted.org/packages/d6/a8/26b606445387d0ceb1eb1f21840094b84e4e3c3c3983d80d10b89823b490/markupsafe-3.0.4-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:26e9867520db70d37f7fb421a7f0d8adb40171011fb84ce869afa1a83370dfa8", size = 23634, upload-time = "2026-10-02T23:06:42.748Z" }, + { url = "https://files.pythonhosted.org/packages/39/a2/b8814de672f1f0094d498bf646f2fec9d6356b503d28ef500b71c5095377/markupsafe-3.0.4-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f03460ff076f70ab595bb45a0205ccea1971443575b6920c52e755dec2b3fbfe", size = 23488, upload-time = "2026-10-02T23:06:44.176Z" }, + { url = "https://files.pythonhosted.org/packages/db/c7/287223376fb73335a3cc5d6eb22c6ab01358cf33945a9c39c06b9dac3f4b/markupsafe-3.0.4-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:436e3ffc6310d3c41878c601db29098102fe5d8a467c49da4a4125254e0980f2", size = 25037, upload-time = "2026-10-02T23:06:45.646Z" }, + { url = "https://files.pythonhosted.org/packages/f9/29/4df8355e313426d19e62ba33e0253c009ca12a0894ee77d67fa67255361c/markupsafe-3.0.4-cp315-cp315t-musllinux_1_2_armv7l.whl", hash = "sha256:4e2c4809c14559aa7ef426f27fb35afbb38104c349a903bf8f3600456764bb38", size = 23543, upload-time = "2026-10-02T23:06:47.264Z" }, + { url = "https://files.pythonhosted.org/packages/71/e5/8377731e8495668dcc768f645e717df18318c841edaf023a99395f6da9b4/markupsafe-3.0.4-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:da2af0d7aebfc2074080d72efa6ab8317c62481ef1f896f65d9999c1c01f4494", size = 25282, upload-time = "2026-10-02T23:06:48.795Z" }, + { url = "https://files.pythonhosted.org/packages/ed/5f/373456e37ceb1478d657d6fe769cbe0a39f0a8dfc1548eeb19c471eefdd9/markupsafe-3.0.4-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:aa2c838cc024642cc04c6854232f32b43e5e22833dd11119c1766c7873b8370d", size = 22993, upload-time = "2026-10-02T23:06:50.31Z" }, + { url = "https://files.pythonhosted.org/packages/d7/93/2cbd5628435afb6f541bbaced4bce0c2edac4b09a142e6e928b8b0da9858/markupsafe-3.0.4-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:b91cc9d336957239ff200f30097e6fea2dc6d6fb3c81e853eaa09eac904fd894", size = 23712, upload-time = "2026-10-02T23:06:51.759Z" }, + { url = "https://files.pythonhosted.org/packages/81/99/157e10966b033b363aeda5263e82596ee232a0b1d082fdbf90aa417ff083/markupsafe-3.0.4-cp315-cp315t-win32.whl", hash = "sha256:e49fb0d1ce92cfa0cb198cc5b1b11cdf9d0638658e2a2db2687e39db7c87fc78", size = 14300, upload-time = "2026-10-02T23:06:53.241Z" }, + { url = "https://files.pythonhosted.org/packages/33/05/55884815414c9706a23deca150b72c25a62109e65b0b6ce232077802c719/markupsafe-3.0.4-cp315-cp315t-win_amd64.whl", hash = "sha256:4f6e0852a0283b1b1fd776eeb7b766a5f440b3e2bd31ab51af3b400585f3965c", size = 14522, upload-time = "2026-10-02T23:06:54.729Z" }, + { url = "https://files.pythonhosted.org/packages/92/f9/ecbde7149e95b8a0f18e16d5d747f7dc06049d5da2e4f77f6f5e4a1f46a8/markupsafe-3.0.4-cp315-cp315t-win_arm64.whl", hash = "sha256:39dbacefc411633db5b4378b066a9aca70a3d7e2922c9e578d825f844026eeba", size = 14417, upload-time = "2026-10-02T23:06:56.246Z" }, +] + +[[package]] +name = "opentelemetry-api" +version = "1.45.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, +] + +[[package]] +name = "packaging" +version = "26.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7d/fa/3944b40b07da9ce895c0e6303a5ab7d53da063554f534556b134a54d6093/packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", size = 313412, upload-time = "2026-08-04T18:15:28.737Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" }, +] + +[[package]] +name = "psycopg" +version = "3.3.9" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, + { name = "tzdata", marker = "sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b4/74/ff710399dfa9fe9b546c2f5a05ea2f9b9d1dc2145c0b59e53a3fa2013679/psycopg-3.3.9.tar.gz", hash = "sha256:87c1d85c3e0e88e811d3c0b3808f947bd967c6faf34af6cd86fd021f77793d6c", size = 171122, upload-time = "2026-11-12T09:04:06.548Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/52/5d/a7957d1b5484f8e5094a15b1a400929324f978b670bd4a95179e1a012ec2/psycopg-3.3.9-py3-none-any.whl", hash = "sha256:d2d7d04a1ce6dab4f5b27316bea3b52585cafa2f2d631e5b09dd69823f5c26f6", size = 219041, upload-time = "2026-11-12T08:58:18.454Z" }, +] + +[package.optional-dependencies] +binary = [ + { name = "psycopg-binary", marker = "implementation_name != 'pypy'" }, +] + +[[package]] +name = "psycopg-binary" +version = "3.3.9" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1a/15/35cd93a0bbbf80b2f47fdc572736a1a050b8eedfb463b7098ca4a144c813/psycopg_binary-3.3.9-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:96ef179795a800f7b8dc7c4abd14ab322cc4986726cfa6dabff552c3e16e446d", size = 4069799, upload-time = "2026-11-12T08:59:14.393Z" }, + { url = "https://files.pythonhosted.org/packages/a6/9d/7f2c869e905a1476c2d2a75b5b1f5c92b86fe54de398ee2e09dfeb4cea4c/psycopg_binary-3.3.9-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:4c064e4d9f5c6a59b975c6d7f6e2f03cab164359cfd3a592817db97f8b0f463a", size = 4118537, upload-time = "2026-11-12T08:59:22.302Z" }, + { url = "https://files.pythonhosted.org/packages/fd/d3/89e0c378206874afa1af7ac4b7ec01ed7c7d37b38124529e4aad9621f57c/psycopg_binary-3.3.9-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:79071f66f484d682b420f08386e835060b2338f23236d918a01a60281a807d3b", size = 4250697, upload-time = "2026-11-12T08:59:26.914Z" }, + { url = "https://files.pythonhosted.org/packages/2e/1d/76ec39728ef21f21b43a29987790509431393ee69adf5639978363390ca1/psycopg_binary-3.3.9-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:0953c1b94c73f97efce5b8fb1dad85cf5e4085b94902e439e27e6805ebc8be99", size = 3944426, upload-time = "2026-11-12T08:59:31.598Z" }, + { url = "https://files.pythonhosted.org/packages/d9/34/4e9e479697f249ad6ab8489b8ca06cc3e578306c4596a278df2368627934/psycopg_binary-3.3.9-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9f6f4108a2e1d55303dfbb41d0f3b16a0aac95232a24ac8eb3df03f56fcb83aa", size = 4159271, upload-time = "2026-11-12T08:59:35.996Z" }, + { url = "https://files.pythonhosted.org/packages/58/ad/c69d9aa809f0e7fbf892a8b993e1fd2774abfc7852102c931ff8cf0700fb/psycopg_binary-3.3.9-cp311-cp311-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:8fee8337812241ce26c6e16f73b2a20e94db643312c6901c00b57a0b2e203e6d", size = 3583287, upload-time = "2026-11-12T08:59:40.153Z" }, + { url = "https://files.pythonhosted.org/packages/4a/c2/689aa5cccb21c623f7e0506470dba9ed222b60b813c716861db495a551d2/psycopg_binary-3.3.9-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:c3dc32af4bed2339bac8110a2c5d65e23fe25d922e075f191e41f2b3a61adc0f", size = 3925250, upload-time = "2026-11-12T08:59:43.973Z" }, + { url = "https://files.pythonhosted.org/packages/bf/84/6825290efeea434c0d485fb07694f576626a565c0fb6b1d4ed7a5e1e63f4/psycopg_binary-3.3.9-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:5bd2e0315dd43b8bb28f4c124f91d9a8eb866d04bd66899ae5d82086f36ac0c2", size = 3620091, upload-time = "2026-11-12T08:59:47.729Z" }, + { url = "https://files.pythonhosted.org/packages/1a/7b/8e2cee1e7034bec74916ade25809d4ba3776d8b14ecead57af5bd327a856/psycopg_binary-3.3.9-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:87e5b145e1363aa6bad904c430e18c3434e7b61565197d71d42157e3084fd9b0", size = 3346805, upload-time = "2026-11-12T08:59:52.153Z" }, + { url = "https://files.pythonhosted.org/packages/5b/f1/e996e9aa6e88e149b720472a934d366765d9477c3e8520a1243d1ce4fc0b/psycopg_binary-3.3.9-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:b2582957ef09a0315fab23cab6ff6445ad73b850bd951a936abec58cb2f3f86e", size = 3651228, upload-time = "2026-11-12T08:59:57.546Z" }, + { url = "https://files.pythonhosted.org/packages/73/08/dc42ab0f86083ce04509464c2cdd8cf24568718ff90debf322dd7d551c75/psycopg_binary-3.3.9-cp311-cp311-win_amd64.whl", hash = "sha256:75dc9ebbad779969174e59422c71444c2bd8d0362d5758a7b6f500eff11aa4ac", size = 2925715, upload-time = "2026-11-12T09:00:03.157Z" }, + { url = "https://files.pythonhosted.org/packages/6e/0c/7fc92c3135ce195bb86052d18f9ef5f64b1592d8f3a5f1d90e9b49c72448/psycopg_binary-3.3.9-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:fcdb76adaab57fdd5b789b13b20699bffaf17000a4bbc0527327581cfdd55e3d", size = 4048935, upload-time = "2026-11-12T09:00:08.958Z" }, + { url = "https://files.pythonhosted.org/packages/f0/a4/e62d11a85fc1a3a49f95b308bd5e2299dfc11125ef87043f6dfc29297d0c/psycopg_binary-3.3.9-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:08689018e9169ca8e6769f5b3f2ce748442bda95b5f1ec260995a8ff63e6d6a4", size = 4111565, upload-time = "2026-11-12T09:00:14.788Z" }, + { url = "https://files.pythonhosted.org/packages/4a/89/d9ca02dfe30a6dc51e7796617dd69cc5c2e66bcc89ced44df4f4a3b5e402/psycopg_binary-3.3.9-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:e7e2e3543ac17cf5bb3eaf738606fc52bcedf993500b9fc8c55a4475a3731ef9", size = 4207484, upload-time = "2026-11-12T09:00:23.781Z" }, + { url = "https://files.pythonhosted.org/packages/4d/aa/f1b6e1cd71aeafa78ab33875adf0339818fe014cde197a1c0c7c419dd0b0/psycopg_binary-3.3.9-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a99f0b9a19ed7a56bf5d6776456b8f15f5364db8853b0f5d184db394a45c391d", size = 3913036, upload-time = "2026-11-12T09:00:30.144Z" }, + { url = "https://files.pythonhosted.org/packages/ae/fe/9e967bfacdda0fef48fee1d869b13de016d82d846a805745b0985ac94a5b/psycopg_binary-3.3.9-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b081348d8992af26e9b252f04876c286428418a6b7845d8d4caae2044b259668", size = 4132657, upload-time = "2026-11-12T09:00:34.401Z" }, + { url = "https://files.pythonhosted.org/packages/cb/b3/c6a9f0bca0fdb06cf408235b698710f400a1d6376ab77e5fec887115aaa5/psycopg_binary-3.3.9-cp312-cp312-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:66b20619acbd434e4e46d734a915768a1192db09754c2ad041d391d72f30e5eb", size = 3545187, upload-time = "2026-11-12T09:00:38.595Z" }, + { url = "https://files.pythonhosted.org/packages/61/24/0443e50d382d3f6dcc03530560e02a02646af6bd8fcbd5a60add68c80208/psycopg_binary-3.3.9-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:b7c4b2039d82f635311e41e7d392ff1bddd94a2447f9668c6531489cc86a8ce2", size = 3897551, upload-time = "2026-11-12T09:00:43.769Z" }, + { url = "https://files.pythonhosted.org/packages/c5/18/e576c5f50f4751ad9f1770134ad57ef216d00e5d79caa1c5b091f41275dc/psycopg_binary-3.3.9-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:3efe96cd98081b755ee3b0a50f2d35d9af55cb1ba462440a41048b9e7c6b9caa", size = 3577016, upload-time = "2026-11-12T09:00:49.375Z" }, + { url = "https://files.pythonhosted.org/packages/cb/c6/434e01b19af141540147427675c116b2205ea58e3ec99e26431edf2d0714/psycopg_binary-3.3.9-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:80ce081d2512ced75f1ca08ff80257a1288a3555079c5fa622164a0f9ed6533a", size = 3305336, upload-time = "2026-11-12T09:00:55.531Z" }, + { url = "https://files.pythonhosted.org/packages/eb/84/0ea715e106cc80a89aca36e34dd6685fa1ee75da9546d41a1d87356efb9f/psycopg_binary-3.3.9-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:30a95cb2b00b94b4ec4fd5d41de047598c60e0db26fd43bd9154152cc380b282", size = 3620366, upload-time = "2026-11-12T09:01:01.033Z" }, + { url = "https://files.pythonhosted.org/packages/81/a7/afe5fe01b4100454ea6543ac84c8b38a3713d6f27790253798ba50f2ef2a/psycopg_binary-3.3.9-cp312-cp312-win_amd64.whl", hash = "sha256:1ce1a6f04211626ca1a3deadee560235e8686e3888fb18f78d2be3e83bceabc4", size = 2907832, upload-time = "2026-11-12T09:01:04.735Z" }, + { url = "https://files.pythonhosted.org/packages/42/9c/68d2172aa2993b129edba644edbdbc7834ddb88f7d43dc1fac2626f59a84/psycopg_binary-3.3.9-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:b98ecad106cd48998517e03aaee56f9d88f8857e043b8e3dbc2aa7facd475db6", size = 4053851, upload-time = "2026-11-12T09:01:08.857Z" }, + { url = "https://files.pythonhosted.org/packages/52/82/f472e2df0b0f7b816efdd18dde10e8a980df74feb5e34564cb3d8aeeef67/psycopg_binary-3.3.9-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:e835af41e74176041d2290b167af92b74793b916ca3413598c39b535dd3674a5", size = 4114709, upload-time = "2026-11-12T09:01:14.257Z" }, + { url = "https://files.pythonhosted.org/packages/eb/0d/71abff2f3219cf61c790e45981ba6e4ff9b4c2f96855f5f89f7da41bf6fd/psycopg_binary-3.3.9-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:4b44a09bb7c92666aec8a00d5d390ff6f4e573d345ccde0f71b45597511449fb", size = 4210297, upload-time = "2026-11-12T09:01:20.266Z" }, + { url = "https://files.pythonhosted.org/packages/fc/b4/713b67741a31c3d93028276b2b634157fdfcf00417023f45bb4410de0ab9/psycopg_binary-3.3.9-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:180e4a99904d7a77f826fbb6dd16834bb3313675d8a6f055e39742fda00c33dc", size = 3915163, upload-time = "2026-11-12T09:01:28.02Z" }, + { url = "https://files.pythonhosted.org/packages/19/22/d67af2a2dd96603b381404d9ae657e3877c763a60cc7c5bf319162652334/psycopg_binary-3.3.9-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:366e2021a785afed9154f83f64793f662348a9ef244fef9779175c0906e8aacc", size = 4132455, upload-time = "2026-11-12T09:01:35.872Z" }, + { url = "https://files.pythonhosted.org/packages/60/c8/662b59cc3e9fb581af9f20d269035ce2a2020732584de05c4e17a3edf0ac/psycopg_binary-3.3.9-cp313-cp313-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:13bfe814718c8a1b9b656c0d754962e0027cc3e43630661825fe197babc99320", size = 3548290, upload-time = "2026-11-12T09:01:41.316Z" }, + { url = "https://files.pythonhosted.org/packages/ec/97/9d1d54a21e881a268a5bc00cdd12a0a87534de07d123d18887ee0ff7f3f6/psycopg_binary-3.3.9-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a0ed63b05046bc40d76109d95c757d3eac38488b17c68ae9e8160040d0ed0f89", size = 3898785, upload-time = "2026-11-12T09:01:45.019Z" }, + { url = "https://files.pythonhosted.org/packages/0e/85/8d7f1fe6161cb663374a06e2d16c408f6353e62e58bb48ff761bd95a028a/psycopg_binary-3.3.9-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:f85821eba1f8c27e080eba955eb9dddaa638f61e363b4f3b2266bd9ec4ff73bd", size = 3577036, upload-time = "2026-11-12T09:01:48.698Z" }, + { url = "https://files.pythonhosted.org/packages/50/bb/4482876d230fa2c330e28d22a135babad7a0f9b3446b54a153a9ffaf25b5/psycopg_binary-3.3.9-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:eb74f5299501f83f3ad7b8e99405ca451b77c74d65767bac7f46d22c4e9411ae", size = 3309862, upload-time = "2026-11-12T09:01:52.208Z" }, + { url = "https://files.pythonhosted.org/packages/4c/1b/f49175ca5bef792c4e3820690b8e81cdf7699f3eee3a7f388c434c04b808/psycopg_binary-3.3.9-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:14666a85aa330058929e4abedd940f754f0e5589efae6366d95c513288856fb5", size = 3621566, upload-time = "2026-11-12T09:01:56.531Z" }, + { url = "https://files.pythonhosted.org/packages/9e/97/06d96b1e9c1b2369cd9d7ada4c70f0649df7c542b8c5da5bb01bacf05eaf/psycopg_binary-3.3.9-cp313-cp313-win_amd64.whl", hash = "sha256:417c3fe0ac2079a82a8c72ba214a65c66c22036a5d2d8c24c77c5708a58938b9", size = 2907276, upload-time = "2026-11-12T09:02:01.257Z" }, + { url = "https://files.pythonhosted.org/packages/25/ef/2369abcb3d7789117bca1f028eeb69e2798237f5b6e5a7b4172eb113a380/psycopg_binary-3.3.9-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:6bc7e10d05f236f53b184d9592e8f3d22587bc2e7b964fea9f5d0de2b1142fe5", size = 4055684, upload-time = "2026-11-12T09:02:06.492Z" }, + { url = "https://files.pythonhosted.org/packages/d3/22/3a2f68ce0e414a6e76f09987f447f155e2ef8b79d13ea6cf4aaa74c941a3/psycopg_binary-3.3.9-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:e853041acf10de2dcb595167138dc9fc27de293d67caa1d80ed282ec27a28e87", size = 4118288, upload-time = "2026-11-12T09:02:10.849Z" }, + { url = "https://files.pythonhosted.org/packages/af/1f/7e9e1f8c00e98fcf9d8be2d4d2120106100db5886cfce807c5d01523d64a/psycopg_binary-3.3.9-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:c25fa1ee28f8fd73aecc5e8612ab9e5700682e8e23f9422437a1617016029934", size = 4215854, upload-time = "2026-11-12T09:02:15.024Z" }, + { url = "https://files.pythonhosted.org/packages/2a/d5/ba4839c38d9d35daa815cb18dfe462582f783ba83b9d932692bb903fba01/psycopg_binary-3.3.9-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:4992acd5a7479013d52615b8c23fdce9bc22f3cacbfb1007fa474e6b5ebe94c7", size = 3918359, upload-time = "2026-11-12T09:02:19.433Z" }, + { url = "https://files.pythonhosted.org/packages/f1/47/243682e14cac97cb7500625a2ca3a53195ddc39e4bb81a59f289286f23d2/psycopg_binary-3.3.9-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:eed1ac135d652e4454777afb4e4bb52cf88520bbfa2f30ae83066cd4df656697", size = 4140188, upload-time = "2026-11-12T09:02:25.013Z" }, + { url = "https://files.pythonhosted.org/packages/c5/4c/5b1a99f245c3a22bd3cca9760f0595e0bd26b4a7c0d5f36fe0288ddc3b2e/psycopg_binary-3.3.9-cp314-cp314-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:85b3892dbc4f5fb21880f82e3aed7329be6bee39fb58a0f059cbb1d0a382e98b", size = 3552025, upload-time = "2026-11-12T09:02:32.354Z" }, + { url = "https://files.pythonhosted.org/packages/c6/cc/32d34dd14d7215b987cb76ce72035963b85a9b4e75d3e3e78104abf7c831/psycopg_binary-3.3.9-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:4ba688a9402e3cc9d425e6ad20f97b96698f59f867279c265c1d0ca6df9dad57", size = 3907596, upload-time = "2026-11-12T09:02:38.276Z" }, + { url = "https://files.pythonhosted.org/packages/79/c4/ac9f35d331f987d83e5534f35d28f76aeac101eebaddc5c0c9f252a2d21f/psycopg_binary-3.3.9-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:300bd86d4b81d297e204a8ba223f54ec09a4b54fd069c32a74bf75b42860703f", size = 3587344, upload-time = "2026-11-12T09:02:41.864Z" }, + { url = "https://files.pythonhosted.org/packages/54/04/e91fedeeab7fe94df2364ad324c0de0e6ebd54b24f3dff396e24ffba9655/psycopg_binary-3.3.9-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:e01a4f4fd0e4beee23af30517123bdde838d53c3ac0ae594da019e36b3adabda", size = 3314235, upload-time = "2026-11-12T09:02:47.199Z" }, + { url = "https://files.pythonhosted.org/packages/da/fc/e522309105d4c1b1f8bfa7e887355a414c1c84e94e32e532a6595c5ded13/psycopg_binary-3.3.9-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5117a4745b3b850872140d3a66a8d83c55801916ae6e3cf502af0a794f64f9b7", size = 3626367, upload-time = "2026-11-12T09:02:52.842Z" }, + { url = "https://files.pythonhosted.org/packages/4e/50/643d5f523fa77a3b808e982716e7aa76da788218e40942721939c5e08c11/psycopg_binary-3.3.9-cp314-cp314-win_amd64.whl", hash = "sha256:109c5df5b0e5117e01a42d3b56a2f4ccd5431bd54d25efdfc89df095ac9f9605", size = 3009572, upload-time = "2026-11-12T09:02:58.474Z" }, + { url = "https://files.pythonhosted.org/packages/c1/81/06d36165c60e32d3909bf9ad036f4120284872ad00234ac384be20fcef5f/psycopg_binary-3.3.9-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:0b513957b283d181ed04961567b9893cae79309e23655d54c91cb8781ad81fc5", size = 4054822, upload-time = "2026-11-12T09:03:04.391Z" }, + { url = "https://files.pythonhosted.org/packages/4c/70/6c9eb0d0f1e124dbeba86dbd4c06b95bf15e7dfe60c0a3b91f6c7b45e237/psycopg_binary-3.3.9-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:a9ee20e3b314c1f36ec13093f1ea46161704a7304a6c334396318d36416bd330", size = 4117160, upload-time = "2026-11-12T09:03:10.7Z" }, + { url = "https://files.pythonhosted.org/packages/7f/84/99ecb47d6ef0752792b60b1fffd3739fae0605f4786aa9827646d1623f4b/psycopg_binary-3.3.9-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:0793764fac48b5f0bf4d7154e38c60def4fa0cce16caa60b737f770bd29016ac", size = 4214359, upload-time = "2026-11-12T09:03:17.69Z" }, + { url = "https://files.pythonhosted.org/packages/b0/32/2fbc8412c6d650886b201a0b1b2d522008d4a8858d885d2ca1b1f35df2d3/psycopg_binary-3.3.9-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:e51c7c493f07b51be56875cfa8a7674824749fa1cda3515339ca64e628f1b992", size = 3920287, upload-time = "2026-11-12T09:03:24.19Z" }, + { url = "https://files.pythonhosted.org/packages/cf/51/cc921a2ce634cbe8ebf3cb2b062d303d97afbf4ee941f8190003d867bea9/psycopg_binary-3.3.9-cp315-cp315-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e5af7a6d4ca7781c03f9f628ef83ff739de8a7e7e0ffe4b6e7a8c274caea6f81", size = 4141389, upload-time = "2026-11-12T09:03:29.754Z" }, + { url = "https://files.pythonhosted.org/packages/db/37/74fd196f755b979de8d2ad8d84f54afe0628036a8d88b63f7fd204e2f8fc/psycopg_binary-3.3.9-cp315-cp315-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e047c843fb5cd3c9ebc370bf9a9394cb97feb71b678f07f58419de6d1c6cb5a5", size = 3558765, upload-time = "2026-11-12T09:03:37.484Z" }, + { url = "https://files.pythonhosted.org/packages/37/16/096ce6aae0063f42b1d6ae6f6fe0276208fb929daa5405a92718cf3061b2/psycopg_binary-3.3.9-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:9452241b4684a6321c8e047f4b31a029823fafceddb0809827ec1d506784a3cd", size = 3907982, upload-time = "2026-11-12T09:03:43.975Z" }, + { url = "https://files.pythonhosted.org/packages/34/09/1e8063b591433174211908d9797c7d0e85304a11c92069f66ec66c2c741b/psycopg_binary-3.3.9-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:9926a6f98fbfbb47ad34fab6151d5e6de917d640a07e78cf07a91005593f7c65", size = 3586055, upload-time = "2026-11-12T09:03:49.195Z" }, + { url = "https://files.pythonhosted.org/packages/f4/04/206ac77650b2313b3e6b2fb0d00ba3bb663095586b824d350a1937738575/psycopg_binary-3.3.9-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:0f049ea20c87608eab3df8f055e8e29743a7af42f5e3e1bdb653611194fa64eb", size = 3322175, upload-time = "2026-11-12T09:03:55.836Z" }, + { url = "https://files.pythonhosted.org/packages/ec/27/22d7d9865c4722abc12be9a15be1f671624f7d440afb66cbd719dcb44a3e/psycopg_binary-3.3.9-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:6ab13f8174a0a63d0b9ec39ac27dd129a4d78f22099f146455b5c3a73957cfb2", size = 3629954, upload-time = "2026-11-12T09:04:01.437Z" }, + { url = "https://files.pythonhosted.org/packages/fb/4e/d066faaffcb5b9d0ef593c2903e767bdd22a12ee36e117c3f13d59cc5efb/psycopg_binary-3.3.9-cp315-cp315-win_amd64.whl", hash = "sha256:d5281f3453caebc911b2c5553398d59e217a8101f6b2596311256ba3772167fb", size = 3010099, upload-time = "2026-11-12T09:04:04.907Z" }, +] + +[[package]] +name = "pycparser" +version = "3.12" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/cb/27/eeb9f307bf07060f3d9f9aa0fb8c15b01bdfded0a941e4b2719c7f94cacd/pycparser-3.12.tar.gz", hash = "sha256:f03387877eab82ce01bbdfd0ba7252ee55a90b1c708d5129e2ce915475cf1db6", size = 158785, upload-time = "2026-10-22T13:40:03.56Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b6/ae/315bbeee126a769cbde43cf4908acb4b40408d8bf8bbf334dd7368d8dadf/pycparser-3.12-py3-none-any.whl", hash = "sha256:a076f3f489b39b43ed13563a1dafe42447445bec2e294154ec5c57fcdda4c85e", size = 62600, upload-time = "2026-10-22T13:40:02.021Z" }, +] + +[[package]] +name = "pydantic" +version = "2.14.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "annotated-types" }, + { name = "pydantic-core" }, + { name = "typing-extensions" }, + { name = "typing-inspection" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b4/fc/1203d011145c98ddce3cd2f505bb54375ef8d43223053df6bfcf3c746f46/pydantic-2.14.3.tar.gz", hash = "sha256:1054f237f4d4733e5a30e1e2333bd33a2004ab9ab1510bd053a9a31bb48e232d", size = 925636, upload-time = "2026-11-05T09:17:04.686Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/72/b8/b864503789ef5c58597d2a7b4adbee62c26440ab1e682581fc6838df8947/pydantic-2.14.3-py3-none-any.whl", hash = "sha256:3f7b347782ab7e4cf4c798496ae3a82787d9f21ec12676a9c564355eeef8daa8", size = 494071, upload-time = "2026-11-05T09:17:02.426Z" }, +] + +[[package]] +name = "pydantic-core" +version = "2.50.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9c/0f/34f9ce4ba701dd0b815033ef94d99b56f66200e578ee6052aa3ac26f064e/pydantic_core-2.50.4.tar.gz", hash = "sha256:aead3b74b68396bf0feab5d57e050b730ded7df55853c1e048a87e00aaf033c6", size = 522249, upload-time = "2026-11-05T09:15:26.774Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/df/00/85e80811834d7cbd9bc228f9b5cdf8ec0edd69b55351ad720aac8c412d8c/pydantic_core-2.50.4-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:3e547ceec1da7382f01f9e13963023e53367a71802c88778b21b9645a077cbdf", size = 2170584, upload-time = "2026-11-05T09:11:41.139Z" }, + { url = "https://files.pythonhosted.org/packages/a3/f1/438de1fb99d717dcc6521922478dc16ef7b757302d4fc1f7faba3aaeac09/pydantic_core-2.50.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c813ada7a651193acda85b6bc1cf12abd4b37cd25c7c6a75d7183512cc374969", size = 2128471, upload-time = "2026-11-05T09:11:42.65Z" }, + { url = "https://files.pythonhosted.org/packages/b7/74/f21ab568c6d3f315988b40e53f809c95b63fafc5403332963aa6dfc2c054/pydantic_core-2.50.4-cp311-cp311-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:57fa0a9490785139f1a4e4f43891830d55dfe4408845c0c9cb5eff4aeaf75f69", size = 2281509, upload-time = "2026-11-05T09:11:44.359Z" }, + { url = "https://files.pythonhosted.org/packages/a1/42/24ed3ea8e2fb6463c9ba5b8b1f089e69040905c7fd81dcfa6f52fcc692d5/pydantic_core-2.50.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:30d4dc35bc0eea52202a90b3820445ee0072c820241bfa710a623a078c9b267b", size = 2128064, upload-time = "2026-11-05T09:11:46.01Z" }, + { url = "https://files.pythonhosted.org/packages/d6/d1/44f541b2c18a46df6f18281a557acefeb5bbf0733a0b80b0a5e835e10ee4/pydantic_core-2.50.4-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:789f88dea57841cdebef392b5d6e90444d767117e9ff2e0d9172df5c9de6690c", size = 2214472, upload-time = "2026-11-05T09:11:47.503Z" }, + { url = "https://files.pythonhosted.org/packages/bd/1b/e9a9ad8733e8051abca9e4acce37ba3ddd13930fd3b8730f4c7816fa979a/pydantic_core-2.50.4-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:d690121e80ab16e623415351ab24713534d4e500b3cadff216409cb6826063d4", size = 2401153, upload-time = "2026-11-05T09:11:49.403Z" }, + { url = "https://files.pythonhosted.org/packages/79/84/d88e8e6aa42d4d677666d6625db9177ad6851be9e7564a25aeb0b0cbcaf2/pydantic_core-2.50.4-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:b42f64825f5d750228f08318a9bf4d723b7ecb4c472aedcb3013c3ec2dc1f949", size = 2453307, upload-time = "2026-11-05T09:11:51.118Z" }, + { url = "https://files.pythonhosted.org/packages/56/51/cbb7a1bc0196ff94d3478d265eed7449f811759988eb760d41f4edd0893b/pydantic_core-2.50.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:0574866e05f6adeecc520d87e87dd06210c0a51706341f6ef8421572f5a64444", size = 2253434, upload-time = "2026-11-05T09:11:52.997Z" }, + { url = "https://files.pythonhosted.org/packages/9e/04/206b4881d631033ae88f005da6e11bd610c850e1850217342c03053d253b/pydantic_core-2.50.4-cp311-cp311-manylinux_2_31_riscv64.whl", hash = "sha256:dcf2c7eaaa4cafe8e49b017e5bb49e76e084ab6f0cd712ee4019c812b5cf68b8", size = 2279365, upload-time = "2026-11-05T09:11:54.822Z" }, + { url = "https://files.pythonhosted.org/packages/a1/7c/d815b5a3f83069b283d3b6a2e61de6e14baac3b20c6cd3418e9e629551cf/pydantic_core-2.50.4-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:3b8ee2589a082739c522c1fe4be227412fcf108b903abb6672ae2f5570558882", size = 2319407, upload-time = "2026-11-05T09:11:56.46Z" }, + { url = "https://files.pythonhosted.org/packages/ee/00/c9a483276d1052d5142e1e01eccac97d939f83a3a3fd94c4766495a9b807/pydantic_core-2.50.4-cp311-cp311-musllinux_1_1_armv7l.whl", hash = "sha256:aec3c2d741a8e3ee993de7f95f37afb51e31b169c95dbd29da4cf6688f340914", size = 2489900, upload-time = "2026-11-05T09:11:58.102Z" }, + { url = "https://files.pythonhosted.org/packages/2d/b5/8cd8ee29a1d63ad47f95593384df92476cef6896c644f280db0748b8e76b/pydantic_core-2.50.4-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:8923fcd49f875e8a0448d7223d1fdf1a9973ae2d1f20d4158753ceb8909facd2", size = 2497732, upload-time = "2026-11-05T09:11:59.928Z" }, + { url = "https://files.pythonhosted.org/packages/60/31/050a48c0c373df16442ac07f3fa167414bb0e22f54a3e886f6d6cb7ad1d4/pydantic_core-2.50.4-cp311-cp311-win32.whl", hash = "sha256:fc04affef30be98c1f36f0c422a4061ef618fdc1dde79f5ad5458dd496fecffa", size = 2132347, upload-time = "2026-11-05T09:12:01.928Z" }, + { url = "https://files.pythonhosted.org/packages/c6/06/cebeeb7a8e87b42a3d8bc189d0d400e47df5d1736cb326764bae8a74c433/pydantic_core-2.50.4-cp311-cp311-win_amd64.whl", hash = "sha256:15bece43a02ad543c621c8305e67dedb5f27d378c5ba741e5a2c36523f8ef37f", size = 2255970, upload-time = "2026-11-05T09:12:03.888Z" }, + { url = "https://files.pythonhosted.org/packages/46/db/5b4bf14347da658c994483043fbabffedcab98929c41c261ec168c3c1f87/pydantic_core-2.50.4-cp311-cp311-win_arm64.whl", hash = "sha256:e498900bfbf7ddddd862f810440c09e9b81674739e8a11d619b40906dccd4a9a", size = 2196799, upload-time = "2026-11-05T09:12:05.389Z" }, + { url = "https://files.pythonhosted.org/packages/10/bf/d1f6b81709538f831ebe1c42f50fb89db3dfda06f9e9b1ea24e90fc69209/pydantic_core-2.50.4-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:32a991aebd165f227b7c7c60bb9d66c2c7de9c24308552da264c9938fde0f8d6", size = 2231444, upload-time = "2026-11-05T09:12:06.969Z" }, + { url = "https://files.pythonhosted.org/packages/c1/39/6618e541658d5a687a8d4962fc304350073a8f322bc4c62e8ed4c2d514d6/pydantic_core-2.50.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1e20cbde2b6deb33a51d08cd168454dd9044ec7d4474056f4d98d63f51578783", size = 2108048, upload-time = "2026-11-05T09:12:08.85Z" }, + { url = "https://files.pythonhosted.org/packages/d9/54/1c941fffa4e14bfc9ab0cd4977075f0e03201447856130d08a33cd45e47b/pydantic_core-2.50.4-cp312-cp312-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:8cceae48ae7f94990c2f4e36291e9ec9868735e8b0f19e4489a17b0422338466", size = 2256866, upload-time = "2026-11-05T09:12:10.495Z" }, + { url = "https://files.pythonhosted.org/packages/61/a0/8028ef3e014be522ce43060aeac82a5be2288215e660866f5e6260acc123/pydantic_core-2.50.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:16902a147b3da4840612164a5e67947104d63e978f7a57c395877a5e26690b9c", size = 2125682, upload-time = "2026-11-05T09:12:12.278Z" }, + { url = "https://files.pythonhosted.org/packages/c3/f2/b98bb73b1734ec4e42e786a766abc24f3c89620a0ddbaf8aa14e4b4c628c/pydantic_core-2.50.4-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:d6e3485a5e5c01fb5339c1ee3d4b9e21e2135a2a9d44caafb71acd994487ee7c", size = 2197108, upload-time = "2026-11-05T09:12:13.873Z" }, + { url = "https://files.pythonhosted.org/packages/f1/d1/7a7142786781400143e8806633fe5b65e2d407c311041fc9494490f05b18/pydantic_core-2.50.4-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:629eae995185540406e3635df5d5cf1d44f19ea240840b835d3f44541ff694d8", size = 2380521, upload-time = "2026-11-05T09:12:15.539Z" }, + { url = "https://files.pythonhosted.org/packages/b5/34/cf710ca48d4498b04a3ea605d45892675dc2b14a94a25121a8d03f56d3e9/pydantic_core-2.50.4-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:41b2cd8b29dbb5a4c9828a70f50d1abfc92011115c813213d3a91205c6f731b3", size = 2457436, upload-time = "2026-11-05T09:12:17.447Z" }, + { url = "https://files.pythonhosted.org/packages/91/23/e0c6e3cd09a0ac809953fea698c816b9f03bf0b35b6820c9553e4f5d85a8/pydantic_core-2.50.4-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c81d98e27d9d9261909dcccab1ba5d6ea1c98b0bb9470e368604614fd1d36ddd", size = 2261727, upload-time = "2026-11-05T09:12:19.097Z" }, + { url = "https://files.pythonhosted.org/packages/f9/00/292a0ed96d5d2d6edb49468ef481336e5b7e54f13435d73b7c912c891c23/pydantic_core-2.50.4-cp312-cp312-manylinux_2_31_riscv64.whl", hash = "sha256:ca83a32b2b41653d89f09a3d22b770bca96da72273bef8f7a68136bdd1e8b823", size = 2262071, upload-time = "2026-11-05T09:12:20.78Z" }, + { url = "https://files.pythonhosted.org/packages/f8/36/d4690faf8c082eacf7754e52ab6bebe1bc73b167272e28699c00480ee908/pydantic_core-2.50.4-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:817953730e4a73a09008b010c4a42396cefe799616a22df2ac21d3927b3080cf", size = 2298931, upload-time = "2026-11-05T09:12:22.614Z" }, + { url = "https://files.pythonhosted.org/packages/21/17/b180af6d17cf6c8e0d3d2661fc501a4a40959744ca4947d6ad0db81b1416/pydantic_core-2.50.4-cp312-cp312-musllinux_1_1_armv7l.whl", hash = "sha256:664e74848c2f5fc27db8505fe24e1ecd3ac669412913bf73d176916f86cc08e2", size = 2474285, upload-time = "2026-11-05T09:12:24.842Z" }, + { url = "https://files.pythonhosted.org/packages/6e/bb/7e44d4ac6e1292f1859384c688713045bdf5448e0635c49c003d2be3bb6c/pydantic_core-2.50.4-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:219114f8dcdcbe4720d82ef016b1287ce5a0a67d7c69ca61524eb72e82aac344", size = 2498172, upload-time = "2026-11-05T09:12:26.434Z" }, + { url = "https://files.pythonhosted.org/packages/d8/84/5101f35294579c4bef7dc32fd4f097d91eedac2e195894266bdabc1e6dfd/pydantic_core-2.50.4-cp312-cp312-win32.whl", hash = "sha256:67f7cc397e1d5556a801d1cba74de0d27d827eb242e6c036c0ca273c745414f1", size = 2119592, upload-time = "2026-11-05T09:12:27.971Z" }, + { url = "https://files.pythonhosted.org/packages/82/88/d438a8fcf3738e9ff2670f724047ca3893ec899bcd5cdfc077a2aab133c6/pydantic_core-2.50.4-cp312-cp312-win_amd64.whl", hash = "sha256:ea2f61b0bc12f3592288503961b764579dea0658852d96a0b3d823614d808821", size = 2264064, upload-time = "2026-11-05T09:12:29.538Z" }, + { url = "https://files.pythonhosted.org/packages/77/d4/4a0c73dc3ef9e50b122b8c3527afcded15a44838f1c9668d2d4b72cc09f0/pydantic_core-2.50.4-cp312-cp312-win_arm64.whl", hash = "sha256:32d6dda86383645ec428ea64dfc277036f5cbc60a72238eab28b91a3fdb9a113", size = 2167792, upload-time = "2026-11-05T09:12:31.103Z" }, + { url = "https://files.pythonhosted.org/packages/1b/21/39f8d97e7ea8e3083606ee9bb1d7f3ec70ded780bb6a872aad76c7eb08b2/pydantic_core-2.50.4-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:0f87ae9db5ba8d8de40dcb93982cf8dd544e6552a80d3345af51941cc2146b80", size = 2232841, upload-time = "2026-11-05T09:12:32.617Z" }, + { url = "https://files.pythonhosted.org/packages/90/a9/fc89a632331882c4cb91b949003418e6f5085ddcf2c9b875d499682bca91/pydantic_core-2.50.4-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:1239daaf063e62213ca1f34d96663900bd7510c42a786e843fd328af70e46445", size = 2108326, upload-time = "2026-11-05T09:12:34.419Z" }, + { url = "https://files.pythonhosted.org/packages/5d/6d/4f6d00e9e4ba2a7bfb206ae49cb32a3ea90c4d658e62f8775277d75e8291/pydantic_core-2.50.4-cp313-cp313-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:1afefe44ec042fbabfb4483ea258c04cf75ff4ff328d754f09b321fdaa232aca", size = 2256276, upload-time = "2026-11-05T09:12:36.212Z" }, + { url = "https://files.pythonhosted.org/packages/b3/b8/936cb0d85a4082e902c7397db0f05c4372eac08372c8bd2d0b43088fcf17/pydantic_core-2.50.4-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:a9ee990bf2cfbd81574c5d4f9f6c9d480a14b5b43d2c4f2ca13f4c6f48089394", size = 2125469, upload-time = "2026-11-05T09:12:37.913Z" }, + { url = "https://files.pythonhosted.org/packages/66/a1/f3b551ce233dcac73286b8b2ae45c23232a9f41c68663e2dcce4bb2dbcfa/pydantic_core-2.50.4-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:ab2822bcdcefb54d1e8ca29f5e3ec3afe160fb794bb3a3a73b09d11ed2671104", size = 2196397, upload-time = "2026-11-05T09:12:39.725Z" }, + { url = "https://files.pythonhosted.org/packages/3d/93/a8a6e7e20826567a73e6f52416667698aa3de704804d7a49d25272246af4/pydantic_core-2.50.4-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:0001d6920e3a5d92758cda460d6dc9f918a78ad6d5d092f1c8b5395e6b775356", size = 2380442, upload-time = "2026-11-05T09:12:41.196Z" }, + { url = "https://files.pythonhosted.org/packages/aa/ba/921d90c9d8ddfa653a35a92f2bbdcd650a9493f5c43f39cdfe4c56659cfa/pydantic_core-2.50.4-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:ad92d255a165cde5f9882ff69699eaf5495e0a1f32e97566bbbb80f11e46781f", size = 2457747, upload-time = "2026-11-05T09:12:42.723Z" }, + { url = "https://files.pythonhosted.org/packages/2b/c0/1c8f2c8f1b03d3fe2fdd7962df8f5a744fe48c90b4c49615e4eb77d04141/pydantic_core-2.50.4-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:fb2bb5b557080da398b866408117d98fe9731a12334afd0cdff221b458cdc5dc", size = 2260946, upload-time = "2026-11-05T09:12:44.185Z" }, + { url = "https://files.pythonhosted.org/packages/07/ab/5b78a78f0c0f11c8b54fac214ed49cbb4795c34881aa5e5a15715917936f/pydantic_core-2.50.4-cp313-cp313-manylinux_2_31_riscv64.whl", hash = "sha256:92f8f63df729061bb14558ed740e7a222f6e2aa6c2e6a5bcfb4e706676562049", size = 2261921, upload-time = "2026-11-05T09:12:45.706Z" }, + { url = "https://files.pythonhosted.org/packages/b3/e8/dd5d154cf3401f836d8754fdc1b82ecadd37944e4355d855e5b54c7d8ae5/pydantic_core-2.50.4-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:2a60ec2a57ac3ef3767e526e9bf706ec75aa3d79c4ea134d9d4fcf7c62a297a7", size = 2298475, upload-time = "2026-11-05T09:12:47.183Z" }, + { url = "https://files.pythonhosted.org/packages/b7/49/af059d9c4483cba168b17e5f84f1090a3e4547a02fc7698ebc231d48298a/pydantic_core-2.50.4-cp313-cp313-musllinux_1_1_armv7l.whl", hash = "sha256:a2f8716344bbbd10443391be0b1f2003b34949e3c4e6883005c2bc498ab6b64b", size = 2473226, upload-time = "2026-11-05T09:12:48.785Z" }, + { url = "https://files.pythonhosted.org/packages/71/ba/4e8cc3064e8bc2ea272cf80dfc57fa4e455f6835c1def21609a9b4f94135/pydantic_core-2.50.4-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:b300a30304c4c6aeab03ed06809819d9eceacdd58441d3c7dffe41edfd006091", size = 2498764, upload-time = "2026-11-05T09:12:50.316Z" }, + { url = "https://files.pythonhosted.org/packages/bf/96/0878499cfa88eb0b07762b488d3cc1b64cb156a4905db99a0d12096b2e17/pydantic_core-2.50.4-cp313-cp313-win32.whl", hash = "sha256:ef8a9ddb2e2a4eae4abb72dc0710eca6c2726779b0664bd10c3ce9fcfaed8c4e", size = 2119158, upload-time = "2026-11-05T09:12:51.834Z" }, + { url = "https://files.pythonhosted.org/packages/e7/e0/95b651213e79ffe0cbee855590bf5cfdf8e3a0d90a7fc73a080e63f7cc38/pydantic_core-2.50.4-cp313-cp313-win_amd64.whl", hash = "sha256:4c29b8f2d6417069bb1f257e6b9113f5d64dc2f554cc200ea90b4fe2c5cdb733", size = 2262887, upload-time = "2026-11-05T09:12:53.282Z" }, + { url = "https://files.pythonhosted.org/packages/08/d3/c3801dc75844a0b13d000bd575bf1b3b3a8aca9f63d19e1809f69c9c5121/pydantic_core-2.50.4-cp313-cp313-win_arm64.whl", hash = "sha256:a0c5210d038418a115e7cf8706bfa611bd14add2f5787274dba45aadca3155e0", size = 2167878, upload-time = "2026-11-05T09:12:54.677Z" }, + { url = "https://files.pythonhosted.org/packages/ee/ed/c9a4982ac3bbc78f27498d9efb85b3dabd739a1724db53c35cc4c018e1de/pydantic_core-2.50.4-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:5c074454dc6d4f6f4ba6561a56bf33a14db7651d882a5a5321ba3ae8868e082d", size = 2236841, upload-time = "2026-11-05T09:12:56.111Z" }, + { url = "https://files.pythonhosted.org/packages/56/32/92c174c17bfc5fc52d0c064e6a7969a727731e25829ede752fba8bacce0f/pydantic_core-2.50.4-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:a4bb174bd65f795c39ad6642d9d5bdc43351b306b7d0a654ab0d0abb38be245f", size = 2108348, upload-time = "2026-11-05T09:12:57.638Z" }, + { url = "https://files.pythonhosted.org/packages/cb/cb/9f637d424a04d3edce7dd527da941950cce05a74b025eef3d54427b86c8e/pydantic_core-2.50.4-cp314-cp314-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:0ec20aca2b067369913716847f7dfe5f4dddf16a46965b7a70bbad5defaaba86", size = 2261331, upload-time = "2026-11-05T09:12:59.154Z" }, + { url = "https://files.pythonhosted.org/packages/91/ff/1117a3cccabb67305bd98d992a84eaf275939a9a043b4f14126ed7252e4f/pydantic_core-2.50.4-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:70dbc9f83c41f37a4faa62dae5203853847223a891da446f48ef2efcfd5df806", size = 2128667, upload-time = "2026-11-05T09:13:00.614Z" }, + { url = "https://files.pythonhosted.org/packages/93/45/6de1b4a6e8c415cd547f90d1408a711e7975116423e3eb3046061c62d7c7/pydantic_core-2.50.4-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:3de6c2a4df2af0ac9ab4dc1488746fe8b1a90e27955d870d9edda3187d20092b", size = 2198183, upload-time = "2026-11-05T09:13:02.259Z" }, + { url = "https://files.pythonhosted.org/packages/d0/bd/c6e64c315d35cc0783a0ea033a3dca062bc368905d0217eab6f6f63007de/pydantic_core-2.50.4-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:3a48a5254d15a0ad050318bfc7a9566d4ec740118187e8f303e47a6840287eb7", size = 2386279, upload-time = "2026-11-05T09:13:03.988Z" }, + { url = "https://files.pythonhosted.org/packages/33/ab/0d56280c89d3841381e9c699c3fa80e3dd3288edf5e7fe4d149136835dca/pydantic_core-2.50.4-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:0af56dbf8822ba9f4efcbbfdc15478f8b6fb08f1609860cb50aa2cc8476b3c34", size = 2464343, upload-time = "2026-11-05T09:13:05.98Z" }, + { url = "https://files.pythonhosted.org/packages/56/9c/621ad8f88590a92a086b1168dce09369d9c5e079e2e635e6646d248af55b/pydantic_core-2.50.4-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f1d62fb172db35c6478c9323da34ff37d1f3d37d7d44337a9d94ba8c583e5730", size = 2265388, upload-time = "2026-11-05T09:13:07.808Z" }, + { url = "https://files.pythonhosted.org/packages/f3/7b/cef68a667bf29b86e293a80a601d488a84c8f45508915ad6201fcfe1a798/pydantic_core-2.50.4-cp314-cp314-manylinux_2_31_riscv64.whl", hash = "sha256:5c1013647be741647895c102831dcf79c34209662dbb683df9efb864417ed7d5", size = 2267012, upload-time = "2026-11-05T09:13:09.273Z" }, + { url = "https://files.pythonhosted.org/packages/4b/9f/3ae4d163d8feda2b52de88b5cd96b1c40f79d11503003b061136d2ece6ab/pydantic_core-2.50.4-cp314-cp314-musllinux_1_1_aarch64.whl", hash = "sha256:aeb2e123cbf978a905e9f55155c1b8316fbbfa7cf64d04521fe174bab302d100", size = 2300478, upload-time = "2026-11-05T09:13:10.758Z" }, + { url = "https://files.pythonhosted.org/packages/e8/72/41881d31f6452430ed6792679c5391795910f0a27a6aebd424683e504ed6/pydantic_core-2.50.4-cp314-cp314-musllinux_1_1_armv7l.whl", hash = "sha256:523466eba8ee10f7480f3c2057563145978011c583130d2cc01fb1e7af808e25", size = 2474874, upload-time = "2026-11-05T09:13:12.188Z" }, + { url = "https://files.pythonhosted.org/packages/05/ef/099874dd6d5ca1e49987dea87eecc05610183249450b1fff883d87f1e8eb/pydantic_core-2.50.4-cp314-cp314-musllinux_1_1_x86_64.whl", hash = "sha256:c9e70012926e97069cdd09221861aff412aa94e4cac2e019055cdb79485b150c", size = 2502771, upload-time = "2026-11-05T09:13:13.981Z" }, + { url = "https://files.pythonhosted.org/packages/c6/07/a7d8615b8677bf69e24666bbce431299850c95a7b084649342582a1c3210/pydantic_core-2.50.4-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:e6da138a1ecc1341c8b788a5ee822670b03788e1f5decf7af9d461de6e508b8e", size = 1496509, upload-time = "2026-11-05T09:13:15.704Z" }, + { url = "https://files.pythonhosted.org/packages/ab/71/fdf2c25c3a4f89968263c1d896c933809ca8d2fb13443626648a17b2e296/pydantic_core-2.50.4-cp314-cp314-win32.whl", hash = "sha256:13b6dd62b5279f5b9d72f3bf918a35443ee8bd549241d9dc52d79a2c3b6d7016", size = 2122015, upload-time = "2026-11-05T09:13:17.09Z" }, + { url = "https://files.pythonhosted.org/packages/3a/9f/3554f0148b01ddaa5e678bf5fbce4679873534e5c0985cdf6c59c41dc9a9/pydantic_core-2.50.4-cp314-cp314-win_amd64.whl", hash = "sha256:b0cdb655fbd1562c2dfc9986f9103a106f7058cd0915afc6e656d4b1d73f3387", size = 2265109, upload-time = "2026-11-05T09:13:18.702Z" }, + { url = "https://files.pythonhosted.org/packages/ed/3c/196ef237d9ec5cca5ea9b773911dee1a387b9b1d4bfea05625b3e191a338/pydantic_core-2.50.4-cp314-cp314-win_arm64.whl", hash = "sha256:df1c174796cd63eb6b139f7daf783affe1f3ed659605850e843b24764c21bfc5", size = 2165745, upload-time = "2026-11-05T09:13:20.245Z" }, + { url = "https://files.pythonhosted.org/packages/36/12/0ee82a41a3995f0b531cf14e0b823dc2365ba4a22330670fccaa72753f12/pydantic_core-2.50.4-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:edbca8789fd10f0de534b660a6b4c71f1fd18039679c918dad392ab044bb37e4", size = 2223917, upload-time = "2026-11-05T09:13:21.623Z" }, + { url = "https://files.pythonhosted.org/packages/90/2c/592f8404abbcc65a70e6a802d1dc8f11412af44913e5146cf5c345370074/pydantic_core-2.50.4-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:33b21f69540a12c2053cd1d95766d8bd9667a3897f7c712a642de8aa37eb0865", size = 2087372, upload-time = "2026-11-05T09:13:23.16Z" }, + { url = "https://files.pythonhosted.org/packages/ea/1d/c7111757c84b5b8c19b1e39ceb5e131e6e48e14169ec6004e0f8f28f43f3/pydantic_core-2.50.4-cp314-cp314t-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:ffb616d8d55965839670301dc3bae3abacff560a7e137a89056058a8a9da4d96", size = 2275190, upload-time = "2026-11-05T09:13:24.634Z" }, + { url = "https://files.pythonhosted.org/packages/3d/ae/6c49cc9b8e66e61adee782d1763894bf64a357cddae82f725059b85bdc98/pydantic_core-2.50.4-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:6c5687b59b6ba0f663c4f2f15470f68507d6b45ccd3a19ee6d224f95cbee70d8", size = 2110343, upload-time = "2026-11-05T09:13:26.168Z" }, + { url = "https://files.pythonhosted.org/packages/ed/39/0ee5261d1daa9ad526371181c13696add0565251b2823f6e00a9a9af397d/pydantic_core-2.50.4-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:c733087ecf7dde06b1d071679bfd5f3ba03266ba77814c1c7253bc48c9adedd9", size = 2207887, upload-time = "2026-11-05T09:13:27.681Z" }, + { url = "https://files.pythonhosted.org/packages/ac/b5/a0652c0e99590107e111088b6d059044380a787da9ffdd0b458ab4cd9453/pydantic_core-2.50.4-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:94733cb447c37b0ce6f71b39ca1288d5f966a084023a5617b4cc35a852586859", size = 2404171, upload-time = "2026-11-05T09:13:29.864Z" }, + { url = "https://files.pythonhosted.org/packages/a3/85/d49f0b8e09a0ffc40dcefb604f9e6020e0d61b51a5f64a504f382fa84c39/pydantic_core-2.50.4-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:b26f39a5be3cd91a2035818be3d0ffdf5282c3e1f5f53d3b80b7024021acee52", size = 2466049, upload-time = "2026-11-05T09:13:31.658Z" }, + { url = "https://files.pythonhosted.org/packages/e6/76/f2b04d7c53edfd8136053c812ea49914fbf4091196cb7baf9ea326fa2ff8/pydantic_core-2.50.4-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c856e439a9d54d514e81a7131229ba151cdf81df7c408e0f6c89340e5003dfe2", size = 2262062, upload-time = "2026-11-05T09:13:33.806Z" }, + { url = "https://files.pythonhosted.org/packages/24/60/016f14cea883adc33df90b8df220df934de49ded9640f45c8e92bb298494/pydantic_core-2.50.4-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:cbf0777d54672990b10cb8ca9b0523499e182d7e2ea39f86b138519a902aa601", size = 2263713, upload-time = "2026-11-05T09:13:35.337Z" }, + { url = "https://files.pythonhosted.org/packages/f1/3f/b05828e978512973e7e215bab69e65e70d223d6309a17bf48084a50692f4/pydantic_core-2.50.4-cp314-cp314t-musllinux_1_1_aarch64.whl", hash = "sha256:edc17549ab592e33cfcaf285f047bb75fcd98f608aa9309af1187fd736ce9641", size = 2305044, upload-time = "2026-11-05T09:13:37.043Z" }, + { url = "https://files.pythonhosted.org/packages/91/c1/fca6c5f623ac45ba284713c614b30173aa0794899a0a457f866fa6f5e886/pydantic_core-2.50.4-cp314-cp314t-musllinux_1_1_armv7l.whl", hash = "sha256:23a9ba564b2db709ff16eca990992ba95a19069972b34bff87c81d4b473cd755", size = 2483506, upload-time = "2026-11-05T09:13:40.524Z" }, + { url = "https://files.pythonhosted.org/packages/94/c2/ec41f68d1208e53e1a73ead940c050c4316bbb555ba42676a5e949fd529e/pydantic_core-2.50.4-cp314-cp314t-musllinux_1_1_x86_64.whl", hash = "sha256:41f4f8ae714e4fea1d635880f8a1af715ecf080eed4d13c5b04a0f3210f9c61a", size = 2512832, upload-time = "2026-11-05T09:13:43.361Z" }, + { url = "https://files.pythonhosted.org/packages/43/22/58583b86309f70cce854e0e77c412839a56ac6c682d6060f5794afeff315/pydantic_core-2.50.4-cp314-cp314t-win32.whl", hash = "sha256:601fce6cea9ddeaa85329e12e7f351def38d233075f42a3012b9c48071b02941", size = 2101977, upload-time = "2026-11-05T09:13:45.735Z" }, + { url = "https://files.pythonhosted.org/packages/6b/28/193bc0994f7fe15f2874c1dfe2f3bc7872aed8283ffda2cf05fb9a5a06b4/pydantic_core-2.50.4-cp314-cp314t-win_amd64.whl", hash = "sha256:22e874666bdbd96d6bf629d32cd8ab376fedf1fd62585b52a42b9fa9fa6c20b6", size = 2240461, upload-time = "2026-11-05T09:13:48.38Z" }, + { url = "https://files.pythonhosted.org/packages/00/ed/5615cfdd5620a4926440eb1a2b73db0dc895824ba565ccaa8d9eb3a8e974/pydantic_core-2.50.4-cp314-cp314t-win_arm64.whl", hash = "sha256:71395a43da5584bb70556f380387e15f845c0dcf76373c1afbfa0025737576ac", size = 2168505, upload-time = "2026-11-05T09:13:50.762Z" }, + { url = "https://files.pythonhosted.org/packages/6d/9f/e6673535165d965a11c1d5339f53995f90234019827eaecb41a57e6e463d/pydantic_core-2.50.4-cp315-cp315-macosx_10_12_x86_64.whl", hash = "sha256:7ac2769a7ddd661e07e26c12220adc31b17014c48234b2a5a88993b8d4109e09", size = 2241950, upload-time = "2026-11-05T09:13:53.055Z" }, + { url = "https://files.pythonhosted.org/packages/6f/02/65951efadbf7826e6a270843f97e3da2ef726de2b6d9cd7c5dfa4c48807e/pydantic_core-2.50.4-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:930ad463d3fb7a340d323bcc496ec32dae469ec9974c29ff569f19806b6b03b4", size = 2112412, upload-time = "2026-11-05T09:13:55.309Z" }, + { url = "https://files.pythonhosted.org/packages/c9/d3/4fb6e2e4a9e4951f1e05b198366ed5330e0874e83d52077e8b985350fe0e/pydantic_core-2.50.4-cp315-cp315-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:b867f9fd183d76977f810c626d539265183c25b2284762893a31e8d6cacc81c0", size = 2263220, upload-time = "2026-11-05T09:13:57.555Z" }, + { url = "https://files.pythonhosted.org/packages/63/83/42e70436c523357b49393b73f161f2741acf36003c8efd2f941d2be56bae/pydantic_core-2.50.4-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:49eb1241a969a5994db6880c18c012b6cbe2340343d8f529721571806583e500", size = 2134716, upload-time = "2026-11-05T09:13:59.413Z" }, + { url = "https://files.pythonhosted.org/packages/36/66/ed9b87f4751fd07e472c62cfe151f575abdf4c452fab943d35ba8efdc6c4/pydantic_core-2.50.4-cp315-cp315-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:477af785d1846e4e96bf56983b92ea7553aaeccdeb8acdaa55c7cee9eda0ae32", size = 2201901, upload-time = "2026-11-05T09:14:01.472Z" }, + { url = "https://files.pythonhosted.org/packages/2b/21/ff2e6ac7202b6d326e9f007c6082f6e6f3aaa063790ea2a355bdc985addc/pydantic_core-2.50.4-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:29358a8ca74e7d81158d14e2b10c904bd18773293ae3788716c0626fe0342347", size = 2389670, upload-time = "2026-11-05T09:14:03.431Z" }, + { url = "https://files.pythonhosted.org/packages/b9/34/e9348bc13d549641791a51843ed140fbb311d9066628e27477343412d5ad/pydantic_core-2.50.4-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:300753f71c73302e218124baf995f00058e085cd01869bd9610bcbd0bd4500c1", size = 2468951, upload-time = "2026-11-05T09:14:05.028Z" }, + { url = "https://files.pythonhosted.org/packages/ac/5e/145a02bf2b9f66981108caf6cc9e78917e31e4caca14d1e3ccd3ff2c7293/pydantic_core-2.50.4-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:26cb012c4b8ca9f847bd0ac15978bd3d0f55b050bfbe6c47355edfc7e945029b", size = 2272957, upload-time = "2026-11-05T09:14:06.587Z" }, + { url = "https://files.pythonhosted.org/packages/fd/38/b71c5b245e923f6cf144e948ed2a9d6b7fb97d8905784db8d860f5176b8b/pydantic_core-2.50.4-cp315-cp315-manylinux_2_31_riscv64.whl", hash = "sha256:9be1cfe715ecaa060ffd5d599ef410b94ef2697a0eed4cee562f788a2aa2175b", size = 2275028, upload-time = "2026-11-05T09:14:08.219Z" }, + { url = "https://files.pythonhosted.org/packages/ba/71/2504dacdc5cd3ea3ec5e68c9b6e097c979500bcff220b97046cc8ea3c1ad/pydantic_core-2.50.4-cp315-cp315-musllinux_1_1_aarch64.whl", hash = "sha256:c81e35862aced259177a537ce1a6264c3a97bae1ced184ca9dc10ea754563688", size = 2305447, upload-time = "2026-11-05T09:14:09.795Z" }, + { url = "https://files.pythonhosted.org/packages/2c/90/904233a6c148bcac9f30bb96a2761e5fb52682d0d6de31a40c74a3714ceb/pydantic_core-2.50.4-cp315-cp315-musllinux_1_1_armv7l.whl", hash = "sha256:b2f2d13239487cecaae98c9f4d5904ad0737643cdf8873c88ec6a78b12214f20", size = 2477852, upload-time = "2026-11-05T09:14:11.443Z" }, + { url = "https://files.pythonhosted.org/packages/72/33/1cbdcbf343ca23b507e967b21dddc4c8bf17a74c8b5cad59228c85ba4efc/pydantic_core-2.50.4-cp315-cp315-musllinux_1_1_x86_64.whl", hash = "sha256:e6b4b08d09054310a4dc389fa61ee22a7a5a292cb23ab8a985136ca8828bf924", size = 2506352, upload-time = "2026-11-05T09:14:13.165Z" }, + { url = "https://files.pythonhosted.org/packages/91/24/3ad9ea0876e6624c90967e5f1446e751b275cfdfaaf798a0d8e0b30025bc/pydantic_core-2.50.4-cp315-cp315-win32.whl", hash = "sha256:6619d49a89a15cd04334f76fec530c155923bfc60da74ff5d815a52629e1aa6c", size = 2127780, upload-time = "2026-11-05T09:14:17.52Z" }, + { url = "https://files.pythonhosted.org/packages/c0/3c/0582532b90a12492471977bdbca1317eca5144f6342ea581d2cee73ccd35/pydantic_core-2.50.4-cp315-cp315-win_amd64.whl", hash = "sha256:e5bd109d095aaae989a0463d5ef0fcc43e9ddd5de125e656d3c119a79e466380", size = 2270596, upload-time = "2026-11-05T09:14:20.955Z" }, + { url = "https://files.pythonhosted.org/packages/6c/50/967cfe4f7043a993c0c80cd3563c598b5281d2276aa775d0f6ff7f714271/pydantic_core-2.50.4-cp315-cp315-win_arm64.whl", hash = "sha256:6118e5a5550e36582e19bac1a403711a748f9f18251b054c326d3db02aaa7a18", size = 2170880, upload-time = "2026-11-05T09:14:24.822Z" }, + { url = "https://files.pythonhosted.org/packages/9e/71/3ec5bd8a82f792482f16d79fdbe8ce85aa71bf7147e556c5fc5f8546818d/pydantic_core-2.50.4-cp315-cp315t-macosx_10_12_x86_64.whl", hash = "sha256:d8201c9f9035520cdcc7dcad383b039ec8123969b87e01cf27c3dd883c02313b", size = 2233053, upload-time = "2026-11-05T09:14:27.942Z" }, + { url = "https://files.pythonhosted.org/packages/6e/2e/614dc37aedf8e9f811c1f2eedaf8eb09a7c196e2d137fe82bcc9d5662ca2/pydantic_core-2.50.4-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:1de7be9a66fc8536770481ab64a05aae5067c725f2b29a09543af00e6a417b97", size = 2090776, upload-time = "2026-11-05T09:14:30.281Z" }, + { url = "https://files.pythonhosted.org/packages/f9/14/aefc14e3e05013070ee959fc0b8703f6860a2776ed6e75b9c748f61aced0/pydantic_core-2.50.4-cp315-cp315t-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:789a6453e5ffd18a7ab6b8c3a0dd8403053829197ec258ecb90c604c21ffcc99", size = 2272481, upload-time = "2026-11-05T09:14:32.578Z" }, + { url = "https://files.pythonhosted.org/packages/13/c9/d56999aa7236dc9303091db2b1ef7303f0b022baf25ebf33cd200c0cb933/pydantic_core-2.50.4-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:6348ad12fa741bcc9c2f173e99fbf27cbc038826d8c31a4a7d836eca27878ba2", size = 2113069, upload-time = "2026-11-05T09:14:34.69Z" }, + { url = "https://files.pythonhosted.org/packages/b7/d5/a62da9e72f272f198f6118c5457332bbd4b9fdc4b77858448120569756de/pydantic_core-2.50.4-cp315-cp315t-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:d49127f137f871cde3c5650af33bbbdcee02679dae76e020902fa106f522b8ae", size = 2202754, upload-time = "2026-11-05T09:14:36.49Z" }, + { url = "https://files.pythonhosted.org/packages/37/4a/e7f21577f96e42ac3082cd014df398c1c913d482afac1c8ef17b9e039198/pydantic_core-2.50.4-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:2f5cc5bcb94063fbbdfd285a2b302da34af07491337c10bb35de1d5220fa1583", size = 2411472, upload-time = "2026-11-05T09:14:38.63Z" }, + { url = "https://files.pythonhosted.org/packages/38/ad/c57c5e13bbfd3404ec1af519764aadbc52ee01e39f9f9ae9d28317f982f2/pydantic_core-2.50.4-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:b99bed995ed7c41515c11fe2beb86f8a6cc298e5537cae2f736de2f982f74ef0", size = 2475330, upload-time = "2026-11-05T09:14:40.519Z" }, + { url = "https://files.pythonhosted.org/packages/6e/63/65cf0e1f1fd8cfaafee3c005712b8020e063b0f3e3571493ea68db5ec44f/pydantic_core-2.50.4-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:faa4e96385c820ce9d7f7a623486e23d4134ae3c9ba2071e44e0ab5a5a5002c4", size = 2265718, upload-time = "2026-11-05T09:14:42.379Z" }, + { url = "https://files.pythonhosted.org/packages/72/5d/fd9fdec9b25e2ef1f788970a84f749f0e28f166573c87654fd5387d8e5ce/pydantic_core-2.50.4-cp315-cp315t-manylinux_2_31_riscv64.whl", hash = "sha256:d6a166978f22f10cb91413f70519861605219346decf65bc79008f9257c94afe", size = 2273454, upload-time = "2026-11-05T09:14:44.286Z" }, + { url = "https://files.pythonhosted.org/packages/34/8c/19705c6d5eb72ff8c25006df8a375da7466176a5968781789e5415384f65/pydantic_core-2.50.4-cp315-cp315t-musllinux_1_1_aarch64.whl", hash = "sha256:a70d5effebd81ebd8e15a8aabdc7980832367b2b00c36543bac378977004cc80", size = 2314862, upload-time = "2026-11-05T09:14:45.97Z" }, + { url = "https://files.pythonhosted.org/packages/b8/fb/acefa27031aba2646b0d3026c4a1602e526489d39395ab17bc47f03234e3/pydantic_core-2.50.4-cp315-cp315t-musllinux_1_1_armv7l.whl", hash = "sha256:f8fd23653a252cefabea11cd041efd7b80bdf403e43a36dea53f9cb0aaa21f0f", size = 2479073, upload-time = "2026-11-05T09:14:47.526Z" }, + { url = "https://files.pythonhosted.org/packages/ef/e1/db08fa1e5edf1779fa0612f8d09f9030bdc513f593687c883cb781b86caa/pydantic_core-2.50.4-cp315-cp315t-musllinux_1_1_x86_64.whl", hash = "sha256:7646353a5a7c553c04167aca628e2550b538f492765b03ccf34321a560acc43c", size = 2521328, upload-time = "2026-11-05T09:14:49.042Z" }, + { url = "https://files.pythonhosted.org/packages/0d/51/bf1ec5b96c076d8d514b08f3bcffb3397df7a0fcc729eb960838a8bbe27f/pydantic_core-2.50.4-cp315-cp315t-win32.whl", hash = "sha256:65376dbe1ab4dbc768ca2b72b7c13993562c035f5925fd3bc7ff9c8c585c515d", size = 2107629, upload-time = "2026-11-05T09:14:50.891Z" }, + { url = "https://files.pythonhosted.org/packages/18/32/43d5db1824ec2314f737ff8d9962ff59954a74616d8656a8cc78790e45f1/pydantic_core-2.50.4-cp315-cp315t-win_amd64.whl", hash = "sha256:f08ee8248aad2d054e5bc4c73554d4505464698f6d754f16198dbc5764e9821d", size = 2244906, upload-time = "2026-11-05T09:14:53.056Z" }, + { url = "https://files.pythonhosted.org/packages/3a/c0/38c505004969c4641c3a077a8e72e354f02d5c06d8f51d7a103699704772/pydantic_core-2.50.4-cp315-cp315t-win_arm64.whl", hash = "sha256:da779ae50b46f3f7d1e1b5f362fdc0ad376a49fd55f6f3122dc2b6149936cdf7", size = 2179018, upload-time = "2026-11-05T09:14:54.448Z" }, + { url = "https://files.pythonhosted.org/packages/9a/18/2f6a25e9104d5af713d16671711927601da1f0db74e785be67bd590385c9/pydantic_core-2.50.4-graalpy312-graalpy250_312_native-macosx_10_12_x86_64.whl", hash = "sha256:c04e9d920e2674f54651fd260a15c5d2843526c73d5242ee4311325ddc9573b3", size = 2212591, upload-time = "2026-11-05T09:14:56.262Z" }, + { url = "https://files.pythonhosted.org/packages/4c/1b/ba8b721af10a7659e7fbbef320ff8eb55462557a72607858af5a9bd22cb1/pydantic_core-2.50.4-graalpy312-graalpy250_312_native-macosx_11_0_arm64.whl", hash = "sha256:5bc1811ef2b4d4ba63e8e452f6e332b6374bd1d2cbbfdf66826c8cb1f71dd10d", size = 2048167, upload-time = "2026-11-05T09:14:57.681Z" }, + { url = "https://files.pythonhosted.org/packages/48/42/3f8638e7d90bdd9a7c7f3e5084723af59e7f43f15a292e242d35624073ce/pydantic_core-2.50.4-graalpy312-graalpy250_312_native-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:0b059a7968b1911be5a2d9a8234827ab0bef9d1e465d4b42da525894143550e8", size = 2119548, upload-time = "2026-11-05T09:14:59.317Z" }, + { url = "https://files.pythonhosted.org/packages/e0/8d/4bfbacaf191f7939893d165e18eb301731fa3366c59a6e57336c4f168fbd/pydantic_core-2.50.4-graalpy312-graalpy250_312_native-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:bee28aab5a580eec673f7b68dfa8dece3dd37bd207ef8d22fafe23a8e9837296", size = 2279952, upload-time = "2026-11-05T09:15:00.907Z" }, + { url = "https://files.pythonhosted.org/packages/9e/3a/d405a50e02ea81cd95e93fc97f43d351eeaa1707c28aa6fb58a9f1c1efa9/pydantic_core-2.50.4-graalpy313-graalpy253_313_native-macosx_11_0_arm64.whl", hash = "sha256:71e03d2ea1a221d020cfc5b6cc8bbbedef23a06704c70fcf4d0afb42965b22d1", size = 2049324, upload-time = "2026-11-05T09:15:02.379Z" }, + { url = "https://files.pythonhosted.org/packages/8f/3b/03e7992115e17cae4131ecd71aadb8fd5e4a04cc2aead72c3c27e9b453d1/pydantic_core-2.50.4-graalpy313-graalpy253_313_native-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:09450778e3ab58d3f565899fcfbf6c82926e31af29e28e799d1d50941316e0cb", size = 2119802, upload-time = "2026-11-05T09:15:03.901Z" }, + { url = "https://files.pythonhosted.org/packages/e3/d5/b76fc647e473377ca6e693c21549ee3a4a7677e4962c28ae4659337c5114/pydantic_core-2.50.4-graalpy313-graalpy253_313_native-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:4eb15be588407148ef5937dc8d9256a71f6b115e6cddadb7aa20b6ee384680dc", size = 2280639, upload-time = "2026-11-05T09:15:05.374Z" }, + { url = "https://files.pythonhosted.org/packages/d8/18/3ca5b3b8ce7a540305e6856d013e9c6b9c0fef93258fef6038db0beb233a/pydantic_core-2.50.4-pp311-pypy311_pp73-macosx_10_12_x86_64.whl", hash = "sha256:39f489ce31272073e6e146f6781690f9c1ee8c126836e6403361ef91154d89fe", size = 2166960, upload-time = "2026-11-05T09:15:06.902Z" }, + { url = "https://files.pythonhosted.org/packages/a3/60/65d725001bffcde0170f6d37ae8bccce715e5311122eb6127f698115957e/pydantic_core-2.50.4-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:5b26e5f1793b96cdc60242bf38da86ff24a27a708aa396214cac9b534bf571c7", size = 2085636, upload-time = "2026-11-05T09:15:08.395Z" }, + { url = "https://files.pythonhosted.org/packages/ac/12/934cf1d44a3fee3c47231d4690dddee19264150c3aa59a3ddf66fa43454d/pydantic_core-2.50.4-pp311-pypy311_pp73-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:7210398a1607ad607dc73196e575b3148b00a333cbb602ddbe1b60ba54554f43", size = 2284621, upload-time = "2026-11-05T09:15:09.82Z" }, + { url = "https://files.pythonhosted.org/packages/c4/91/52248eee98d76f8d9239166d24928f805292df16729109f4f189cdb59be4/pydantic_core-2.50.4-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:2f42584e5785385f681163a42506cab0d51295e17599a648396c52a7046c1372", size = 2277673, upload-time = "2026-11-05T09:15:11.236Z" }, + { url = "https://files.pythonhosted.org/packages/9f/89/900a7970ef19843aa79522a95b461e9c365b7fedd7ee80ef28a84dae9a41/pydantic_core-2.50.4-pp311-pypy311_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:2039e323acee9abfec1fb5f661776e8965fe5928f3b7f8431900a774cba5c317", size = 2297354, upload-time = "2026-11-05T09:15:12.798Z" }, + { url = "https://files.pythonhosted.org/packages/de/ec/053d829437f70070cdd7116a0257cc0da651103328ff1e9e82954c45efd6/pydantic_core-2.50.4-pp311-pypy311_pp73-musllinux_1_1_armv7l.whl", hash = "sha256:71ade6d2e445839350d589ff99bbddfde16f3f32db28da5c894a09f99c8b2a03", size = 2469913, upload-time = "2026-11-05T09:15:14.319Z" }, + { url = "https://files.pythonhosted.org/packages/80/af/207c821cb0813e16d630660e0073491e3ab07370efaa6fa0b8b10fffb7b6/pydantic_core-2.50.4-pp311-pypy311_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:d7d406709ae924cf0b08b8282ca2f0e1c90526911d93bc040557cbc83b74c55f", size = 2503746, upload-time = "2026-11-05T09:15:15.736Z" }, + { url = "https://files.pythonhosted.org/packages/e7/ca/8a053f24e22d8150349cabaecb2f35c89dcf07fbaadb5e48295184dd0e5b/pydantic_core-2.50.4-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:7472c39480ccc11dda69a196d1b7c7a6b48eb6594b77f05d945599d3e47f731c", size = 2333540, upload-time = "2026-11-05T09:15:17.883Z" }, + { url = "https://files.pythonhosted.org/packages/ac/9d/41b374c62cdb87f84081e2ef2963a115eacc6284a26dbc96bb83568e83ec/pydantic_core-2.50.4-pp311-pypy311_pp80-macosx_10_12_x86_64.whl", hash = "sha256:b67d38e8bb0ade7e6e84575e4bb153fab35b122458077273aeb08fdf12be9d2c", size = 2166962, upload-time = "2026-11-05T09:15:20.276Z" }, + { url = "https://files.pythonhosted.org/packages/9a/4f/51ef440ee346d4388a2c4a3ac4b271fcc7b1d3ff68be8da2ed2be4d488b0/pydantic_core-2.50.4-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:4eda7e3fdef382b7d4492745988a5baaf6953923a337f8b9dde5f76fa8afde20", size = 2085634, upload-time = "2026-11-05T09:15:21.953Z" }, + { url = "https://files.pythonhosted.org/packages/4b/5f/c9ed62b96beb9050db221d29e81856b6e28f277db601f8b0c3a08f8cf913/pydantic_core-2.50.4-pp311-pypy311_pp80-manylinux_2_28_x86_64.whl", hash = "sha256:474f7e598c7902165662a5d5160d3fce31037890a2975a9871ebf7c05862300b", size = 2277804, upload-time = "2026-11-05T09:15:23.836Z" }, + { url = "https://files.pythonhosted.org/packages/63/bd/b912a5e251ef10ed7be5e543a2bfbeebb0c79bf6302bee786f8dc3bf4341/pydantic_core-2.50.4-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:3e0b395648c6cb871bceb2906907f255dc876ec425f2d5b024e129985cea8519", size = 2333539, upload-time = "2026-11-05T09:15:25.354Z" }, +] + +[[package]] +name = "registry-python-portal-example" +version = "0.1.0" +source = { virtual = "." } +dependencies = [ + { name = "authlib" }, + { name = "cryptography" }, + { name = "fastapi" }, + { name = "flask" }, + { name = "gunicorn" }, + { name = "psycopg", extra = ["binary"] }, + { name = "requests" }, + { name = "uvicorn" }, +] + +[package.dev-dependencies] +dev = [ + { name = "httpx" }, + { name = "ruff" }, +] + +[package.metadata] +requires-dist = [ + { name = "authlib", specifier = ">=1.9.5,<2" }, + { name = "cryptography", specifier = ">=50.0.2,<51" }, + { name = "fastapi", specifier = ">=0.115,<1" }, + { name = "flask", specifier = ">=3.1,<4" }, + { name = "gunicorn", specifier = ">=23,<24" }, + { name = "psycopg", extras = ["binary"], specifier = ">=3.3.6,<4" }, + { name = "requests", specifier = ">=2.31,<3" }, + { name = "uvicorn", specifier = ">=0.34,<1" }, +] + +[package.metadata.requires-dev] +dev = [ + { name = "httpx", specifier = ">=0.28,<1" }, + { name = "ruff", specifier = "==0.14.3" }, +] + +[[package]] +name = "requests" +version = "2.34.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "charset-normalizer" }, + { name = "idna" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ac/c3/e2a2b89f2d3e2179abd6d00ebd70bff6273f37fb3e0cc209f48b39d00cbf/requests-2.34.2.tar.gz", hash = "sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed", size = 142856, upload-time = "2026-05-14T19:25:27.735Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075, upload-time = "2026-05-14T19:25:26.443Z" }, +] + +[[package]] +name = "ruff" +version = "0.14.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/75/62/50b7727004dfe361104dfbf898c45a9a2fdfad8c72c04ae62900224d6ecf/ruff-0.14.3.tar.gz", hash = "sha256:4ff876d2ab2b161b6de0aa1f5bd714e8e9b4033dc122ee006925fbacc4f62153", size = 5558687, upload-time = "2025-10-31T00:26:26.878Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ce/8e/0c10ff1ea5d4360ab8bfca4cb2c9d979101a391f3e79d2616c9bf348cd26/ruff-0.14.3-py3-none-linux_armv6l.whl", hash = "sha256:876b21e6c824f519446715c1342b8e60f97f93264012de9d8d10314f8a79c371", size = 12535613, upload-time = "2025-10-31T00:25:44.302Z" }, + { url = "https://files.pythonhosted.org/packages/d3/c8/6724f4634c1daf52409fbf13fefda64aa9c8f81e44727a378b7b73dc590b/ruff-0.14.3-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:b6fd8c79b457bedd2abf2702b9b472147cd860ed7855c73a5247fa55c9117654", size = 12855812, upload-time = "2025-10-31T00:25:47.793Z" }, + { url = "https://files.pythonhosted.org/packages/de/03/db1bce591d55fd5f8a08bb02517fa0b5097b2ccabd4ea1ee29aa72b67d96/ruff-0.14.3-py3-none-macosx_11_0_arm64.whl", hash = "sha256:71ff6edca490c308f083156938c0c1a66907151263c4abdcb588602c6e696a14", size = 11944026, upload-time = "2025-10-31T00:25:49.657Z" }, + { url = "https://files.pythonhosted.org/packages/0b/75/4f8dbd48e03272715d12c87dc4fcaaf21b913f0affa5f12a4e9c6f8a0582/ruff-0.14.3-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:786ee3ce6139772ff9272aaf43296d975c0217ee1b97538a98171bf0d21f87ed", size = 12356818, upload-time = "2025-10-31T00:25:51.949Z" }, + { url = "https://files.pythonhosted.org/packages/ec/9b/506ec5b140c11d44a9a4f284ea7c14ebf6f8b01e6e8917734a3325bff787/ruff-0.14.3-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:cd6291d0061811c52b8e392f946889916757610d45d004e41140d81fb6cd5ddc", size = 12336745, upload-time = "2025-10-31T00:25:54.248Z" }, + { url = "https://files.pythonhosted.org/packages/c7/e1/c560d254048c147f35e7f8131d30bc1f63a008ac61595cf3078a3e93533d/ruff-0.14.3-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a497ec0c3d2c88561b6d90f9c29f5ae68221ac00d471f306fa21fa4264ce5fcd", size = 13101684, upload-time = "2025-10-31T00:25:56.253Z" }, + { url = "https://files.pythonhosted.org/packages/a5/32/e310133f8af5cd11f8cc30f52522a3ebccc5ea5bff4b492f94faceaca7a8/ruff-0.14.3-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:e231e1be58fc568950a04fbe6887c8e4b85310e7889727e2b81db205c45059eb", size = 14535000, upload-time = "2025-10-31T00:25:58.397Z" }, + { url = "https://files.pythonhosted.org/packages/a2/a1/7b0470a22158c6d8501eabc5e9b6043c99bede40fa1994cadf6b5c2a61c7/ruff-0.14.3-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:469e35872a09c0e45fecf48dd960bfbce056b5db2d5e6b50eca329b4f853ae20", size = 14156450, upload-time = "2025-10-31T00:26:00.889Z" }, + { url = "https://files.pythonhosted.org/packages/0a/96/24bfd9d1a7f532b560dcee1a87096332e461354d3882124219bcaff65c09/ruff-0.14.3-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:3d6bc90307c469cb9d28b7cfad90aaa600b10d67c6e22026869f585e1e8a2db0", size = 13568414, upload-time = "2025-10-31T00:26:03.291Z" }, + { url = "https://files.pythonhosted.org/packages/a7/e7/138b883f0dfe4ad5b76b58bf4ae675f4d2176ac2b24bdd81b4d966b28c61/ruff-0.14.3-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0e2f8a0bbcffcfd895df39c9a4ecd59bb80dca03dc43f7fb63e647ed176b741e", size = 13315293, upload-time = "2025-10-31T00:26:05.708Z" }, + { url = "https://files.pythonhosted.org/packages/33/f4/c09bb898be97b2eb18476b7c950df8815ef14cf956074177e9fbd40b7719/ruff-0.14.3-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:678fdd7c7d2d94851597c23ee6336d25f9930b460b55f8598e011b57c74fd8c5", size = 13539444, upload-time = "2025-10-31T00:26:08.09Z" }, + { url = "https://files.pythonhosted.org/packages/9c/aa/b30a1db25fc6128b1dd6ff0741fa4abf969ded161599d07ca7edd0739cc0/ruff-0.14.3-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:1ec1ac071e7e37e0221d2f2dbaf90897a988c531a8592a6a5959f0603a1ecf5e", size = 12252581, upload-time = "2025-10-31T00:26:10.297Z" }, + { url = "https://files.pythonhosted.org/packages/da/13/21096308f384d796ffe3f2960b17054110a9c3828d223ca540c2b7cc670b/ruff-0.14.3-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:afcdc4b5335ef440d19e7df9e8ae2ad9f749352190e96d481dc501b753f0733e", size = 12307503, upload-time = "2025-10-31T00:26:12.646Z" }, + { url = "https://files.pythonhosted.org/packages/cb/cc/a350bac23f03b7dbcde3c81b154706e80c6f16b06ff1ce28ed07dc7b07b0/ruff-0.14.3-py3-none-musllinux_1_2_i686.whl", hash = "sha256:7bfc42f81862749a7136267a343990f865e71fe2f99cf8d2958f684d23ce3dfa", size = 12675457, upload-time = "2025-10-31T00:26:15.044Z" }, + { url = "https://files.pythonhosted.org/packages/cb/76/46346029fa2f2078826bc88ef7167e8c198e58fe3126636e52f77488cbba/ruff-0.14.3-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:a65e448cfd7e9c59fae8cf37f9221585d3354febaad9a07f29158af1528e165f", size = 13403980, upload-time = "2025-10-31T00:26:17.81Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a4/35f1ef68c4e7b236d4a5204e3669efdeefaef21f0ff6a456792b3d8be438/ruff-0.14.3-py3-none-win32.whl", hash = "sha256:f3d91857d023ba93e14ed2d462ab62c3428f9bbf2b4fbac50a03ca66d31991f7", size = 12500045, upload-time = "2025-10-31T00:26:20.503Z" }, + { url = "https://files.pythonhosted.org/packages/03/15/51960ae340823c9859fb60c63301d977308735403e2134e17d1d2858c7fb/ruff-0.14.3-py3-none-win_amd64.whl", hash = "sha256:d7b7006ac0756306db212fd37116cce2bd307e1e109375e1c6c106002df0ae5f", size = 13594005, upload-time = "2025-10-31T00:26:22.533Z" }, + { url = "https://files.pythonhosted.org/packages/b7/73/4de6579bac8e979fca0a77e54dec1f1e011a0d268165eb8a9bc0982a6564/ruff-0.14.3-py3-none-win_arm64.whl", hash = "sha256:26eb477ede6d399d898791d01961e16b86f02bc2486d0d1a7a9bb2379d055dc1", size = 12590017, upload-time = "2025-10-31T00:26:24.52Z" }, +] + +[[package]] +name = "starlette" +version = "1.10.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/48/bb/3d8757f21e9a53d9035c9eb039a777047139a16bfdbedfc7a58241c3d914/starlette-1.10.0.tar.gz", hash = "sha256:b8399098d4c1e3522734f7235dc79b1fc967f96cf139c81e0fa30479e0685f9b", size = 2734356, upload-time = "2026-10-24T15:04:12.342Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/88/2e/947cfe02def9371c07cd5bf5b6b61c829e9aecb9904db02a66cfafbc1eec/starlette-1.10.0-py3-none-any.whl", hash = "sha256:478c0ab3b4ced6e82719849c118fa406f0278a3499c1a898cd15cd31bdc38ce4", size = 80571, upload-time = "2026-10-24T15:04:10.371Z" }, +] + +[[package]] +name = "typing-extensions" +version = "4.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, +] + +[[package]] +name = "typing-inspection" +version = "0.4.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ff/50/0195198eb1d75bab716bb0a813abea4cc394bfa17a92a189f021a34859af/typing_inspection-0.4.5.tar.gz", hash = "sha256:7f16c411e7930dc79596d42ab44672a3fe5f60eb34b781a1647e7872363120c7", size = 81194, upload-time = "2026-11-04T14:13:23.774Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/de/0c/ea2544850a7c135e15033a5c7a8e7211136184b7ae63e2239d557c2b3019/typing_inspection-0.4.5-py3-none-any.whl", hash = "sha256:bc210535442b39e1bf2805e0c7a17dfd6a4ace760c84c7f7d16245d23a6b1c39", size = 14874, upload-time = "2026-11-04T14:13:22.616Z" }, +] + +[[package]] +name = "tzdata" +version = "2026.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7a/29/6a1391d31cd00ff9e927215a224a880e1e84e826b64ba80a499e51c074d8/tzdata-2026.6.tar.gz", hash = "sha256:85d2cd9c09f81f0bb29db27759fc83af4f1e620efb814f8c5bf8b4cc4feece6d", size = 201017, upload-time = "2026-10-28T09:57:09.137Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0a/66/9a06c2227fedfd4919f0eaaa8b94377d9730882a7e4f95823c9a331ab5e1/tzdata-2026.6-py2.py3-none-any.whl", hash = "sha256:0a10eec6e13ef16b627fabed9a5f2ba61a62b1c67f327305f4e7e412a70b4aec", size = 348210, upload-time = "2026-10-28T09:57:07.276Z" }, +] + +[[package]] +name = "urllib3" +version = "2.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e3/05/b17359e1cefb4f909b5e40b1b90a496d987258916dbbf88e842c729f510e/urllib3-2.8.0.tar.gz", hash = "sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63", size = 458972, upload-time = "2026-09-15T19:29:36.253Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/92/9d/c4e665119135114480843e7ab388fa94d8480650450e6f8e26b70d323a4c/urllib3-2.8.0-py3-none-any.whl", hash = "sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3", size = 135717, upload-time = "2026-09-15T19:29:34.577Z" }, +] + +[[package]] +name = "uvicorn" +version = "0.54.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "h11" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/da/34/30e9280707135d2cfc589dfff3cb796bd07a3aeb1a3e415ba09dd89d7bb4/uvicorn-0.54.0.tar.gz", hash = "sha256:a2e33cbfaa0306f8e6b0c13e0cb89d7d7a2da3e62b90c66e18c33d9807b28620", size = 112283, upload-time = "2026-09-25T06:52:37.601Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/38/0c/b54a4fdd7f90a3af8b02ebc9ce6712c2c208b7926a2f7bad95c33ebbe943/uvicorn-0.54.0-py3-none-any.whl", hash = "sha256:505bdb0f318731d45f1f712071fc781a8981f6847a31c902c9f5e652d4f67faf", size = 87427, upload-time = "2026-09-25T06:52:35.829Z" }, +] + +[[package]] +name = "werkzeug" +version = "3.1.9" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markupsafe" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a4/34/4dd12fc8bb7d61c91467ec3efe415ffa7d5456f799954b40c5bbaeae470e/werkzeug-3.1.9.tar.gz", hash = "sha256:55ca7c70a75689be937aa27f8ff4b018f06ff4838fc73045560bf0f5a1291060", size = 940188, upload-time = "2026-09-27T18:33:41.637Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a1/38/df03f564f43cec2684823f3cccae1a652ee7face1cbaa76fb223096e64d7/werkzeug-3.1.9-py3-none-any.whl", hash = "sha256:6392e50c78460ba618e5b21f08a71f59c99ce99cdc6cf6e3dd7e6ccca8754fab", size = 228700, upload-time = "2026-09-27T18:33:39.685Z" }, +] diff --git a/products/platform/examples/python-script/README.md b/products/platform/examples/python-script/README.md new file mode 100644 index 0000000000..a7a5651bad --- /dev/null +++ b/products/platform/examples/python-script/README.md @@ -0,0 +1,75 @@ +# Python script with generated workload credentials + +This prepared script reads the synthetic licensing application from BReg and +submits one Registry Messaging request under a stable caller-owned key. It then +reads the original Messaging receipt with the same key and request. The script +uses `registry_client.connect()` and the private connection generated by +`rstack dev`; it never reads or passes a bearer token. + +The example targets the candidate Python APIs in this checkout. Treat it as a +released workflow only after the assembled `registry-stack-client` wheel and +matching Registry Stack release have passed their distribution and live +acceptance checks. + +## Start the prepared project + +Use Python 3.11 or later, `uv`, matching BReg, Casework, and Messaging +components, and the dedicated PostgreSQL server described in +[PROJECT-DEV](../../PROJECT-DEV.md). The licensing project's Messaging provider +is deliberately unconfigured. Its receipt proves authenticated local +acceptance and retained command identity, not external email delivery. + +Run these commands from this directory. Supply the database URL and CA through +your normal secret provider before starting the run. + +```sh +uv sync --locked +sdk='registry-stack-client==' +# For prepared source, sdk may instead name the absolute assembled wheel. +RUN_REPORT="$(mktemp "${TMPDIR:-/tmp}/rstack-python-script.XXXXXX")" +rstack dev check ../licensing --json +rstack dev start ../licensing --ttl 10m --json > "$RUN_REPORT" +RUN_ID="$(jq -er .run_id "$RUN_REPORT")" +export REGISTRY_STACK_CONNECTION="$(jq -er .connection_file "$RUN_REPORT")" +uv run --locked --with "$sdk" python script.py +rstack dev stop "$RUN_ID" +``` + +The command prints a small JSON summary containing the visible application +count and the message receipt's identifier and status. It does not print the +connection document, token state, bearer, or trace identifiers. The fixed +synthetic request and `python-script-application-received` key make a rerun ask +Messaging for the same command rather than choose a new key. + +If a native submission error says its outcome is unknown, the script reads the +original receipt once. It does not resubmit automatically. A known refusal, an +unresolved receipt, or a stopped or expired development run fails visibly. +Always stop the run by its reported ID after a script failure as well. + +## Exercise one live rotation + +Use the optional mode to retain one `Connection` and Python process across the +runner's one-minute credential rotation. It repeats the BReg read after 65 +seconds before making the Messaging calls: + +```sh +uv run --locked --with "$sdk" python script.py --wait-for-rotation +``` + +Passing this command against a live runner demonstrates the runtime behavior. +The source test below proves only that the same connection is retained and the +second protected call is made; it cannot prove that a token file rotated. + +## Verify the source example + +```sh +uv run --locked python -m unittest discover -s tests -v +uv run --with 'ruff==0.14.3' ruff format --check . +uv run --with 'ruff==0.14.3' ruff check . +``` + +These tests use protocol doubles. They cover exact BReg options, identical +Messaging key/body reuse, unknown-outcome receipt recovery, known-refusal +propagation, one-process rotation control flow, and bounded secret-free output. +They do not establish a built-wheel import, a live runner, PostgreSQL, product +authorization, token rotation, stop/expiry behavior, or external delivery. diff --git a/products/platform/examples/python-script/pyproject.toml b/products/platform/examples/python-script/pyproject.toml new file mode 100644 index 0000000000..934ddfe21e --- /dev/null +++ b/products/platform/examples/python-script/pyproject.toml @@ -0,0 +1,8 @@ +[project] +name = "registry-stack-python-script-example" +version = "0.1.0" +requires-python = ">=3.11" +dependencies = [] + +[tool.uv] +package = false diff --git a/products/platform/examples/python-script/script.py b/products/platform/examples/python-script/script.py new file mode 100644 index 0000000000..c3e2ce681e --- /dev/null +++ b/products/platform/examples/python-script/script.py @@ -0,0 +1,78 @@ +"""Read licensing records, then submit and recover one message receipt.""" + +import argparse +import json +from time import sleep + +from registry_client import connect, messaging + + +MESSAGE_KEY = "python-script-application-received" +MESSAGE = { + "senderProfile": "licensing-email", + "to": {"email": "applicant@example.test"}, + "template": {"id": "application-received", "version": "1"}, + "locale": "en", + "data": {"reference": "application-001"}, + "correlationId": "python-script-application-001", +} + + +def _applications(stack): + return stack.breg.list_records( + "applications", + top=1, + select=["reference", "profession"], + access_profile="applicant", + ) + + +def run(*, wait_for_rotation: bool = False) -> dict[str, object]: + stack = connect() + applications = _applications(stack) + if wait_for_rotation: + sleep(65) + applications = _applications(stack) + try: + submitted = stack.messaging.submit(MESSAGE_KEY, MESSAGE) + except messaging.MessagingClientError as error: + if not error.outcome_unknown: + raise + submitted = None + receipt = stack.messaging.message_receipt(MESSAGE_KEY, MESSAGE) + if applications.get("kind") != "complete": + raise RuntimeError("the BReg read did not complete") + records = applications.get("value") + if not isinstance(records, dict) or not isinstance(records.get("items"), list): + raise RuntimeError("the BReg read returned an invalid page") + if receipt.get("kind") != "complete" or ( + submitted is not None and submitted.get("kind") != "complete" + ): + raise RuntimeError("the Messaging request did not complete") + if submitted is not None and submitted["value"]["id"] != receipt["value"]["id"]: + raise RuntimeError("the Messaging receipt did not match the submission") + return { + "applications": len(records["items"]), + "message": receipt["value"]["id"], + "status": receipt["value"]["status"], + } + + +def main(arguments: list[str] | None = None) -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--wait-for-rotation", + action="store_true", + help="repeat the BReg read after one local runner token rotation", + ) + options = parser.parse_args(arguments) + print( + json.dumps( + run(wait_for_rotation=options.wait_for_rotation), + sort_keys=True, + ) + ) + + +if __name__ == "__main__": + main() diff --git a/products/platform/examples/python-script/tests/test_script.py b/products/platform/examples/python-script/tests/test_script.py new file mode 100644 index 0000000000..f0bcd4028b --- /dev/null +++ b/products/platform/examples/python-script/tests/test_script.py @@ -0,0 +1,207 @@ +import contextlib +import importlib.util +import io +import json +from pathlib import Path +import sys +import types +import unittest + + +ROOT = Path(__file__).resolve().parents[1] + + +def load_script(): + client = types.ModuleType("registry_client") + client.connect = lambda: None + client.messaging = types.SimpleNamespace(MessagingClientError=MessagingClientError) + previous = sys.modules.get("registry_client") + sys.modules["registry_client"] = client + spec = importlib.util.spec_from_file_location( + "registry_python_script", ROOT / "script.py" + ) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + try: + spec.loader.exec_module(module) + finally: + if previous is None: + del sys.modules["registry_client"] + else: + sys.modules["registry_client"] = previous + return module + + +class BReg: + def __init__(self): + self.calls = [] + + def list_records(self, route, **options): + self.calls.append((route, options)) + return { + "kind": "complete", + "value": { + "items": [{"data": {"reference": "application-001"}}], + "meta": {}, + "pageInfo": {}, + }, + "trace_id": "breg-trace-canary", + "etag": None, + "continuation": None, + } + + +class MessagingClientError(Exception): + def __init__(self, *, outcome_unknown): + super().__init__("synthetic Messaging failure") + self.outcome_unknown = outcome_unknown + + +class Messaging: + def __init__(self, submit_error=None): + self.calls = [] + self.submit_error = submit_error + + def submit(self, key, request): + self.calls.append(("submit", key, request)) + if self.submit_error is not None: + raise self.submit_error + return { + "kind": "complete", + "value": {"id": "message-from-receipt", "status": "queued"}, + "trace_id": "submit-trace-canary", + } + + def message_receipt(self, key, request): + self.calls.append(("message_receipt", key, request)) + return { + "kind": "complete", + "value": {"id": "message-from-receipt", "status": "queued"}, + "trace_id": "receipt-trace-canary", + } + + +class Stack: + def __init__(self): + self.breg = BReg() + self.messaging = Messaging() + + +class ScriptTests(unittest.TestCase): + def test_run_uses_generated_defaults_and_reads_the_original_message_receipt(self): + module = load_script() + stack = Stack() + connections = [] + module.connect = lambda: connections.append(True) or stack + + result = module.run() + + self.assertEqual(connections, [True]) + self.assertEqual( + stack.breg.calls, + [ + ( + "applications", + { + "top": 1, + "select": ["reference", "profession"], + "access_profile": "applicant", + }, + ) + ], + ) + self.assertEqual( + [operation for operation, _, _ in stack.messaging.calls], + ["submit", "message_receipt"], + ) + submitted = stack.messaging.calls[0] + recovered = stack.messaging.calls[1] + self.assertEqual(submitted[1], "python-script-application-received") + self.assertEqual(submitted[1:], recovered[1:]) + self.assertEqual( + submitted[2], + { + "senderProfile": "licensing-email", + "to": {"email": "applicant@example.test"}, + "template": {"id": "application-received", "version": "1"}, + "locale": "en", + "data": {"reference": "application-001"}, + "correlationId": "python-script-application-001", + }, + ) + self.assertEqual( + result, + { + "applications": 1, + "message": "message-from-receipt", + "status": "queued", + }, + ) + + def test_main_prints_only_the_bounded_summary(self): + module = load_script() + module.run = lambda **_options: { + "applications": 1, + "message": "message-1", + "status": "queued", + } + output = io.StringIO() + + with contextlib.redirect_stdout(output): + module.main([]) + + self.assertEqual( + json.loads(output.getvalue()), + {"applications": 1, "message": "message-1", "status": "queued"}, + ) + for canary in ("bearer", "connection", "trace", "token"): + self.assertNotIn(canary, output.getvalue().lower()) + + def test_unknown_submit_reads_the_same_original_receipt(self): + module = load_script() + stack = Stack() + stack.messaging = Messaging(MessagingClientError(outcome_unknown=True)) + module.connect = lambda: stack + + result = module.run() + + self.assertEqual( + [operation for operation, _, _ in stack.messaging.calls], + ["submit", "message_receipt"], + ) + self.assertEqual(stack.messaging.calls[0][1:], stack.messaging.calls[1][1:]) + self.assertEqual(result["message"], "message-from-receipt") + + def test_known_submit_refusal_is_not_treated_as_a_receipt_recovery(self): + module = load_script() + refusal = MessagingClientError(outcome_unknown=False) + stack = Stack() + stack.messaging = Messaging(refusal) + module.connect = lambda: stack + + with self.assertRaises(MessagingClientError) as caught: + module.run() + + self.assertIs(caught.exception, refusal) + self.assertEqual( + [operation for operation, _, _ in stack.messaging.calls], ["submit"] + ) + + def test_rotation_check_keeps_one_connection_and_repeats_the_protected_read(self): + module = load_script() + stack = Stack() + connections = [] + waits = [] + module.connect = lambda: connections.append(True) or stack + module.sleep = waits.append + + result = module.run(wait_for_rotation=True) + + self.assertEqual(connections, [True]) + self.assertEqual(waits, [65]) + self.assertEqual(len(stack.breg.calls), 2) + self.assertEqual(result["applications"], 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/products/platform/examples/python-script/uv.lock b/products/platform/examples/python-script/uv.lock new file mode 100644 index 0000000000..175fa1ebf9 --- /dev/null +++ b/products/platform/examples/python-script/uv.lock @@ -0,0 +1,8 @@ +version = 1 +revision = 3 +requires-python = ">=3.11" + +[[package]] +name = "registry-stack-python-script-example" +version = "0.1.0" +source = { virtual = "." } diff --git a/products/platform/schemas/dev-workload-token.v1alpha1.schema.json b/products/platform/schemas/dev-workload-token.v1alpha1.schema.json new file mode 100644 index 0000000000..bf4b9b222a --- /dev/null +++ b/products/platform/schemas/dev-workload-token.v1alpha1.schema.json @@ -0,0 +1,157 @@ +{ + "$defs": { + "ExternalId": { + "description": "An identifier another system issues, written exactly as its issuer gives it.", + "maxLength": 512, + "minLength": 1, + "pattern": "^[^\\u0000-\\u001F\\u007F-\\u009F]+$", + "type": "string" + }, + "Url": { + "description": "An absolute http or https URL with a host preserved as written, no user information, and no backslash, whitespace or control character. DNS case and equivalent IPv6 literals are permitted.", + "format": "uri", + "maxLength": 2048, + "pattern": "^[Hh][Tt][Tt][Pp][Ss]?://[^/?#@\\u005C\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000]+([/?#][^\\u005C\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000]*)?$", + "type": "string" + }, + "WorkloadProduct": { + "enum": [ + "breg", + "messaging" + ], + "type": "string" + }, + "WorkloadTokenStatus": { + "enum": [ + "stopped" + ], + "type": "string" + } + }, + "$id": "https://id.registrystack.org/schemas/platform/dev-workload-token/dev-workload-token.v1alpha1.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "oneOf": [ + { + "not": { + "required": [ + "status" + ] + }, + "required": [ + "token" + ] + }, + { + "not": { + "required": [ + "token" + ] + }, + "required": [ + "status" + ] + } + ], + "properties": { + "apiVersion": { + "const": "id.registrystack.org/formats/platform/dev-workload-token/v1alpha1", + "type": "string" + }, + "binding": { + "$ref": "#/$defs/ExternalId" + }, + "claims": { + "additionalProperties": true, + "propertyNames": { + "$ref": "#/$defs/ExternalId" + }, + "type": "object", + "x-registry-passthrough": "Claim values are written into the workload token as declared." + }, + "clientId": { + "$ref": "#/$defs/ExternalId" + }, + "expiresAt": { + "maximum": 18446744073709551615, + "minimum": 0, + "type": "integer" + }, + "generation": { + "format": "uint64", + "maximum": 18446744073709551615, + "minimum": 1, + "type": "integer" + }, + "issuedAt": { + "maximum": 18446744073709551615, + "minimum": 0, + "type": "integer" + }, + "issuer": { + "$ref": "#/$defs/Url" + }, + "kind": { + "const": "PlatformDevWorkloadToken", + "type": "string" + }, + "product": { + "$ref": "#/$defs/WorkloadProduct" + }, + "profile": { + "$ref": "#/$defs/ExternalId" + }, + "resource": { + "$ref": "#/$defs/ExternalId" + }, + "runExpiresAt": { + "format": "uint64", + "maximum": 18446744073709551615, + "minimum": 1, + "type": "integer" + }, + "runId": { + "$ref": "#/$defs/ExternalId" + }, + "scopes": { + "items": { + "$ref": "#/$defs/ExternalId" + }, + "minItems": 1, + "type": "array", + "uniqueItems": true + }, + "status": { + "$ref": "#/$defs/WorkloadTokenStatus" + }, + "subject": { + "$ref": "#/$defs/ExternalId" + }, + "token": { + "maxLength": 8192, + "minLength": 1, + "pattern": "^\\S+$", + "type": "string" + } + }, + "required": [ + "apiVersion", + "kind", + "runId", + "binding", + "product", + "issuer", + "subject", + "clientId", + "profile", + "resource", + "scopes", + "claims", + "generation", + "issuedAt", + "expiresAt", + "runExpiresAt" + ], + "title": "DevWorkloadToken", + "type": "object" +} diff --git a/products/platform/schemas/identity-deployment.schema.json b/products/platform/schemas/identity-deployment.schema.json index fd9657d666..a75bd19ae4 100644 --- a/products/platform/schemas/identity-deployment.schema.json +++ b/products/platform/schemas/identity-deployment.schema.json @@ -4,6 +4,10 @@ "additionalProperties": false, "description": "A browser application: an authorization-code client with PKCE.", "properties": { + "clientProfile": { + "$ref": "#/$defs/BrowserClientProfile", + "description": "Optional client behavior. When omitted, the client remains\nauthorization-code-only with only its origin as a logout return.\n`python-portal` also admits refresh grants and same-origin `/auth/login`." + }, "clientSecretRef": { "$ref": "#/$defs/SecretReference", "allOf": [ @@ -78,6 +82,16 @@ ], "type": "object" }, + "BrowserClientProfile": { + "description": "An optional browser-client behavior profile.", + "oneOf": [ + { + "const": "python-portal", + "description": "A confidential Python portal using authorization code with PKCE and\nrotating refresh tokens for one requested resource. It also registers\nsame-origin `/auth/login` for an account-switch logout return.", + "type": "string" + } + ] + }, "ClaimValue": { "anyOf": [ { diff --git a/products/platform/schemas/python-connection.v1alpha1.schema.json b/products/platform/schemas/python-connection.v1alpha1.schema.json new file mode 100644 index 0000000000..0fbe87b8fc --- /dev/null +++ b/products/platform/schemas/python-connection.v1alpha1.schema.json @@ -0,0 +1,384 @@ +{ + "$defs": { + "EnvironmentSecretProviderConfig": { + "additionalProperties": false, + "description": "The environment secret provider. It takes no settings.", + "type": "object" + }, + "ExternalId": { + "description": "An identifier another system issues, written exactly as its issuer gives it.", + "maxLength": 512, + "minLength": 1, + "pattern": "^[^\\u0000-\\u001F\\u007F-\\u009F]+$", + "type": "string" + }, + "FileSecretProviderConfig": { + "additionalProperties": false, + "description": "The file secret provider.", + "properties": { + "root": { + "description": "Absolute directory holding one file per secret. Each file must be a\nregular file owned by the runtime user, mode 0400 or 0600, with exactly\none hard link.", + "pattern": "^/", + "type": "string" + } + }, + "required": [ + "root" + ], + "type": "object" + }, + "MachineAdmission": { + "additionalProperties": false, + "properties": { + "accessTokenType": { + "$ref": "#/$defs/ExternalId" + }, + "algorithm": { + "$ref": "#/$defs/TokenAlgorithm" + }, + "allowInsecureHttp": { + "type": "boolean" + }, + "clientId": { + "$ref": "#/$defs/ExternalId" + }, + "clockSkewSeconds": { + "format": "uint64", + "maximum": 300, + "minimum": 0, + "type": "integer" + }, + "issuer": { + "$ref": "#/$defs/Url" + }, + "jwksUri": { + "$ref": "#/$defs/Url" + }, + "maximumAccessTokenLifetimeSeconds": { + "format": "uint64", + "maximum": 7200, + "minimum": 1, + "type": "integer" + }, + "profile": { + "$ref": "#/$defs/ExternalId" + }, + "requiredClaims": { + "additionalProperties": false, + "minProperties": 1, + "patternProperties": { + "^[^\\u0000-\\u001F\\u007F-\\u009F]+$": { + "$ref": "#/$defs/ExternalId" + } + }, + "propertyNames": { + "$ref": "#/$defs/ExternalId" + }, + "type": "object" + }, + "requiredScopes": { + "items": { + "$ref": "#/$defs/ExternalId" + }, + "minItems": 1, + "type": "array", + "uniqueItems": true + }, + "resource": { + "$ref": "#/$defs/ExternalId" + } + }, + "required": [ + "issuer", + "resource", + "clientId", + "profile", + "requiredScopes", + "requiredClaims", + "algorithm", + "accessTokenType", + "maximumAccessTokenLifetimeSeconds" + ], + "type": "object" + }, + "SecretProvidersConfig": { + "additionalProperties": false, + "anyOf": [ + { + "properties": { + "file": { + "$ref": "#/$defs/FileSecretProviderConfig" + } + }, + "required": [ + "file" + ] + }, + { + "properties": { + "environment": { + "$ref": "#/$defs/EnvironmentSecretProviderConfig" + } + }, + "required": [ + "environment" + ] + } + ], + "description": "The secret providers a runtime enables. A reference is resolved only by a\nprovider declared here: `secret:file/name` under `file.root`, and\n`secret:env/NAME` only when `environment: {}` is present.", + "properties": { + "environment": { + "$ref": "#/$defs/EnvironmentSecretProviderConfig", + "description": "Enables `secret:env/NAME` references, read from the process\nenvironment. Declared as an empty mapping: `environment: {}`." + }, + "file": { + "$ref": "#/$defs/FileSecretProviderConfig", + "description": "Enables `secret:file/name` references, read from files under `root`." + } + }, + "type": "object" + }, + "SecretReference": { + "description": "An exact secret reference: secret:file/name, resolved under secretProviders.file.root, or secret:env/NAME, resolved only when secretProviders.environment is declared.", + "pattern": "^(?:secret:env/[A-Z][A-Z0-9_]{0,127}|secret:file/[a-z][a-z0-9._-]{0,127})$", + "type": "string" + }, + "ServiceAudience": { + "enum": [ + "service", + "holder", + "staff" + ], + "type": "string" + }, + "TokenAlgorithm": { + "enum": [ + "EdDSA", + "ES256", + "ES384", + "RS256", + "RS384" + ], + "type": "string" + }, + "Url": { + "description": "An absolute http or https URL with a host preserved as written, no user information, and no backslash, whitespace or control character. DNS case and equivalent IPv6 literals are permitted.", + "format": "uri", + "maxLength": 2048, + "pattern": "^[Hh][Tt][Tt][Pp][Ss]?://[^/?#@\\u005C\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000]+([/?#][^\\u005C\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000]*)?$", + "type": "string" + }, + "WorkloadBinding": { + "additionalProperties": false, + "properties": { + "credential": { + "$ref": "#/$defs/WorkloadCredential" + }, + "default": { + "type": "boolean" + }, + "name": { + "pattern": "^[a-z][a-z0-9-]{0,63}$", + "type": "string" + }, + "product": { + "$ref": "#/$defs/WorkloadProduct" + }, + "url": { + "$ref": "#/$defs/Url" + } + }, + "required": [ + "name", + "product", + "url", + "default", + "credential" + ], + "type": "object" + }, + "WorkloadCredential": { + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "claims": { + "additionalProperties": true, + "propertyNames": { + "$ref": "#/$defs/ExternalId" + }, + "type": "object", + "x-registry-passthrough": "Claim values are written into the workload token as declared." + }, + "clientId": { + "$ref": "#/$defs/ExternalId" + }, + "clientKeyRef": { + "$ref": "#/$defs/SecretReference" + }, + "issuer": { + "$ref": "#/$defs/Url" + }, + "profile": { + "$ref": "#/$defs/ExternalId" + }, + "resource": { + "$ref": "#/$defs/ExternalId" + }, + "scopes": { + "items": { + "$ref": "#/$defs/ExternalId" + }, + "minItems": 1, + "type": "array", + "uniqueItems": true + }, + "subject": { + "$ref": "#/$defs/ExternalId" + }, + "tokenEndpoint": { + "$ref": "#/$defs/Url" + }, + "type": { + "const": "private-key-jwt", + "type": "string" + } + }, + "required": [ + "type", + "issuer", + "subject", + "tokenEndpoint", + "clientId", + "profile", + "clientKeyRef", + "resource", + "scopes", + "claims" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "binding": { + "$ref": "#/$defs/ExternalId" + }, + "claims": { + "additionalProperties": true, + "propertyNames": { + "$ref": "#/$defs/ExternalId" + }, + "type": "object", + "x-registry-passthrough": "Claim values are written into the workload token as declared." + }, + "clientId": { + "$ref": "#/$defs/ExternalId" + }, + "issuer": { + "$ref": "#/$defs/Url" + }, + "profile": { + "$ref": "#/$defs/ExternalId" + }, + "resource": { + "$ref": "#/$defs/ExternalId" + }, + "runExpiresAt": { + "format": "uint64", + "maximum": 18446744073709551615, + "minimum": 1, + "type": "integer" + }, + "runId": { + "$ref": "#/$defs/ExternalId" + }, + "scopes": { + "items": { + "$ref": "#/$defs/ExternalId" + }, + "minItems": 1, + "type": "array", + "uniqueItems": true + }, + "subject": { + "$ref": "#/$defs/ExternalId" + }, + "tokenRef": { + "$ref": "#/$defs/SecretReference" + }, + "type": { + "const": "runner-token", + "type": "string" + } + }, + "required": [ + "type", + "tokenRef", + "runId", + "binding", + "issuer", + "subject", + "clientId", + "profile", + "resource", + "scopes", + "claims", + "runExpiresAt" + ], + "type": "object" + } + ] + }, + "WorkloadProduct": { + "enum": [ + "breg", + "messaging" + ], + "type": "string" + } + }, + "$id": "https://id.registrystack.org/schemas/platform/python-connection/python-connection.v1alpha1.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "admission": { + "$ref": "#/$defs/MachineAdmission" + }, + "apiVersion": { + "const": "id.registrystack.org/formats/platform/python-connection/v1alpha1", + "type": "string" + }, + "audience": { + "$ref": "#/$defs/ServiceAudience" + }, + "bindings": { + "items": { + "$ref": "#/$defs/WorkloadBinding" + }, + "type": "array" + }, + "kind": { + "const": "PlatformPythonConnection", + "type": "string" + }, + "secretProviders": { + "$ref": "#/$defs/SecretProvidersConfig" + }, + "service": { + "maxLength": 512, + "minLength": 1, + "type": "string" + } + }, + "required": [ + "apiVersion", + "kind", + "service", + "audience", + "secretProviders", + "bindings" + ], + "title": "PythonConnection", + "type": "object" +} diff --git a/products/platform/scripts/test-rstack-dev.py b/products/platform/scripts/test-rstack-dev.py index 8131cdfbf3..801f9b9d5c 100644 --- a/products/platform/scripts/test-rstack-dev.py +++ b/products/platform/scripts/test-rstack-dev.py @@ -4,6 +4,7 @@ from __future__ import annotations import argparse +import ast import base64 import concurrent.futures import fcntl @@ -16,6 +17,7 @@ import signal import socket import subprocess +import sys import tempfile import time from pathlib import Path @@ -222,12 +224,17 @@ def dev_output(bin_dir, env, cwd, *args, expected=0): return report, result.stdout + result.stderr -def credential(bin_dir, env, cwd, run, alias): +def credential(bin_dir, env, cwd, run, alias, product=None): before = time.time() report = dev(bin_dir, env, cwd, "token", run, "--as", alias) # The report gives the expiry the tokens carry, at most five minutes away. assert before < report["expires_at"] <= time.time() + 300, report - [entry] = report["credentials"] + selected = [ + entry + for entry in report["credentials"] + if product is None or entry["product"] == product + ] + [entry] = selected header_file = Path(entry["header_file"]) assert header_file.stat().st_mode & 0o077 == 0 return dict(line.split(": ", 1) for line in header_file.read_text().splitlines()) @@ -404,7 +411,7 @@ def create_owner(pg, pg_env, url): return owner_url, {**pg_env, "PGUSER": "devowner", "PGPASSWORD": password} -def exercise(root, bin_dir, pg, project, ca, url, pg_env, spatial): +def exercise(root, bin_dir, pg, project, ca, url, pg_env, spatial, python_client): checkout = root / "licensing" shutil.copytree(project, checkout) before = files(checkout) @@ -419,9 +426,11 @@ def exercise(root, bin_dir, pg, project, ca, url, pg_env, spatial): "RSTACK_BREG_BIN": str(bin_dir / "breg"), "RSTACK_CASEWORKCTL_BIN": str(bin_dir / "caseworkctl"), "RSTACK_CASEWORK_BIN": str(bin_dir / "casework"), + "RSTACK_MESSAGINGCTL_BIN": str(bin_dir / "messagingctl"), + "RSTACK_MESSAGING_BIN": str(bin_dir / "messaging"), } try: - exercise_runs(root, bin_dir, pg, checkout, state, env, pg_env) + exercise_runs(root, bin_dir, pg, checkout, state, env, pg_env, python_client) verify_lost_supervisor(bin_dir, pg, checkout, state, env, pg_env, owner_env) verify_startup_loss(bin_dir, pg, checkout, state, env, pg_env) verify_provisioning_deadline(bin_dir, pg, checkout, state, env, pg_env) @@ -438,7 +447,7 @@ def exercise(root, bin_dir, pg, project, ca, url, pg_env, spatial): dev(bin_dir, env, checkout, "stop", run_root.name) -def exercise_runs(root, bin_dir, pg, checkout, state, env, pg_env): +def exercise_runs(root, bin_dir, pg, checkout, state, env, pg_env, python_client): baseline = inventory(pg, pg_env) baseline_locks = administrator_locks(pg, pg_env) with concurrent.futures.ThreadPoolExecutor(2) as pool: @@ -449,11 +458,11 @@ def exercise_runs(root, bin_dir, pg, checkout, state, env, pg_env): assert all(run["journey"]["result"] == "passed" for run in runs) assert a["run_id"] != b["run_id"] assert len(administrator_locks(pg, pg_env) - baseline_locks) == 2 - assert len({url for run in runs for url in run["products"].values()}) == 4 + assert len({url for run in runs for url in run["products"].values()}) == 6 databases, roles = inventory(pg, pg_env) - assert all(sum(run["run_id"] in item for item in databases) == 3 for run in runs) - assert all(sum(run["run_id"] in item for item in roles) == 6 for run in runs) - for product in ("breg", "casework"): + assert all(sum(run["run_id"] in item for item in databases) == 4 for run in runs) + assert all(sum(run["run_id"] in item for item in roles) == 8 for run in runs) + for product in ("breg", "casework", "messaging"): own_db = next( name for name in databases @@ -485,8 +494,8 @@ def exercise_runs(root, bin_dir, pg, checkout, state, env, pg_env): ("breg", "applicant", "/v1/records/applications?accessProfile=applicant"), ("casework", "intake", "/v1/review-policies/licensing-approval"), ]: - first = credential(bin_dir, env, checkout, a["run_id"], alias) - second = credential(bin_dir, env, checkout, b["run_id"], alias) + first = credential(bin_dir, env, checkout, a["run_id"], alias, product) + second = credential(bin_dir, env, checkout, b["run_id"], alias, product) assert kid(first) != kid(second) assert get(a["products"][product] + path, first) == 200 assert get(b["products"][product] + path, second) == 200 @@ -497,8 +506,48 @@ def exercise_runs(root, bin_dir, pg, checkout, state, env, pg_env): bin_dir, env, state / a["run_id"], - credential(bin_dir, env, checkout, a["run_id"], "applicant"), + credential(bin_dir, env, checkout, a["run_id"], "applicant", "breg"), ) + if python_client is not None: + connection_file = a.get("connection_file") + assert isinstance(connection_file, str), "the run omitted its Python connection" + script = STACK / "products/platform/examples/python-script/script.py" + + def call_python(connection): + return command( + python_client, + script, + env={**env, "REGISTRY_STACK_CONNECTION": str(connection)}, + cwd=checkout, + ) + + result = call_python(connection_file) + assert result.returncode == 0, "the generated Python workload call failed" + receipt = json.loads(result.stdout) + assert receipt["applications"] == 1 and receipt["status"] == "queued" + + for name, mutation in ( + ("foreign-endpoint", ("url", b["products"]["messaging"])), + ("foreign-run", ("runId", b["run_id"])), + ): + alternate = json.loads(Path(connection_file).read_text()) + messaging = next( + binding + for binding in alternate["bindings"] + if binding["product"] == "messaging" + ) + field, value = mutation + target = messaging if field == "url" else messaging["credential"] + target[field] = value + alternate_path = root / f"{name}-python-connection.json" + alternate_path.write_text(json.dumps(alternate)) + alternate_path.chmod(0o600) + refused = call_python(alternate_path) + assert refused.returncode != 0, f"Python accepted a {name} workload" + print( + "A Python service used local BReg and Messaging workload grants; " + "foreign-run and endpoint substitutions failed" + ) print( "Concurrent licensing journeys passed with isolated product tokens, ports, databases and roles" ) @@ -663,7 +712,11 @@ def verify_lost_supervisor(bin_dir, pg, checkout, state, env, pg_env, owner_env) assert recovery["run_directory"] == str(state / run), recovery processes = recovery["processes"] assert processes == recorded - assert sorted(p["product"] for p in processes) == ["breg", "casework"], recovery + assert sorted(p["product"] for p in processes) == [ + "breg", + "casework", + "messaging", + ], recovery assert_nothing_listening(bin_dir, report["products"].values()) databases, roles = inventory(pg, pg_env) assert {item["database"] for item in recovery["objects"]} == ( @@ -703,7 +756,7 @@ def verify_recover(bin_dir, pg, checkout, state, env, pg_env): report, run = lose_supervisor(bin_dir, checkout, state, env) recovered = dev(bin_dir, env, checkout, "stop", run, "--recover") assert recovered["status"] == "stopped", recovered - assert len(recovered["recovered"]["stopped_process_groups"]) == 2, recovered + assert len(recovered["recovered"]["stopped_process_groups"]) == 3, recovered assert_nothing_listening(bin_dir, report["products"].values()) assert inventory(pg, pg_env) == baseline eventually( @@ -725,7 +778,7 @@ def verify_recover(bin_dir, pg, checkout, state, env, pg_env): refused = dev(bin_dir, no_url, checkout, "stop", run, "--recover", expected=3) assert "no PostgreSQL administrator URL" in refused["error"]["message"], refused assert refused["run_id"] == run, refused - assert len(refused["recovery"]["processes"]) == 2, refused + assert len(refused["recovery"]["processes"]) == 3, refused assert (state / run).is_dir() and inventory(pg, pg_env) != baseline dev(bin_dir, env, checkout, "stop", run, "--recover") assert_nothing_listening(bin_dir, report["products"].values()) @@ -876,7 +929,7 @@ def verify_startup_loss(bin_dir, pg, checkout, state, env, pg_env): baseline = inventory(pg, pg_env) shim = state.parent / "slow-bregctl" ready = state.parent / "slow-bregctl-ready" - shim.write_text("""#!/usr/bin/env python3 + shim.write_text(f"""#!{sys.executable} import os import sys import time @@ -899,7 +952,37 @@ def verify_startup_loss(bin_dir, pg, checkout, state, env, pg_env): starting = pool.submit( dev, bin_dir, slow_env, checkout, "start", ".", expected=3 ) - eventually(ready.is_file, "the provisioning tool did not start", timeout=30) + + def rehearsal_started(): + if ready.is_file(): + return True + if starting.done(): + try: + result = starting.result() + except Exception as error: + match = re.search( + r"rstack dev start exited [0-9]+: (\{.*\})", str(error) + ) + try: + report = ast.literal_eval(match.group(1)) if match else {} + except (SyntaxError, ValueError): + report = {} + failure = report.get("error", {}) + no_json = "did not return JSON" in str(error) + exit_code = re.search(r"exit(?:ed)? (-?[0-9]+)", str(error)) + raise AssertionError( + "development startup failed before the BReg rehearsal: " + f"{type(error).__name__}, no_json={no_json}, " + f"exit={exit_code.group(1) if exit_code else 'unknown'}, " + f"{failure.get('class')}, " + f"{[(item.get('code'), item.get('path')) for item in report.get('diagnostics', [])]}" + ) from None + raise AssertionError( + f"development startup returned {result['status']} before the BReg rehearsal" + ) + return False + + eventually(rehearsal_started, "the provisioning tool did not start", timeout=60) [run_root] = live_runs(state) assert not (run_root / "processes.json").exists() assert inventory(pg, pg_env) != baseline @@ -1351,10 +1434,12 @@ def verify_offline_plan(root, bin_dir, project): "RSTACK_DEV_DATABASE_CA", "RSTACK_BREG_BIN", "RSTACK_CASEWORK_BIN", + "RSTACK_MESSAGING_BIN", } } check_env["RSTACK_BREGCTL_BIN"] = str(bin_dir / "bregctl") check_env["RSTACK_CASEWORKCTL_BIN"] = str(bin_dir / "caseworkctl") + check_env["RSTACK_MESSAGINGCTL_BIN"] = str(bin_dir / "messagingctl") check_env["RSTACK_DEV_STATE_DIR"] = str(state) report = dev(bin_dir, check_env, project, "check", ".") assert report["ok"] and report["status"] == "complete" @@ -1403,6 +1488,11 @@ def main(): parser.add_argument("--postgres-bin-dir", type=Path, required=True) parser.add_argument("--scratch-parent", type=Path) parser.add_argument("--spatial", action="store_true", help="also verify PostGIS") + parser.add_argument( + "--python-client", + type=Path, + help="installed-wheel Python executable for the generated workload call", + ) args = parser.parse_args() with tempfile.TemporaryDirectory( prefix="rstack-dev-", dir=args.scratch_parent @@ -1434,6 +1524,7 @@ def main(): url, pg_env, args.spatial, + args.python_client, ) finally: checked(pg / "pg_ctl", "-D", cluster, "-m", "fast", "-w", "stop") diff --git a/release/scripts/assemble-registry-client-packages.py b/release/scripts/assemble-registry-client-packages.py index e468ac1a82..7f45accb21 100644 --- a/release/scripts/assemble-registry-client-packages.py +++ b/release/scripts/assemble-registry-client-packages.py @@ -330,6 +330,32 @@ def python_steps( cwd, ) ) + include_oidc = client_registry.release_version(version) >= (0, 46, 1) + if include_oidc: + if napi_platform.startswith("linux-"): + verifier_argv = ( + str(root / "release" / "scripts" / "build-linux-python-client"), + "--client", "oidc", "--target", PLATFORMS[napi_platform]["rust_target"], + "--compatibility", "manylinux_2_17", "--zig-python", zig_python, + "--maturin", maturin, "--out", str(built), "--profile", python_profile, + ) + verifier_cwd = root + else: + verifier_argv = (maturin, "build", *profile_flags, "--locked", "--out", str(built)) + verifier_cwd = root / "crates" / "registry-platform-oidc-py" + steps.append(Step("build the OIDC verifier wheel", verifier_argv, verifier_cwd)) + if napi_platform.startswith("linux-"): + reader_argv = ( + str(root / "release" / "scripts" / "build-linux-python-client"), + "--client", "yaml", "--target", PLATFORMS[napi_platform]["rust_target"], + "--compatibility", "manylinux_2_17", "--zig-python", zig_python, + "--maturin", maturin, "--out", str(built), "--profile", python_profile, + ) + reader_cwd = root + else: + reader_argv = (maturin, "build", *profile_flags, "--locked", "--out", str(built)) + reader_cwd = root / "crates" / "registry-platform-yaml-py" + steps.append(Step("build the shared configuration reader wheel", reader_argv, reader_cwd)) assemble = [ "python3", str(root / "release" / "scripts" / "assemble-registry-client-wheel.py"), @@ -338,6 +364,15 @@ def python_steps( "--output-dir", str(output_dir), ] + if include_oidc: + assemble += [ + "--include-oidc", + "--oidc-wheel", + str(built / f"registry_platform_oidc-{version}-{wheel_tag}.whl"), + "--include-yaml", + "--yaml-wheel", + str(built / f"registry_platform_yaml-{version}-{wheel_tag}.whl"), + ] if include_casework: assemble.append("--include-casework") if include_messaging: diff --git a/release/scripts/assemble-registry-client-wheel.py b/release/scripts/assemble-registry-client-wheel.py index fe8bd7bdb9..6581fcfeda 100644 --- a/release/scripts/assemble-registry-client-wheel.py +++ b/release/scripts/assemble-registry-client-wheel.py @@ -59,6 +59,26 @@ def metadata(version: str) -> bytes: # PyPI renders the facade README, so the page that a Python developer reads # first carries the install name, the import name, and a working example. description = (FACADE / "README.md").read_text(encoding="utf-8") + project = tomllib.loads((FACADE / "pyproject.toml").read_text(encoding="utf-8"))["project"] + requirements: list[str] = [] + for dependency in project.get("dependencies", []): + if "\n" in dependency or "\r" in dependency: + raise ValueError("invalid Python dependency metadata") + requirements.append(f"Requires-Dist: {dependency}\n") + for extra, dependencies in sorted(project.get("optional-dependencies", {}).items()): + if not re.fullmatch(r"[a-z][a-z0-9-]*", extra): + raise ValueError("invalid Python extra name") + requirements.append(f"Provides-Extra: {extra}\n") + for dependency in dependencies: + if "\n" in dependency or "\r" in dependency: + raise ValueError("invalid Python dependency metadata") + requirement, separator, marker = dependency.partition(";") + if separator: + requirements.append( + f'Requires-Dist: {requirement.strip()}; ({marker.strip()}) and extra == "{extra}"\n' + ) + else: + requirements.append(f'Requires-Dist: {dependency}; extra == "{extra}"\n') return ( "Metadata-Version: 2.4\n" "Name: registry-stack-client\n" @@ -72,6 +92,7 @@ def metadata(version: str) -> bytes: "Classifier: Development Status :: 4 - Beta\n" "Classifier: License :: OSI Approved :: Apache Software License\n" "Classifier: Programming Language :: Python :: 3\n" + f"{''.join(requirements)}" "Description-Content-Type: text/markdown\n\n" f"{description}" ).encode() @@ -106,6 +127,7 @@ def bundle_macos_wheel_files( consumers=consumers, library_roots=library_roots, library_directory=staging / "registry_client" / ".dylibs", + allow_plain_consumers=True, ) return { path.relative_to(staging).as_posix(): path.read_bytes() @@ -142,6 +164,10 @@ def main() -> int: ) parser.add_argument("--include-render", action="store_true") parser.add_argument("--include-coordinator", action="store_true") + parser.add_argument("--include-oidc", action="store_true") + parser.add_argument("--oidc-wheel", type=Path) + parser.add_argument("--include-yaml", action="store_true") + parser.add_argument("--yaml-wheel", type=Path) for product in PRODUCTS: parser.add_argument(f"--{product}-wheel", type=Path, required=product != "render") args = parser.parse_args() @@ -178,9 +204,10 @@ def main() -> int: configured_version = None try: - configured_version = tomllib.loads( + configured_project = tomllib.loads( (FACADE / "pyproject.toml").read_text(encoding="utf-8") - )["project"]["version"] + )["project"] + configured_version = configured_project["version"] except (OSError, KeyError, TypeError, tomllib.TOMLDecodeError) as exc: parser.error(f"cannot read the unified client version: {exc}") if configured_version != args.version: @@ -188,6 +215,14 @@ def main() -> int: "the unified Python facade version does not match " f"{args.version}: {configured_version}" ) + if configured_project.get("optional-dependencies") and not args.include_oidc: + parser.error("Python service extras require --include-oidc and its verifier wheel") + if args.include_oidc != (args.oidc_wheel is not None): + parser.error("--include-oidc requires --oidc-wheel, and the wheel requires the flag") + if args.include_yaml != (args.yaml_wheel is not None): + parser.error("--include-yaml requires --yaml-wheel, and the wheel requires the flag") + if client_registry.release_version(args.version) >= (0, 46, 1) and not args.include_yaml: + parser.error("the Python connection format requires --include-yaml") products = client_registry.stack_python_namespaces(args.version, include_casework=args.include_casework, include_messaging=args.include_messaging, @@ -223,6 +258,38 @@ def main() -> int: if destination in files and files[destination] != data: parser.error(f"conflicting wheel member: {destination}") files[destination] = data + if args.include_oidc: + match = WHEEL_PATTERN.match(args.oidc_wheel.name) + if match is None or match.group("version") != args.version: + parser.error("the OIDC verifier wheel does not match the unified client version") + tags.add(match.group("tag")) + with zipfile.ZipFile(args.oidc_wheel) as archive: + for name in archive.namelist(): + if ".dist-info/" in name or name.endswith("/"): + continue + prefix = "registry_platform_oidc/" + if not name.startswith(prefix): + parser.error("the OIDC verifier wheel contains an unexpected namespace") + destination = f"registry_client/oidc/{name[len(prefix):]}" + if destination in files and files[destination] != archive.read(name): + parser.error(f"conflicting wheel member: {destination}") + files[destination] = archive.read(name) + if args.include_yaml: + match = WHEEL_PATTERN.match(args.yaml_wheel.name) + if match is None or match.group("version") != args.version: + parser.error("the shared configuration reader wheel does not match the unified client version") + tags.add(match.group("tag")) + with zipfile.ZipFile(args.yaml_wheel) as archive: + for name in archive.namelist(): + if ".dist-info/" in name or name.endswith("/"): + continue + prefix = "registry_platform_yaml/" + if not name.startswith(prefix): + parser.error("the shared configuration reader wheel contains an unexpected namespace") + destination = f"registry_client/yaml/{name[len(prefix):]}" + if destination in files and files[destination] != archive.read(name): + parser.error(f"conflicting wheel member: {destination}") + files[destination] = archive.read(name) if len(tags) != 1: parser.error(f"input wheels have different compatibility tags: {sorted(tags)}") tag = tags.pop() @@ -247,7 +314,13 @@ def main() -> int: data = data.replace(b"import registry_client.render as render\n", b"") data = data.replace(b"from . import render as render\n", b"") data = data.replace(b'"render", ', b"") + data = data.replace(b' "render",\n', b"") files[f"registry_client/{path.name}"] = data + if (facade_root / "portal_postgres.py").is_file(): + migration = facade_root / "_sql" / "portal_postgres_v1.sql" + if not migration.is_file(): + parser.error("the portal PostgreSQL migration is missing") + files["registry_client/_sql/portal_postgres_v1.sql"] = migration.read_bytes() try: files["registry_client/compatibility.json"] = compatibility_metadata( args.version diff --git a/release/scripts/build-linux-python-client b/release/scripts/build-linux-python-client index 3ac1a2403a..486ece6526 100755 --- a/release/scripts/build-linux-python-client +++ b/release/scripts/build-linux-python-client @@ -8,10 +8,10 @@ zig_python="" maturin="" output_dir="" profile="release" -while (( "$#" )); do +while (("$#")); do case "$1" in - --client|--target|--compatibility|--zig-python|--maturin|--out|--profile) - if (( "$#" < 2 )); then + --client | --target | --compatibility | --zig-python | --maturin | --out | --profile) + if (("$#" < 2)); then printf '%s requires a value\n' "$1" >&2 exit 2 fi @@ -34,9 +34,9 @@ while (( "$#" )); do done case "${client}" in - discovery|evidence|breg|casework|messaging|scheduling|coordinator|render) ;; + discovery | evidence | breg | casework | messaging | scheduling | coordinator | render | oidc | yaml) ;; *) - printf 'client must be discovery, evidence, breg, casework, messaging, scheduling, coordinator, or render\n' >&2 + printf 'client must be discovery, evidence, breg, casework, messaging, scheduling, coordinator, render, oidc, or yaml\n' >&2 exit 2 ;; esac @@ -55,7 +55,7 @@ case "${rust_target}" in esac case "${compatibility}" in - linux|manylinux_2_17) ;; + linux | manylinux_2_17) ;; *) printf 'compatibility must be linux or manylinux_2_17\n' >&2 exit 2 @@ -80,7 +80,11 @@ esac script_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" repo_root="$(cd -- "${script_dir}/../.." && pwd)" -client_dir="${repo_root}/crates/registry-${client}-client-py" +if [[ "${client}" == "oidc" || "${client}" == "yaml" ]]; then + client_dir="${repo_root}/crates/registry-platform-${client}-py" +else + client_dir="${repo_root}/crates/registry-${client}-client-py" +fi if [[ ! -f "${client_dir}/pyproject.toml" ]]; then printf 'Python client manifest is missing: %s\n' "${client_dir}/pyproject.toml" >&2 exit 2 @@ -127,7 +131,7 @@ fi for driver in zig-cc zig-cxx; do if ! ln -s "${compiler}" "${wrapper_root}/${driver}" 2>/dev/null; then if [[ ! -L "${wrapper_root}/${driver}" || - "$(readlink -- "${wrapper_root}/${driver}")" != "${compiler}" ]]; then + "$(readlink -- "${wrapper_root}/${driver}")" != "${compiler}" ]]; then printf 'unexpected compiler wrapper: %s\n' "${wrapper_root}/${driver}" >&2 exit 2 fi diff --git a/release/scripts/macos_fips_packaging.py b/release/scripts/macos_fips_packaging.py index b2640b4023..de063c314b 100755 --- a/release/scripts/macos_fips_packaging.py +++ b/release/scripts/macos_fips_packaging.py @@ -109,8 +109,12 @@ def _assert_supported_macos_deployment_target(path: Path) -> None: def _assert_plain_macos_loads(path: Path) -> None: _assert_supported_macos_deployment_target(path) + identity_lines = _run(["otool", "-D", str(path)]).splitlines()[1:] + identities = {line.strip() for line in identity_lines if line.strip()} + if len(identities) > 1: + raise PackagingError(f"multiple macOS install names in plain binary {path}") for command in _load_commands(path): - if not command.startswith(SYSTEM_LOAD_PREFIXES): + if command not in identities and not command.startswith(SYSTEM_LOAD_PREFIXES): raise PackagingError( f"non-system macOS load command in plain binary {path}: {command}" ) @@ -190,6 +194,8 @@ def bundle_macos_fips( consumers: Sequence[Path], library_roots: Sequence[Path], library_directory: Path, + *, + allow_plain_consumers: bool = False, ) -> list[str]: """Bundle and relocate the complete FIPS dylib closure for consumers. @@ -215,7 +221,12 @@ def bundle_macos_fips( for consumer in normalized_consumers: loads = _fips_load_commands(consumer) if not loads: - raise PackagingError(f"macOS consumer has no AWS-LC FIPS dylib: {consumer}") + if not allow_plain_consumers: + raise PackagingError( + f"macOS consumer has no AWS-LC FIPS dylib: {consumer}" + ) + _assert_plain_macos_loads(consumer) + continue direct_loads[consumer] = loads pending.extend(loads) diff --git a/release/scripts/smoke-registry-client-extras.py b/release/scripts/smoke-registry-client-extras.py new file mode 100644 index 0000000000..5afc9918d4 --- /dev/null +++ b/release/scripts/smoke-registry-client-extras.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Check isolated optional service installs of an assembled client wheel.""" + +from __future__ import annotations + +import argparse +import importlib.util +from pathlib import Path + +import registry_client +from registry_client.machine import MachineContext + + +def present(name: str) -> bool: + return importlib.util.find_spec(name) is not None + + +def check_dependencies(mode: str) -> None: + expected = { + "flask": mode in ("flask", "human-flask"), + "fastapi": mode in ("fastapi", "human-fastapi"), + "authlib": mode.startswith("human-"), + "psycopg": mode.startswith("human-"), + "cryptography": mode.startswith("human-"), + } + for package, required in expected.items(): + if present(package) != required: + raise AssertionError(f"{mode} has the wrong {package} dependency boundary") + if not callable(registry_client.connect): + raise AssertionError("the installed core API is missing") + if "site-packages" not in Path(registry_client.__file__).resolve().parts: + raise AssertionError("the smoke must import an installed wheel") + + +class Stack: + def admit(self, values): + if values.get("authorization") != ["Bearer synthetic-machine"]: + from registry_client.machine import AdmissionError + + raise AdmissionError() + return MachineContext( + "caller", + "client", + "invoker", + "https://issuer.example.invalid/", + "urn:example:service", + ) + + +def flask_request() -> None: + from flask import Flask, g, jsonify + from registry_client.flask_adapter import install + + app = Flask(__name__) + + @app.get("/work") + def work(): + return jsonify({"subject": g.registry_context.subject}) + + install(app, Stack(), request_seconds=5) + client = app.test_client() + if client.get("/work").status_code != 401: + raise AssertionError("Flask allowed a missing bearer") + response = client.get( + "/work", headers={"Authorization": "Bearer synthetic-machine"} + ) + if response.status_code != 200 or response.json != {"subject": "caller"}: + raise AssertionError("Flask did not admit the installed machine client") + + +def fastapi_request() -> None: + from fastapi import FastAPI, Request + from fastapi.testclient import TestClient + from registry_client.fastapi_adapter import install + + app = FastAPI() + + @app.get("/work") + def work(request: Request): + return {"subject": request.state.registry_context.subject} + + install(app, Stack(), request_seconds=5) + with TestClient(app) as client: + if client.get("/work").status_code != 401: + raise AssertionError("FastAPI allowed a missing bearer") + response = client.get( + "/work", headers={"Authorization": "Bearer synthetic-machine"} + ) + if response.status_code != 200 or response.json() != {"subject": "caller"}: + raise AssertionError("FastAPI did not admit the installed machine client") + + +def human_import(framework: str) -> None: + from registry_client.portal import AuthlibOIDCClient, GrantPolicy + from registry_client.portal_postgres import ( + PortalEncryptionKeys, + PostgresSessionStore, + ) + + if not callable(AuthlibOIDCClient) or not callable(PostgresSessionStore): + raise AssertionError("the human session modules are unavailable") + PortalEncryptionKeys(primary_key_id="test", keys={"test": b"s" * 32}) + policy = GrantPolicy( + "casework", + "urn:example:casework", + ("casework:review", "breg:read"), + "reviewer", + {"registry_actor_kind": "human"}, + forward_resource="urn:example:breg", + ) + if policy.requested_resources != ("urn:example:casework", "urn:example:breg"): + raise AssertionError("the human bridge policy is missing") + if framework == "flask": + from registry_client.portal_flask import install + else: + from registry_client.portal_fastapi import install + if not callable(install): + raise AssertionError("the human framework adapter is unavailable") + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "mode", choices=("core", "flask", "fastapi", "human-flask", "human-fastapi") + ) + mode = parser.parse_args().mode + check_dependencies(mode) + if mode == "flask": + flask_request() + elif mode == "fastapi": + fastapi_request() + elif mode.startswith("human-"): + human_import(mode.removeprefix("human-")) + print(f"Installed Python client {mode} boundary passed") + + +if __name__ == "__main__": + main() diff --git a/release/scripts/smoke-registry-client-service.py b/release/scripts/smoke-registry-client-service.py new file mode 100644 index 0000000000..59598c48e2 --- /dev/null +++ b/release/scripts/smoke-registry-client-service.py @@ -0,0 +1,225 @@ +#!/usr/bin/env python3 +"""Exercise service authority APIs from an installed unified Python wheel.""" + +from __future__ import annotations + +import base64 +from dataclasses import dataclass +import json +from pathlib import Path +import tempfile +import time + +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat + +import registry_client +from registry_client import fastapi_adapter, flask_adapter, portal_fastapi, portal_flask +from registry_client.machine import MachineAdmission +from registry_client.oidc import AccessTokenVerifier, TokenVerificationError +from registry_client.portal import GrantPolicy, PortalContext +from registry_client.portal_postgres import PortalEncryptionKeys +from registry_client.portal_products import bind_person + + +def encoded(value: bytes) -> str: + return base64.urlsafe_b64encode(value).rstrip(b"=").decode("ascii") + + +@dataclass(frozen=True) +class MachineToken: + kind: str = "access" + issuer: str = "https://issuer.example.invalid/" + audiences: tuple[str, ...] = ("urn:example:machine",) + client_id: str = "coordinator-client" + subject: str = "coordinator-service" + scopes: tuple[str, ...] = ("service:invoke",) + claims: dict[str, str] | None = None + + +class MachineVerifier: + def verify(self, token: str) -> MachineToken: + if token != "synthetic-token": + raise ValueError("invalid synthetic token") + return MachineToken(claims={"registry_actor_kind": "machine"}) + + +def main() -> None: + if not callable(registry_client.connect): + raise AssertionError("the installed connection entry point is missing") + for adapter in (fastapi_adapter, flask_adapter, portal_fastapi, portal_flask): + if not callable(adapter.install): + raise AssertionError("the installed framework adapter is missing") + package = Path(registry_client.__file__).resolve() + if "site-packages" not in package.parts: + raise AssertionError("the service smoke must import the installed wheel") + + connection_document = { + "apiVersion": "id.registrystack.org/formats/platform/python-connection/v1alpha1", + "kind": "PlatformPythonConnection", + "service": "installed-wheel-smoke", + "audience": "service", + "secretProviders": {"environment": {}}, + "bindings": [ + { + "name": "notices", + "product": "messaging", + "url": "https://messaging.example.invalid/", + "default": True, + "credential": { + "type": "private-key-jwt", + "issuer": "https://issuer.example.invalid/", + "subject": "notice-service", + "tokenEndpoint": "https://issuer.example.invalid/token", + "clientId": "notice-client", + "profile": "service-sender", + "clientKeyRef": "secret:env/REGISTRY_CLIENT_SMOKE_KEY", + "resource": "urn:registry:messaging:test", + "scopes": ["messaging:send"], + "claims": {"registry_actor_kind": "service"}, + }, + } + ], + } + with tempfile.TemporaryDirectory() as temporary: + connection_path = Path(temporary) / "connection.json" + connection_path.write_text(json.dumps(connection_document), encoding="utf-8") + stack = registry_client.connect(path=connection_path) + authority = stack.authority("messaging") + expected_authority = ( + "messaging", + "https://issuer.example.invalid/", + "notice-service", + "notice-client", + "service-sender", + "urn:registry:messaging:test", + ("messaging:send",), + {"registry_actor_kind": "service"}, + ) + actual_authority = ( + authority.product, + authority.issuer, + authority.subject, + authority.client_id, + authority.profile, + authority.resource, + authority.scopes, + dict(authority.claims), + ) + if actual_authority != expected_authority: + raise AssertionError("the installed connection lost declared authority fields") + if authority.fingerprint != ( + "2695c2353eb6efea60f324d2f432f0cd747bfee5ff5fa84fb5f6b54fc475df35" + ): + raise AssertionError( + "the installed connection changed its authority fingerprint" + ) + + admission = MachineAdmission( + MachineVerifier(), + issuer="https://issuer.example.invalid/", + resource="urn:example:machine", + client_id="coordinator-client", + profile="invoker", + required_scopes=("service:invoke",), + required_claims={"registry_actor_kind": "machine"}, + ) + caller = admission.admit({"authorization": "Bearer synthetic-token"}) + if (caller.issuer, caller.resource) != ( + "https://issuer.example.invalid/", + "urn:example:machine", + ): + raise AssertionError("machine authority lost its issuer or resource") + + context = PortalContext( + "session", + "person", + "person", + "holder", + {"breg": "breg-canary", "casework": "casework-canary"}, + "csrf", + time.time() + 300, + ) + products = bind_person( + context, + persona="holder", + breg_url="https://breg.example.invalid/", + casework_url="https://casework.example.invalid/", + casework_profile="applicant", + ) + if hasattr(products.casework, "review_tasks") or not callable( + products.casework.review_history + ): + raise AssertionError("the installed holder Casework surface is too broad") + PortalEncryptionKeys(primary_key_id="test", keys={"test": b"s" * 32}) + + casework = "urn:example:casework" + breg = "urn:example:breg" + grant = GrantPolicy( + "casework", + casework, + ("casework:review", "breg:read"), + "reviewer", + {"registry_actor_kind": "human"}, + forward_resource=breg, + ) + if grant.requested_resources != (casework, breg): + raise AssertionError("the installed portal lost its forwarded resource") + + key = Ed25519PrivateKey.generate() + public = key.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw) + jwks = json.dumps( + { + "keys": [ + {"kty": "OKP", "crv": "Ed25519", "kid": "test", "x": encoded(public)} + ] + } + ) + verifier = AccessTokenVerifier.from_static_jwks( + jwks, + "https://issuer.example.invalid/", + casework, + "portal-client", + algorithm="EdDSA", + maximum_access_token_lifetime_seconds=600, + clock_skew_seconds=0, + additional_audiences=(breg,), + ) + + def token(audiences: list[str]) -> str: + now = int(time.time()) + header = encoded( + json.dumps({"alg": "EdDSA", "kid": "test", "typ": "at+jwt"}).encode() + ) + claims = encoded( + json.dumps( + { + "iss": "https://issuer.example.invalid/", + "aud": audiences, + "sub": "person", + "azp": "portal-client", + "iat": now, + "nbf": now - 1, + "exp": now + 300, + "scope": "casework:review breg:read", + } + ).encode() + ) + value = f"{header}.{claims}" + return f"{value}.{encoded(key.sign(value.encode('ascii')))}" + + if set(verifier.verify(token([casework, breg])).audiences) != {casework, breg}: + raise AssertionError("the installed native verifier lost the bridge audience") + try: + verifier.verify(token([casework])) + except TokenVerificationError: + pass + else: + raise AssertionError( + "the installed native verifier accepted a partial audience" + ) + print("Installed Python service client smoke passed") + + +if __name__ == "__main__": + main() diff --git a/release/scripts/test_assemble_registry_client_packages.py b/release/scripts/test_assemble_registry_client_packages.py index 3d3d7cda1c..57fe864f2a 100644 --- a/release/scripts/test_assemble_registry_client_packages.py +++ b/release/scripts/test_assemble_registry_client_packages.py @@ -201,7 +201,7 @@ def test_the_binding_wheels_are_built_before_the_public_wheel(self) -> None: for index, line in enumerate(self.rendered) if "maturin build --release --locked" in line ] - self.assertEqual(len(self.module.PRODUCTS), len(builds)) + self.assertEqual(len(self.module.PRODUCTS) + 2, len(builds)) assemble = next( index for index, line in enumerate(self.rendered) @@ -280,6 +280,11 @@ def test_ci_profile_only_changes_all_binding_build_profiles(self) -> None: f"registry-{product}-client-py" for product in self.module.PRODUCTS ] + expected_products.append("registry-platform-oidc-py") + expected_products.append("registry-platform-yaml-py") + else: + expected_products.append("oidc") + expected_products.append("yaml") self.assertEqual(products, expected_products) def test_source_integration_can_explicitly_include_unreleased_messaging(self) -> None: @@ -346,7 +351,7 @@ def test_linux_wheels_use_the_canonical_zig_compiler_helper(self) -> None: for step in steps if step.argv[0].endswith("build-linux-python-client") ] - self.assertEqual(len(builds), len(self.module.PRODUCTS)) + self.assertEqual(len(builds), len(self.module.PRODUCTS) + 2) for product, step in zip(self.module.PRODUCTS, builds): self.assertEqual(step.cwd, ROOT) self.assertIn(("--client", product), tuple(zip(step.argv, step.argv[1:]))) @@ -373,6 +378,30 @@ def test_each_platform_names_the_wheel_tag_its_release_matrix_builds(self) -> No for entry in self.module.PLATFORMS.values(): self.assertIn(f"registry_wheel_tag: {entry['wheel_tag']}", candidate) + def test_python_plan_builds_and_packs_the_oidc_verifier(self) -> None: + steps = self.module.python_steps( + ROOT, "0.46.1", "darwin-arm64", "maturin", Path("/work"), Path("/out") + ) + verifier = [step for step in steps if step.description == "build the OIDC verifier wheel"] + self.assertEqual(len(verifier), 1) + self.assertEqual(verifier[0].cwd, ROOT / "crates" / "registry-platform-oidc-py") + assemble = steps[-1].argv + self.assertIn("--include-oidc", assemble) + self.assertIn("--oidc-wheel", assemble) + self.assertIn( + "/work/product-wheels/registry_platform_oidc-0.46.1-cp311-abi3-macosx_11_0_arm64.whl", + assemble, + ) + reader = [step for step in steps if step.description == "build the shared configuration reader wheel"] + self.assertEqual(len(reader), 1) + self.assertEqual(reader[0].cwd, ROOT / "crates" / "registry-platform-yaml-py") + self.assertIn("--include-yaml", assemble) + self.assertIn("--yaml-wheel", assemble) + self.assertIn( + "/work/product-wheels/registry_platform_yaml-0.46.1-cp311-abi3-macosx_11_0_arm64.whl", + assemble, + ) + def test_the_artifact_selection_splits_the_two_halves(self) -> None: node_only = self.candidate_plan( ROOT, "9.9.9", "darwin-arm64", "node", "maturin", Path("/work"), Path("/out") diff --git a/release/scripts/test_assemble_registry_client_wheel.py b/release/scripts/test_assemble_registry_client_wheel.py index 845137b815..966a8b83d1 100644 --- a/release/scripts/test_assemble_registry_client_wheel.py +++ b/release/scripts/test_assemble_registry_client_wheel.py @@ -46,7 +46,7 @@ def setUp(self) -> None: pyproject = self.facade / "pyproject.toml" configured_version = tomllib.loads(pyproject.read_text(encoding="utf-8"))["project"]["version"] pyproject.write_text( - pyproject.read_text(encoding="utf-8").replace( + pyproject.read_text(encoding="utf-8").split("\n[project.optional-dependencies]\n")[0].replace( f'version = "{configured_version}"', f'version = "{self.version}"' ), encoding="utf-8", @@ -88,11 +88,25 @@ def setUp(self) -> None: f"Name: registry-{product}-client\nVersion: {self.version}\n", ) self.wheels[product] = wheel + self.oidc_wheel = self.directory / f"registry_platform_oidc-{self.version}-{TAG}.whl" + with zipfile.ZipFile(self.oidc_wheel, "w") as archive: + archive.writestr("registry_platform_oidc/__init__.py", "class AccessTokenVerifier: pass\n") + archive.writestr("registry_platform_oidc/__init__.pyi", "class AccessTokenVerifier: ...\n") + archive.writestr("registry_platform_oidc/py.typed", b"") + archive.writestr("registry_platform_oidc/registry_platform_oidc.abi3.so", b"native") + self.yaml_wheel = self.directory / f"registry_platform_yaml-{self.version}-{TAG}.whl" + with zipfile.ZipFile(self.yaml_wheel, "w") as archive: + archive.writestr("registry_platform_yaml/__init__.py", "class ConfigReadError: pass\n") + archive.writestr("registry_platform_yaml/__init__.pyi", "class ConfigReadError: ...\n") + archive.writestr("registry_platform_yaml/py.typed", b"") + archive.writestr("registry_platform_yaml/registry_platform_yaml.abi3.so", b"native") def run_assembler( self, *, version: str | None = None, include_casework: bool = False, include_messaging: bool = False, include_scheduling: bool = False, - include_coordinator: bool = True, include_render: bool = True + include_coordinator: bool = True, include_render: bool = True, + include_oidc: bool = False, + include_yaml: bool = False, ) -> subprocess.CompletedProcess[str]: command = [ "python3", @@ -106,6 +120,10 @@ def run_assembler( command.append("--include-render") if include_coordinator: command.append("--include-coordinator") + if include_oidc: + command.extend(("--include-oidc", "--oidc-wheel", str(self.oidc_wheel))) + if include_yaml: + command.extend(("--include-yaml", "--yaml-wheel", str(self.yaml_wheel))) if include_casework: command.append("--include-casework") if include_messaging: @@ -255,6 +273,90 @@ def test_the_pypi_page_states_the_install_name_and_the_import_name(self) -> None for product in PRODUCTS: self.assertIn(f"`registry_client.{product}`", description) + def test_connection_core_is_in_the_wheel_without_web_dependencies(self) -> None: + result = self.run_assembler() + self.assertEqual(result.returncode, 0, result.stderr) + with zipfile.ZipFile(Path(result.stdout.strip())) as archive: + names = set(archive.namelist()) + self.assertIn("registry_client/connection.py", names) + self.assertIn("registry_client/connection.pyi", names) + self.assertIn("registry_client/workload.py", names) + self.assertIn("registry_client/workload.pyi", names) + self.assertIn("registry_client/runner.py", names) + self.assertIn("registry_client/machine.py", names) + self.assertIn("registry_client/machine.pyi", names) + for module in ("web", "flask_adapter", "fastapi_adapter"): + self.assertIn(f"registry_client/{module}.py", names) + self.assertIn(f"registry_client/{module}.pyi", names) + self.assertIn("registry_client/workload_breg.py", names) + self.assertIn("registry_client/workload_breg.pyi", names) + self.assertIn("registry_client/py.typed", names) + self.assertIn("registry_client/_sql/portal_postgres_v1.sql", names) + metadata = archive.read( + f"registry_stack_client-{self.version}.dist-info/METADATA" + ).decode() + for line in metadata.splitlines(): + if line.lower().startswith( + ("requires-dist: flask", "requires-dist: fastapi", "requires-dist: authlib") + ): + self.assertIn('extra == "', line) + + def test_optional_dependencies_in_project_are_emitted_in_wheel_metadata(self) -> None: + pyproject = self.facade / "pyproject.toml" + with pyproject.open("a", encoding="utf-8") as project: + project.write( + "\n[project.optional-dependencies]\n" + 'flask = ["Flask>=3.1,<4"]\n' + 'fastapi = ["fastapi>=0.115,<1"]\n' + ) + result = self.run_assembler(include_oidc=True) + self.assertEqual(result.returncode, 0, result.stderr) + with zipfile.ZipFile(Path(result.stdout.strip())) as archive: + metadata = archive.read( + f"registry_stack_client-{self.version}.dist-info/METADATA" + ).decode() + self.assertIn("Provides-Extra: flask\n", metadata) + self.assertIn('Requires-Dist: Flask>=3.1,<4; extra == "flask"\n', metadata) + self.assertIn("Provides-Extra: fastapi\n", metadata) + self.assertIn('Requires-Dist: fastapi>=0.115,<1; extra == "fastapi"\n', metadata) + + def test_current_extras_keep_optional_frameworks_and_session_packages_out_of_core(self) -> None: + module = load_module() + metadata = module.metadata("0.46.1").decode() + self.assertIn('Requires-Dist: Flask>=3.1,<4; extra == "flask"', metadata) + self.assertIn('Requires-Dist: fastapi>=0.115,<1; extra == "fastapi"', metadata) + self.assertIn('Requires-Dist: Authlib>=1.9.5,<2; extra == "human"', metadata) + self.assertIn('Requires-Dist: psycopg[binary]>=3.3.6,<4; extra == "postgres"', metadata) + self.assertNotIn("Requires-Dist: Flask>=3.1,<4\n", metadata) + + def test_oidc_extra_cannot_be_advertised_without_verifier_wheel(self) -> None: + pyproject = self.facade / "pyproject.toml" + with pyproject.open("a", encoding="utf-8") as project: + project.write('\n[project.optional-dependencies]\nflask = ["Flask>=3.1,<4"]\n') + result = self.run_assembler() + self.assertEqual(result.returncode, 2) + self.assertIn("--include-oidc", result.stderr) + + def test_optional_verifier_is_relocated_with_typing(self) -> None: + result = self.run_assembler(include_oidc=True) + self.assertEqual(result.returncode, 0, result.stderr) + with zipfile.ZipFile(Path(result.stdout.strip())) as archive: + names = set(archive.namelist()) + self.assertIn("registry_client/oidc/__init__.py", names) + self.assertIn("registry_client/oidc/__init__.pyi", names) + self.assertIn("registry_client/oidc/py.typed", names) + self.assertIn("registry_client/oidc/registry_platform_oidc.abi3.so", names) + + def test_shared_configuration_reader_is_relocated_with_typing(self) -> None: + result = self.run_assembler(include_yaml=True) + self.assertEqual(result.returncode, 0, result.stderr) + with zipfile.ZipFile(Path(result.stdout.strip())) as archive: + names = set(archive.namelist()) + self.assertIn("registry_client/yaml/__init__.py", names) + self.assertIn("registry_client/yaml/__init__.pyi", names) + self.assertIn("registry_client/yaml/py.typed", names) + self.assertIn("registry_client/yaml/registry_platform_yaml.abi3.so", names) + def test_assembled_facade_imports_all_six_product_namespaces(self) -> None: result = self.run_assembler() self.assertEqual(result.returncode, 0, result.stderr) @@ -358,12 +460,13 @@ def test_macos_extensions_are_relinked_before_wheel_recording(self) -> None: files["registry_client/discovery/client.py"] = b"class Client: pass\n" seen: dict[str, object] = {} - def fake_bundle(*, consumers, library_roots, library_directory): + def fake_bundle(*, consumers, library_roots, library_directory, allow_plain_consumers): seen["consumers"] = [ path.relative_to(library_directory.parents[1]).as_posix() for path in consumers ] seen["library_roots"] = list(library_roots) + seen["allow_plain_consumers"] = allow_plain_consumers for consumer in consumers: consumer.write_bytes(consumer.read_bytes() + b" signed") library_directory.mkdir(parents=True) @@ -382,6 +485,7 @@ def fake_bundle(*, consumers, library_roots, library_directory): ), ) self.assertEqual(seen["library_roots"], [Path("/cargo-target")]) + self.assertTrue(seen["allow_plain_consumers"]) for product in PRODUCTS: self.assertEqual( bundled[f"registry_client/{product}/native.abi3.so"], diff --git a/release/scripts/test_macos_fips_packaging.py b/release/scripts/test_macos_fips_packaging.py index 0273ec11a0..14b25f5a62 100755 --- a/release/scripts/test_macos_fips_packaging.py +++ b/release/scripts/test_macos_fips_packaging.py @@ -46,6 +46,12 @@ def setUp(self) -> None: print(f" minos {line.split('=', 1)[1]}") print(" sdk 26.5") raise SystemExit(0) +if sys.argv[1] == "-D": + print(f"{path}:") + for line in path.read_text().splitlines(): + if line.startswith("id="): + print(line.split("=", 1)[1]) + raise SystemExit(0) print(f"{path}:") for line in path.read_text().splitlines(): if line.startswith(("id=", "load=")): @@ -139,6 +145,40 @@ def test_missing_and_nonidentical_libraries_are_refused(self) -> None: with self.assertRaisesRegex(MODULE.PackagingError, "2 nonidentical files"): MODULE.bundle_macos_fips([consumer], roots, self.root / "ambiguous") + def test_plain_extension_can_join_a_fips_wheel_without_unchecked_loads( + self, + ) -> None: + package = self.root / "package" + fips = package / "registry_client" / "oidc" / "native.so" + plain = package / "registry_client" / "yaml" / "native.so" + self._macho(fips, f"@rpath/{CRYPTO}") + self._macho( + plain, + "/usr/lib/libSystem.B.dylib", + identity="@rpath/registry_platform_yaml.registry_platform_yaml.abi3.so", + ) + libraries = self.root / "build" + self._macho(libraries / CRYPTO, identity=f"@rpath/{CRYPTO}") + + with self.assertRaisesRegex(MODULE.PackagingError, "no AWS-LC FIPS dylib"): + MODULE.bundle_macos_fips([fips, plain], [libraries], package / ".dylibs") + + names = MODULE.bundle_macos_fips( + [fips, plain], [libraries], package / ".dylibs", allow_plain_consumers=True + ) + self.assertEqual(names, [CRYPTO]) + self.assertIn("/usr/lib/libSystem.B.dylib", plain.read_text()) + + disallowed = package / "registry_client" / "yaml" / "untrusted.so" + self._macho(disallowed, "@rpath/libunexpected.dylib") + with self.assertRaisesRegex(MODULE.PackagingError, "non-system macOS load"): + MODULE.bundle_macos_fips( + [disallowed], + [libraries], + package / "rejected", + allow_plain_consumers=True, + ) + def test_byte_identical_library_copies_are_one_unambiguous_input(self) -> None: consumer = self.root / "consumer" self._macho(consumer, f"@rpath/{CRYPTO}") From 1ca793f8dbbcc9038414d78f7c3ccd78c0264ee1 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 03:41:34 +0700 Subject: [PATCH 06/34] docs(breg): record local Python grant boundaries Signed-off-by: Jeremi Joslin --- products/breg/SECURITY-MODEL.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/products/breg/SECURITY-MODEL.md b/products/breg/SECURITY-MODEL.md index bfc21f025e..d512c9721e 100644 --- a/products/breg/SECURITY-MODEL.md +++ b/products/breg/SECURITY-MODEL.md @@ -496,6 +496,22 @@ mitigation, and related matrix IDs. refuses it with `breg.runtime.plaintext-database`. `rstack dev` can instead activate BReg as part of an isolated project run. +Its generated Python connection and person picker remain inside that run's +owner-only state. Workload bindings name one configured product endpoint, +issuer, subject, client, profile, resource, scopes and declared claims; the +runner replaces short-lived token state atomically without extending the run. +The Python client checks each generation against the declared binding and +refuses a stopped, expired, mismatched or reversed generation before another +product call. A picker accepts only its live-run descriptor and exact loopback +origin, resolves a complete declared person grant set before opening a session, +and keeps tokens and the issuer signing key out of the browser. The picker is +local admission simulation, not proof of production OIDC or consent. The +session owner can edit or replace these private development files; production +deployments require an operated issuer, separate registrations and the +runtime's own token and access-profile checks. The runner and picker +regressions are in `crates/registry-bregctl/src/project_dev/` and +`crates/registry-stack-client-py/tests/test_dev_picker.py`; the combined +licensing journey uses `products/platform/scripts/test-rstack-dev.py`. It uses the normal package and database activation checks, distinct TLS PostgreSQL credentials, and a loopback listener. The runtime trusts the run's static signing key under the declared issuer name. See From 08b8a4a511e1914b96f6e9aea88f1884dbf311a1 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 04:27:03 +0700 Subject: [PATCH 07/34] fix: close Python service admission and session gaps Signed-off-by: Jeremi Joslin --- .../tests/deployment_postgres.rs | 6 + .../python/registry_client/connection.py | 5 +- .../python/registry_client/portal.py | 68 ++++++- .../python/registry_client/portal.pyi | 13 ++ .../python/registry_client/portal_fastapi.py | 48 ++++- .../python/registry_client/portal_flask.py | 58 +++++- .../python/registry_client/portal_postgres.py | 32 +++- .../registry_client/portal_postgres.pyi | 3 + .../tests/test_connection.py | 19 ++ .../tests/test_portal.py | 38 ++++ .../tests/test_portal_fastapi.py | 16 +- .../tests/test_portal_frameworks.py | 178 +++++++++++++++++- .../tests/test_portal_postgres.py | 101 +++++++++- products/coordinator/SECURITY-MODEL.md | 8 + .../examples/external-job/README.md | 50 +++-- .../examples/external-job/runtime.yaml | 11 ++ .../examples/external-job/service.py | 42 ++++- .../external-job/tests/test_runtime.py | 26 +++ .../external-job/tests/test_service.py | 132 +++++++++++-- .../examples/python-machine-service/README.md | 5 +- .../examples/python-machine-service/effect.py | 55 +++++- .../python-machine-service/service.py | 35 +++- .../tests/test_effect.py | 117 ++++++++++++ .../tests/test_service.py | 88 ++++++++- .../scripts/smoke-registry-client-extras.py | 31 ++- 25 files changed, 1102 insertions(+), 83 deletions(-) create mode 100644 products/coordinator/examples/external-job/tests/test_runtime.py diff --git a/crates/registry-coordinator/tests/deployment_postgres.rs b/crates/registry-coordinator/tests/deployment_postgres.rs index 4f39730e6d..78de71e255 100644 --- a/crates/registry-coordinator/tests/deployment_postgres.rs +++ b/crates/registry-coordinator/tests/deployment_postgres.rs @@ -5096,6 +5096,12 @@ async fn generated_typed_client_journeys(projects: &[&str]) { RuntimeConfig::load(&examples.join("external-job/runtime.yaml")).unwrap(); f.doc["connections"]["jobs"] = serde_json::to_value(&external.connections["jobs"]).unwrap(); + // This fixture exercises the workflow's GET observation against a mock + // provider; it has no issuer for the example service authorization. + f.doc["connections"]["jobs"] + .as_object_mut() + .unwrap() + .remove("authorization"); f.doc["connections"]["jobs"]["baseUrl"] = json!(jobs.as_ref().unwrap().uri()); } if workflow == "standalone-review" { diff --git a/crates/registry-stack-client-py/python/registry_client/connection.py b/crates/registry-stack-client-py/python/registry_client/connection.py index d311dea8be..f6feedb4dc 100644 --- a/crates/registry-stack-client-py/python/registry_client/connection.py +++ b/crates/registry-stack-client-py/python/registry_client/connection.py @@ -128,8 +128,9 @@ def _reference(value: Any, path: str, providers: Mapping[str, Any]) -> str: if not isinstance(value, str) or not _REFERENCE.fullmatch(value): raise ConnectionError(f"{path} must be a secret:file or secret:env reference") provider = value[7:].split("/", 1)[0] - if provider not in providers: - raise ConnectionError(f"{path} needs the declared {provider} secret provider") + declared = "environment" if provider == "env" else provider + if declared not in providers: + raise ConnectionError(f"{path} needs the declared {declared} secret provider") return value diff --git a/crates/registry-stack-client-py/python/registry_client/portal.py b/crates/registry-stack-client-py/python/registry_client/portal.py index b904e56d00..0e733a0934 100644 --- a/crates/registry-stack-client-py/python/registry_client/portal.py +++ b/crates/registry-stack-client-py/python/registry_client/portal.py @@ -29,6 +29,10 @@ def __init__(self): super().__init__(self.code) +class _PendingChainMismatch(AdmissionError): + """Callback state does not belong to the browser's current login chain.""" + + class ReauthenticationRequired(ValueError): """No complete usable server-side session remains.""" @@ -254,6 +258,10 @@ def put_pending(self, pending: PendingGrant) -> bool: ... def consume_pending(self, state: str) -> PendingGrant | None: ... + def consume_pending_for_chain( + self, state: str, chain_id: str + ) -> PendingGrant | None: ... + def close_chain(self, chain_id: str) -> None: ... def create_session(self, chain_id: str, session: PortalSession) -> bool: ... @@ -275,6 +283,7 @@ class MemorySessionStore: def __init__(self): self._pending: dict[str, PendingGrant] = {} self._sessions: dict[str, PortalSession] = {} + self._open_chains: set[str] = set() self._closed_chains: set[str] = set() self._lock = threading.Lock() self._refresh_locks = WeakValueDictionary() @@ -297,6 +306,7 @@ def put_pending(self, pending: PendingGrant) -> bool: or pending.state in self._pending ): return False + self._open_chains.add(pending.chain_id) self._pending[pending.state] = pending return True @@ -307,8 +317,25 @@ def consume_pending(self, state: str) -> PendingGrant | None: return None return pending + def consume_pending_for_chain( + self, state: str, chain_id: str + ) -> PendingGrant | None: + with self._lock: + pending = self._pending.get(state) + if ( + pending is None + or pending.chain_id in self._closed_chains + or not hmac.compare_digest(pending.chain_id, chain_id) + ): + return None + del self._pending[state] + return pending + def close_chain(self, chain_id: str) -> None: with self._lock: + if chain_id not in self._open_chains: + return + self._open_chains.remove(chain_id) self._closed_chains.add(chain_id) self._pending = { state: pending @@ -318,9 +345,14 @@ def close_chain(self, chain_id: str) -> None: def create_session(self, chain_id: str, session: PortalSession) -> bool: with self._lock: - if chain_id in self._closed_chains or session.session_id in self._sessions: + if ( + chain_id not in self._open_chains + or chain_id in self._closed_chains + or session.session_id in self._sessions + ): return False self._sessions[session.session_id] = session + self._open_chains.remove(chain_id) self._closed_chains.add(chain_id) return True @@ -383,8 +415,26 @@ def replace_account( return self.start(return_to) def callback(self, callback_url: str, *, state: str) -> CallbackResult: - pending = self._store.consume_pending(state) + return self._callback(callback_url, state=state, chain_id=None) + + def _callback_for_chain( + self, callback_url: str, *, state: str, chain_id: str + ) -> CallbackResult: + """Complete only the login chain held by this browser.""" + return self._callback(callback_url, state=state, chain_id=chain_id) + + def _callback( + self, callback_url: str, *, state: str, chain_id: str | None + ) -> CallbackResult: + if chain_id is None: + pending = self._store.consume_pending(state) + else: + if not _valid_chain_id(chain_id): + raise _PendingChainMismatch() + pending = self._store.consume_pending_for_chain(state, chain_id) if pending is None: + if chain_id is not None: + raise _PendingChainMismatch() raise AdmissionError() now = self._clock() try: @@ -439,7 +489,8 @@ def callback(self, callback_url: str, *, state: str) -> CallbackResult: raise AdmissionError() from None def cancel(self, chain_id: str) -> None: - self._store.close_chain(chain_id) + if _valid_chain_id(chain_id): + self._store.close_chain(chain_id) def context( self, session_id: str, *, minimum_valid_seconds: float = 30 @@ -887,6 +938,17 @@ def _token(value: str) -> bool: ) +def _valid_chain_id(value: str) -> bool: + return bool( + isinstance(value, str) + and len(value) == 43 + and all( + character.isascii() and (character.isalnum() or character in ("-", "_")) + for character in value + ) + ) + + def _text(value: str) -> bool: return bool( isinstance(value, str) diff --git a/crates/registry-stack-client-py/python/registry_client/portal.pyi b/crates/registry-stack-client-py/python/registry_client/portal.pyi index bced59175a..5053253490 100644 --- a/crates/registry-stack-client-py/python/registry_client/portal.pyi +++ b/crates/registry-stack-client-py/python/registry_client/portal.pyi @@ -4,6 +4,8 @@ from typing import Any, ContextManager, Protocol class AdmissionError(ValueError): code: str +class _PendingChainMismatch(AdmissionError): ... + class ReauthenticationRequired(ValueError): code: str @@ -152,6 +154,9 @@ class SessionStore(Protocol): def refresh_lock(self, session_id: str) -> ContextManager[None]: ... def put_pending(self, pending: PendingGrant) -> bool: ... def consume_pending(self, state: str) -> PendingGrant | None: ... + def consume_pending_for_chain( + self, state: str, chain_id: str + ) -> PendingGrant | None: ... def close_chain(self, chain_id: str) -> None: ... def create_session(self, chain_id: str, session: PortalSession) -> bool: ... def get_session(self, session_id: str) -> PortalSession | None: ... @@ -167,6 +172,9 @@ class MemorySessionStore(SessionStore): def refresh_lock(self, session_id: str) -> ContextManager[None]: ... def put_pending(self, pending: PendingGrant) -> bool: ... def consume_pending(self, state: str) -> PendingGrant | None: ... + def consume_pending_for_chain( + self, state: str, chain_id: str + ) -> PendingGrant | None: ... def close_chain(self, chain_id: str) -> None: ... def create_session(self, chain_id: str, session: PortalSession) -> bool: ... def get_session(self, session_id: str) -> PortalSession | None: ... @@ -192,6 +200,9 @@ class PortalSessions: self, session_id: str, return_to: str = ... ) -> AuthorizationRequest: ... def callback(self, callback_url: str, *, state: str) -> CallbackResult: ... + def _callback_for_chain( + self, callback_url: str, *, state: str, chain_id: str + ) -> CallbackResult: ... def cancel(self, chain_id: str) -> None: ... def context( self, session_id: str, *, minimum_valid_seconds: float = ... @@ -206,6 +217,8 @@ TokenVerifier = Callable[ VerifiedGrant, ] +def _valid_chain_id(value: str) -> bool: ... + class AuthlibOIDCClient(OIDCClient): def __init__( self, diff --git a/crates/registry-stack-client-py/python/registry_client/portal_fastapi.py b/crates/registry-stack-client-py/python/registry_client/portal_fastapi.py index a0d51dde3d..6dcd1f7f99 100644 --- a/crates/registry-stack-client-py/python/registry_client/portal_fastapi.py +++ b/crates/registry-stack-client-py/python/registry_client/portal_fastapi.py @@ -9,6 +9,8 @@ PortalContext, PortalSessions, ReauthenticationRequired, + _PendingChainMismatch, + _valid_chain_id, ) from .web import form_csrf_token, is_public from .workload import request_budget @@ -32,6 +34,7 @@ def install( if persona not in ("holder", "staff") or same_site not in ("Lax", "Strict"): raise ValueError("portal persona and SameSite policy are unsupported") cookie_name = f"__Host-registry-{persona}" + pending_cookie_name = f"__Host-registry-{persona}-pending" auth_paths = frozenset( ("/auth/login", "/auth/callback", "/auth/logout", "/auth/switch") ) @@ -53,18 +56,23 @@ def route_is_public(scope: MutableMapping[str, Any]) -> bool: def request_origin(request: Request) -> str: return f"{request.url.scheme}://{request.headers.get('host', '')}" - def clear_cookie(response: Any) -> None: + def clear_cookie(response: Any, name: str, *, pending: bool = False) -> None: response.set_cookie( - cookie_name, + name, "", max_age=0, expires=0, secure=True, httponly=True, - samesite="lax" if same_site == "Lax" else "strict", + samesite=("lax" if pending or same_site == "Lax" else "strict"), path="/", ) + async def cancel_pending(request: Request) -> None: + chain_id = request.cookies.get(pending_cookie_name) + if chain_id and _valid_chain_id(chain_id): + await asyncio.to_thread(sessions.cancel, chain_id) + async def authorized_mutation(request: Request) -> PortalContext: session_id = request.cookies.get(cookie_name) if not session_id: @@ -120,25 +128,46 @@ async def admit_request(request: Request, call_next: Callable): @app.get("/auth/login") async def registry_login(request: Request): try: + await cancel_pending(request) authorization = await asyncio.to_thread( sessions.start, request.query_params.get("return_to", "/") ) except ValueError: return error(AdmissionError.code, 400) response = RedirectResponse(authorization.url, status_code=302) + response.set_cookie( + pending_cookie_name, + authorization.chain_id, + secure=True, + httponly=True, + samesite="lax", + path="/", + ) response.headers["Cache-Control"] = "no-store" return response @app.get("/auth/callback") async def registry_callback(request: Request): + chain_id = request.cookies.get(pending_cookie_name) + if not chain_id: + return error(AdmissionError.code, 401) + if not _valid_chain_id(chain_id): + response = error(AdmissionError.code, 401) + clear_cookie(response, pending_cookie_name, pending=True) + return response try: result = await asyncio.to_thread( - sessions.callback, + sessions._callback_for_chain, str(request.url), state=request.query_params.get("state", ""), + chain_id=chain_id, ) - except AdmissionError: + except _PendingChainMismatch: return error(AdmissionError.code, 401) + except AdmissionError: + response = error(AdmissionError.code, 401) + clear_cookie(response, pending_cookie_name, pending=True) + return response if result.authorization is not None: response = RedirectResponse(result.authorization.url, status_code=302) else: @@ -153,6 +182,7 @@ async def registry_callback(request: Request): samesite="lax" if same_site == "Lax" else "strict", path="/", ) + clear_cookie(response, pending_cookie_name, pending=True) response.headers["Cache-Control"] = "no-store" return response @@ -164,9 +194,11 @@ async def registry_logout(request: Request): return error(ReauthenticationRequired.code, 401) except CSRFError: return error(CSRFError.code, 403) + await cancel_pending(request) result = await asyncio.to_thread(sessions.logout, request.cookies[cookie_name]) response = RedirectResponse(result.end_session_url or "/", status_code=302) - clear_cookie(response) + clear_cookie(response, cookie_name) + clear_cookie(response, pending_cookie_name, pending=True) response.headers["Cache-Control"] = "no-store" return response @@ -178,6 +210,7 @@ async def registry_switch(request: Request): return error(ReauthenticationRequired.code, 401) except CSRFError: return error(CSRFError.code, 403) + await cancel_pending(request) result = await asyncio.to_thread( sessions.logout, request.cookies[cookie_name], switch=True ) @@ -185,6 +218,7 @@ async def registry_switch(request: Request): response = RedirectResponse(result.end_session_url, status_code=302) else: response = error("authentication.account-switch-unavailable", 409) - clear_cookie(response) + clear_cookie(response, cookie_name) + clear_cookie(response, pending_cookie_name, pending=True) response.headers["Cache-Control"] = "no-store" return response diff --git a/crates/registry-stack-client-py/python/registry_client/portal_flask.py b/crates/registry-stack-client-py/python/registry_client/portal_flask.py index ae79fc404f..7929009389 100644 --- a/crates/registry-stack-client-py/python/registry_client/portal_flask.py +++ b/crates/registry-stack-client-py/python/registry_client/portal_flask.py @@ -10,6 +10,8 @@ PortalContext, PortalSessions, ReauthenticationRequired, + _PendingChainMismatch, + _valid_chain_id, ) from .web import form_csrf_token, is_public from .workload import request_budget @@ -31,6 +33,7 @@ def install( if persona not in ("holder", "staff") or same_site not in ("Lax", "Strict"): raise ValueError("portal persona and SameSite policy are unsupported") cookie_name = f"__Host-registry-{persona}" + pending_cookie_name = f"__Host-registry-{persona}-pending" auth_paths = frozenset( ("/auth/login", "/auth/callback", "/auth/logout", "/auth/switch") ) @@ -41,6 +44,20 @@ def error(code: str, status: int): response.headers["Cache-Control"] = "no-store" return response + def clear_cookie(response: Any, name: str, *, pending: bool = False) -> None: + response.delete_cookie( + name, + path="/", + secure=True, + httponly=True, + samesite="Lax" if pending else same_site, + ) + + def cancel_pending() -> None: + chain_id = request.cookies.get(pending_cookie_name) + if chain_id and _valid_chain_id(chain_id): + sessions.cancel(chain_id) + def authorized_mutation(): session_id = request.cookies.get(cookie_name) if not session_id: @@ -97,19 +114,43 @@ def finish_request(_error): @app.get("/auth/login") def registry_login(): try: + cancel_pending() authorization = sessions.start(request.args.get("return_to", "/")) except ValueError: return error(AdmissionError.code, 400) response = redirect(authorization.url) + response.set_cookie( + pending_cookie_name, + authorization.chain_id, + secure=True, + httponly=True, + samesite="Lax", + path="/", + ) response.headers["Cache-Control"] = "no-store" return response @app.get("/auth/callback") def registry_callback(): + chain_id = request.cookies.get(pending_cookie_name) + if not chain_id: + return error(AdmissionError.code, 401) + if not _valid_chain_id(chain_id): + response = error(AdmissionError.code, 401) + clear_cookie(response, pending_cookie_name, pending=True) + return response try: - result = sessions.callback(request.url, state=request.args.get("state", "")) - except AdmissionError: + result = sessions._callback_for_chain( + request.url, + state=request.args.get("state", ""), + chain_id=chain_id, + ) + except _PendingChainMismatch: return error(AdmissionError.code, 401) + except AdmissionError: + response = error(AdmissionError.code, 401) + clear_cookie(response, pending_cookie_name, pending=True) + return response if result.authorization is not None: response = redirect(result.authorization.url) else: @@ -124,6 +165,7 @@ def registry_callback(): samesite=same_site, path="/", ) + clear_cookie(response, pending_cookie_name, pending=True) response.headers["Cache-Control"] = "no-store" return response @@ -135,11 +177,11 @@ def registry_logout(): return error(ReauthenticationRequired.code, 401) except CSRFError: return error(CSRFError.code, 403) + cancel_pending() result = sessions.logout(request.cookies[cookie_name]) response = redirect(result.end_session_url or "/") - response.delete_cookie( - cookie_name, path="/", secure=True, httponly=True, samesite=same_site - ) + clear_cookie(response, cookie_name) + clear_cookie(response, pending_cookie_name, pending=True) response.headers["Cache-Control"] = "no-store" return response @@ -151,6 +193,7 @@ def registry_switch(): return error(ReauthenticationRequired.code, 401) except CSRFError: return error(CSRFError.code, 403) + cancel_pending() result = sessions.logout(request.cookies[cookie_name], switch=True) response = ( redirect(result.end_session_url) @@ -159,8 +202,7 @@ def registry_switch(): jsonify({"code": "authentication.account-switch-unavailable"}), 409 ) ) - response.delete_cookie( - cookie_name, path="/", secure=True, httponly=True, samesite=same_site - ) + clear_cookie(response, cookie_name) + clear_cookie(response, pending_cookie_name, pending=True) response.headers["Cache-Control"] = "no-store" return response diff --git a/crates/registry-stack-client-py/python/registry_client/portal_postgres.py b/crates/registry-stack-client-py/python/registry_client/portal_postgres.py index 7e6a697d1d..66a17c033b 100644 --- a/crates/registry-stack-client-py/python/registry_client/portal_postgres.py +++ b/crates/registry-stack-client-py/python/registry_client/portal_postgres.py @@ -271,15 +271,39 @@ def consume_pending(self, state: str) -> PendingGrant | None: raise SessionStateError("portal session state is unreadable") return result + def consume_pending_for_chain( + self, state: str, chain_id: str + ) -> PendingGrant | None: + state_digest = _lookup_digest("state", state) + chain_digest = _lookup_digest("chain", chain_id) + row = None + with self._transaction() as cursor: + self._assert_ready(cursor) + cursor.execute( + "DELETE FROM registry_client_portal.pending " + "WHERE state_digest = %s AND chain_digest = %s " + "RETURNING key_id, ciphertext", + (state_digest, chain_digest), + ) + row = cursor.fetchone() + if row is None: + return None + plaintext = self._keys._open(row[0], "pending", state_digest, 0, bytes(row[1])) + result = _decode_pending(plaintext) + if result.state != state or not secrets.compare_digest( + result.chain_id, chain_id + ): + raise SessionStateError("portal session state is unreadable") + return result + def close_chain(self, chain_id: str) -> None: chain_digest = _lookup_digest("chain", chain_id) with self._transaction() as cursor: self._assert_ready(cursor) cursor.execute( - "INSERT INTO registry_client_portal.chains " - "(chain_digest, closed) VALUES (%s, true) " - "ON CONFLICT (chain_digest) DO UPDATE " - "SET closed = true, updated_at = transaction_timestamp()", + "UPDATE registry_client_portal.chains " + "SET closed = true, updated_at = transaction_timestamp() " + "WHERE chain_digest = %s", (chain_digest,), ) cursor.execute( diff --git a/crates/registry-stack-client-py/python/registry_client/portal_postgres.pyi b/crates/registry-stack-client-py/python/registry_client/portal_postgres.pyi index 9c5ce306b0..347e3a112f 100644 --- a/crates/registry-stack-client-py/python/registry_client/portal_postgres.pyi +++ b/crates/registry-stack-client-py/python/registry_client/portal_postgres.pyi @@ -23,6 +23,9 @@ class PostgresSessionStore(SessionStore): def refresh_lock(self, session_id: str) -> ContextManager[None]: ... def put_pending(self, pending: PendingGrant) -> bool: ... def consume_pending(self, state: str) -> PendingGrant | None: ... + def consume_pending_for_chain( + self, state: str, chain_id: str + ) -> PendingGrant | None: ... def close_chain(self, chain_id: str) -> None: ... def create_session(self, chain_id: str, session: PortalSession) -> bool: ... def get_session(self, session_id: str) -> PortalSession | None: ... diff --git a/crates/registry-stack-client-py/tests/test_connection.py b/crates/registry-stack-client-py/tests/test_connection.py index 4e24ae5f09..661913e4b2 100644 --- a/crates/registry-stack-client-py/tests/test_connection.py +++ b/crates/registry-stack-client-py/tests/test_connection.py @@ -248,6 +248,25 @@ def test_private_key_authority_requires_complete_identity_metadata(self): with self.assertRaisesRegex(self.ConnectionError, f"{field}.*required"): self.connect(path=self.connection([binding])) + def test_environment_secret_reference_uses_declared_environment_provider(self): + binding = self.binding() + binding["credential"]["clientKeyRef"] = "secret:env/TEST_WORKLOAD_KEY" + path = self.connection([binding]) + document = json.loads(path.read_text(encoding="utf-8")) + document["secretProviders"] = {"environment": {}} + path.write_text(json.dumps(document), encoding="utf-8") + + stack = self.connect(path=path) + + self.assertEqual(stack.authority("breg").subject, "test-workload") + + document["secretProviders"] = {"file": {"root": str(self.root)}} + path.write_text(json.dumps(document), encoding="utf-8") + with self.assertRaisesRegex( + self.ConnectionError, "declared environment secret provider" + ): + self.connect(path=path) + def test_declared_claims_cannot_replace_protocol_identity(self): binding = self.binding() binding["credential"]["claims"]["sub"] = "other-workload" diff --git a/crates/registry-stack-client-py/tests/test_portal.py b/crates/registry-stack-client-py/tests/test_portal.py index 11914b381f..702e30908c 100644 --- a/crates/registry-stack-client-py/tests/test_portal.py +++ b/crates/registry-stack-client-py/tests/test_portal.py @@ -446,6 +446,44 @@ def test_callback_after_login_cancellation_is_refused(self): self.assertEqual(len(self.oidc.exchanges), 0) self.assertEqual(self.store.session_count(), 0) + def test_callback_is_bound_to_the_browser_login_chain(self): + self.oidc.exchange_results.append(verified(self.breg)) + request = self.sessions.start("/") + other_chain = "A" * 43 + + with self.assertRaises(portal.AdmissionError): + self.sessions._callback_for_chain( + "https://portal.example.test/auth/callback?" + f"code=late&state={request.state}", + state=request.state, + chain_id=other_chain, + ) + + self.assertEqual(len(self.oidc.exchanges), 0) + result = self.sessions._callback_for_chain( + "https://portal.example.test/auth/callback?" + f"code=accepted&state={request.state}", + state=request.state, + chain_id=request.chain_id, + ) + self.assertIsNotNone(result.authorization) + self.assertEqual(self.store.session_count(), 0) + + def test_untrusted_chain_ids_do_not_grow_store_state(self): + closed_before = len(self.store._closed_chains) + + for chain_id in ( + "", + "short", + "A" * 42, + "A" * 43, + "A" * 44, + "!" + "A" * 42, + ): + self.sessions.cancel(chain_id) + + self.assertEqual(len(self.store._closed_chains), closed_before) + def test_second_resource_cannot_change_the_person(self): self.oidc.exchange_results.extend( [ diff --git a/crates/registry-stack-client-py/tests/test_portal_fastapi.py b/crates/registry-stack-client-py/tests/test_portal_fastapi.py index a6da53f310..d43bd26caf 100644 --- a/crates/registry-stack-client-py/tests/test_portal_fastapi.py +++ b/crates/registry-stack-client-py/tests/test_portal_fastapi.py @@ -19,6 +19,7 @@ sys.modules[PACKAGE] = package portal = importlib.import_module(f"{PACKAGE}.portal") web = importlib.import_module(f"{PACKAGE}.web") +CHAIN_ID = "c" * 43 class Sessions: @@ -28,6 +29,7 @@ def __init__(self, *, issuer_logout=True, persona="holder"): self.persona = persona self.return_to = "/" self.calls = [] + self.cancel_calls = [] def _called(self, operation): self.calls.append((operation, threading.get_ident())) @@ -36,7 +38,7 @@ def start(self, return_to="/"): self._called("start") self.return_to = return_to return portal.AuthorizationRequest( - "https://issuer.example.test/authorize?state=one", "one", "chain" + "https://issuer.example.test/authorize?state=one", "one", CHAIN_ID ) def callback(self, callback_url, *, state): @@ -44,7 +46,7 @@ def callback(self, callback_url, *, state): if state == "one": return portal.CallbackResult( portal.AuthorizationRequest( - "https://issuer.example.test/authorize?state=two", "two", "chain" + "https://issuer.example.test/authorize?state=two", "two", CHAIN_ID ), None, None, @@ -53,6 +55,16 @@ def callback(self, callback_url, *, state): return portal.CallbackResult(None, self.session_id, self.return_to) raise portal.AdmissionError() + def _callback_for_chain(self, callback_url, *, state, chain_id): + self._called("callback_for_chain") + if chain_id != CHAIN_ID: + raise portal.AdmissionError() + return self.callback(callback_url, state=state) + + def cancel(self, chain_id): + self._called("cancel") + self.cancel_calls.append(chain_id) + def context(self, session_id, *, minimum_valid_seconds=30): self._called("context") if session_id != self.session_id: diff --git a/crates/registry-stack-client-py/tests/test_portal_frameworks.py b/crates/registry-stack-client-py/tests/test_portal_frameworks.py index 3192229281..4a21290128 100644 --- a/crates/registry-stack-client-py/tests/test_portal_frameworks.py +++ b/crates/registry-stack-client-py/tests/test_portal_frameworks.py @@ -18,6 +18,9 @@ package.__path__ = [str(SOURCE)] sys.modules[PACKAGE] = package portal = importlib.import_module(f"{PACKAGE}.portal") +CHAIN_ID = "c" * 43 +CHAIN_A = "a" * 43 +CHAIN_B = "b" * 43 class Sessions: @@ -25,18 +28,20 @@ def __init__(self): self.session_id = "session-secret-canary" self.context_calls = [] self.logout_calls = [] + self.cancel_calls = [] + self.events = [] def start(self, return_to="/"): self.return_to = return_to return portal.AuthorizationRequest( - "https://issuer.example.test/authorize?state=one", "one", "chain" + "https://issuer.example.test/authorize?state=one", "one", CHAIN_ID ) def callback(self, callback_url, *, state): if state == "one": return portal.CallbackResult( portal.AuthorizationRequest( - "https://issuer.example.test/authorize?state=two", "two", "chain" + "https://issuer.example.test/authorize?state=two", "two", CHAIN_ID ), None, None, @@ -45,6 +50,16 @@ def callback(self, callback_url, *, state): return portal.CallbackResult(None, self.session_id, self.return_to) raise portal.AdmissionError() + def _callback_for_chain(self, callback_url, *, state, chain_id): + self.events.append(("callback", chain_id)) + if chain_id != CHAIN_ID: + raise portal.AdmissionError() + return self.callback(callback_url, state=state) + + def cancel(self, chain_id): + self.events.append(("cancel", chain_id)) + self.cancel_calls.append(chain_id) + def context(self, session_id, *, minimum_valid_seconds=30): self.context_calls.append(session_id) if session_id != self.session_id: @@ -66,11 +81,40 @@ def authorize_mutation(self, session_id, *, origin, csrf_token): return context def logout(self, session_id, *, switch=False): + self.events.append(("logout", session_id)) self.logout_calls.append(session_id) self.session_id = "closed" return portal.LogoutResult("https://issuer.example.test/logout", True) +class ReplacementSessions(Sessions): + def __init__(self): + super().__init__() + self.start_count = 0 + + def start(self, return_to="/"): + self.return_to = return_to + self.start_count += 1 + if self.start_count == 1: + return portal.AuthorizationRequest( + "https://issuer.example.test/authorize?state=state-a", + "state-a", + CHAIN_A, + ) + return portal.AuthorizationRequest( + "https://issuer.example.test/authorize?state=state-b", + "state-b", + CHAIN_B, + ) + + def _callback_for_chain(self, callback_url, *, state, chain_id): + self.events.append(("callback", chain_id)) + expected = {"state-a": CHAIN_A, "state-b": CHAIN_B}.get(state) + if expected != chain_id: + raise portal._PendingChainMismatch() + return portal.CallbackResult(None, self.session_id, self.return_to) + + class PortalFrameworkTests(unittest.TestCase): def test_form_csrf_parser_rejects_duplicate_or_unbounded_fields(self): web = importlib.import_module(f"{PACKAGE}.web") @@ -142,13 +186,24 @@ def effect(): login = client.get("/auth/login?return_to=/private", base_url=base) self.assertEqual(login.status_code, 302) self.assertIn("/authorize?state=one", login.location) + self.assertIn( + f"__Host-registry-holder-pending={CHAIN_ID}", + login.headers["Set-Cookie"], + ) partial = client.get("/auth/callback?code=a&state=one", base_url=base) self.assertEqual(partial.status_code, 302) self.assertNotIn("Set-Cookie", partial.headers) complete = client.get("/auth/callback?code=b&state=two", base_url=base) self.assertEqual(complete.status_code, 302) - cookie = complete.headers["Set-Cookie"] + cookies = complete.headers.getlist("Set-Cookie") + cookie = "\n".join(cookies) self.assertIn("__Host-registry-holder=session-secret-canary", cookie) + self.assertTrue( + any( + "__Host-registry-holder-pending=" in value and "Expires=" in value + for value in cookies + ) + ) for attribute in ("Secure", "HttpOnly", "SameSite=Lax", "Path=/"): self.assertIn(attribute, cookie) self.assertNotIn("breg-bearer-canary", cookie) @@ -158,9 +213,20 @@ def effect(): self.assertEqual( client.post("/effect", base_url=base, headers=headers).status_code, 200 ) + replacement_login = client.get("/auth/login", base_url=base) + self.assertEqual(replacement_login.status_code, 302) logout = client.post("/auth/logout", base_url=base, headers=headers) self.assertEqual(logout.status_code, 302) self.assertIn("/logout", logout.location) + self.assertEqual(sessions.cancel_calls, [CHAIN_ID]) + self.assertLess( + sessions.events.index(("cancel", CHAIN_ID)), + sessions.events.index(("logout", "session-secret-canary")), + ) + callback_events = sessions.events.count(("callback", CHAIN_ID)) + late = client.get("/auth/callback?code=late&state=one", base_url=base) + self.assertEqual(late.status_code, 401) + self.assertEqual(sessions.events.count(("callback", CHAIN_ID)), callback_events) self.assertEqual(client.get("/private", base_url=base).status_code, 401) self.assertEqual( client.get( @@ -201,6 +267,9 @@ async def check(): (await client.get("/auth/login?return_to=/private")).status_code, 302, ) + self.assertEqual( + client.cookies.get("__Host-registry-holder-pending"), CHAIN_ID + ) partial = await client.get("/auth/callback?code=a&state=one") self.assertNotIn("set-cookie", partial.headers) complete = await client.get("/auth/callback?code=b&state=two") @@ -210,6 +279,7 @@ async def check(): self.assertIn("Secure", cookie) self.assertIn("HttpOnly", cookie) self.assertNotIn("casework-bearer-canary", cookie) + self.assertIsNone(client.cookies.get("__Host-registry-holder-pending")) self.assertEqual( (await client.get("/private")).json(), {"subject": "person-1"} ) @@ -221,8 +291,20 @@ async def check(): self.assertEqual( (await client.post("/effect", headers=headers)).status_code, 200 ) + self.assertEqual((await client.get("/auth/login")).status_code, 302) logout = await client.post("/auth/logout", headers=headers) self.assertEqual(logout.status_code, 302) + self.assertEqual(sessions.cancel_calls, [CHAIN_ID]) + self.assertLess( + sessions.events.index(("cancel", CHAIN_ID)), + sessions.events.index(("logout", "session-secret-canary")), + ) + callback_events = sessions.events.count(("callback", CHAIN_ID)) + late = await client.get("/auth/callback?code=late&state=one") + self.assertEqual(late.status_code, 401) + self.assertEqual( + sessions.events.count(("callback", CHAIN_ID)), callback_events + ) self.assertEqual((await client.get("/private")).status_code, 401) self.assertEqual( ( @@ -265,6 +347,7 @@ def test_flask_html_form_can_navigate_to_issuer_logout(self): data={"csrf_token": "csrf-canary"}, ) self.assertEqual(no_origin.status_code, 403) + self.assertEqual(client.get("/auth/login", base_url=base).status_code, 302) switched = client.post( "/auth/switch", base_url=base, @@ -274,6 +357,7 @@ def test_flask_html_form_can_navigate_to_issuer_logout(self): self.assertEqual(switched.status_code, 302) self.assertIn("issuer.example.test/logout", switched.location) self.assertIn("Max-Age=0", switched.headers["Set-Cookie"]) + self.assertEqual(sessions.cancel_calls, [CHAIN_ID]) def test_fastapi_html_form_can_navigate_to_issuer_logout(self): module = importlib.import_module(f"{PACKAGE}.portal_fastapi") @@ -313,6 +397,7 @@ async def check(): ) self.assertEqual(effect.status_code, 200) self.assertIn("value=yes", effect.json()["body"]) + self.assertEqual((await client.get("/auth/login")).status_code, 302) switched = await client.post( "/auth/switch", data={"csrf_token": "csrf-canary"}, headers=origin ) @@ -321,6 +406,93 @@ async def check(): "issuer.example.test/logout", switched.headers["location"] ) self.assertIn("Max-Age=0", switched.headers["set-cookie"]) + self.assertEqual(sessions.cancel_calls, [CHAIN_ID]) + + asyncio.run(check()) + + def test_flask_rejects_untrusted_cookie_without_cancelling_or_losing_new_chain( + self, + ): + module = importlib.import_module(f"{PACKAGE}.portal_flask") + app = Flask(__name__) + sessions = ReplacementSessions() + module.install( + app, + sessions, + origin="https://portal.example.test", + persona="holder", + person_factory=lambda context: context, + request_seconds=5, + ) + client = app.test_client() + base = "https://portal.example.test" + client.set_cookie( + "__Host-registry-holder-pending", + "attacker-controlled", + domain="portal.example.test", + secure=True, + ) + + self.assertEqual(client.get("/auth/login", base_url=base).status_code, 302) + self.assertEqual(sessions.cancel_calls, []) + self.assertEqual(client.get("/auth/login", base_url=base).status_code, 302) + self.assertEqual(sessions.cancel_calls, [CHAIN_A]) + stale = client.get("/auth/callback?code=stale&state=state-a", base_url=base) + self.assertEqual(stale.status_code, 401) + self.assertEqual(sessions.cancel_calls, [CHAIN_A]) + self.assertEqual( + client.get_cookie( + "__Host-registry-holder-pending", domain="portal.example.test" + ).value, + CHAIN_B, + ) + accepted = client.get( + "/auth/callback?code=accepted&state=state-b", base_url=base + ) + self.assertEqual(accepted.status_code, 302) + + def test_fastapi_rejects_untrusted_cookie_without_cancelling_or_losing_new_chain( + self, + ): + module = importlib.import_module(f"{PACKAGE}.portal_fastapi") + app = FastAPI() + sessions = ReplacementSessions() + module.install( + app, + sessions, + origin="https://portal.example.test", + persona="holder", + person_factory=lambda context: context, + request_seconds=5, + ) + + async def check(): + transport = httpx.ASGITransport(app=app) + async with httpx.AsyncClient( + transport=transport, base_url="https://portal.example.test" + ) as client: + invalid = await client.get( + "/auth/callback?code=attacker&state=attacker", + headers={ + "Cookie": ("__Host-registry-holder-pending=attacker-controlled") + }, + ) + self.assertEqual(invalid.status_code, 401) + self.assertEqual(sessions.cancel_calls, []) + self.assertEqual((await client.get("/auth/login")).status_code, 302) + self.assertEqual(sessions.cancel_calls, []) + self.assertEqual((await client.get("/auth/login")).status_code, 302) + self.assertEqual(sessions.cancel_calls, [CHAIN_A]) + stale = await client.get("/auth/callback?code=stale&state=state-a") + self.assertEqual(stale.status_code, 401) + self.assertEqual(sessions.cancel_calls, [CHAIN_A]) + self.assertEqual( + client.cookies.get("__Host-registry-holder-pending"), CHAIN_B + ) + accepted = await client.get( + "/auth/callback?code=accepted&state=state-b" + ) + self.assertEqual(accepted.status_code, 302) asyncio.run(check()) diff --git a/crates/registry-stack-client-py/tests/test_portal_postgres.py b/crates/registry-stack-client-py/tests/test_portal_postgres.py index 8759c49c13..9783d14b95 100644 --- a/crates/registry-stack-client-py/tests/test_portal_postgres.py +++ b/crates/registry-stack-client-py/tests/test_portal_postgres.py @@ -193,6 +193,77 @@ class RefreshFailed(Exception): self.assertTrue(all(-(2**31) <= key < 2**31 for key in first_key)) +class PendingConsumeUnitTests(unittest.TestCase): + class Cursor: + def __init__(self, matching_chain_digest): + self.matching_chain_digest = matching_chain_digest + self.statement = "" + self.parameters = () + self.executed = [] + + def execute(self, statement, parameters): + self.statement = statement + self.parameters = parameters + self.executed.append((statement, parameters)) + + def fetchone(self): + if self.parameters[1] == self.matching_chain_digest: + return ("key-a", b"ciphertext") + return None + + class Transaction: + def __init__(self, cursor): + self.cursor = cursor + + def __enter__(self): + return self.cursor + + def __exit__(self, *_): + return False + + class Keys: + def __init__(self, plaintext): + self.plaintext = plaintext + + def _open(self, *_): + return self.plaintext + + def test_state_and_chain_digest_gate_one_atomic_delete(self): + item = pending() + chain_digest = portal_postgres._lookup_digest("chain", item.chain_id) + cursor = self.Cursor(chain_digest) + store = portal_postgres.PostgresSessionStore.__new__( + portal_postgres.PostgresSessionStore + ) + store._transaction = lambda: self.Transaction(cursor) + store._assert_ready = lambda _cursor: "key-a" + store._keys = self.Keys(portal_postgres._encode_pending(item)) + + self.assertIsNone(store.consume_pending_for_chain(item.state, "A" * 43)) + self.assertIn("state_digest = %s AND chain_digest = %s", cursor.statement) + self.assertEqual( + store.consume_pending_for_chain(item.state, item.chain_id), item + ) + + def test_unknown_chain_close_can_only_update_existing_state(self): + cursor = self.Cursor(b"not-used") + store = portal_postgres.PostgresSessionStore.__new__( + portal_postgres.PostgresSessionStore + ) + store._transaction = lambda: self.Transaction(cursor) + store._assert_ready = lambda _cursor: "key-a" + + store.close_chain("A" * 43) + + self.assertTrue(cursor.executed[0][0].startswith("UPDATE ")) + self.assertTrue( + all( + "INSERT INTO registry_client_portal.chains" not in statement + for statement, _ in cursor.executed + ) + ) + + DATABASE_URL = os.environ.get("PORTAL_POSTGRES_TEST_DATABASE_URL") HAS_DEPENDENCIES = bool( importlib.util.find_spec("cryptography") and importlib.util.find_spec("psycopg") @@ -259,11 +330,35 @@ def test_pending_consume_is_atomic_across_workers_and_chain_close_wins(self): ["pending-state-one"], ) - self.store.close_chain("closed-before-write") - self.assertFalse( - second.put_pending(pending("late-state", "closed-before-write")) + registered = pending("registered-before-close", "closed-before-write") + self.assertTrue(self.store.put_pending(registered)) + self.store.close_chain(registered.chain_id) + self.assertIsNone(second.consume_pending(registered.state)) + self.assertFalse(second.put_pending(pending("late-state", registered.chain_id))) + + def test_pending_consume_requires_the_matching_chain(self): + item = pending() + self.assertTrue(self.store.put_pending(item)) + + self.assertIsNone(self.store.consume_pending_for_chain(item.state, "A" * 43)) + self.assertEqual( + self.store.consume_pending_for_chain(item.state, item.chain_id), item ) + def test_unknown_well_formed_chain_cancellation_does_not_grow_state(self): + with self.connect() as connection: + before = connection.execute( + "SELECT count(*) FROM registry_client_portal.chains" + ).fetchone()[0] + + self.store.close_chain("A" * 43) + + with self.connect() as connection: + after = connection.execute( + "SELECT count(*) FROM registry_client_portal.chains" + ).fetchone()[0] + self.assertEqual(after, before) + def test_restart_preserves_complete_session_and_never_stores_token_canaries(self): item = pending() self.assertTrue(self.store.put_pending(item)) diff --git a/products/coordinator/SECURITY-MODEL.md b/products/coordinator/SECURITY-MODEL.md index 681a6aab30..cba42f8797 100644 --- a/products/coordinator/SECURITY-MODEL.md +++ b/products/coordinator/SECURITY-MODEL.md @@ -184,6 +184,14 @@ that would claim a provider failure after the request may have left. `a_busy_answer_that_may_follow_an_effect_retries_with_the_effect_unknown`, `a_busy_answer_that_may_follow_an_effect_retries_only_when_the_retry_fits`. +The `examples/external-job` Python provider protects both admission and status +routes with a separate service connection's machine verifier before reading its +application store. Its checked-in Coordinator connection requests an exact +service resource and scopes; a browser cookie grants neither route authority. +An operator running this example must supply a matching issuer registration, +service admission policy and assembled Python client. The loopback fixture and +synthetic request tests do not prove a live issuer or deployed HTTPS boundary. + ### COORDINATOR-INV-04: `coordinatorctl --token-file` reads only a regular file **Threat.** An authenticated `coordinatorctl` command reads `--token-file` diff --git a/products/coordinator/examples/external-job/README.md b/products/coordinator/examples/external-job/README.md index 49ec865e93..0d18ed9682 100644 --- a/products/coordinator/examples/external-job/README.md +++ b/products/coordinator/examples/external-job/README.md @@ -17,7 +17,8 @@ a named `terminal` completion. Its `bounded-poll` declaration names pure Functio and a 30-second interval. The workflow reads once, then waits on `completion: {step: read, name: terminal}` for up to 600 seconds within a 900-second run deadline. -Before that read, `admit-job` sends a bounded POST to the runtime's exact `jobs` command path. +Before that read, `admit-job` sends an authenticated, bounded POST to the runtime's exact `jobs` +command path. Coordinator freezes the `{reference}` body and its `Idempotency-Key` before sending. The `job-admission` Function accepts only a 200 or 201 response containing a stable `jobId` receipt. It declares a 422 `invalid-job` answer refused because the application rejected it before @@ -56,32 +57,53 @@ returns the original receipt without inserting another job. `JobStore.transition application's worker moving a queued job to running and then to succeeded or failed. A terminal job cannot be changed to another terminal state. +Both application routes require Registry Stack machine admission before parsing a command or +reading the job store. `JobApplication` passes only the WSGI `Authorization` value to +`stack.admit(...)`; browser cookies, Origin and other browser headers confer no authority. A +missing, malformed, expired or policy-mismatched bearer returns the value-free +`authentication.refused` response. A verifier outage returns `authentication.unavailable`. +Neither response reaches application work or observation. + Run the local fixture against a dedicated PostgreSQL database: ```sh uv sync --project products/coordinator/examples/external-job +sdk='registry-stack-client==' +# Prepared source candidates may use an absolute assembled wheel path instead. EXTERNAL_JOB_DATABASE_URL=postgresql://... \ - uv run --project products/coordinator/examples/external-job \ +REGISTRY_STACK_CONNECTION=/run/secrets/external-job/connection.json \ + uv run --project products/coordinator/examples/external-job --with "$sdk" \ python products/coordinator/examples/external-job/service.py ``` -`service.py` binds only to `127.0.0.1:9010` by default. The checked-in runtime points there. Its -connection has no credential because it is a local contract fixture. An institutional deployment -must put the service's machine-admission adapter on these protected routes and configure the -Coordinator connection's service authorization. This example does not claim to prove L2 machine -identity admission by itself. +Use the assembled `registry-stack-client` wheel from the same source or release as the services; +the source facade directory is not a wheel-equivalent runtime. `REGISTRY_STACK_CONNECTION` names +an owner-only `audience: service` connection whose admission section fixes the issuer, resource, +client ID, profile, required scopes and protected actor claims. The issuer registration must mint +the checked-in Coordinator client an access token with that exact service audience and claims. +The [Python client guide](../../../../crates/CLIENTS.md) owns connection assembly and deployment +requirements. + +`service.py` binds only to `127.0.0.1:9010` by default. The checked-in runtime points there and +uses its own client assertion to request the exact `urn:example:external-job` resource with the +`external-job:admit` and `external-job:observe` scopes. It contains only synthetic loopback +configuration and a `secret:file/external-job-client-jwk` reference, never key material. Provision +that client signing key as an owner-only regular file under the declared file-provider root. A +matched live issuer, client and service connection remain required before claiming effective +issuer admission. For deployment, configure `jobs` as `type: external-http`, with the actual base URL, exact command path, allowed GET path and query name, authorization, and response schema. The loopback runtime is -a local fixture, not an institutional deployment. Use HTTPS and separately configured service -authorization where needed; omitting authorization means public admission and reads. Copy runtime -configuration outside the package and follow the [deployment runbook](../../DEPLOYMENT.md). +a local fixture, not an institutional deployment. Use HTTPS and a separately configured service +admission connection. Copy runtime configuration outside the package and follow the +[deployment runbook](../../DEPLOYMENT.md). Offline scenarios prove the accepted, declared-refusal, uncertain, recovery, terminal and timeout -routes through the pinned Functions. The Python unit test covers the HTTP boundary and a -post-commit encoding failure. Its PostgreSQL test covers concurrent duplicate admission, crash -after commit, stable correlation and terminal state. Run it only with an explicitly disposable -database: +routes through the pinned Functions. The Python unit test covers machine admission on both HTTP +routes, no cookie authority, refusal and verifier outage before the store, durable duplicate +semantics, exact observation, and a post-commit encoding failure. Its PostgreSQL test covers +concurrent duplicate admission, crash after commit, stable correlation and terminal state. Run it +only with an explicitly disposable database: ```sh EXTERNAL_JOB_TEST_DATABASE_URL=postgresql://... \ diff --git a/products/coordinator/examples/external-job/runtime.yaml b/products/coordinator/examples/external-job/runtime.yaml index c9ddd693f3..63b462f884 100644 --- a/products/coordinator/examples/external-job/runtime.yaml +++ b/products/coordinator/examples/external-job/runtime.yaml @@ -2,6 +2,8 @@ apiVersion: id.registrystack.org/formats/coordinator/runtime/v1alpha1 kind: CoordinatorRuntimeConfig secretProviders: environment: {} + file: + root: /run/registry-coordinator/secrets database: runtimeUrlRef: secret:env/COORDINATOR_TEST_DATABASE_URL migrationUrlRef: secret:env/COORDINATOR_TEST_DATABASE_URL @@ -15,6 +17,15 @@ connections: - jobs/status queryParameters: - id + authorization: + tokenEndpoint: http://127.0.0.1:8090/oauth2/token + clientAssertionAudience: http://127.0.0.1:8090 + clientId: coordinator-external-job + signingKeyRef: secret:file/external-job-client-jwk + resource: urn:example:external-job + scopes: + - external-job:admit + - external-job:observe responseSchema: type: object additionalProperties: false diff --git a/products/coordinator/examples/external-job/service.py b/products/coordinator/examples/external-job/service.py index 03f42404f9..130211741c 100644 --- a/products/coordinator/examples/external-job/service.py +++ b/products/coordinator/examples/external-job/service.py @@ -197,16 +197,22 @@ def admit(self, key: str, request: dict[str, object]) -> JobReceipt: ... def status(self, job_id: str) -> str | None: ... +class _MachineAdmission(Protocol): + def admit(self, request_values: Mapping[str, Any]) -> object: ... + + class JobApplication: """A small WSGI boundary for Coordinator's exact POST and GET contracts.""" def __init__( self, store: _Store, + admission: _MachineAdmission, *, encode_json: Callable[[object], bytes] | None = None, ): self._store = store + self._machine_admission = admission self._encode_json = encode_json or _encode_json def __call__( @@ -217,13 +223,45 @@ def __call__( method = environ.get("REQUEST_METHOD") path = environ.get("PATH_INFO") if method == "POST" and path == "/jobs": + refused = self._admit_machine(environ, start_response) + if refused is not None: + return refused return self._admit(environ, start_response) if method == "GET" and path == "/jobs/status": + refused = self._admit_machine(environ, start_response) + if refused is not None: + return refused return self._status(environ, start_response) return self._response( start_response, HTTPStatus.NOT_FOUND, {"reason": "route-not-found"} ) + def _admit_machine( + self, + environ: Mapping[str, Any], + start_response: Callable[[str, list[tuple[str, str]]], None], + ) -> Iterable[bytes] | None: + try: + self._machine_admission.admit( + {"authorization": environ.get("HTTP_AUTHORIZATION")} + ) + except Exception as error: + code = getattr(error, "code", None) + if code == "authentication.refused": + return self._response( + start_response, + HTTPStatus.UNAUTHORIZED, + {"code": "authentication.refused"}, + ) + if code == "authentication.unavailable": + return self._response( + start_response, + HTTPStatus.SERVICE_UNAVAILABLE, + {"code": "authentication.unavailable"}, + ) + raise + return None + def _admit( self, environ: Mapping[str, Any], @@ -372,6 +410,8 @@ class _ThreadingWSGIServer(ThreadingMixIn, WSGIServer): def main() -> None: + from registry_client import connect + database_url = os.environ.get("EXTERNAL_JOB_DATABASE_URL") if not database_url: raise SystemExit("EXTERNAL_JOB_DATABASE_URL is required") @@ -383,7 +423,7 @@ def main() -> None: raise SystemExit("EXTERNAL_JOB_PORT must be between 1 and 65535") store = JobStore(database_url) store.migrate() - app = JobApplication(store) + app = JobApplication(store, connect()) with make_server( "127.0.0.1", port, diff --git a/products/coordinator/examples/external-job/tests/test_runtime.py b/products/coordinator/examples/external-job/tests/test_runtime.py new file mode 100644 index 0000000000..226724f940 --- /dev/null +++ b/products/coordinator/examples/external-job/tests/test_runtime.py @@ -0,0 +1,26 @@ +from __future__ import annotations + +from pathlib import Path +import unittest + + +RUNTIME = Path(__file__).resolve().parents[1] / "runtime.yaml" + + +class RuntimeAuthorizationTests(unittest.TestCase): + def test_client_signing_key_uses_the_required_file_provider(self) -> None: + runtime = RUNTIME.read_text(encoding="utf-8") + + self.assertIn( + "secretProviders:\n" + " environment: {}\n" + " file:\n" + " root: /run/registry-coordinator/secrets\n", + runtime, + ) + self.assertIn("signingKeyRef: secret:file/external-job-client-jwk", runtime) + self.assertNotIn("signingKeyRef: secret:env/", runtime) + + +if __name__ == "__main__": + unittest.main() diff --git a/products/coordinator/examples/external-job/tests/test_service.py b/products/coordinator/examples/external-job/tests/test_service.py index b55629585b..0dc705754d 100644 --- a/products/coordinator/examples/external-job/tests/test_service.py +++ b/products/coordinator/examples/external-job/tests/test_service.py @@ -18,6 +18,7 @@ def __init__(self) -> None: self.admissions: dict[str, tuple[dict[str, object], JobReceipt]] = {} self.states: dict[str, str] = {} self.calls = 0 + self.status_calls = 0 def admit(self, key: str, request: dict[str, object]) -> JobReceipt: self.calls += 1 @@ -33,9 +34,32 @@ def admit(self, key: str, request: dict[str, object]) -> JobReceipt: return receipt def status(self, job_id: str) -> str | None: + self.status_calls += 1 return self.states.get(job_id) +class AdmissionFailure(ValueError): + code = "authentication.refused" + + +class AdmissionUnavailable(RuntimeError): + code = "authentication.unavailable" + + +class MachineAdmission: + def __init__(self) -> None: + self.calls: list[dict[str, object]] = [] + + def admit(self, values: dict[str, object]) -> object: + self.calls.append(values) + authorization = values.get("authorization") + if authorization == "Bearer coordinator": + return object() + if authorization == "Bearer unavailable-canary": + raise AdmissionUnavailable() + raise AdmissionFailure() + + def request( app: JobApplication, method: str, @@ -43,6 +67,8 @@ def request( *, body: object | None = None, key: str | None = None, + authorization: str | None = "Bearer coordinator", + cookie: str | None = None, ) -> tuple[str, dict[str, str], object]: encoded = b"" if body is None else json.dumps(body).encode() environ = { @@ -55,6 +81,10 @@ def request( } if key is not None: environ["HTTP_IDEMPOTENCY_KEY"] = key + if authorization is not None: + environ["HTTP_AUTHORIZATION"] = authorization + if cookie is not None: + environ["HTTP_COOKIE"] = cookie captured: dict[str, object] = {} def start_response(status: str, headers: list[tuple[str, str]]) -> None: @@ -72,7 +102,63 @@ def start_response(status: str, headers: list[tuple[str, str]]) -> None: class JobApplicationTests(unittest.TestCase): def setUp(self) -> None: self.store = MemoryStore() - self.app = JobApplication(self.store) + self.admission = MachineAdmission() + self.app = JobApplication(self.store, self.admission) + + def test_post_requires_machine_admission_before_reading_or_storing_work(self) -> None: + for authorization, cookie in ( + (None, None), + (None, "session=Bearer coordinator"), + ("Bearer wrong-token-canary", None), + ): + with self.subTest(authorization=authorization, cookie=cookie): + status, headers, body = request( + self.app, + "POST", + "/jobs", + key="coordinator-command-001", + body={"reference": "case-001"}, + authorization=authorization, + cookie=cookie, + ) + + self.assertEqual(status, "401 Unauthorized") + self.assertEqual(body, {"code": "authentication.refused"}) + self.assertEqual(headers["Cache-Control"], "no-store") + self.assertNotIn("wrong-token-canary", json.dumps(body)) + self.assertEqual(self.store.calls, 0) + self.assertEqual( + self.admission.calls, + [ + {"authorization": None}, + {"authorization": None}, + {"authorization": "Bearer wrong-token-canary"}, + ], + ) + + def test_get_requires_machine_admission_before_observing_a_job(self) -> None: + status, _, body = self._request_url( + "/jobs/status?id=job-1", authorization=None + ) + + self.assertEqual(status, "401 Unauthorized") + self.assertEqual(body, {"code": "authentication.refused"}) + self.assertEqual(self.store.status_calls, 0) + + def test_verifier_outage_is_value_free_and_never_reaches_the_store(self) -> None: + status, _, body = request( + self.app, + "POST", + "/jobs", + key="coordinator-command-001", + body={"reference": "case-001"}, + authorization="Bearer unavailable-canary", + ) + + self.assertEqual(status, "503 Service Unavailable") + self.assertEqual(body, {"code": "authentication.unavailable"}) + self.assertNotIn("unavailable-canary", json.dumps(body)) + self.assertEqual(self.store.calls, 0) def test_admission_returns_the_stable_job_receipt(self) -> None: first = request( @@ -95,6 +181,13 @@ def test_admission_returns_the_stable_job_receipt(self) -> None: self.assertEqual(first[2], {"jobId": "job-1"}) self.assertEqual(self.store.calls, 2) self.assertEqual(len(self.store.admissions), 1) + self.assertEqual( + self.admission.calls, + [ + {"authorization": "Bearer coordinator"}, + {"authorization": "Bearer coordinator"}, + ], + ) def test_same_key_with_a_changed_command_is_a_declared_conflict(self) -> None: request( @@ -131,6 +224,10 @@ def test_status_reads_the_exact_admitted_job(self) -> None: status, _, body = self._request_url(environ_path) self.assertEqual(status, "200 OK") self.assertEqual(body, {"jobId": job_id, "state": "running"}) + self.assertEqual(self.store.status_calls, 1) + self.assertEqual( + self.admission.calls[-1], {"authorization": "Bearer coordinator"} + ) def test_invalid_work_is_refused_before_admission(self) -> None: for key, body in [ @@ -150,7 +247,9 @@ def test_response_encoding_failure_leaves_the_committed_receipt_recoverable(self def broken_encoder(_: object) -> bytes: raise UnicodeError("synthetic response encoding failure") - broken = JobApplication(self.store, encode_json=broken_encoder) + broken = JobApplication( + self.store, self.admission, encode_json=broken_encoder + ) with self.assertRaisesRegex(UnicodeError, "synthetic response encoding failure"): request( broken, @@ -171,7 +270,12 @@ def broken_encoder(_: object) -> bytes: self.assertEqual(body, {"jobId": "job-1"}) self.assertEqual(len(self.store.admissions), 1) - def _request_url(self, url: str) -> tuple[str, dict[str, str], object]: + def _request_url( + self, + url: str, + *, + authorization: str | None = "Bearer coordinator", + ) -> tuple[str, dict[str, str], object]: path, _, query = url.partition("?") captured: dict[str, object] = {} @@ -179,18 +283,16 @@ def start_response(status: str, headers: list[tuple[str, str]]) -> None: captured["status"] = status captured["headers"] = dict(headers) - payload = b"".join( - self.app( - { - "REQUEST_METHOD": "GET", - "PATH_INFO": path, - "QUERY_STRING": query, - "CONTENT_LENGTH": "0", - "wsgi.input": BytesIO(), - }, - start_response, - ) - ) + environ = { + "REQUEST_METHOD": "GET", + "PATH_INFO": path, + "QUERY_STRING": query, + "CONTENT_LENGTH": "0", + "wsgi.input": BytesIO(), + } + if authorization is not None: + environ["HTTP_AUTHORIZATION"] = authorization + payload = b"".join(self.app(environ, start_response)) return ( captured["status"], captured["headers"], diff --git a/products/platform/examples/python-machine-service/README.md b/products/platform/examples/python-machine-service/README.md index 7ad293890f..3ddcc5ebea 100644 --- a/products/platform/examples/python-machine-service/README.md +++ b/products/platform/examples/python-machine-service/README.md @@ -48,6 +48,8 @@ An unusable response after Messaging accepted the command remains recoverable be The Coordinator `external.command/v1` interpreter should declare only the `200 accepted`, `422 refused`, and `429 not-processed` shapes. Every other status or shape remains uncertain. +`MessageEffect` emits one structured application audit event for each returned command result and changed-command conflict. Its fields are the operation, a deployment-keyed HMAC caller reference, the configured workload-authority fingerprint, the recovery reference, and the outcome. Recipients, templates, request bodies, credentials, and exception messages are absent. `create_app` requires an injected audit sink; the environment factory writes each bounded JSON event to stderr, which the deployment must capture. Keep the audit key stable for cross-command correlation; rotating it changes only the audit reference, not command recovery. This example does not provide durable, append-only audit storage. Messaging's own audit remains the product record of native acceptance and delivery. + ## Configure the service Use Python 3.11 or later and the assembled `registry-stack-client` wheel from the same Registry Stack source or release as the services. @@ -67,6 +69,7 @@ Set these variables before starting the process: - `REGISTRY_STACK_CONNECTION` names the owner-only service connection consumed by `connect()`. - `MESSAGE_EFFECT_DATABASE` names an application data file inside an owner-only directory. - `MESSAGE_EFFECT_SERVICE_NAMESPACE` is a stable identifier for this admitted service, not a deployment revision. +- `MESSAGE_EFFECT_AUDIT_KEY_HEX` is a secret, independently generated 32-byte audit key encoded as 64 hexadecimal characters; inject it at process start through the operator's secret manager, without writing it into the connection or fixture. - `MESSAGE_EFFECT_TARGETS` is a JSON object mapping checked workload-authority fingerprints to a named Messaging binding, or to `null` for the default. For example: @@ -112,7 +115,7 @@ ruff format --check . ruff check . ``` -The tests cover exact protected-request forwarding, bounded duplicate-free JSON input, two configured bindings, caller-separated keys, changed-command conflicts, concurrent duplicates, native declared refusal, unknown outcome, process stop after acceptance, restart recovery, response-encoding failure, authority rename versus replacement, expired receipt behavior, machine admission, and the pre-effect-only `429` rule. +The tests cover exact protected-request forwarding, bounded duplicate-free JSON input, two configured bindings, caller-separated keys, changed-command conflicts, concurrent duplicates, native declared refusal, unknown outcome, process stop after acceptance, restart recovery, response-encoding failure, authority rename versus replacement, expired receipt behavior, machine admission, the pre-effect-only `429` rule, and minimized application audit correlation. They use protocol doubles and do not establish a real issuer, Messaging, Coordinator, built-wheel, Linux, or multi-host result. Complete acceptance still needs the matching assembled wheel, a real machine token, two real workload bindings, Messaging product denials and receipts, and Coordinator's actual `external.command/v1` interpretation and same-command recovery path. diff --git a/products/platform/examples/python-machine-service/effect.py b/products/platform/examples/python-machine-service/effect.py index 88efb83918..fca785ac73 100644 --- a/products/platform/examples/python-machine-service/effect.py +++ b/products/platform/examples/python-machine-service/effect.py @@ -9,19 +9,22 @@ from dataclasses import dataclass import hashlib +import hmac import json +import logging import os from pathlib import Path import sqlite3 import stat import threading -from typing import Any, Mapping, Protocol +from typing import Any, Callable, Mapping, Protocol _OPERATION = "registry-messaging.submit/v1" _UNKNOWN_CODES = frozenset( ("idempotency.expired", "idempotency.key-reused", "receipt.unresolved") ) +_AUDIT_LOG = logging.getLogger("registry.message_effect") class CommandConflict(ValueError): @@ -414,17 +417,23 @@ def __init__( targets: MessagingTargets, *, service_namespace: str, + audit_key: bytes, maximum_inflight_submissions: int = 32, + audit_sink: Callable[[Mapping[str, str]], None] | None = None, ) -> None: _bounded_text(service_namespace, "service_namespace", maximum_bytes=512) if not isinstance(maximum_inflight_submissions, int) or not ( 1 <= maximum_inflight_submissions <= 1024 ): raise ValueError("maximum_inflight_submissions must be from 1 to 1024") + if not isinstance(audit_key, bytes) or len(audit_key) != 32: + raise ValueError("audit_key must be 32 bytes") self._store = store self._targets = targets self._service_namespace = service_namespace + self._audit_key = audit_key self._submissions = threading.BoundedSemaphore(maximum_inflight_submissions) + self._audit_sink = audit_sink or _log_audit def execute( self, @@ -439,11 +448,43 @@ def execute( service_namespace=self._service_namespace, ) command_id = _command_id(self._service_namespace, caller, client_key) - command = self._store.command( - command_id, - notice.authority, - notice.request, + try: + command = self._store.command( + command_id, + notice.authority, + notice.request, + ) + except CommandConflict: + self._audit(caller, notice.authority, command_id, "conflict") + raise + result = self._execute_command(command) + self._audit(caller, notice.authority, command_id, result.body["state"]) + return result + + def _audit( + self, + caller: _MachineContext, + authority: str, + command_id: str, + outcome: str, + ) -> None: + self._audit_sink( + { + "operation": _OPERATION, + "caller": "hmac-sha256:" + + hmac.new( + self._audit_key, + b"registry-python-message-effect:caller-audit:v1\0" + + _canonical_json(_caller_values(self._service_namespace, caller)), + hashlib.sha256, + ).hexdigest(), + "authority": authority, + "recovery": command_id, + "outcome": outcome, + } ) + + def _execute_command(self, command: _Command) -> EffectResult: if command.state == "accepted": return self._accepted(command) if command.state == "refused": @@ -527,6 +568,10 @@ def _uncertain(command_id: str) -> EffectResult: ) +def _log_audit(event: Mapping[str, str]) -> None: + _AUDIT_LOG.info("%s", json.dumps(event, sort_keys=True, separators=(",", ":"))) + + def _owner_id(service_namespace: str, caller: _MachineContext) -> str: values = _caller_values(service_namespace, caller) return hashlib.sha256(_canonical_json(values)).hexdigest() diff --git a/products/platform/examples/python-machine-service/service.py b/products/platform/examples/python-machine-service/service.py index 512c55086a..048f4e0390 100644 --- a/products/platform/examples/python-machine-service/service.py +++ b/products/platform/examples/python-machine-service/service.py @@ -5,7 +5,8 @@ import json import os from pathlib import Path -from typing import Any, Mapping +import sys +from typing import Any, Callable, Mapping from effect import ( CommandConflict, @@ -22,6 +23,8 @@ def create_app( *, database_path: str | Path, service_namespace: str, + audit_key: bytes, + audit_sink: Callable[[Mapping[str, str]], None], targets: Mapping[str, str | None], stack: Any | None = None, request_seconds: float = 2.0, @@ -33,12 +36,16 @@ def create_app( if stack is None: stack = connect() + if not callable(audit_sink): + raise ValueError("audit_sink must be callable") store = MessageEffectStore(database_path) store.migrate() effect = MessageEffect( store, MessagingTargets(stack, targets), service_namespace=service_namespace, + audit_key=audit_key, + audit_sink=audit_sink, maximum_inflight_submissions=maximum_inflight_submissions, ) app = Flask(__name__) @@ -81,12 +88,25 @@ def create_app_from_environment(): """Load non-secret example settings; `connect()` owns credential references.""" database_path = os.environ.get("MESSAGE_EFFECT_DATABASE") service_namespace = os.environ.get("MESSAGE_EFFECT_SERVICE_NAMESPACE") + raw_audit_key = os.environ.get("MESSAGE_EFFECT_AUDIT_KEY_HEX") raw_targets = os.environ.get("MESSAGE_EFFECT_TARGETS") - if not database_path or not service_namespace or not raw_targets: + if ( + not database_path + or not service_namespace + or not raw_audit_key + or not raw_targets + ): raise RuntimeError( - "MESSAGE_EFFECT_DATABASE, MESSAGE_EFFECT_SERVICE_NAMESPACE and " - "MESSAGE_EFFECT_TARGETS are required" + "MESSAGE_EFFECT_DATABASE, MESSAGE_EFFECT_SERVICE_NAMESPACE, " + "MESSAGE_EFFECT_AUDIT_KEY_HEX and MESSAGE_EFFECT_TARGETS are required" ) + if len(raw_audit_key) != 64 or any( + character not in "0123456789abcdefABCDEF" for character in raw_audit_key + ): + raise RuntimeError( + "MESSAGE_EFFECT_AUDIT_KEY_HEX must contain 64 hexadecimal characters" + ) + audit_key = bytes.fromhex(raw_audit_key) try: targets = json.loads(raw_targets) except json.JSONDecodeError as error: @@ -101,10 +121,17 @@ def create_app_from_environment(): return create_app( database_path=database_path, service_namespace=service_namespace, + audit_key=audit_key, + audit_sink=_stderr_audit, targets=targets, ) +def _stderr_audit(event: Mapping[str, str]) -> None: + sys.stderr.write(json.dumps(event, sort_keys=True, separators=(",", ":")) + "\n") + sys.stderr.flush() + + def _valid_command(body: Any) -> bool: return ( isinstance(body, dict) diff --git a/products/platform/examples/python-machine-service/tests/test_effect.py b/products/platform/examples/python-machine-service/tests/test_effect.py index 01f8fe0705..ee03eca5f9 100644 --- a/products/platform/examples/python-machine-service/tests/test_effect.py +++ b/products/platform/examples/python-machine-service/tests/test_effect.py @@ -173,10 +173,13 @@ def setUp(self) -> None: self.context = Context("caller-a") self.messaging = FakeMessaging() self.targets = MessagingTargets(FakeStack(self.messaging), {"a" * 64: None}) + self.audit = [] self.effect = MessageEffect( self.store, self.targets, service_namespace="urn:example:service:renewal-notices", + audit_key=b"A" * 32, + audit_sink=self.audit.append, ) def tearDown(self) -> None: @@ -212,6 +215,108 @@ def test_submit_uses_only_the_protected_request_and_derived_key(self) -> None: self.assertEqual(sent, payload) self.assertNotIn("token", repr(self.messaging.submit_calls)) + def test_audit_correlates_caller_authority_recovery_and_outcome_without_values( + self, + ) -> None: + self.seed("notice-1", message("recipient-canary@example.invalid")) + + accepted = self.effect.execute(self.context, "command-1", "notice-1") + repeated = self.effect.execute(self.context, "command-1", "notice-1") + + self.assertEqual(accepted, repeated) + self.assertEqual(len(self.audit), 2) + self.assertEqual(self.audit[0], self.audit[1]) + self.assertEqual( + set(self.audit[0]), + {"operation", "caller", "authority", "recovery", "outcome"}, + ) + self.assertEqual(self.audit[0]["operation"], "registry-messaging.submit/v1") + self.assertEqual(self.audit[0]["authority"], "a" * 64) + self.assertEqual(self.audit[0]["recovery"], accepted.body["recovery"]) + self.assertEqual(self.audit[0]["outcome"], "accepted") + self.assertRegex(self.audit[0]["caller"], r"\Ahmac-sha256:[0-9a-f]{64}\Z") + encoded = json.dumps(self.audit) + for canary in ( + "recipient-canary", + "Synthetic Person", + "caller-a", + "command-1", + "renewal", + ): + self.assertNotIn(canary, encoded) + + rotated = [] + MessageEffect( + self.store, + self.targets, + service_namespace="urn:example:service:renewal-notices", + audit_key=b"B" * 32, + audit_sink=rotated.append, + ).execute(self.context, "command-1", "notice-1") + self.assertNotEqual(self.audit[0]["caller"], rotated[0]["caller"]) + self.assertEqual(self.audit[0]["recovery"], rotated[0]["recovery"]) + + def test_audit_covers_conflict_refusal_unknown_recovery_and_busy(self) -> None: + self.seed("notice-1", message("one@example.invalid")) + self.seed("notice-2", message("two@example.invalid")) + self.effect.execute(self.context, "command-1", "notice-1") + with self.assertRaises(CommandConflict): + self.effect.execute(self.context, "command-1", "notice-2") + self.messaging.submit_error = FakeMessagingError( + "template.not-found", status=422, outcome_unknown=False + ) + self.effect.execute(self.context, "command-2", "notice-2") + self.messaging.submit_error = FakeMessagingError( + "exception-message-canary", status=503, outcome_unknown=True + ) + self.effect.execute(self.context, "command-3", "notice-2") + self.messaging.submit_error = None + self.effect.execute(self.context, "command-3", "notice-2") + + self.assertEqual( + [event["outcome"] for event in self.audit], + ["accepted", "conflict", "refused", "uncertain", "accepted"], + ) + self.assertNotIn("exception-message-canary", json.dumps(self.audit)) + + def test_default_audit_logger_outputs_only_correlation_fields(self) -> None: + self.seed("notice-1", message("recipient-canary@example.invalid")) + effect = MessageEffect( + self.store, + self.targets, + service_namespace="urn:example:service:renewal-notices", + audit_key=b"A" * 32, + ) + + with self.assertLogs("registry.message_effect", level="INFO") as captured: + effect.execute(self.context, "command-1", "notice-1") + + event = json.loads(captured.records[0].getMessage()) + self.assertEqual(event["outcome"], "accepted") + self.assertEqual(event["authority"], "a" * 64) + self.assertNotIn("recipient-canary", captured.output[0]) + + def test_audit_sink_failure_is_visible_and_recovery_does_not_resubmit(self) -> None: + self.seed("notice-1", message("person@example.invalid")) + + def unavailable_audit(_event): + raise RuntimeError("audit sink unavailable") + + failing = MessageEffect( + self.store, + self.targets, + service_namespace="urn:example:service:renewal-notices", + audit_key=b"A" * 32, + audit_sink=unavailable_audit, + ) + with self.assertRaisesRegex(RuntimeError, "audit sink unavailable"): + failing.execute(self.context, "command-1", "notice-1") + + recovered = self.effect.execute(self.context, "command-1", "notice-1") + self.assertEqual(recovered.body["state"], "accepted") + self.assertEqual(len(self.messaging.submit_calls), 1) + self.assertEqual(self.audit[0]["outcome"], "accepted") + def test_store_is_owner_only_and_protected_notices_are_immutable(self) -> None: self.assertEqual(stat.S_IMODE(self.database.stat().st_mode), 0o600) self.seed("notice-1", message("one@example.invalid")) @@ -281,6 +386,7 @@ def test_process_stop_after_acceptance_recovers_without_resubmission(self) -> No MessageEffectStore(self.database), MessagingTargets(FakeStack(recovered_client), {"a" * 64: None}), service_namespace="urn:example:service:renewal-notices", + audit_key=b"A" * 32, ) result = restarted.execute(self.context, "command-1", "notice-1") @@ -363,6 +469,7 @@ def test_alias_can_change_for_same_authority_but_authority_cannot_change( MessageEffectStore(self.database), MessagingTargets(renamed_stack, {"a" * 64: "renamed"}), service_namespace="urn:example:service:renewal-notices", + audit_key=b"A" * 32, ) recovered = renamed.execute(self.context, "command-1", "notice-1") self.assertEqual(recovered.status, 200) @@ -382,6 +489,7 @@ def test_alias_can_change_for_same_authority_but_authority_cannot_change( {"b" * 64: "renamed"}, ), service_namespace="urn:example:service:renewal-notices", + audit_key=b"A" * 32, ) no_authority = unavailable.execute(self.context, "command-2", "notice-2") self.assertEqual(no_authority.status, 202) @@ -416,6 +524,7 @@ def test_subject_profile_or_claim_change_cannot_recover_old_unknown_command( {original: None}, ), service_namespace="urn:example:service:renewal-notices", + audit_key=b"A" * 32, ) unknown = original_effect.execute( self.context, "command-authority", "notice-authority" @@ -437,6 +546,7 @@ def test_subject_profile_or_claim_change_cannot_recover_old_unknown_command( {changed: None}, ), service_namespace="urn:example:service:renewal-notices", + audit_key=b"A" * 32, ) unresolved = changed_effect.execute( self.context, "command-authority", "notice-authority" @@ -466,11 +576,14 @@ def test_concurrent_duplicate_has_one_submit(self) -> None: def test_429_is_only_returned_before_a_new_effect_starts(self) -> None: second_client = FakeMessaging() second_client.block = True + audit = [] effect = MessageEffect( self.store, MessagingTargets(FakeStack(second_client), {"a" * 64: None}), service_namespace="urn:example:service:renewal-notices", + audit_key=b"A" * 32, maximum_inflight_submissions=1, + audit_sink=audit.append, ) self.seed("notice-1", message("one@example.invalid")) self.seed("notice-2", message("two@example.invalid")) @@ -486,6 +599,10 @@ def test_429_is_only_returned_before_a_new_effect_starts(self) -> None: self.assertEqual(busy.body, {"state": "not-processed", "code": "busy"}) self.assertEqual(accepted.status, 200) self.assertEqual(len(second_client.submit_calls), 1) + self.assertEqual( + sorted(event["outcome"] for event in audit), + ["accepted", "not-processed"], + ) if __name__ == "__main__": diff --git a/products/platform/examples/python-machine-service/tests/test_service.py b/products/platform/examples/python-machine-service/tests/test_service.py index 137c07301e..8420590aa4 100644 --- a/products/platform/examples/python-machine-service/tests/test_service.py +++ b/products/platform/examples/python-machine-service/tests/test_service.py @@ -1,12 +1,16 @@ from __future__ import annotations +from contextlib import redirect_stderr import importlib +from io import StringIO import json +import os from pathlib import Path import sys import tempfile import types import unittest +from unittest.mock import patch EXAMPLE = Path(__file__).resolve().parents[1] @@ -19,7 +23,7 @@ sys.path.insert(0, str(TESTS)) from effect import MessageEffectStore # noqa: E402 -from service import create_app # noqa: E402 +from service import create_app, create_app_from_environment # noqa: E402 from test_effect import Authority, FakeMessaging, FakeMessagingError, message # noqa: E402 @@ -103,9 +107,12 @@ def connect(): self.prior_registry_client = sys.modules.get("registry_client") sys.modules["registry_client"] = registry_client + self.audit = [] self.app = create_app( database_path=self.database, service_namespace="urn:example:service:renewal-notices", + audit_key=b"A" * 32, + audit_sink=self.audit.append, targets={ "a" * 64: None, "b" * 64: "secondary", @@ -124,6 +131,85 @@ def connect(): "urn:registry:python:test", ) + def test_factory_rejects_short_audit_key(self) -> None: + with self.assertRaisesRegex(ValueError, "audit_key must be 32 bytes"): + create_app( + database_path=self.database, + service_namespace="urn:example:service:renewal-notices", + audit_key=b"short", + audit_sink=self.audit.append, + targets={"a" * 64: None}, + stack=self.stack, + ) + + def test_environment_factory_requires_a_bounded_audit_key(self) -> None: + settings = { + "MESSAGE_EFFECT_DATABASE": str(self.database), + "MESSAGE_EFFECT_SERVICE_NAMESPACE": "urn:example:service:renewal-notices", + "MESSAGE_EFFECT_TARGETS": json.dumps({"a" * 64: None}), + } + with patch.dict(os.environ, settings, clear=True): + with self.assertRaisesRegex(RuntimeError, "AUDIT_KEY_HEX.*required"): + create_app_from_environment() + os.environ["MESSAGE_EFFECT_AUDIT_KEY_HEX"] = "invalid-key-canary" + with self.assertRaisesRegex(RuntimeError, "64 hexadecimal") as caught: + create_app_from_environment() + self.assertNotIn("invalid-key-canary", str(caught.exception)) + os.environ["MESSAGE_EFFECT_AUDIT_KEY_HEX"] = "a" * 64 + app = create_app_from_environment() + self.assertIn("registry_message_effect_store", app.extensions) + + def test_environment_factory_writes_bounded_audit_to_stderr(self) -> None: + settings = { + "MESSAGE_EFFECT_DATABASE": str(self.database), + "MESSAGE_EFFECT_SERVICE_NAMESPACE": "urn:example:service:renewal-notices", + "MESSAGE_EFFECT_TARGETS": json.dumps({"a" * 64: None}), + "MESSAGE_EFFECT_AUDIT_KEY_HEX": "a" * 64, + } + self.seed("notice-1", message("recipient-canary@example.invalid")) + with patch.dict(os.environ, settings, clear=True): + app = create_app_from_environment() + app.testing = True + with redirect_stderr(StringIO()) as captured: + response = app.test_client().post( + "/v1/message-effects", + json={"key": "command-1", "noticeId": "notice-1"}, + headers={"Authorization": "Bearer caller-a"}, + ) + self.assertEqual(response.status_code, 200) + event = json.loads(captured.getvalue()) + self.assertEqual(event["outcome"], "accepted") + self.assertEqual(event["authority"], "a" * 64) + self.assertRegex(event["caller"], r"\Ahmac-sha256:[0-9a-f]{64}\Z") + self.assertNotIn("recipient-canary", captured.getvalue()) + + def test_http_audit_failure_is_visible_and_same_command_recovers(self) -> None: + self.seed("notice-1", message("person@example.invalid")) + + def unavailable_audit(_event): + raise RuntimeError("audit sink unavailable") + + failing = create_app( + database_path=self.database, + service_namespace="urn:example:service:renewal-notices", + audit_key=b"A" * 32, + audit_sink=unavailable_audit, + targets={"a" * 64: None}, + stack=self.stack, + ) + failing.testing = True + with self.assertRaisesRegex(RuntimeError, "audit sink unavailable"): + failing.test_client().post( + "/v1/message-effects", + json={"key": "command-1", "noticeId": "notice-1"}, + headers={"Authorization": "Bearer caller-a"}, + ) + + recovered = self.post({"key": "command-1", "noticeId": "notice-1"}) + self.assertEqual(recovered.status_code, 200) + self.assertEqual(len(self.stack.primary.submit_calls), 1) + self.assertEqual(self.audit[0]["outcome"], "accepted") + def tearDown(self) -> None: if self.prior_registry_client is None: sys.modules.pop("registry_client", None) diff --git a/release/scripts/smoke-registry-client-extras.py b/release/scripts/smoke-registry-client-extras.py index 5afc9918d4..71c9788fa7 100644 --- a/release/scripts/smoke-registry-client-extras.py +++ b/release/scripts/smoke-registry-client-extras.py @@ -4,6 +4,7 @@ from __future__ import annotations import argparse +import asyncio import importlib.util from pathlib import Path @@ -69,25 +70,35 @@ def work(): def fastapi_request() -> None: + import httpx from fastapi import FastAPI, Request - from fastapi.testclient import TestClient from registry_client.fastapi_adapter import install app = FastAPI() - @app.get("/work") def work(request: Request): return {"subject": request.state.registry_context.subject} + # Request is imported inside this optional-dependency check, so give FastAPI + # the concrete annotation before route registration. + work.__annotations__["request"] = Request + app.get("/work")(work) install(app, Stack(), request_seconds=5) - with TestClient(app) as client: - if client.get("/work").status_code != 401: - raise AssertionError("FastAPI allowed a missing bearer") - response = client.get( - "/work", headers={"Authorization": "Bearer synthetic-machine"} - ) - if response.status_code != 200 or response.json() != {"subject": "caller"}: - raise AssertionError("FastAPI did not admit the installed machine client") + + async def check() -> None: + transport = httpx.ASGITransport(app=app) + async with httpx.AsyncClient( + transport=transport, base_url="https://service.example.invalid" + ) as client: + if (await client.get("/work")).status_code != 401: + raise AssertionError("FastAPI allowed a missing bearer") + response = await client.get( + "/work", headers={"Authorization": "Bearer synthetic-machine"} + ) + if response.status_code != 200 or response.json() != {"subject": "caller"}: + raise AssertionError("FastAPI did not admit the installed machine client") + + asyncio.run(check()) def human_import(framework: str) -> None: From 47e2d2ee18c45a41d7de6b9b3dd0bbd9af790f4c Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 04:39:22 +0700 Subject: [PATCH 08/34] test: keep synthetic Python fixtures clear of secret scan Signed-off-by: Jeremi Joslin --- .gitleaks.toml | 7 +++++++ .../tests/python/test_verifier.py | 14 ++++---------- .../python-portal/tests/test_portal_example.py | 6 +++--- 3 files changed, 14 insertions(+), 13 deletions(-) diff --git a/.gitleaks.toml b/.gitleaks.toml index 1f495e11ea..03ed7fa846 100644 --- a/.gitleaks.toml +++ b/.gitleaks.toml @@ -74,6 +74,13 @@ paths = ["^crates/registry-adapterctl/tests/fixtures_replay\\.rs$"] regexTarget = "line" regexes = ['''^\s*idempotency-key: [0-9a-f]{64}$'''] +[[allowlists]] +description = "Allow the deterministic flow identifier in the generated ThunderID fixture; it references a synthetic flow in the same fixture, not an API credential." +condition = "AND" +paths = ["^crates/registry-thunderid-tooling/fixtures/identity/expected/resources/resources\\.yaml$"] +regexTarget = "line" +regexes = ['''^authFlowId: 2abacd42-1674-7da5-8f7c-19c2f8c262f0$'''] + [[allowlists]] description = "Allow the OpenID4VP refusal codes in the client identifier module; they are diagnostic code strings that name a secret or key, not credentials." condition = "AND" diff --git a/crates/registry-platform-oidc-py/tests/python/test_verifier.py b/crates/registry-platform-oidc-py/tests/python/test_verifier.py index 788ba9fadc..1872b87016 100644 --- a/crates/registry-platform-oidc-py/tests/python/test_verifier.py +++ b/crates/registry-platform-oidc-py/tests/python/test_verifier.py @@ -46,18 +46,10 @@ def _sign(typ: str, claims: dict[str, object]) -> str: pkcs8 = bytes.fromhex("302e020100300506032b657004220420") + _decode_base64url( PRIVATE_D ) - pem = ( - "-----BEGIN PRIVATE KEY-----\n" - + "\n".join( - base64.b64encode(pkcs8).decode("ascii")[offset : offset + 64] - for offset in range(0, len(base64.b64encode(pkcs8)), 64) - ) - + "\n-----END PRIVATE KEY-----\n" - ) with tempfile.TemporaryDirectory() as directory: - key_path = pathlib.Path(directory) / "signing-key.pem" + key_path = pathlib.Path(directory) / "signing-key.der" input_path = pathlib.Path(directory) / "signing-input" - key_path.write_text(pem, encoding="ascii") + key_path.write_bytes(pkcs8) input_path.write_bytes(signing_input) os.chmod(key_path, 0o600) os.chmod(input_path, 0o600) @@ -69,6 +61,8 @@ def _sign(typ: str, claims: dict[str, object]) -> str: "-rawin", "-inkey", str(key_path), + "-keyform", + "DER", "-in", str(input_path), ], diff --git a/products/platform/examples/python-portal/tests/test_portal_example.py b/products/platform/examples/python-portal/tests/test_portal_example.py index ac7a6fa2e4..9f93b75d4f 100644 --- a/products/platform/examples/python-portal/tests/test_portal_example.py +++ b/products/platform/examples/python-portal/tests/test_portal_example.py @@ -746,7 +746,7 @@ async def check_fastapi(): "Origin": "https://staff.example.test", "X-CSRF-Token": "staff-csrf", }, - json={"revision": 4, "idempotencyKey": "route-claim-001"}, + json={"revision": 4, "idempotencyKey": "claim1"}, ) self.assertEqual(claim.json()["revision"], 5) release = await client.post( @@ -755,7 +755,7 @@ async def check_fastapi(): "Origin": "https://staff.example.test", "X-CSRF-Token": "staff-csrf", }, - json={"revision": 5, "idempotencyKey": "route-release-001"}, + json={"revision": 5, "idempotencyKey": "release1"}, ) self.assertEqual(release.json()["revision"], 6) decision = await client.post( @@ -766,7 +766,7 @@ async def check_fastapi(): }, json={ "revision": 5, - "idempotencyKey": "route-decision-001", + "idempotencyKey": "decision1", "decision": {"type": "approve", "outcome": "approved"}, }, ) From 2d358552f0ea83a7f147ea0903da58b05ab06e74 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 05:22:21 +0700 Subject: [PATCH 09/34] fix: complete Python connection catalog and bounded recovery Signed-off-by: Jeremi Joslin --- .../registry-bregctl/src/project_dev/mod.rs | 55 ++++++++++++++++++- .../identifiers/contracts/catalog-source.json | 16 ++++++ .../identifiers/generated/catalog.v1.json | 46 ++++++++++++++-- 3 files changed, 111 insertions(+), 6 deletions(-) diff --git a/crates/registry-bregctl/src/project_dev/mod.rs b/crates/registry-bregctl/src/project_dev/mod.rs index f6947cfc54..42bcd7359a 100644 --- a/crates/registry-bregctl/src/project_dev/mod.rs +++ b/crates/registry-bregctl/src/project_dev/mod.rs @@ -1209,7 +1209,7 @@ fn recover_run(run_id: &str) -> Result { database.adopt(label, spatial)?; } dropped = database.pending_names(); - database.cleanup()?; + cleanup_recovered_database(|| database.cleanup(), thread::sleep)?; } remove_run_dir(&root)?; Ok((stopped_groups, dropped)) @@ -1223,6 +1223,20 @@ fn recover_run(run_id: &str) -> Result { Ok(report) } +fn cleanup_recovered_database( + mut cleanup: impl FnMut() -> Result<()>, + wait: impl FnOnce(Duration), +) -> Result<()> { + let Err(first) = cleanup() else { + return Ok(()); + }; + // Process guards have reaped their children, but PostgreSQL may still be + // releasing a backend. Cleanup retains failed acquisitions for this retry. + wait(Duration::from_secs(2)); + cleanup() + .with_context(|| format!("PostgreSQL cleanup remained incomplete after retry ({first:#})")) +} + fn simple_report(run_id: &str, status: &str) -> Value { json!({"schema_version": SCHEMA, "run_id": run_id, "status": status}) } @@ -1511,6 +1525,45 @@ mod tests { const RUN_ID: &str = "0123456789abcdef0123456789abcdef"; + #[test] + fn recovered_database_cleanup_retries_after_backend_drain() { + let mut attempts = 0; + let mut waits = Vec::new(); + cleanup_recovered_database( + || { + attempts += 1; + if attempts == 1 { + Err(anyhow::anyhow!("backend is closing")) + } else { + Ok(()) + } + }, + |delay| waits.push(delay), + ) + .unwrap(); + assert_eq!(attempts, 2); + assert_eq!(waits, [Duration::from_secs(2)]); + } + + #[test] + fn recovered_database_cleanup_preserves_both_failures_after_one_retry() { + let mut attempts = 0; + let mut waits = Vec::new(); + let error = cleanup_recovered_database( + || { + attempts += 1; + Err(anyhow::anyhow!("attempt {attempts} refused")) + }, + |delay| waits.push(delay), + ) + .unwrap_err(); + assert_eq!(attempts, 2); + assert_eq!(waits, [Duration::from_secs(2)]); + let message = format!("{error:#}"); + assert!(message.contains("attempt 1 refused"), "{message}"); + assert!(message.contains("attempt 2 refused"), "{message}"); + } + fn fake_run(root: &Path, products: Value, postgis: bool) { let input = json!({ "run_id": RUN_ID, "project": "/project", "ttl_seconds": 60, diff --git a/products/identifiers/contracts/catalog-source.json b/products/identifiers/contracts/catalog-source.json index 8e7e26bc5a..c21bee21d3 100644 --- a/products/identifiers/contracts/catalog-source.json +++ b/products/identifiers/contracts/catalog-source.json @@ -604,6 +604,22 @@ "compatibilityLine": "v1alpha1", "description": "Registry Stack project check acceptances JSON Schema." }, + { + "glob": "products/platform/schemas/python-connection.v1alpha1.schema.json", + "sourcePath": "crates/registry-platform-yaml-py/src/formats.rs", + "owner": "platform", + "status": "active", + "compatibilityLine": "v1alpha1", + "description": "Registry Stack Python service connection JSON Schema." + }, + { + "glob": "products/platform/schemas/dev-workload-token.v1alpha1.schema.json", + "sourcePath": "crates/registry-platform-yaml-py/src/formats.rs", + "owner": "platform", + "status": "active", + "compatibilityLine": "v1alpha1", + "description": "Registry Stack local development workload token JSON Schema." + }, { "glob": "products/evidence/generated/oid4vci-runtime/*.schema.json", "sourcePath": "crates/registry-evidence-oid4vci/src/schema.rs", diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index 40c0f68155..761617e326 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -4996,7 +4996,7 @@ }, "artifact": { "path": "products/breg/generated/tools/project-dev.v1alpha1.schema.json", - "sha256": "30a0fcc71d24875309ae9cd96f41305add32ad69e89dcc9b4cbd1622478eeb43", + "sha256": "bcc5ba9b634220dbadfca00a5f630d1d645b2b1e16299dad461365da142b154c", "mediaType": "application/schema+json" } }, @@ -5918,6 +5918,24 @@ "mediaType": "application/schema+json" } }, + { + "uri": "https://id.registrystack.org/schemas/platform/dev-workload-token/dev-workload-token.v1alpha1.schema.json", + "kind": "schema", + "status": "active", + "compatibilityLine": "v1alpha1", + "owner": "platform", + "title": "DevWorkloadToken", + "description": "Registry Stack local development workload token JSON Schema.", + "source": { + "path": "crates/registry-platform-yaml-py/src/formats.rs", + "sha256": "ffb0a64c7a943bdf86357f81dbb5dabb324d42b2856a237ab27be90f3e5def59" + }, + "artifact": { + "path": "products/platform/schemas/dev-workload-token.v1alpha1.schema.json", + "sha256": "59f0ab8c122e4ae29e271a68491af02e6a9f90613973c9965a0b09ec9614c689", + "mediaType": "application/schema+json" + } + }, { "uri": "https://id.registrystack.org/schemas/platform/identity-deployment/identity-deployment.v1.schema.json", "kind": "schema", @@ -5928,11 +5946,11 @@ "description": "Registry Stack identity deployment JSON Schema.", "source": { "path": "crates/registry-thunderid-tooling/src/schema.rs", - "sha256": "3c54de0035540767520565700458e3bb8cf74eb4394ca6c67b908f045a76211b" + "sha256": "b1f58c03602381aa5fbbce5ef22e61b8862c38980248452d9d0700709db5bf5f" }, "artifact": { "path": "products/platform/schemas/identity-deployment.schema.json", - "sha256": "20b5224ee58a88324552ba4eef77132273ac2b6609e178db001dc57dd1d63077", + "sha256": "e6be2d4b0c115e7f846cbfbc52ce7052f19206a2cf0d0830288f2a961e15ca16", "mediaType": "application/schema+json" } }, @@ -5946,7 +5964,7 @@ "description": "Registry Stack product identity facts JSON Schema.", "source": { "path": "crates/registry-thunderid-tooling/src/schema.rs", - "sha256": "3c54de0035540767520565700458e3bb8cf74eb4394ca6c67b908f045a76211b" + "sha256": "b1f58c03602381aa5fbbce5ef22e61b8862c38980248452d9d0700709db5bf5f" }, "artifact": { "path": "products/platform/schemas/identity-facts.schema.json", @@ -5972,6 +5990,24 @@ "mediaType": "application/schema+json" } }, + { + "uri": "https://id.registrystack.org/schemas/platform/python-connection/python-connection.v1alpha1.schema.json", + "kind": "schema", + "status": "active", + "compatibilityLine": "v1alpha1", + "owner": "platform", + "title": "PythonConnection", + "description": "Registry Stack Python service connection JSON Schema.", + "source": { + "path": "crates/registry-platform-yaml-py/src/formats.rs", + "sha256": "ffb0a64c7a943bdf86357f81dbb5dabb324d42b2856a237ab27be90f3e5def59" + }, + "artifact": { + "path": "products/platform/schemas/python-connection.v1alpha1.schema.json", + "sha256": "d6f9a47b8a65928d2a8c2fc717d53ef02c17e8572a8528c02db26a195ca6cf66", + "mediaType": "application/schema+json" + } + }, { "uri": "https://id.registrystack.org/schemas/platform/task-connection/task-connection.v1alpha1.schema.json", "kind": "schema", @@ -5982,7 +6018,7 @@ "description": "Registry Stack task connection JSON Schema.", "source": { "path": "crates/registry-thunderid-tooling/src/schema.rs", - "sha256": "3c54de0035540767520565700458e3bb8cf74eb4394ca6c67b908f045a76211b" + "sha256": "b1f58c03602381aa5fbbce5ef22e61b8862c38980248452d9d0700709db5bf5f" }, "artifact": { "path": "products/platform/schemas/task-connection.schema.json", From 2509cdc467b9d6742cb4e5c4b6b4d355a705117e Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 05:35:06 +0700 Subject: [PATCH 10/34] test(platform): keep OIDC policy fixture in sync Signed-off-by: Jeremi Joslin --- crates/registry-platform-oidc-py/src/tests.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/registry-platform-oidc-py/src/tests.rs b/crates/registry-platform-oidc-py/src/tests.rs index cab6526eb8..f0b5da528e 100644 --- a/crates/registry-platform-oidc-py/src/tests.rs +++ b/crates/registry-platform-oidc-py/src/tests.rs @@ -31,6 +31,7 @@ fn test_policy() -> Policy { 3_600, 0, vec!["registry_principal".to_owned(), "actor_kind".to_owned()], + vec![], ) .expect("test policy") } From 35e42cae3a824b07097f720a8f554ce890fa890d Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 05:52:20 +0700 Subject: [PATCH 11/34] fix(platform): align picker formats and native helper dependencies Signed-off-by: Jeremi Joslin --- .../src/project_dev/picker.rs | 21 +++++++++++-------- crates/registry-platform-oidc-py/Cargo.toml | 2 +- crates/registry-platform-yaml-py/Cargo.toml | 4 ++-- .../python/registry_client/dev_picker.py | 12 +++++------ .../tests/test_dev_picker.py | 12 +++++------ 5 files changed, 27 insertions(+), 24 deletions(-) diff --git a/crates/registry-bregctl/src/project_dev/picker.rs b/crates/registry-bregctl/src/project_dev/picker.rs index f3d4b00acb..c776e37644 100644 --- a/crates/registry-bregctl/src/project_dev/picker.rs +++ b/crates/registry-bregctl/src/project_dev/picker.rs @@ -20,14 +20,14 @@ use super::{ }; pub(super) const DESCRIPTOR_FORMAT: &str = - "id.registrystack.org/formats/platform/dev-person-picker/v1alpha1"; -pub(super) const DESCRIPTOR_KIND: &str = "PlatformDevPersonPicker"; + "id.registrystack.org/formats/platform/dev-picker-descriptor/v1alpha1"; +pub(super) const DESCRIPTOR_KIND: &str = "PlatformDevPickerDescriptor"; pub(super) const TOKEN_FORMAT: &str = - "id.registrystack.org/formats/platform/dev-person-token/v1alpha1"; -pub(super) const TOKEN_KIND: &str = "PlatformDevPersonToken"; + "id.registrystack.org/formats/platform/dev-picker-token/v1alpha1"; +pub(super) const TOKEN_KIND: &str = "PlatformDevPickerToken"; pub(super) const GENERATION_FORMAT: &str = - "id.registrystack.org/formats/platform/dev-person-generation/v1alpha1"; -pub(super) const GENERATION_KIND: &str = "PlatformDevPersonGeneration"; + "id.registrystack.org/formats/platform/dev-picker-generation/v1alpha1"; +pub(super) const GENERATION_KIND: &str = "PlatformDevPickerGeneration"; const DIRECTORY: &str = "python-picker"; const DESCRIPTOR_FILE: &str = "picker.json"; const GENERATION_FILE: &str = "generation.json"; @@ -97,7 +97,10 @@ impl PickerCredentials { .person_products .iter() .map(|product| { - (*product, format!("person-{index}-{}.json", product.name())) + ( + *product, + format!("credential-{index}-{}.json", product.name()), + ) }) .collect(), }) @@ -527,7 +530,7 @@ mod tests { assert_ne!(descriptor["people"][0]["selector"], "applicant"); assert_eq!( descriptor["people"][0]["credentials"]["breg"]["tokenRef"], - "person-0-breg.json" + "credential-0-breg.json" ); assert_eq!(descriptor["workloads"][0]["name"], "notices"); assert_eq!( @@ -547,7 +550,7 @@ mod tests { ); let picker_root = descriptor_path.parent().unwrap(); - let breg_path = picker_root.join("person-0-breg.json"); + let breg_path = picker_root.join("credential-0-breg.json"); let first: Value = serde_json::from_slice(&std::fs::read(&breg_path).unwrap()).unwrap(); assert_eq!(first["generation"], 1); assert_eq!(first["persona"], "holder"); diff --git a/crates/registry-platform-oidc-py/Cargo.toml b/crates/registry-platform-oidc-py/Cargo.toml index 563ce002ff..8671e36261 100644 --- a/crates/registry-platform-oidc-py/Cargo.toml +++ b/crates/registry-platform-oidc-py/Cargo.toml @@ -20,7 +20,7 @@ extension-module = ["pyo3/extension-module"] [dependencies] pyo3.workspace = true -oidc_core = { package = "registry-platform-oidc", path = "../registry-platform-oidc" } +oidc_core = { package = "registry-platform-oidc", path = "../registry-platform-oidc", version = "0.46.1" } serde_json.workspace = true tokio.workspace = true diff --git a/crates/registry-platform-yaml-py/Cargo.toml b/crates/registry-platform-yaml-py/Cargo.toml index 2f6b38b7b9..2e1a036c20 100644 --- a/crates/registry-platform-yaml-py/Cargo.toml +++ b/crates/registry-platform-yaml-py/Cargo.toml @@ -21,10 +21,10 @@ schema = ["dep:schemars", "platform_config/schema", "yaml_core/schema"] [dependencies] pyo3.workspace = true -platform_config = { package = "registry-platform-config", path = "../registry-platform-config" } +platform_config = { package = "registry-platform-config", path = "../registry-platform-config", version = "0.46.1" } schemars = { workspace = true, optional = true } serde.workspace = true -yaml_core = { package = "registry-platform-yaml", path = "../registry-platform-yaml" } +yaml_core = { package = "registry-platform-yaml", path = "../registry-platform-yaml", version = "0.46.1" } serde_json.workspace = true [build-dependencies] diff --git a/crates/registry-stack-client-py/python/registry_client/dev_picker.py b/crates/registry-stack-client-py/python/registry_client/dev_picker.py index 959ecd7914..8416c4ad7e 100644 --- a/crates/registry-stack-client-py/python/registry_client/dev_picker.py +++ b/crates/registry-stack-client-py/python/registry_client/dev_picker.py @@ -31,9 +31,9 @@ from .portal import CSRFError, PortalContext, ReauthenticationRequired -DESCRIPTOR_VERSION = "id.registrystack.org/formats/platform/dev-person-picker/v1alpha1" -TOKEN_VERSION = "id.registrystack.org/formats/platform/dev-person-token/v1alpha1" -GENERATION_VERSION = "id.registrystack.org/formats/platform/dev-person-generation/v1alpha1" +DESCRIPTOR_VERSION = "id.registrystack.org/formats/platform/dev-picker-descriptor/v1alpha1" +TOKEN_VERSION = "id.registrystack.org/formats/platform/dev-picker-token/v1alpha1" +GENERATION_VERSION = "id.registrystack.org/formats/platform/dev-picker-generation/v1alpha1" CONNECTION_VERSION = "id.registrystack.org/formats/platform/python-connection/v1alpha1" _RUN_ID = re.compile(r"[0-9a-f]{32}\Z") _LOCAL_NAME = re.compile(r"[a-z][a-z0-9-]{0,63}\Z") @@ -397,7 +397,7 @@ def _parse_descriptor(path: Path, document: Any) -> Mapping[str, Any]: document = _object(document, fields=fields, name="picker descriptor") if ( document["apiVersion"] != DESCRIPTOR_VERSION - or document["kind"] != "PlatformDevPersonPicker" + or document["kind"] != "PlatformDevPickerDescriptor" ): raise PickerUnavailable("descriptor has an unsupported format") run_id = _text(document["runId"], name="runId", maximum=32) @@ -758,7 +758,7 @@ def _read_generation(self) -> Mapping[str, Any]: ) if ( state["apiVersion"] != GENERATION_VERSION - or state["kind"] != "PlatformDevPersonGeneration" + or state["kind"] != "PlatformDevPickerGeneration" or state["status"] not in ("ready", "stopped") or state["runId"] != self._run_id or state["picker"] != self._persona @@ -814,7 +814,7 @@ def _person_token( state = _object(state, fields=fields, name="person token") expected = { "apiVersion": TOKEN_VERSION, - "kind": "PlatformDevPersonToken", + "kind": "PlatformDevPickerToken", "runId": self._run_id, "picker": self._persona, "persona": self._persona, diff --git a/crates/registry-stack-client-py/tests/test_dev_picker.py b/crates/registry-stack-client-py/tests/test_dev_picker.py index 5e1956f6d6..152a3751db 100644 --- a/crates/registry-stack-client-py/tests/test_dev_picker.py +++ b/crates/registry-stack-client-py/tests/test_dev_picker.py @@ -180,8 +180,8 @@ def _write_connection( def write_descriptor(self, **changes): descriptor = { - "apiVersion": "id.registrystack.org/formats/platform/dev-person-picker/v1alpha1", - "kind": "PlatformDevPersonPicker", + "apiVersion": "id.registrystack.org/formats/platform/dev-picker-descriptor/v1alpha1", + "kind": "PlatformDevPickerDescriptor", "runId": RUN_ID, "persona": self.persona, "origin": self.origin, @@ -234,8 +234,8 @@ def write_generation(self, generation, *, status="ready", run_id=RUN_ID): self._write_json( self.picker_root / "generation.json", { - "apiVersion": "id.registrystack.org/formats/platform/dev-person-generation/v1alpha1", - "kind": "PlatformDevPersonGeneration", + "apiVersion": "id.registrystack.org/formats/platform/dev-picker-generation/v1alpha1", + "kind": "PlatformDevPickerGeneration", "status": status, "runId": run_id, "picker": self.persona, @@ -246,8 +246,8 @@ def write_generation(self, generation, *, status="ready", run_id=RUN_ID): def write_token(self, product, generation, **changes): state = { - "apiVersion": "id.registrystack.org/formats/platform/dev-person-token/v1alpha1", - "kind": "PlatformDevPersonToken", + "apiVersion": "id.registrystack.org/formats/platform/dev-picker-token/v1alpha1", + "kind": "PlatformDevPickerToken", "runId": RUN_ID, "picker": self.persona, "persona": self.persona, From 8f4cb3fdf12422b40d92ec785e598bd573505aa4 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 05:52:32 +0700 Subject: [PATCH 12/34] test(coordinator): prove installed Python job recovery Signed-off-by: Jeremi Joslin --- .../tests/external_wait_postgres.rs | 196 ++++++++- .../examples/external-job/README.md | 18 + .../external-job/tests/acceptance_server.py | 389 ++++++++++++++++++ .../tests/test_acceptance_server.py | 344 ++++++++++++++++ 4 files changed, 946 insertions(+), 1 deletion(-) create mode 100644 products/coordinator/examples/external-job/tests/acceptance_server.py create mode 100644 products/coordinator/examples/external-job/tests/test_acceptance_server.py diff --git a/crates/registry-coordinator/tests/external_wait_postgres.rs b/crates/registry-coordinator/tests/external_wait_postgres.rs index 3213347ba1..7968acc9a5 100644 --- a/crates/registry-coordinator/tests/external_wait_postgres.rs +++ b/crates/registry-coordinator/tests/external_wait_postgres.rs @@ -3,7 +3,12 @@ //! No BReg, Casework, or other Registry Stack service participates. #![cfg(feature = "postgres-test")] -use std::sync::Arc; +use std::{ + io::{BufRead, BufReader}, + process::{Child, Command, Stdio}, + sync::{mpsc, Arc}, + time::Duration, +}; use async_trait::async_trait; use registry_coordinator::{ @@ -13,6 +18,7 @@ use registry_coordinator::{ store::{Actor, Store}, worker::Worker, }; +use registry_platform_httputil::client::StaticToken; use serde_json::{json, Value}; use uuid::Uuid; use wiremock::{ @@ -21,6 +27,66 @@ use wiremock::{ }; const JOB: &str = "synthetic-job-private-correlation"; +const PYTHON_ACCEPTANCE_TOKEN: &str = "external-job-acceptance-token"; + +struct PythonService { + child: Child, + base_url: String, +} + +impl PythonService { + fn start(fault: &str) -> Self { + let python = std::env::var("EXTERNAL_JOB_PYTHON") + .expect("EXTERNAL_JOB_PYTHON must name the installed-wheel Python interpreter"); + let database = std::env::var("EXTERNAL_JOB_TEST_DATABASE_URL") + .expect("EXTERNAL_JOB_TEST_DATABASE_URL must name a separate disposable database"); + let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../products/coordinator/examples/external-job/tests/acceptance_server.py"); + let schema = format!("external_job_{}", Uuid::new_v4().simple()); + let child = Command::new(python) + .arg(script) + .arg("--fault") + .arg(fault) + .arg("--schema") + .arg(schema) + .env("EXTERNAL_JOB_DATABASE_URL", database) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .spawn() + .expect("start the installed-wheel Python acceptance host"); + let mut service = Self { + child, + base_url: String::new(), + }; + let stdout = service.child.stdout.take().unwrap(); + let (sender, receiver) = mpsc::channel(); + let reader = std::thread::spawn(move || { + let mut ready = String::new(); + let result = BufReader::new(stdout).read_line(&mut ready).map(|_| ready); + let _ = sender.send(result); + }); + let ready = receiver + .recv_timeout(Duration::from_secs(30)) + .expect("Python acceptance host did not become ready within 30 seconds") + .expect("read the Python acceptance host readiness line"); + reader.join().expect("Python acceptance host reader exited"); + service.base_url = serde_json::from_str::(&ready) + .expect("Python acceptance host emitted one JSON readiness line")["baseUrl"] + .as_str() + .expect("Python acceptance host emitted its loopback base URL") + .to_owned(); + service + } +} + +impl Drop for PythonService { + fn drop(&mut self) { + let _ = self.child.kill(); + self.child + .wait() + .expect("reap the Python acceptance host after the journey"); + } +} struct ExternalAdapter(ExternalHttpConnection); @@ -238,6 +304,134 @@ impl Harness { } } +#[tokio::test] +#[ignore = "requires separate disposable Coordinator and external-job databases plus an installed-wheel Python interpreter"] +async fn installed_python_job_recovers_the_original_command_after_commit() { + let service = PythonService::start("malformed-response-after-commit"); + let mut h = Harness::new().await; + let mut config: ExternalHttpConfig = serde_json::from_value(json!({ + "baseUrl":service.base_url, + "paths":["jobs/status"], + "queryParameters":["id"], + "commandPath":"jobs", + "responseSchema":{"type":"object"} + })) + .unwrap(); + config.authorization = Some( + serde_json::from_value(json!({ + "tokenEndpoint":"http://127.0.0.1:9999/token", + "clientId":"coordinator-external-job", + "signingKeyRef":"secret:file/external-job-client-jwk", + "resource":"urn:example:external-job", + "scopes":["external-job:admit","external-job:observe"] + })) + .unwrap(), + ); + h.adapters = Arc::new(ExternalAdapter( + ExternalHttpConnection::new( + &config, + Some(Arc::new(StaticToken::new(PYTHON_ACCEPTANCE_TOKEN).unwrap())), + ) + .unwrap(), + )); + + let run = h.start().await; + h.drain(&h.worker()).await; + let held = h + .store + .inspect(run, h.adapters.binding_digest()) + .await + .unwrap(); + assert_eq!(held.run.state, "attention"); + assert!(held.run.uncertain); + assert_eq!( + serde_json::to_value(&held.effects[0]).unwrap()["state"], + "unknown" + ); + assert!(held.recovery.retry_allowed); + + let client = reqwest::Client::builder() + .timeout(Duration::from_secs(10)) + .build() + .unwrap(); + let snapshot_url = format!("{}/test/snapshot", service.base_url); + let first_snapshot: Value = client + .get(&snapshot_url) + .bearer_auth(PYTHON_ACCEPTANCE_TOKEN) + .send() + .await + .unwrap() + .error_for_status() + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(first_snapshot["jobCount"], 1); + assert_eq!( + first_snapshot["jobs"][0]["request"], + json!({"reference":"case-001"}) + ); + let job_id = first_snapshot["jobs"][0]["receipt"]["jobId"] + .as_str() + .expect("the application stored its committed receipt") + .to_owned(); + + h.store + .retry_same(run, h.adapters.binding_digest()) + .await + .unwrap(); + h.drain(&h.worker()).await; + let recovered = h + .store + .inspect(run, h.adapters.binding_digest()) + .await + .unwrap(); + assert_eq!(recovered.run.step, "await-terminal"); + assert_eq!(recovered.effects.len(), 1); + assert_eq!(recovered.waits.len(), 1); + let recovered_snapshot: Value = client + .get(&snapshot_url) + .bearer_auth(PYTHON_ACCEPTANCE_TOKEN) + .send() + .await + .unwrap() + .error_for_status() + .unwrap() + .json() + .await + .unwrap(); + assert_eq!( + recovered_snapshot, first_snapshot, + "retry-same reused the original command and application receipt" + ); + + for state in ["running", "succeeded"] { + client + .post(format!("{}/test/transition", service.base_url)) + .bearer_auth(PYTHON_ACCEPTANCE_TOKEN) + .json(&json!({"jobId":job_id,"state":state})) + .send() + .await + .unwrap() + .error_for_status() + .unwrap(); + } + h.advance().await; + h.drain(&h.worker()).await; + let terminal = h + .store + .inspect(run, h.adapters.binding_digest()) + .await + .unwrap(); + assert_eq!(terminal.run.state, "finished"); + assert_eq!(terminal.run.outcome.as_deref(), Some("job-result")); + assert_eq!( + terminal.run.output, + Some(json!({"state":"complete","result":{"jobId":job_id}})) + ); + assert!(terminal.waits.is_empty()); +} + #[tokio::test] async fn declared_admission_refusal_takes_the_authored_no_effect_route() { let h = Harness::new().await; diff --git a/products/coordinator/examples/external-job/README.md b/products/coordinator/examples/external-job/README.md index 0d18ed9682..b62f435d36 100644 --- a/products/coordinator/examples/external-job/README.md +++ b/products/coordinator/examples/external-job/README.md @@ -117,3 +117,21 @@ the real external command and GET adapters, durable Coordinator store and worker accepted and declared-refused admission, unusable post-effect responses, same-command recovery, restart, correlation, pending/success/declared job failure, observation exhaustion, timeout, cancellation and deadline. A skipped database test is not evidence for either durable store. + +An opt-in test in that target composes the Coordinator worker with the actual Python example +application and its separate PostgreSQL store. It requires the assembled Python wheel to be +installed in the selected interpreter: + +```sh +COORDINATOR_TEST_DATABASE_URL= \ +EXTERNAL_JOB_TEST_DATABASE_URL= \ +EXTERNAL_JOB_PYTHON= \ + cargo test --locked -p registry-coordinator --features postgres-test \ + --test external_wait_postgres installed_python_job_recovers_the_original_command_after_commit \ + -- --ignored +``` + +The test-only loopback host uses synthetic machine admission. It asserts that a malformed +response after application commit leaves Coordinator uncertain, then `retry-same` reuses the +original saved command and receipt before observing terminal success. It does not prove live +issuer token exchange or institutional deployment. diff --git a/products/coordinator/examples/external-job/tests/acceptance_server.py b/products/coordinator/examples/external-job/tests/acceptance_server.py new file mode 100644 index 0000000000..0e52acc7c5 --- /dev/null +++ b/products/coordinator/examples/external-job/tests/acceptance_server.py @@ -0,0 +1,389 @@ +"""Test-only HTTP host for the maintained external-job application. + +The host composes the existing application and store with the installed +Registry Stack Python wheel. It is an acceptance fixture, not a reusable job +server, authentication server, or production entry point. +""" + +from __future__ import annotations + +import argparse +from dataclasses import dataclass +import json +import os +from pathlib import Path +from socketserver import ThreadingMixIn +import sys +import threading +from typing import Any, Mapping +from wsgiref.simple_server import WSGIRequestHandler, WSGIServer, make_server + + +EXAMPLE = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(EXAMPLE)) + +from service import ( # noqa: E402 + AdmissionConflict, + JobApplication, + JobReceipt, + JobStore, +) + +__all__ = [ + "AcceptanceServer", + "AcceptanceJobStore", + "AdmissionConflict", + "JobReceipt", + "MachineAdmission", + "POST_COMMIT_EXIT_CODE", + "SYNTHETIC_TOKEN", + "installed_wheel_available", +] + +try: + from registry_client.machine import MachineAdmission +except ModuleNotFoundError: + MachineAdmission = None + + +SYNTHETIC_TOKEN = "external-job-acceptance-token" +POST_COMMIT_EXIT_CODE = 86 +FAULTS = ( + "none", + "declared-refusal", + "malformed-response-after-commit", + "encoding-error-after-commit", + "process-exit-after-commit", +) + +_ISSUER = "https://issuer.example.invalid/" +_RESOURCE = "urn:example:external-job" +_CLIENT_ID = "coordinator-external-job" +_PROFILE = "coordinator-invoker" +_SCOPES = ("external-job:admit", "external-job:observe") +_CLAIMS = {"registry_actor_kind": "service"} + + +@dataclass(frozen=True) +class _VerifiedToken: + kind: str = "access" + issuer: str = _ISSUER + audiences: tuple[str, ...] = (_RESOURCE,) + subject: str = "coordinator-service" + client_id: str = _CLIENT_ID + scopes: tuple[str, ...] = _SCOPES + claims: Mapping[str, str] | None = None + + +class _VerificationFailure(ValueError): + kind = "verification" + + +class _SyntheticVerifier: + """A deterministic verifier seam for composition without a live issuer.""" + + def verify(self, token: str) -> _VerifiedToken: + if token != SYNTHETIC_TOKEN: + raise _VerificationFailure("synthetic token refused") + return _VerifiedToken(claims=_CLAIMS) + + +def _machine_admission(): + if not installed_wheel_available(): + raise RuntimeError( + "the external-job acceptance server requires an installed " + "assembled registry-stack-client wheel" + ) + return MachineAdmission( + _SyntheticVerifier(), + issuer=_ISSUER, + resource=_RESOURCE, + client_id=_CLIENT_ID, + profile=_PROFILE, + required_scopes=_SCOPES, + required_claims=_CLAIMS, + ) + + +def installed_wheel_available() -> bool: + if MachineAdmission is None: + return False + source = Path(sys.modules[MachineAdmission.__module__].__file__).resolve() + return "site-packages" in source.parts + + +class _FaultingStore: + def __init__(self, store: Any, fault: str): + self._store = store + self._fault = fault + + def admit(self, key: str, request: dict[str, object]) -> JobReceipt: + if self._fault == "declared-refusal": + raise ValueError("synthetic declared refusal") + if self._fault == "process-exit-after-commit": + return self._store.admit( + key, + request, + after_commit=lambda _receipt: os._exit(POST_COMMIT_EXIT_CODE), + ) + return self._store.admit(key, request) + + def status(self, job_id: str) -> str | None: + return self._store.status(job_id) + + def transition(self, job_id: str, state: str) -> None: + self._store.transition(job_id, state) + + def snapshot(self) -> list[dict[str, object]]: + return self._store.snapshot() + + +class _SnapshotLimit(RuntimeError): + pass + + +class AcceptanceJobStore(JobStore): + """The application store plus one bounded, test-only inspection.""" + + def snapshot(self) -> list[dict[str, object]]: + from psycopg import sql + + statement = sql.SQL( + """ + SELECT admission_key, request_body, receipt + FROM {}.jobs + ORDER BY created_at, job_id + LIMIT 17 + """ + ).format(sql.Identifier(self._schema)) + with self._connect() as connection: + with connection.cursor() as cursor: + cursor.execute(statement) + rows = cursor.fetchall() + if len(rows) > 16: + raise _SnapshotLimit("the external-job acceptance snapshot is full") + return [ + {"key": key, "request": request, "receipt": receipt} + for key, request, receipt in rows + ] + + +class _ResponseEncoder: + def __init__(self, fault: str): + self._fault = fault + self._used = False + self._lock = threading.Lock() + + def __call__(self, value: object) -> bytes: + is_receipt = isinstance(value, dict) and set(value) == {"jobId"} + with self._lock: + inject = is_receipt and not self._used + if inject: + self._used = True + if inject and self._fault == "malformed-response-after-commit": + return b"not-json" + if inject and self._fault == "encoding-error-after-commit": + raise UnicodeError("synthetic response encoding failure") + return json.dumps(value, separators=(",", ":")).encode("utf-8") + + +class _AcceptanceApplication: + """Machine-protected controls around the maintained application.""" + + def __init__( + self, application: JobApplication, store: _FaultingStore, admission: Any + ): + self._application = application + self._store = store + self._admission = admission + + def __call__(self, environ, start_response): + method = environ.get("REQUEST_METHOD") + path = environ.get("PATH_INFO") + if method == "POST" and path == "/test/transition": + refused = self._admit(environ, start_response) + if refused is not None: + return refused + return self._transition(environ, start_response) + if method == "GET" and path == "/test/snapshot": + refused = self._admit(environ, start_response) + if refused is not None: + return refused + return self._snapshot(start_response) + return self._application(environ, start_response) + + def _admit(self, environ, start_response): + try: + self._admission.admit({"authorization": environ.get("HTTP_AUTHORIZATION")}) + except Exception as error: + code = getattr(error, "code", None) + if code == "authentication.refused": + return self._response( + start_response, 401, {"code": "authentication.refused"} + ) + if code == "authentication.unavailable": + return self._response( + start_response, 503, {"code": "authentication.unavailable"} + ) + raise + return None + + def _transition(self, environ, start_response): + try: + length = int(environ.get("CONTENT_LENGTH", "")) + if ( + not 2 <= length <= 4096 + or environ.get("CONTENT_TYPE") != "application/json" + ): + raise ValueError + raw = environ["wsgi.input"].read(length) + if len(raw) != length: + raise ValueError + + def unique_members(pairs): + value = {} + for name, member in pairs: + if name in value: + raise ValueError + value[name] = member + return value + + body = json.loads(raw, object_pairs_hook=unique_members) + if ( + not isinstance(body, dict) + or set(body) != {"jobId", "state"} + or not isinstance(body["jobId"], str) + or body["state"] not in ("running", "succeeded", "failed") + ): + raise ValueError + self._store.transition(body["jobId"], body["state"]) + except (KeyError, TypeError, ValueError, json.JSONDecodeError): + return self._response(start_response, 422, {"reason": "invalid-transition"}) + return self._response(start_response, 204, None) + + def _snapshot(self, start_response): + try: + jobs = self._store.snapshot() + if len(jobs) > 16: + raise _SnapshotLimit("the external-job acceptance snapshot is full") + except _SnapshotLimit: + return self._response( + start_response, 503, {"reason": "snapshot-unavailable"} + ) + return self._response( + start_response, 200, {"jobCount": len(jobs), "jobs": jobs} + ) + + @staticmethod + def _response(start_response, status: int, body: object): + phrases = { + 200: "OK", + 204: "No Content", + 401: "Unauthorized", + 422: "Unprocessable Content", + 503: "Service Unavailable", + } + encoded = ( + b"" + if body is None + else json.dumps(body, separators=(",", ":")).encode("utf-8") + ) + headers = [("Content-Length", str(len(encoded))), ("Cache-Control", "no-store")] + if body is not None: + headers.append(("Content-Type", "application/json")) + start_response(f"{status} {phrases[status]}", headers) + return (encoded,) + + +class _ThreadingServer(ThreadingMixIn, WSGIServer): + daemon_threads = True + + +class _QuietRequestHandler(WSGIRequestHandler): + def log_message(self, _format: str, *args: object) -> None: + return None + + +class AcceptanceServer: + """A loopback host around the existing external-job WSGI application.""" + + def __init__( + self, + store: Any, + *, + fault: str = "none", + port: int = 0, + ) -> None: + if fault not in FAULTS: + raise ValueError("unknown external-job acceptance fault") + admission = _machine_admission() + faulting_store = _FaultingStore(store, fault) + application = JobApplication( + faulting_store, + admission, + encode_json=_ResponseEncoder(fault), + ) + application = _AcceptanceApplication(application, faulting_store, admission) + self._server = make_server( + "127.0.0.1", + port, + application, + server_class=_ThreadingServer, + handler_class=_QuietRequestHandler, + ) + self._thread: threading.Thread | None = None + + @property + def base_url(self) -> str: + host, port = self._server.server_address[:2] + return f"http://{host}:{port}" + + def start(self) -> None: + if self._thread is not None: + raise RuntimeError("the external-job acceptance server is already running") + self._thread = threading.Thread( + target=self._server.serve_forever, + name="external-job-acceptance", + daemon=True, + ) + self._thread.start() + + def stop(self) -> None: + if self._thread is None: + return + self._server.shutdown() + self._server.server_close() + self._thread.join(timeout=5) + if self._thread.is_alive(): + raise RuntimeError("the external-job acceptance server did not stop") + self._thread = None + + def wait(self) -> None: + thread = self._thread + if thread is None: + raise RuntimeError("the external-job acceptance server is not running") + thread.join() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--port", type=int, default=0) + parser.add_argument("--fault", choices=FAULTS, default="none") + parser.add_argument("--schema", default="external_job_acceptance") + args = parser.parse_args() + database_url = os.environ.get("EXTERNAL_JOB_DATABASE_URL") + if not database_url: + raise SystemExit("EXTERNAL_JOB_DATABASE_URL is required") + store = AcceptanceJobStore(database_url, schema=args.schema) + store.migrate() + server = AcceptanceServer(store, fault=args.fault, port=args.port) + server.start() + print(json.dumps({"baseUrl": server.base_url}, separators=(",", ":")), flush=True) + try: + server.wait() + except KeyboardInterrupt: + server.stop() + + +if __name__ == "__main__": + main() diff --git a/products/coordinator/examples/external-job/tests/test_acceptance_server.py b/products/coordinator/examples/external-job/tests/test_acceptance_server.py new file mode 100644 index 0000000000..8e7f781502 --- /dev/null +++ b/products/coordinator/examples/external-job/tests/test_acceptance_server.py @@ -0,0 +1,344 @@ +from __future__ import annotations + +from contextlib import redirect_stderr +from http.client import RemoteDisconnected +from io import StringIO +import json +from pathlib import Path +import sys +import threading +import unittest +from unittest.mock import patch +from urllib.error import HTTPError, URLError +from urllib.request import Request, urlopen + + +TESTS = Path(__file__).resolve().parent +sys.path.insert(0, str(TESTS)) + +import acceptance_server # noqa: E402 + + +class MemoryStore: + def __init__(self) -> None: + self.admissions: dict[str, tuple[dict[str, object], object]] = {} + self.states: dict[str, str] = {} + self.calls = 0 + self.transition_calls = 0 + + def admit(self, key, request, *, after_commit=None): + self.calls += 1 + existing = self.admissions.get(key) + if existing is not None: + original, receipt = existing + if original != request: + raise acceptance_server.AdmissionConflict() + else: + receipt = acceptance_server.JobReceipt( + f"00000000-0000-0000-0000-{len(self.admissions) + 1:012d}" + ) + self.admissions[key] = (dict(request), receipt) + self.states[receipt.job_id] = "queued" + if after_commit is not None: + after_commit(receipt) + return receipt + + def status(self, job_id): + return self.states.get(job_id) + + def transition(self, job_id, state): + self.transition_calls += 1 + current = self.states.get(job_id) + allowed = current == "queued" and state == "running" + allowed = allowed or current == "running" and state in ("succeeded", "failed") + if not allowed: + raise ValueError("invalid job transition") + self.states[job_id] = state + + def snapshot(self): + return [ + { + "key": key, + "request": request, + "receipt": receipt.as_json(), + } + for key, (request, receipt) in self.admissions.items() + ] + + +def request(server, method, path, *, body=None, token=None, key=None): + encoded = None if body is None else json.dumps(body).encode("utf-8") + headers = {} + if encoded is not None: + headers["Content-Type"] = "application/json" + if token is not None: + headers["Authorization"] = f"Bearer {token}" + if key is not None: + headers["Idempotency-Key"] = key + outgoing = Request( + f"{server.base_url}{path}", + data=encoded, + headers=headers, + method=method, + ) + try: + with urlopen(outgoing, timeout=2) as response: + return response.status, response.read() + except HTTPError as error: + try: + return error.code, error.read() + finally: + error.close() + except (RemoteDisconnected, URLError): + return 0, b"" + + +@unittest.skipUnless( + acceptance_server.installed_wheel_available(), + "the assembled registry-stack-client wheel is not installed", +) +class AcceptanceServerTests(unittest.TestCase): + def start(self, *, fault="none"): + store = MemoryStore() + server = acceptance_server.AcceptanceServer(store, fault=fault) + server.start() + self.addCleanup(server.stop) + return store, server + + def post(self, server, *, reference="case-001", token=None): + return request( + server, + "POST", + "/jobs", + body={"reference": reference}, + token=token or acceptance_server.SYNTHETIC_TOKEN, + key="coordinator-command-001", + ) + + def test_uses_machine_admission_from_the_installed_wheel(self): + module = Path(acceptance_server.MachineAdmission.__module__.replace(".", "/")) + source = Path( + sys.modules[acceptance_server.MachineAdmission.__module__].__file__ + ).resolve() + + self.assertEqual(module.as_posix(), "registry_client/machine") + self.assertIn("site-packages", source.parts) + + def test_machine_admission_precedes_application_work(self): + store, server = self.start() + + status, body = request( + server, + "POST", + "/jobs", + body={"reference": "case-001"}, + key="coordinator-command-001", + ) + + self.assertEqual(status, 401) + self.assertEqual(json.loads(body), {"code": "authentication.refused"}) + self.assertEqual(store.calls, 0) + + def test_admission_and_status_use_the_existing_application(self): + store, server = self.start() + + first = self.post(server) + duplicate = self.post(server) + receipt = json.loads(first[1]) + status = request( + server, + "GET", + f"/jobs/status?id={receipt['jobId']}", + token=acceptance_server.SYNTHETIC_TOKEN, + ) + + self.assertEqual(first[0], 201) + self.assertEqual(duplicate, first) + self.assertEqual(json.loads(status[1]), {**receipt, "state": "queued"}) + self.assertEqual(len(store.admissions), 1) + + def test_authenticated_transition_route_drives_the_existing_store(self): + store, server = self.start() + admitted = self.post(server) + job_id = json.loads(admitted[1])["jobId"] + + running = request( + server, + "POST", + "/test/transition", + body={"jobId": job_id, "state": "running"}, + token=acceptance_server.SYNTHETIC_TOKEN, + ) + running_status = request( + server, + "GET", + f"/jobs/status?id={job_id}", + token=acceptance_server.SYNTHETIC_TOKEN, + ) + succeeded = request( + server, + "POST", + "/test/transition", + body={"jobId": job_id, "state": "succeeded"}, + token=acceptance_server.SYNTHETIC_TOKEN, + ) + + self.assertEqual(running, (204, b"")) + self.assertEqual(json.loads(running_status[1])["state"], "running") + self.assertEqual(succeeded, (204, b"")) + self.assertEqual(store.states[job_id], "succeeded") + self.assertEqual(store.transition_calls, 2) + + def test_transition_requires_machine_admission_before_parsing_or_mutation(self): + store, server = self.start() + + status, body = request( + server, + "POST", + "/test/transition", + body={"jobId": "not-a-job", "state": "running"}, + ) + + self.assertEqual(status, 401) + self.assertEqual(json.loads(body), {"code": "authentication.refused"}) + self.assertEqual(store.transition_calls, 0) + + def test_transition_refuses_invalid_shape_and_state_without_details(self): + store, server = self.start() + admitted = self.post(server) + job_id = json.loads(admitted[1])["jobId"] + + invalid_shape = request( + server, + "POST", + "/test/transition", + body={"jobId": job_id, "state": "running", "extra": True}, + token=acceptance_server.SYNTHETIC_TOKEN, + ) + invalid_state = request( + server, + "POST", + "/test/transition", + body={"jobId": job_id, "state": "succeeded"}, + token=acceptance_server.SYNTHETIC_TOKEN, + ) + + self.assertEqual(invalid_shape[0], 422) + self.assertEqual(invalid_state[0], 422) + self.assertEqual(json.loads(invalid_shape[1]), {"reason": "invalid-transition"}) + self.assertEqual(json.loads(invalid_state[1]), {"reason": "invalid-transition"}) + self.assertEqual(store.states[job_id], "queued") + + def test_authenticated_snapshot_reports_one_exact_saved_command(self): + store, server = self.start() + admitted = self.post(server) + duplicate = self.post(server) + + status, body = request( + server, + "GET", + "/test/snapshot", + token=acceptance_server.SYNTHETIC_TOKEN, + ) + + self.assertEqual(admitted, duplicate) + self.assertEqual(status, 200) + self.assertEqual( + json.loads(body), + { + "jobCount": 1, + "jobs": [ + { + "key": "coordinator-command-001", + "request": {"reference": "case-001"}, + "receipt": json.loads(admitted[1]), + } + ], + }, + ) + self.assertEqual(store.calls, 2) + + def test_snapshot_requires_machine_admission_before_store_access(self): + store, server = self.start() + + status, body = request(server, "GET", "/test/snapshot") + + self.assertEqual(status, 401) + self.assertEqual(json.loads(body), {"code": "authentication.refused"}) + self.assertEqual(store.calls, 0) + + def test_snapshot_refuses_more_than_sixteen_jobs(self): + store = MemoryStore() + for index in range(17): + store.admit(f"command-{index}", {"reference": f"case-{index}"}) + server = acceptance_server.AcceptanceServer(store) + server.start() + self.addCleanup(server.stop) + + status, body = request( + server, + "GET", + "/test/snapshot", + token=acceptance_server.SYNTHETIC_TOKEN, + ) + + self.assertEqual(status, 503) + self.assertEqual(json.loads(body), {"reason": "snapshot-unavailable"}) + + def test_declared_refusal_is_test_only_and_commits_no_job(self): + store, server = self.start(fault="declared-refusal") + + status, body = self.post(server) + + self.assertEqual(status, 422) + self.assertEqual(json.loads(body), {"reason": "invalid-job"}) + self.assertEqual(store.admissions, {}) + + def test_malformed_response_after_commit_recovers_the_receipt(self): + store, server = self.start(fault="malformed-response-after-commit") + + first = self.post(server) + recovered = self.post(server) + + self.assertEqual(first, (201, b"not-json")) + self.assertEqual(recovered[0], 201) + self.assertIn("jobId", json.loads(recovered[1])) + self.assertEqual(len(store.admissions), 1) + + def test_encoding_error_after_commit_recovers_without_a_second_job(self): + store, server = self.start(fault="encoding-error-after-commit") + captured = StringIO() + + with redirect_stderr(captured): + first = self.post(server) + recovered = self.post(server) + + self.assertIn(first[0], (0, 500)) + self.assertIn("synthetic response encoding failure", captured.getvalue()) + self.assertEqual(recovered[0], 201) + self.assertEqual(len(store.admissions), 1) + + def test_process_exit_fault_runs_only_after_the_receipt_is_committed(self): + store, server = self.start(fault="process-exit-after-commit") + exited = threading.Event() + + def record_exit(code): + self.assertEqual(code, acceptance_server.POST_COMMIT_EXIT_CODE) + exited.set() + raise RuntimeError("synthetic process exit intercepted") + + captured = StringIO() + with ( + patch.object(acceptance_server.os, "_exit", record_exit), + redirect_stderr(captured), + ): + first = self.post(server) + + self.assertIn(first[0], (0, 500)) + self.assertTrue(exited.is_set()) + self.assertEqual(len(store.admissions), 1) + self.assertIn("synthetic process exit intercepted", captured.getvalue()) + + +if __name__ == "__main__": + unittest.main() From 5fefb47aac69459bec0c30fdb8b9159c75bfd677 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 05:55:31 +0700 Subject: [PATCH 13/34] chore(platform): include native helper license copies Signed-off-by: Jeremi Joslin --- crates/registry-platform-oidc-py/LICENSE | 201 +++++++++++++++++++++++ crates/registry-platform-yaml-py/LICENSE | 201 +++++++++++++++++++++++ 2 files changed, 402 insertions(+) create mode 100644 crates/registry-platform-oidc-py/LICENSE create mode 100644 crates/registry-platform-yaml-py/LICENSE diff --git a/crates/registry-platform-oidc-py/LICENSE b/crates/registry-platform-oidc-py/LICENSE new file mode 100644 index 0000000000..0421f3c2d5 --- /dev/null +++ b/crates/registry-platform-oidc-py/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 Jeremi Joslin + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/crates/registry-platform-yaml-py/LICENSE b/crates/registry-platform-yaml-py/LICENSE new file mode 100644 index 0000000000..0421f3c2d5 --- /dev/null +++ b/crates/registry-platform-yaml-py/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 Jeremi Joslin + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. From 8ba01d1f0253a857d71d76fa4d3961b9c2e52fde Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 06:45:04 +0700 Subject: [PATCH 14/34] fix(platform): align picker read-back validation with producer authority Signed-off-by: Jeremi Joslin --- .../src/project_dev/picker.rs | 60 +- .../registry-bregctl/src/project_dev/plan.rs | 29 +- crates/registry-platform-yaml-py/README.md | 14 +- .../registry-platform-yaml-py/src/formats.rs | 566 ++++++++++++++++- crates/registry-platform-yaml-py/src/lib.rs | 28 +- crates/registry-platform-yaml-py/src/tests.rs | 273 +++++++++ .../registry_client/check_dev_picker.py | 239 ++++++++ .../python/registry_client/dev_picker.py | 575 +++++++++++++----- .../tests/test_dev_picker.py | 391 ++++++++++-- .../tools/project-dev.v1alpha1.schema.json | 8 +- .../identifiers/contracts/catalog-source.json | 24 + .../identifiers/generated/catalog.v1.json | 60 +- .../examples/formats/ctl-report.json | 4 +- .../config-conventions-exceptions.yaml | 12 + products/platform/config-formats.yaml | 257 ++++++++ .../examples/dev-picker/check-report.json | 12 + .../dev-picker/credential-0-breg.json | 27 + .../examples/dev-picker/generation.json | 9 + .../platform/examples/dev-picker/picker.json | 41 ++ ...dev-picker-descriptor.v1alpha1.schema.json | 302 +++++++++ ...dev-picker-generation.v1alpha1.schema.json | 66 ++ .../dev-picker-token.v1alpha1.schema.json | 190 ++++++ .../scripts/test_build_linux_python_client.py | 2 +- 23 files changed, 2952 insertions(+), 237 deletions(-) create mode 100644 crates/registry-stack-client-py/python/registry_client/check_dev_picker.py create mode 100644 products/platform/examples/dev-picker/check-report.json create mode 100644 products/platform/examples/dev-picker/credential-0-breg.json create mode 100644 products/platform/examples/dev-picker/generation.json create mode 100644 products/platform/examples/dev-picker/picker.json create mode 100644 products/platform/schemas/dev-picker-descriptor.v1alpha1.schema.json create mode 100644 products/platform/schemas/dev-picker-generation.v1alpha1.schema.json create mode 100644 products/platform/schemas/dev-picker-token.v1alpha1.schema.json diff --git a/crates/registry-bregctl/src/project_dev/picker.rs b/crates/registry-bregctl/src/project_dev/picker.rs index c776e37644..b0f24f477a 100644 --- a/crates/registry-bregctl/src/project_dev/picker.rs +++ b/crates/registry-bregctl/src/project_dev/picker.rs @@ -280,7 +280,7 @@ impl PickerCredentials { ( product.name().to_owned(), json!({ - "tokenRef": token_ref, + "tokenFile": token_ref, "profile": grant.profile, "resource": self.input.plan.product(*product).audience, "audiences": audiences(&self.input, declared, *product), @@ -320,16 +320,13 @@ impl PickerCredentials { }) }) .collect::>(); - let connection_ref = if plan.workloads.is_empty() { - Value::Null - } else { + if !plan.workloads.is_empty() { ensure!( self.workload_connection.is_some(), "development picker workloads need the run's generated connection" ); - json!("../../python-workload/python-connection.json") - }; - Ok(json!({ + } + let mut descriptor = json!({ "apiVersion": DESCRIPTOR_FORMAT, "kind": DESCRIPTOR_KIND, "runId": self.input.run_id, @@ -338,12 +335,16 @@ impl PickerCredentials { "sessionNamespace": picker.session_namespace, "issuedAt": issued_at, "expiresAt": self.run_expires, - "generationRef": GENERATION_FILE, + "generationFile": GENERATION_FILE, "products": products, "people": people, - "workloadConnectionRef": connection_ref, "workloads": workloads, - })) + }); + if !plan.workloads.is_empty() { + descriptor["workloadConnectionFile"] = + json!("../../python-workload/python-connection.json"); + } + Ok(descriptor) } fn token_metadata( @@ -489,6 +490,41 @@ mod tests { }) } + #[test] + fn descriptor_omits_workload_reference_when_no_workloads_exist() { + let scratch = tempfile::tempdir().unwrap(); + std::fs::set_permissions(scratch.path(), PermissionsExt::from_mode(0o700)).unwrap(); + let mut input = input(scratch.path()); + let plan = &mut Arc::get_mut(&mut input).unwrap().plan; + plan.workloads.clear(); + plan.development_pickers + .holder + .as_mut() + .unwrap() + .workloads + .clear(); + let issuer = Arc::new(Issuer::create(scratch.path()).unwrap()); + let now = super::super::clock().unwrap(); + let credentials = PickerCredentials::prepare( + scratch.path(), + input, + issuer, + &BTreeMap::from([ + (Product::Breg, "http://127.0.0.1:41001".to_owned()), + (Product::Casework, "http://127.0.0.1:41002".to_owned()), + ]), + None, + now, + now + 600, + ) + .unwrap() + .unwrap(); + let descriptor: Value = + serde_json::from_slice(&std::fs::read(&credentials.paths()["holder"]).unwrap()) + .unwrap(); + assert!(descriptor.get("workloadConnectionFile").is_none()); + } + #[test] fn descriptor_and_tokens_are_bounded_to_one_live_run_and_rotate_as_a_set() { let scratch = tempfile::tempdir().unwrap(); @@ -529,12 +565,12 @@ mod tests { assert_eq!(descriptor["people"][0]["label"], "applicant"); assert_ne!(descriptor["people"][0]["selector"], "applicant"); assert_eq!( - descriptor["people"][0]["credentials"]["breg"]["tokenRef"], + descriptor["people"][0]["credentials"]["breg"]["tokenFile"], "credential-0-breg.json" ); assert_eq!(descriptor["workloads"][0]["name"], "notices"); assert_eq!( - descriptor["workloadConnectionRef"], + descriptor["workloadConnectionFile"], "../../python-workload/python-connection.json" ); let descriptor_text = String::from_utf8(descriptor_bytes).unwrap(); diff --git a/crates/registry-bregctl/src/project_dev/plan.rs b/crates/registry-bregctl/src/project_dev/plan.rs index 50947e4c9d..cd2a49104d 100644 --- a/crates/registry-bregctl/src/project_dev/plan.rs +++ b/crates/registry-bregctl/src/project_dev/plan.rs @@ -140,7 +140,7 @@ fn expected_json_schema(generator: &mut schemars::SchemaGenerator) -> schemars:: } /// A product the development run can start. -#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)] +#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "lowercase")] pub(super) enum Product { @@ -291,8 +291,10 @@ impl PickerPersona { #[serde(deny_unknown_fields)] pub(super) struct DevelopmentPickers { /// A holder-only local admission simulation. + #[serde(skip_serializing_if = "Option::is_none")] pub holder: Option, /// A staff-only local admission simulation. + #[serde(skip_serializing_if = "Option::is_none")] pub staff: Option, } @@ -319,7 +321,7 @@ pub(super) struct DevelopmentPicker { /// Test-person aliases eligible for this persona. The browser receives opaque selectors instead. pub people: Vec, /// Complete person credential set required before a picker session opens. - pub person_products: Vec, + pub person_products: UniqueList, /// Service workload bindings available to this picker-backed application. #[serde(default)] pub workloads: Vec, @@ -974,10 +976,8 @@ impl Plan { "Use separate synthetic test people for holder and staff services.", )?; } - let person_products = picker.person_products.iter().collect::>(); require( - !picker.person_products.is_empty() - && person_products.len() == picker.person_products.len(), + !picker.person_products.is_empty(), &format!("{field}/personProducts"), "A development picker needs a distinct nonempty person product set.", "List every product grant required before the local session opens.", @@ -1597,7 +1597,7 @@ mod tests { plan.validate(&canonical(&root)).unwrap(); let picker = plan.development_pickers.holder.as_ref().unwrap(); assert_eq!(picker.people, ["operator"]); - assert_eq!(picker.person_products, [Product::Breg]); + assert_eq!(&picker.person_products[..], &[Product::Breg]); assert_eq!(picker.workloads, ["registry"]); } @@ -1638,6 +1638,23 @@ mod tests { .contains("both local picker personas")); } + #[test] + fn development_picker_defaults_and_duplicate_products_match_the_schema() { + assert_eq!( + serde_json::to_value(DevelopmentPickers::default()).unwrap(), + json!({}) + ); + let (_, plan) = plan(json!({ + "id": "read", "product": "breg", "as": "operator", + "method": "GET", "path": "/v1/records", "expect": {"status": 200} + })); + let mut value = serde_json::to_value(plan).unwrap(); + value["developmentPickers"] = json!({ + "holder": {"people": ["operator"], "personProducts": ["breg", "breg"]} + }); + assert!(serde_json::from_value::(value).is_err()); + } + #[test] fn validation_accepts_dotted_steps_and_camel_case_captures() { let (root, plan) = plan(json!({ diff --git a/crates/registry-platform-yaml-py/README.md b/crates/registry-platform-yaml-py/README.md index a292b548ea..905f676f89 100644 --- a/crates/registry-platform-yaml-py/README.md +++ b/crates/registry-platform-yaml-py/README.md @@ -29,11 +29,15 @@ of the shared reader's JSON diagnostic objects. The reader caps the input at add one `config.too-many-problems` overflow diagnostic. Diagnostic messages do not repeat scalar values from the document. The binding additionally bounds the diagnostic file name to 4 KiB and each -expected format identifier to 256 bytes. The registered Python connection and -development workload-token envelopes are decoded into their closed native -types at the same boundary, including their non-empty authority sets. Other -formats receive the generic envelope and structural checks before their -product-specific validation. +expected format identifier to 256 bytes. The registered Python connection, +development workload-token, development picker descriptor, picker +person-token, and picker generation envelopes are decoded into their closed +native types at the same boundary. Their collections and generated +credentials are bounded, set-like lists refuse duplicates, and an inline +picker bearer token is never repeated in a diagnostic. Cross-file +consistency, path confinement, token claims, and live-run authority remain +with the Python consumer. Other formats receive the generic envelope and +structural checks before their product-specific validation. The standalone development import is: diff --git a/crates/registry-platform-yaml-py/src/formats.rs b/crates/registry-platform-yaml-py/src/formats.rs index acfd17ebb3..dd55c88f6b 100644 --- a/crates/registry-platform-yaml-py/src/formats.rs +++ b/crates/registry-platform-yaml-py/src/formats.rs @@ -1,12 +1,12 @@ // SPDX-License-Identifier: Apache-2.0 -//! Typed structure and schemas for the two Python service read-back formats. +//! Typed structure and schemas for Python service read-back formats. use std::{collections::BTreeMap, hash::Hash}; use platform_config::SecretProvidersConfig; use registry_platform_yaml::{ - ApiVersion, BoundedU64, Decoded, EnvelopeRule, Expect, ExternalId, FormatSpec, Reader, Report, - SecretReference, UniqueList, Url, + ApiVersion, BoundedU64, Decoded, DisplayText, EnvelopeRule, Expect, ExternalId, FormatSpec, + Reader, Report, SecretReference, Severity, UniqueList, Url, }; use serde::{de, Deserialize, Deserializer}; use serde_json::Value; @@ -22,6 +22,21 @@ pub const DEV_WORKLOAD_TOKEN_API_VERSION: &str = pub const DEV_WORKLOAD_TOKEN_KIND: &str = "PlatformDevWorkloadToken"; pub const DEV_WORKLOAD_TOKEN_SCHEMA_ID: &str = "https://id.registrystack.org/schemas/platform/dev-workload-token/dev-workload-token.v1alpha1.schema.json"; pub const DEV_WORKLOAD_TOKEN_SCHEMA_FILE: &str = "dev-workload-token.v1alpha1.schema.json"; +pub const DEV_PICKER_DESCRIPTOR_API_VERSION: &str = + "id.registrystack.org/formats/platform/dev-picker-descriptor/v1alpha1"; +pub const DEV_PICKER_DESCRIPTOR_KIND: &str = "PlatformDevPickerDescriptor"; +pub const DEV_PICKER_DESCRIPTOR_SCHEMA_ID: &str = "https://id.registrystack.org/schemas/platform/dev-picker-descriptor/dev-picker-descriptor.v1alpha1.schema.json"; +pub const DEV_PICKER_DESCRIPTOR_SCHEMA_FILE: &str = "dev-picker-descriptor.v1alpha1.schema.json"; +pub const DEV_PICKER_TOKEN_API_VERSION: &str = + "id.registrystack.org/formats/platform/dev-picker-token/v1alpha1"; +pub const DEV_PICKER_TOKEN_KIND: &str = "PlatformDevPickerToken"; +pub const DEV_PICKER_TOKEN_SCHEMA_ID: &str = "https://id.registrystack.org/schemas/platform/dev-picker-token/dev-picker-token.v1alpha1.schema.json"; +pub const DEV_PICKER_TOKEN_SCHEMA_FILE: &str = "dev-picker-token.v1alpha1.schema.json"; +pub const DEV_PICKER_GENERATION_API_VERSION: &str = + "id.registrystack.org/formats/platform/dev-picker-generation/v1alpha1"; +pub const DEV_PICKER_GENERATION_KIND: &str = "PlatformDevPickerGeneration"; +pub const DEV_PICKER_GENERATION_SCHEMA_ID: &str = "https://id.registrystack.org/schemas/platform/dev-picker-generation/dev-picker-generation.v1alpha1.schema.json"; +pub const DEV_PICKER_GENERATION_SCHEMA_FILE: &str = "dev-picker-generation.v1alpha1.schema.json"; pub const PYTHON_CONNECTION_FORMAT: FormatSpec<'static> = FormatSpec { kind: PYTHON_CONNECTION_KIND, @@ -41,6 +56,33 @@ pub const DEV_WORKLOAD_TOKEN_FORMAT: FormatSpec<'static> = FormatSpec { removed_keys: &[], }; +pub const DEV_PICKER_DESCRIPTOR_FORMAT: FormatSpec<'static> = FormatSpec { + kind: DEV_PICKER_DESCRIPTOR_KIND, + envelope: EnvelopeRule::ApiVersionKind { + api_versions: &[ApiVersion::current(DEV_PICKER_DESCRIPTOR_API_VERSION)], + retired_api_versions: &[], + }, + removed_keys: &[], +}; + +pub const DEV_PICKER_TOKEN_FORMAT: FormatSpec<'static> = FormatSpec { + kind: DEV_PICKER_TOKEN_KIND, + envelope: EnvelopeRule::ApiVersionKind { + api_versions: &[ApiVersion::current(DEV_PICKER_TOKEN_API_VERSION)], + retired_api_versions: &[], + }, + removed_keys: &[], +}; + +pub const DEV_PICKER_GENERATION_FORMAT: FormatSpec<'static> = FormatSpec { + kind: DEV_PICKER_GENERATION_KIND, + envelope: EnvelopeRule::ApiVersionKind { + api_versions: &[ApiVersion::current(DEV_PICKER_GENERATION_API_VERSION)], + retired_api_versions: &[], + }, + removed_keys: &[], +}; + #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Deserialize)] #[serde(rename_all = "lowercase")] @@ -234,6 +276,245 @@ pub struct DevWorkloadToken { pub token: Option, } +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Copy, Deserialize, Eq, Ord, PartialEq, PartialOrd)] +#[serde(rename_all = "lowercase")] +pub enum DevPickerPersona { + Holder, + Staff, +} + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Copy, Deserialize, Eq, Ord, PartialEq, PartialOrd)] +#[serde(rename_all = "lowercase")] +pub enum DevPickerProduct { + Breg, + Casework, + Messaging, +} + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Copy, Deserialize, Eq, Ord, PartialEq, PartialOrd)] +#[serde(rename_all = "lowercase")] +pub enum DevPickerPersonProduct { + Breg, + Casework, +} + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Copy, Deserialize, Eq, Ord, PartialEq, PartialOrd)] +#[serde(rename_all = "lowercase")] +pub enum DevPickerWorkloadProduct { + Breg, + Messaging, +} + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct DevPickerProductTarget { + pub url: Url, + pub resource: ExternalId, +} + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct DevPickerCredential { + pub token_file: ExternalId, + pub profile: ExternalId, + pub resource: ExternalId, + #[serde(deserialize_with = "picker_audiences")] + #[cfg_attr(feature = "schema", schemars(length(min = 1, max = 4)))] + pub audiences: UniqueList, + #[serde(deserialize_with = "picker_scopes")] + #[cfg_attr(feature = "schema", schemars(length(min = 1, max = 32)))] + pub scopes: UniqueList, + pub principal_claim: ExternalId, +} + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct DevPickerPerson { + #[serde(deserialize_with = "opaque_picker_value")] + #[cfg_attr( + feature = "schema", + schemars( + length(min = 20, max = 128), + regex(pattern = "^[A-Za-z0-9_-]{20,128}$") + ) + )] + pub selector: String, + #[serde(deserialize_with = "picker_label")] + #[cfg_attr(feature = "schema", schemars(length(min = 1, max = 128)))] + pub label: String, + pub subject: ExternalId, + pub principal: ExternalId, + pub client_id: ExternalId, + #[serde(deserialize_with = "picker_credentials")] + #[cfg_attr( + feature = "schema", + schemars(schema_with = "picker_credentials_schema") + )] + pub credentials: BTreeMap, +} + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct DevPickerWorkload { + #[serde(deserialize_with = "picker_local_name")] + #[cfg_attr( + feature = "schema", + schemars(regex(pattern = "^[a-z][a-z0-9-]{0,63}$")) + )] + pub name: String, + pub product: DevPickerWorkloadProduct, + pub default: bool, + pub url: Url, + pub issuer: Url, + pub subject: ExternalId, + pub client_id: ExternalId, + pub profile: ExternalId, + pub resource: ExternalId, + #[serde(deserialize_with = "picker_scopes")] + #[cfg_attr(feature = "schema", schemars(length(min = 1, max = 32)))] + pub scopes: UniqueList, + #[serde(deserialize_with = "picker_claims")] + #[cfg_attr(feature = "schema", schemars(schema_with = "picker_claims_schema"))] + pub claims: BTreeMap, +} + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct DevPickerDescriptor { + #[serde(deserialize_with = "picker_run_id")] + #[cfg_attr( + feature = "schema", + schemars(length(min = 32, max = 32), regex(pattern = "^[0-9a-f]{32}$")) + )] + pub run_id: String, + pub persona: DevPickerPersona, + pub origin: Url, + #[serde(deserialize_with = "opaque_picker_value")] + #[cfg_attr( + feature = "schema", + schemars( + length(min = 20, max = 128), + regex(pattern = "^[A-Za-z0-9_-]{20,128}$") + ) + )] + pub session_namespace: String, + pub issued_at: BoundedU64<1, { u64::MAX }>, + pub expires_at: BoundedU64<1, { u64::MAX }>, + pub generation_file: ExternalId, + #[serde(deserialize_with = "picker_products")] + #[cfg_attr(feature = "schema", schemars(schema_with = "picker_products_schema"))] + pub products: BTreeMap, + #[serde(deserialize_with = "picker_people")] + #[cfg_attr(feature = "schema", schemars(length(min = 1, max = 32)))] + pub people: Vec, + #[serde( + default, + deserialize_with = "present_external_id", + skip_serializing_if = "Option::is_none" + )] + pub workload_connection_file: Option, + #[serde(deserialize_with = "picker_workloads")] + #[cfg_attr(feature = "schema", schemars(length(max = 32)))] + pub workloads: Vec, +} + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum DevPickerTokenStatus { + Stopped, +} + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct DevPickerToken { + #[serde(deserialize_with = "picker_run_id")] + #[cfg_attr( + feature = "schema", + schemars(length(min = 32, max = 32), regex(pattern = "^[0-9a-f]{32}$")) + )] + pub run_id: String, + pub picker: DevPickerPersona, + pub persona: DevPickerPersona, + #[serde(deserialize_with = "opaque_picker_value")] + #[cfg_attr( + feature = "schema", + schemars( + length(min = 20, max = 128), + regex(pattern = "^[A-Za-z0-9_-]{20,128}$") + ) + )] + pub selector: String, + pub product: DevPickerPersonProduct, + pub issuer: Url, + pub subject: ExternalId, + pub principal: ExternalId, + pub client_id: ExternalId, + pub profile: ExternalId, + pub resource: ExternalId, + #[serde(deserialize_with = "picker_audiences")] + #[cfg_attr(feature = "schema", schemars(length(min = 1, max = 4)))] + pub audiences: UniqueList, + #[serde(deserialize_with = "picker_scopes")] + #[cfg_attr(feature = "schema", schemars(length(min = 1, max = 32)))] + pub scopes: UniqueList, + pub principal_claim: ExternalId, + pub generation: BoundedU64<1, { u64::MAX }>, + pub issued_at: BoundedU64<1, { u64::MAX }>, + pub expires_at: BoundedU64<1, { u64::MAX }>, + pub run_expires_at: BoundedU64<1, { u64::MAX }>, + #[serde( + default, + deserialize_with = "present_option", + skip_serializing_if = "Option::is_none" + )] + pub status: Option, + #[serde( + default, + deserialize_with = "present_bearer_token", + skip_serializing_if = "Option::is_none" + )] + #[cfg_attr( + feature = "schema", + schemars(length(min = 1, max = 8192), regex(pattern = "^\\S+$")) + )] + pub token: Option, +} + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum DevPickerGenerationStatus { + Ready, + Stopped, +} + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct DevPickerGeneration { + pub status: DevPickerGenerationStatus, + #[serde(deserialize_with = "picker_run_id")] + #[cfg_attr( + feature = "schema", + schemars(length(min = 32, max = 32), regex(pattern = "^[0-9a-f]{32}$")) + )] + pub run_id: String, + pub picker: DevPickerPersona, + pub generation: BoundedU64<1, { u64::MAX }>, + pub run_expires_at: BoundedU64<1, { u64::MAX }>, +} + fn non_empty_unique_list<'de, D, T>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, @@ -259,6 +540,166 @@ where Ok(values) } +fn bounded_unique_list<'de, D, T, const MIN: usize, const MAX: usize>( + deserializer: D, +) -> Result, D::Error> +where + D: Deserializer<'de>, + T: Deserialize<'de> + Eq + Hash, +{ + let values = UniqueList::::deserialize(deserializer)?; + if !(MIN..=MAX).contains(&values.len()) { + return Err(de::Error::custom("the list length is outside its bounds")); + } + Ok(values) +} + +fn picker_audiences<'de, D>(deserializer: D) -> Result, D::Error> +where + D: Deserializer<'de>, +{ + bounded_unique_list::(deserializer) +} + +fn picker_scopes<'de, D>(deserializer: D) -> Result, D::Error> +where + D: Deserializer<'de>, +{ + bounded_unique_list::(deserializer) +} + +fn bounded_map<'de, D, K, V, const MIN: usize, const MAX: usize>( + deserializer: D, +) -> Result, D::Error> +where + D: Deserializer<'de>, + K: Deserialize<'de> + Ord, + V: Deserialize<'de>, +{ + let values = BTreeMap::::deserialize(deserializer)?; + if !(MIN..=MAX).contains(&values.len()) { + return Err(de::Error::custom("the mapping size is outside its bounds")); + } + Ok(values) +} + +fn picker_products<'de, D>( + deserializer: D, +) -> Result, D::Error> +where + D: Deserializer<'de>, +{ + bounded_map::(deserializer) +} + +fn picker_credentials<'de, D>( + deserializer: D, +) -> Result, D::Error> +where + D: Deserializer<'de>, +{ + bounded_map::(deserializer) +} + +fn picker_claims<'de, D>(deserializer: D) -> Result, D::Error> +where + D: Deserializer<'de>, +{ + bounded_map::(deserializer) +} + +fn bounded_vec<'de, D, T, const MIN: usize, const MAX: usize>( + deserializer: D, +) -> Result, D::Error> +where + D: Deserializer<'de>, + T: Deserialize<'de>, +{ + let values = Vec::::deserialize(deserializer)?; + if !(MIN..=MAX).contains(&values.len()) { + return Err(de::Error::custom("the list length is outside its bounds")); + } + Ok(values) +} + +fn picker_people<'de, D>(deserializer: D) -> Result, D::Error> +where + D: Deserializer<'de>, +{ + bounded_vec::(deserializer) +} + +fn picker_workloads<'de, D>(deserializer: D) -> Result, D::Error> +where + D: Deserializer<'de>, +{ + bounded_vec::(deserializer) +} + +fn picker_run_id<'de, D>(deserializer: D) -> Result +where + D: Deserializer<'de>, +{ + let value = String::deserialize(deserializer)?; + if value.len() != 32 + || !value + .bytes() + .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f')) + { + return Err(de::Error::custom( + "the run id must be 32 lowercase hexadecimal digits", + )); + } + Ok(value) +} + +fn opaque_picker_value<'de, D>(deserializer: D) -> Result +where + D: Deserializer<'de>, +{ + let value = String::deserialize(deserializer)?; + if !(20..=128).contains(&value.len()) + || !value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-')) + { + return Err(de::Error::custom("the opaque value has an invalid shape")); + } + Ok(value) +} + +fn picker_local_name<'de, D>(deserializer: D) -> Result +where + D: Deserializer<'de>, +{ + let value = String::deserialize(deserializer)?; + let bytes = value.as_bytes(); + if !matches!(bytes.first(), Some(b'a'..=b'z')) + || bytes.len() > 64 + || !bytes + .iter() + .all(|byte| matches!(byte, b'a'..=b'z' | b'0'..=b'9' | b'-')) + { + return Err(de::Error::custom("the local name has an invalid shape")); + } + Ok(value) +} + +fn picker_label<'de, D>(deserializer: D) -> Result +where + D: Deserializer<'de>, +{ + let value = DisplayText::deserialize(deserializer)?.into_string(); + if value.is_empty() + || value.chars().count() > 128 + || value.trim() != value + || value.chars().any(char::is_control) + { + return Err(de::Error::custom("the display label has an invalid shape")); + } + Ok(value) +} + #[cfg(feature = "schema")] fn authority_claims_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema { schemars::json_schema!({ @@ -269,6 +710,47 @@ fn authority_claims_schema(generator: &mut schemars::SchemaGenerator) -> schemar }) } +#[cfg(feature = "schema")] +fn picker_products_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema { + let _ = generator.subschema_for::(); + schemars::json_schema!({ + "type": "object", + "propertyNames": { + "$ref": "#/$defs/ExternalId", + "enum": ["breg", "casework", "messaging"], + }, + "additionalProperties": generator.subschema_for::(), + "minProperties": 1, + "maxProperties": 3, + }) +} + +#[cfg(feature = "schema")] +fn picker_credentials_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema { + let _ = generator.subschema_for::(); + schemars::json_schema!({ + "type": "object", + "propertyNames": { + "$ref": "#/$defs/ExternalId", + "enum": ["breg", "casework"], + }, + "additionalProperties": generator.subschema_for::(), + "minProperties": 1, + "maxProperties": 2, + }) +} + +#[cfg(feature = "schema")] +fn picker_claims_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema { + schemars::json_schema!({ + "type": "object", + "propertyNames": generator.subschema_for::(), + "additionalProperties": true, + "maxProperties": 64, + "x-registry-passthrough": "Claim values are written into the workload token as declared.", + }) +} + fn present_option<'de, D, T>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, @@ -277,6 +759,24 @@ where T::deserialize(deserializer).map(Some) } +fn present_external_id<'de, D>(deserializer: D) -> Result, D::Error> +where + D: Deserializer<'de>, +{ + ExternalId::deserialize(deserializer).map(Some) +} + +fn present_bearer_token<'de, D>(deserializer: D) -> Result, D::Error> +where + D: Deserializer<'de>, +{ + let value = String::deserialize(deserializer)?; + if value.is_empty() || value.len() > 8192 || value.chars().any(char::is_whitespace) { + return Err(de::Error::custom("the bearer token has an invalid shape")); + } + Ok(Some(value)) +} + fn document_value(decoded: Decoded) -> Value { decoded.document.to_json_value() } @@ -293,6 +793,39 @@ pub fn read_dev_workload_token(file: &str, bytes: &[u8]) -> Result Result { + Reader::new(file) + .decode::(bytes, &Expect::one(&DEV_PICKER_DESCRIPTOR_FORMAT)) + .map(document_value) +} + +pub fn read_dev_picker_token(file: &str, bytes: &[u8]) -> Result { + let decoded = Reader::new(file) + .decode::(bytes, &Expect::one(&DEV_PICKER_TOKEN_FORMAT))?; + if decoded.value.status.is_some() == decoded.value.token.is_some() { + let pointer = if decoded.value.status.is_some() { + "/status" + } else { + "" + }; + let diagnostic = decoded.document.diagnostic_at_value( + Severity::Error, + "config.invalid-value", + pointer, + "the token document does not hold one supported credential state", + "Write `token` for a ready credential, or `status: stopped` without `token`.", + ); + return Err(decoded.document.report_with([diagnostic])); + } + Ok(decoded.document.to_json_value()) +} + +pub fn read_dev_picker_generation(file: &str, bytes: &[u8]) -> Result { + Reader::new(file) + .decode::(bytes, &Expect::one(&DEV_PICKER_GENERATION_FORMAT)) + .map(document_value) +} + #[cfg(feature = "schema")] fn schema(api_version: &str, kind: &str, id: &str) -> Value { let mut schema = serde_json::to_value(schemars::schema_for!(T)).expect("schema is JSON"); @@ -351,7 +884,7 @@ fn refuse_null(schema: &mut Value) { } #[cfg(feature = "schema")] -pub fn schema_documents() -> [(&'static str, Value); 2] { +pub fn schema_documents() -> [(&'static str, Value); 5] { let mut connection = schema::( PYTHON_CONNECTION_API_VERSION, PYTHON_CONNECTION_KIND, @@ -388,8 +921,33 @@ pub fn schema_documents() -> [(&'static str, Value); 2] { .remove("format"); refuse_null(&mut token["properties"]["status"]); refuse_null(&mut token["properties"]["token"]); + let mut picker_descriptor = schema::( + DEV_PICKER_DESCRIPTOR_API_VERSION, + DEV_PICKER_DESCRIPTOR_KIND, + DEV_PICKER_DESCRIPTOR_SCHEMA_ID, + ); + refuse_null(&mut picker_descriptor["properties"]["workloadConnectionFile"]); + let mut picker_token = schema::( + DEV_PICKER_TOKEN_API_VERSION, + DEV_PICKER_TOKEN_KIND, + DEV_PICKER_TOKEN_SCHEMA_ID, + ); + picker_token["oneOf"] = serde_json::json!([ + {"required": ["token"], "not": {"required": ["status"]}}, + {"required": ["status"], "not": {"required": ["token"]}} + ]); + refuse_null(&mut picker_token["properties"]["status"]); + refuse_null(&mut picker_token["properties"]["token"]); + let picker_generation = schema::( + DEV_PICKER_GENERATION_API_VERSION, + DEV_PICKER_GENERATION_KIND, + DEV_PICKER_GENERATION_SCHEMA_ID, + ); [ (PYTHON_CONNECTION_SCHEMA_FILE, connection), (DEV_WORKLOAD_TOKEN_SCHEMA_FILE, token), + (DEV_PICKER_DESCRIPTOR_SCHEMA_FILE, picker_descriptor), + (DEV_PICKER_TOKEN_SCHEMA_FILE, picker_token), + (DEV_PICKER_GENERATION_SCHEMA_FILE, picker_generation), ] } diff --git a/crates/registry-platform-yaml-py/src/lib.rs b/crates/registry-platform-yaml-py/src/lib.rs index 839dfef9c2..bf548d3fed 100644 --- a/crates/registry-platform-yaml-py/src/lib.rs +++ b/crates/registry-platform-yaml-py/src/lib.rs @@ -17,7 +17,14 @@ use yaml_core::{ #[cfg(feature = "schema")] pub use formats::schema_documents; pub use formats::{ - read_dev_workload_token, read_python_connection, DevWorkloadToken, PythonConnection, + read_dev_picker_descriptor, read_dev_picker_generation, read_dev_picker_token, + read_dev_workload_token, read_python_connection, DevPickerDescriptor, DevPickerGeneration, + DevPickerToken, DevWorkloadToken, PythonConnection, DEV_PICKER_DESCRIPTOR_API_VERSION, + DEV_PICKER_DESCRIPTOR_FORMAT, DEV_PICKER_DESCRIPTOR_KIND, DEV_PICKER_DESCRIPTOR_SCHEMA_FILE, + DEV_PICKER_DESCRIPTOR_SCHEMA_ID, DEV_PICKER_GENERATION_API_VERSION, + DEV_PICKER_GENERATION_FORMAT, DEV_PICKER_GENERATION_KIND, DEV_PICKER_GENERATION_SCHEMA_FILE, + DEV_PICKER_GENERATION_SCHEMA_ID, DEV_PICKER_TOKEN_API_VERSION, DEV_PICKER_TOKEN_FORMAT, + DEV_PICKER_TOKEN_KIND, DEV_PICKER_TOKEN_SCHEMA_FILE, DEV_PICKER_TOKEN_SCHEMA_ID, DEV_WORKLOAD_TOKEN_API_VERSION, DEV_WORKLOAD_TOKEN_KIND, DEV_WORKLOAD_TOKEN_SCHEMA_FILE, DEV_WORKLOAD_TOKEN_SCHEMA_ID, PYTHON_CONNECTION_API_VERSION, PYTHON_CONNECTION_KIND, PYTHON_CONNECTION_SCHEMA_FILE, PYTHON_CONNECTION_SCHEMA_ID, @@ -79,6 +86,25 @@ fn read_checked( if (api_version, kind) == (DEV_WORKLOAD_TOKEN_API_VERSION, DEV_WORKLOAD_TOKEN_KIND) { return read_dev_workload_token(file, contents); } + if (api_version, kind) + == ( + DEV_PICKER_DESCRIPTOR_API_VERSION, + DEV_PICKER_DESCRIPTOR_KIND, + ) + { + return read_dev_picker_descriptor(file, contents); + } + if (api_version, kind) == (DEV_PICKER_TOKEN_API_VERSION, DEV_PICKER_TOKEN_KIND) { + return read_dev_picker_token(file, contents); + } + if (api_version, kind) + == ( + DEV_PICKER_GENERATION_API_VERSION, + DEV_PICKER_GENERATION_KIND, + ) + { + return read_dev_picker_generation(file, contents); + } let api_versions = [ApiVersion::current(api_version)]; let format = FormatSpec { kind, diff --git a/crates/registry-platform-yaml-py/src/tests.rs b/crates/registry-platform-yaml-py/src/tests.rs index 5f485a78d1..be5fd17134 100644 --- a/crates/registry-platform-yaml-py/src/tests.rs +++ b/crates/registry-platform-yaml-py/src/tests.rs @@ -235,6 +235,279 @@ fn registered_token_reader_does_not_treat_null_as_omission() { assert_eq!(report.diagnostics()[0].path, "/token"); } +const PICKER_DESCRIPTOR: &[u8] = br#"{ + "apiVersion":"id.registrystack.org/formats/platform/dev-picker-descriptor/v1alpha1", + "kind":"PlatformDevPickerDescriptor", + "runId":"0123456789abcdef0123456789abcdef", + "persona":"holder", + "origin":"http://127.0.0.1:41000", + "sessionNamespace":"0123456789abcdef0123456789abcdef", + "issuedAt":1700000000, + "expiresAt":1700000600, + "generationFile":"generation.json", + "products":{ + "breg":{"url":"http://127.0.0.1:41001","resource":"urn:test:breg"}, + "casework":{"url":"http://127.0.0.1:41002","resource":"urn:test:casework"}, + "messaging":{"url":"http://127.0.0.1:41003","resource":"urn:test:messaging"} + }, + "people":[{ + "selector":"abcdef0123456789abcdef0123456789", + "label":"applicant", + "subject":"person-one", + "principal":"person-one", + "clientId":"portal-client", + "credentials":{ + "breg":{ + "tokenFile":"credential-0-breg.json", + "profile":"applicant", + "resource":"urn:test:breg", + "audiences":["urn:test:breg"], + "scopes":["breg:read"], + "principalClaim":"registry_principal" + }, + "casework":{ + "tokenFile":"credential-0-casework.json", + "profile":"requester", + "resource":"urn:test:casework", + "audiences":["urn:test:casework","urn:test:breg"], + "scopes":["casework:read"], + "principalClaim":"registry_principal" + } + } + }], + "workloadConnectionFile":"../../python-workload/python-connection.json", + "workloads":[{ + "name":"notices", + "product":"messaging", + "default":true, + "url":"http://127.0.0.1:41003", + "issuer":"https://issuer.example.test", + "subject":"notice-service", + "clientId":"notice-client", + "profile":"service-sender", + "resource":"urn:test:messaging", + "scopes":["messaging:send"], + "claims":{"registry_actor_kind":"service"} + }] +}"#; + +const PICKER_TOKEN: &[u8] = br#"{ + "apiVersion":"id.registrystack.org/formats/platform/dev-picker-token/v1alpha1", + "kind":"PlatformDevPickerToken", + "runId":"0123456789abcdef0123456789abcdef", + "picker":"holder", + "persona":"holder", + "selector":"abcdef0123456789abcdef0123456789", + "product":"breg", + "issuer":"https://issuer.example.test", + "subject":"person-one", + "principal":"person-one", + "clientId":"portal-client", + "profile":"applicant", + "resource":"urn:test:breg", + "audiences":["urn:test:breg"], + "scopes":["breg:read"], + "principalClaim":"registry_principal", + "generation":1, + "issuedAt":1700000000, + "expiresAt":1700000300, + "runExpiresAt":1700000600, + "token":"header.payload.signature" +}"#; + +const PICKER_GENERATION: &[u8] = br#"{ + "apiVersion":"id.registrystack.org/formats/platform/dev-picker-generation/v1alpha1", + "kind":"PlatformDevPickerGeneration", + "status":"ready", + "runId":"0123456789abcdef0123456789abcdef", + "picker":"holder", + "generation":1, + "runExpiresAt":1700000600 +}"#; + +#[test] +fn registered_picker_readers_accept_representative_emitted_documents() { + let descriptor = crate::read_dev_picker_descriptor("picker.json", PICKER_DESCRIPTOR) + .expect("descriptor reads"); + assert_eq!( + descriptor["people"][0]["credentials"]["breg"]["scopes"][0], + "breg:read" + ); + + let token = crate::read_dev_picker_token("credential-0-breg.json", PICKER_TOKEN) + .expect("ready token reads"); + assert_eq!(token["generation"], 1); + + let generation = crate::read_dev_picker_generation("generation.json", PICKER_GENERATION) + .expect("generation reads"); + assert_eq!(generation["status"], "ready"); +} + +#[test] +fn picker_formats_are_typed_through_read_document_dispatch() { + for (contents, file, api_version, kind) in [ + ( + PICKER_DESCRIPTOR, + "picker.json", + crate::DEV_PICKER_DESCRIPTOR_API_VERSION, + crate::DEV_PICKER_DESCRIPTOR_KIND, + ), + ( + PICKER_TOKEN, + "credential-0-breg.json", + crate::DEV_PICKER_TOKEN_API_VERSION, + crate::DEV_PICKER_TOKEN_KIND, + ), + ( + PICKER_GENERATION, + "generation.json", + crate::DEV_PICKER_GENERATION_API_VERSION, + crate::DEV_PICKER_GENERATION_KIND, + ), + ] { + read_checked(contents, file, api_version, kind).expect("registered format reads"); + } +} + +#[test] +fn picker_descriptor_refuses_unknown_nested_members_and_duplicate_sets() { + let mut descriptor: serde_json::Value = + serde_json::from_slice(PICKER_DESCRIPTOR).expect("descriptor JSON"); + descriptor["people"][0]["credentials"]["breg"]["unexpected"] = + serde_json::json!("value-canary"); + let bytes = serde_json::to_vec(&descriptor).expect("descriptor JSON"); + let report = crate::read_dev_picker_descriptor("picker.json", &bytes) + .expect_err("an unknown credential member refuses"); + assert_eq!(report.diagnostics()[0].code, "config.unknown-key"); + assert_eq!( + report.diagnostics()[0].path, + "/people/0/credentials/breg/unexpected" + ); + assert!(!report.to_json_value().to_string().contains("value-canary")); + + descriptor["people"][0]["credentials"]["breg"] + .as_object_mut() + .expect("credential") + .remove("unexpected"); + descriptor["people"][0]["credentials"]["breg"]["scopes"] = + serde_json::json!(["breg:read", "breg:read"]); + let bytes = serde_json::to_vec(&descriptor).expect("descriptor JSON"); + let report = crate::read_dev_picker_descriptor("picker.json", &bytes) + .expect_err("duplicate scopes refuse"); + assert_eq!(report.diagnostics()[0].code, "config.duplicate-item"); + assert_eq!( + report.diagnostics()[0].path, + "/people/0/credentials/breg/scopes/1" + ); +} + +#[test] +fn picker_descriptor_refuses_explicit_null_and_unbounded_people() { + let mut descriptor: serde_json::Value = + serde_json::from_slice(PICKER_DESCRIPTOR).expect("descriptor JSON"); + descriptor["workloadConnectionFile"] = serde_json::Value::Null; + let bytes = serde_json::to_vec(&descriptor).expect("descriptor JSON"); + let report = crate::read_dev_picker_descriptor("picker.json", &bytes) + .expect_err("explicit null refuses"); + assert_eq!(report.diagnostics()[0].code, "config.null-value"); + assert_eq!(report.diagnostics()[0].path, "/workloadConnectionFile"); + + descriptor + .as_object_mut() + .expect("descriptor") + .remove("workloadConnectionFile"); + descriptor["workloads"] = serde_json::json!([]); + descriptor["people"] = serde_json::Value::Array(vec![descriptor["people"][0].clone(); 33]); + let bytes = serde_json::to_vec(&descriptor).expect("descriptor JSON"); + let report = crate::read_dev_picker_descriptor("picker.json", &bytes) + .expect_err("more than 32 people refuse"); + assert_eq!(report.diagnostics()[0].path, "/people"); +} + +#[test] +fn picker_readers_refuse_products_outside_each_supported_surface() { + let mut descriptor: serde_json::Value = + serde_json::from_slice(PICKER_DESCRIPTOR).expect("descriptor JSON"); + descriptor["people"][0]["credentials"]["messaging"] = + descriptor["people"][0]["credentials"]["breg"].clone(); + let report = crate::read_dev_picker_descriptor( + "picker.json", + &serde_json::to_vec(&descriptor).expect("descriptor JSON"), + ) + .expect_err("a person messaging credential refuses"); + assert_eq!(report.diagnostics()[0].code, "config.unknown-variant"); + assert_eq!( + report.diagnostics()[0].path, + "/people/0/credentials/messaging" + ); + + let mut descriptor: serde_json::Value = + serde_json::from_slice(PICKER_DESCRIPTOR).expect("descriptor JSON"); + descriptor["workloads"][0]["product"] = serde_json::json!("casework"); + let report = crate::read_dev_picker_descriptor( + "picker.json", + &serde_json::to_vec(&descriptor).expect("descriptor JSON"), + ) + .expect_err("a Casework service workload refuses"); + assert_eq!(report.diagnostics()[0].code, "config.unknown-variant"); + assert_eq!(report.diagnostics()[0].path, "/workloads/0/product"); + + let mut token: serde_json::Value = serde_json::from_slice(PICKER_TOKEN).expect("token JSON"); + token["product"] = serde_json::json!("messaging"); + let report = crate::read_dev_picker_token( + "credential-0-messaging.json", + &serde_json::to_vec(&token).expect("token JSON"), + ) + .expect_err("a person Messaging token refuses"); + assert_eq!(report.diagnostics()[0].code, "config.unknown-variant"); + assert_eq!(report.diagnostics()[0].path, "/product"); +} + +#[test] +fn picker_token_refuses_invalid_state_shapes_without_exposing_bearer() { + let canary = "bearer-value-canary"; + let mut token: serde_json::Value = serde_json::from_slice(PICKER_TOKEN).expect("token JSON"); + token["status"] = serde_json::json!("stopped"); + token["token"] = serde_json::json!(canary); + let bytes = serde_json::to_vec(&token).expect("token JSON"); + let report = crate::read_dev_picker_token("credential-0-breg.json", &bytes) + .expect_err("token and stopped state together refuse"); + assert!(!report.to_json_value().to_string().contains(canary)); + + token.as_object_mut().expect("token").remove("token"); + crate::read_dev_picker_token( + "credential-0-breg.json", + &serde_json::to_vec(&token).unwrap(), + ) + .expect("stopped token metadata reads"); +} + +#[test] +fn picker_generation_refuses_zero_and_unknown_status() { + let mut generation: serde_json::Value = + serde_json::from_slice(PICKER_GENERATION).expect("generation JSON"); + generation["generation"] = serde_json::json!(0); + let report = crate::read_dev_picker_generation( + "generation.json", + &serde_json::to_vec(&generation).unwrap(), + ) + .expect_err("zero generation refuses"); + assert_eq!(report.diagnostics()[0].code, "config.out-of-range"); + assert_eq!(report.diagnostics()[0].path, "/generation"); + + generation["generation"] = serde_json::json!(1); + generation["status"] = serde_json::json!("retired-value-canary"); + let report = crate::read_dev_picker_generation( + "generation.json", + &serde_json::to_vec(&generation).unwrap(), + ) + .expect_err("unknown status refuses"); + assert!(!report + .to_json_value() + .to_string() + .contains("retired-value-canary")); +} + #[cfg(feature = "schema")] #[test] fn generated_schema_documents_match_the_committed_files() { diff --git a/crates/registry-stack-client-py/python/registry_client/check_dev_picker.py b/crates/registry-stack-client-py/python/registry_client/check_dev_picker.py new file mode 100644 index 0000000000..ca44ad676b --- /dev/null +++ b/crates/registry-stack-client-py/python/registry_client/check_dev_picker.py @@ -0,0 +1,239 @@ +"""Check a development picker read-back file's shape without contacting a service.""" + +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import stat +import sys +from typing import Any, Mapping, Sequence + +from . import __version__ as CLIENT_VERSION +from .connection import ConnectionError +from .dev_picker import ( + DESCRIPTOR_VERSION, + GENERATION_VERSION, + TOKEN_VERSION, + DevelopmentPicker, + PickerUnavailable, + PickerValidationError, + _validate_generation_document, + _validate_token_document, +) + + +FORMATS = { + "descriptor": (DESCRIPTOR_VERSION, "PlatformDevPickerDescriptor"), + "generation": (GENERATION_VERSION, "PlatformDevPickerGeneration"), + "token": (TOKEN_VERSION, "PlatformDevPickerToken"), +} +MAXIMUM_FILE_BYTES = 1_048_576 +REPORT_API_VERSION = "id.registrystack.org/formats/platform/dev-picker-check-report/v1alpha1" +REPORT_KIND = "PlatformDevPickerCheckReport" +REPORT_COMMAND = "dev-picker check" + + +class _UsageError(ValueError): + pass + + +class _Parser(argparse.ArgumentParser): + def error(self, message: str) -> None: + raise _UsageError(message) + + +def _diagnostic( + file: str | Path | None, + *, + code: str = "config.invalid-value", + path: str = "", + message: str = "the generated picker state is inconsistent", + suggested_action: str = "Regenerate the development picker state.", +) -> dict[str, Any]: + diagnostic: dict[str, Any] = { + "severity": "error", + "code": code, + "path": path, + "message": message, + "suggestedAction": suggested_action, + } + if file is not None: + diagnostic["source"] = {"file": os.fspath(file)} + return diagnostic + + +def _report(status: str, diagnostics: Sequence[Mapping[str, Any]]) -> dict[str, Any]: + errors = sum(diagnostic.get("severity") == "error" for diagnostic in diagnostics) + warnings = sum(diagnostic.get("severity") == "warning" for diagnostic in diagnostics) + return { + "ok": status == "complete", + "command": REPORT_COMMAND, + "status": status, + "apiVersion": REPORT_API_VERSION, + "kind": REPORT_KIND, + "version": CLIENT_VERSION, + "filesChecked": 1 if status in ("complete", "domain-refusal") else 0, + "errors": errors, + "warnings": warnings, + "diagnostics": list(diagnostics), + } + + +def _json_requested(arguments: Sequence[str]) -> bool: + for index, argument in enumerate(arguments): + if argument == "--": + return False + if argument == "--format=json": + return True + if argument == "--format" and index + 1 < len(arguments): + return arguments[index + 1] == "json" + return False + + +def _human_lines(diagnostics: Sequence[Mapping[str, Any]]) -> list[str]: + lines = [] + for diagnostic in diagnostics: + severity = diagnostic.get("severity", "error") + code = diagnostic.get("code", "config.invalid-value") + path = diagnostic.get("path") or "" + source = diagnostic.get("source") + location = "" + if isinstance(source, Mapping): + location = str(source.get("file") or location) + line = source.get("line") + column = source.get("column") + if isinstance(line, int) and not isinstance(line, bool) and line > 0: + location += f":{line}" + if isinstance(column, int) and not isinstance(column, bool) and column > 0: + location += f":{column}" + lines.append(f"{severity}[{code}] {location} {path}".rstrip()) + lines.append(f" {diagnostic.get('message', 'the input was refused')}") + lines.append(f" next: {diagnostic.get('suggestedAction', 'Correct the input and retry.')}") + errors = sum(diagnostic.get("severity") == "error" for diagnostic in diagnostics) + warnings = sum(diagnostic.get("severity") == "warning" for diagnostic in diagnostics) + lines.append( + f"{errors} {'error' if errors == 1 else 'errors'}, " + f"{warnings} {'warning' if warnings == 1 else 'warnings'} in 1 file" + ) + return lines + + +def _display_source(selected: Path, source: Path | None) -> Path: + if source is None: + return selected + try: + resolved_selected = selected.resolve(strict=True) + except OSError: + return source + bases = [(resolved_selected.parent, selected.parent)] + if len(resolved_selected.parents) >= 3 and len(selected.parents) >= 3: + bases.append((resolved_selected.parents[2], selected.parents[2])) + for resolved_base, given_base in bases: + try: + return given_base / source.relative_to(resolved_base) + except ValueError: + continue + return source + + +def check_file(path: str | Path, *, kind: str) -> None: + """Validate one generated picker document and its local references.""" + selected = Path(path) + try: + descriptor = os.open(selected, os.O_RDONLY | os.O_NOFOLLOW) + with os.fdopen(descriptor, "rb") as source: + metadata = os.fstat(source.fileno()) + if not stat.S_ISREG(metadata.st_mode) or metadata.st_size > MAXIMUM_FILE_BYTES: + raise ConnectionError( + "picker state was refused", + diagnostics=(_diagnostic(selected),), + ) + contents = source.read(MAXIMUM_FILE_BYTES + 1) + if len(contents) > MAXIMUM_FILE_BYTES: + raise ConnectionError("picker state was refused", diagnostics=(_diagnostic(selected),)) + except OSError as exc: + raise ConnectionError( + "picker state was refused", diagnostics=(_diagnostic(selected),) + ) from exc + + from .yaml import ConfigReadError, read_document # pyright: ignore[reportMissingImports] + + api_version, format_kind = FORMATS[kind] + try: + document = read_document( + contents, + file=os.fspath(selected), + api_version=api_version, + kind=format_kind, + ) + except ConfigReadError as exc: + raise ConnectionError("picker state was refused", diagnostics=exc.diagnostics) from None + try: + if kind == "descriptor": + DevelopmentPicker.check_descriptor(selected, document) + elif kind == "generation": + _validate_generation_document(document) + elif kind == "token": + state = _validate_token_document(document) + if "token" in state and ( + metadata.st_uid != os.getuid() or metadata.st_nlink != 1 or metadata.st_mode & 0o177 + ): + raise PickerUnavailable("live person token file is not private") + else: + raise PickerUnavailable("picker state kind is unsupported") + except PickerValidationError as exc: + raise ConnectionError( + "picker state was refused", + diagnostics=(_diagnostic(_display_source(selected, exc.source), path=exc.path),), + ) from None + except PickerUnavailable: + raise ConnectionError( + "picker state was refused", + diagnostics=(_diagnostic(selected),), + ) from None + + +def main() -> int: + arguments = sys.argv[1:] + json_output = _json_requested(arguments) + parser = _Parser(description=__doc__) + parser.add_argument("--kind", required=True, choices=tuple(FORMATS)) + parser.add_argument("file", help="development picker descriptor, token, or generation file") + parser.add_argument("--format", choices=("human", "json"), default="human") + parser.add_argument("--deny-warnings", action="store_true") + try: + args = parser.parse_args(arguments) + except _UsageError: + diagnostics = ( + _diagnostic( + None, + code="check-dev-picker.usage-error", + message="the command arguments are invalid", + suggested_action="Use --help to review the accepted arguments.", + ), + ) + if json_output: + print(json.dumps(_report("usage-error", diagnostics))) + else: + parser.print_usage(sys.stderr) + print("check-dev-picker: the command arguments are invalid", file=sys.stderr) + return 2 + try: + check_file(args.file, kind=args.kind) + except ConnectionError as exc: + if args.format == "json": + print(json.dumps(_report("domain-refusal", exc.diagnostics))) + return 1 + print("\n".join(_human_lines(exc.diagnostics)), file=sys.stderr) + return 1 + if args.format == "json": + print(json.dumps(_report("complete", ()))) + return 0 + print("picker read-back file valid") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/crates/registry-stack-client-py/python/registry_client/dev_picker.py b/crates/registry-stack-client-py/python/registry_client/dev_picker.py index 8416c4ad7e..760fe2c9cc 100644 --- a/crates/registry-stack-client-py/python/registry_client/dev_picker.py +++ b/crates/registry-stack-client-py/python/registry_client/dev_picker.py @@ -52,6 +52,15 @@ def __init__(self, detail: str = "development picker is unavailable"): super().__init__(f"{self.code}: {detail}") +class PickerValidationError(PickerUnavailable): + """Value-free location for a picker document that failed semantic validation.""" + + def __init__(self, detail: str, *, path: str = "", source: Path | None = None) -> None: + super().__init__(detail) + self.path = path + self.source = source + + class PickerAdmissionError(ValueError): """A local browser selection did not establish one complete person.""" @@ -133,7 +142,8 @@ def breg(self): return BRegWorkload( breg.BaseRegistryClient( - target["url"], authorization={"static": self._context._token_for("breg")} + target["url"], + authorization={"static": self._context._token_for("breg")}, ) ) @@ -184,8 +194,15 @@ class _StoredSession: expires_at: float -def _json(path: Path) -> Any: - _private_file(path) +def _json( + path: Path, + *, + api_version: str | None = None, + kind: str | None = None, + private: bool = True, +) -> Any: + if private: + _private_file(path) try: contents = path.read_bytes() except OSError as exc: @@ -193,6 +210,14 @@ def _json(path: Path) -> Any: if len(contents) > _MAXIMUM_FILE_BYTES: raise PickerUnavailable("runner state exceeds its size limit") + if api_version is not None and kind is not None: + from .yaml import ConfigReadError, read_document # pyright: ignore[reportMissingImports] + + try: + return read_document(contents, file=os.fspath(path), api_version=api_version, kind=kind) + except (ConfigReadError, ValueError) as exc: + raise PickerUnavailable("runner state is malformed") from exc + def unique(pairs): value = {} for name, member in pairs: @@ -321,9 +346,169 @@ def _relative_file(root: Path, reference: Any, *, name: str, allow_parent: bool resolved = (root / candidate).resolve(strict=True) except OSError as exc: raise PickerUnavailable(f"{name} is unavailable") from exc + if not allow_parent: + try: + resolved.relative_to(root.resolve(strict=True)) + except (OSError, ValueError) as exc: + raise PickerUnavailable(f"{name} must be a runner-local file reference") from exc return resolved +def _validate_generation_document( + state: Any, + *, + run_id: str | None = None, + picker: str | None = None, + run_expires_at: int | None = None, +) -> Mapping[str, Any]: + state = _object( + state, + fields={ + "apiVersion", + "kind", + "status", + "runId", + "picker", + "generation", + "runExpiresAt", + }, + name="person generation", + ) + state_run_id = _text(state["runId"], name="generation runId", maximum=32) + generation = state["generation"] + expires = _epoch(state["runExpiresAt"], name="generation runExpiresAt") + if ( + state["apiVersion"] != GENERATION_VERSION + or state["kind"] != "PlatformDevPickerGeneration" + or state["status"] not in ("ready", "stopped") + or not _RUN_ID.fullmatch(state_run_id) + or state["picker"] not in ("holder", "staff") + or not isinstance(generation, int) + or isinstance(generation, bool) + or generation < 1 + ): + raise PickerValidationError("person credential generation is malformed") + if run_id is not None and state_run_id != run_id: + raise PickerValidationError( + "person credential generation is for another run", path="/runId" + ) + if picker is not None and state["picker"] != picker: + raise PickerValidationError( + "person credential generation is for another picker", path="/picker" + ) + if run_expires_at is not None and expires != run_expires_at: + raise PickerValidationError( + "person credential generation has another run lifetime", + path="/runExpiresAt", + ) + return state + + +def _validate_token_document(state: Any, *, current_time: bool = False) -> Mapping[str, Any]: + common = { + "apiVersion", + "kind", + "runId", + "picker", + "persona", + "selector", + "product", + "issuer", + "subject", + "principal", + "clientId", + "profile", + "resource", + "audiences", + "scopes", + "principalClaim", + "generation", + "issuedAt", + "expiresAt", + "runExpiresAt", + } + if not isinstance(state, dict) or set(state) not in ( + common | {"token"}, + common | {"status"}, + ): + raise PickerUnavailable("person token has unsupported or missing fields") + run_id = _text(state["runId"], name="person token runId", maximum=32) + picker = state["picker"] + persona = state["persona"] + selector = _text(state["selector"], name="person token selector", maximum=128) + product = _text(state["product"], name="person token product", maximum=64) + issuer = _resource(state["issuer"], name="person token issuer") + subject = _text(state["subject"], name="person token subject") + principal = _text(state["principal"], name="person token principal") + client_id = _text(state["clientId"], name="person token clientId") + profile = _text(state["profile"], name="person token profile", maximum=64) + resource = _resource(state["resource"], name="person token resource") + audiences_raw = state["audiences"] + if ( + not isinstance(audiences_raw, list) + or not 1 <= len(audiences_raw) <= 4 + or len(set(audiences_raw)) != len(audiences_raw) + ): + raise PickerUnavailable("person token audiences are malformed") + audiences = tuple(_resource(value, name="person token audience") for value in audiences_raw) + scopes = _scopes(state["scopes"], name="person token scopes") + principal_claim = _text( + state["principalClaim"], name="person token principalClaim", maximum=128 + ) + generation = state["generation"] + issued = _epoch(state["issuedAt"], name="person token issuedAt") + expires = _epoch(state["expiresAt"], name="person token expiresAt") + run_expires = _epoch(state["runExpiresAt"], name="person token runExpiresAt") + if ( + state["apiVersion"] != TOKEN_VERSION + or state["kind"] != "PlatformDevPickerToken" + or not _RUN_ID.fullmatch(run_id) + or picker not in ("holder", "staff") + or persona != picker + or not _OPAQUE.fullmatch(selector) + or not _LOCAL_NAME.fullmatch(product) + or not _LOCAL_NAME.fullmatch(profile) + or resource not in audiences + or not isinstance(generation, int) + or isinstance(generation, bool) + or generation < 1 + or issued > expires + or expires - issued > 300 + or expires > run_expires + or (current_time and (issued > int(time.time()) + 60 or int(time.time()) >= expires)) + ): + raise PickerUnavailable("person token is expired or has an invalid lifetime") + if "status" in state: + if state["status"] != "stopped": + raise PickerUnavailable("person token has an unsupported credential state") + return state + token = state["token"] + if ( + not isinstance(token, str) + or not token + or len(token) > 8192 + or any(character.isspace() for character in token) + or token.count(".") != 2 + ): + raise PickerUnavailable("person token is malformed") + claims = _b64_json(token.split(".")[1]) + audience = claims.get("aud") + token_audiences = [audience] if isinstance(audience, str) else audience + if ( + claims.get("iss") != issuer + or token_audiences != list(audiences) + or claims.get("sub") != subject + or claims.get("client_id") != client_id + or claims.get("scope") != " ".join(sorted(scopes)) + or claims.get(principal_claim) != principal + or claims.get("registry_dev_persona") != persona + or claims.get("iat") != issued + or claims.get("exp") != expires + ): + raise PickerUnavailable("person token claims differ from the declared run authority") + return state + + def _b64_json(segment: str) -> Mapping[str, Any]: try: raw = base64.urlsafe_b64decode(segment + "=" * (-len(segment) % 4)) @@ -354,7 +539,7 @@ def __init__(self, path: Path, document: Mapping[str, Any], digest: bytes): self._issued_at = document["issuedAt"] self._expires_at = document["expiresAt"] self._generation_path = _relative_file( - self._picker_root, document["generationRef"], name="generationRef" + self._picker_root, document["generationFile"], name="generationFile" ) self._products = document["products"] self._people = document["people"] @@ -379,8 +564,10 @@ def from_descriptor(cls, path: str | Path) -> DevelopmentPicker: for directory in (selected.parent, selected.parent.parent, selected.parents[2]): _private_directory(directory) raw = selected.read_bytes() - document = _json(selected) - document = cls._parse_descriptor(selected, document) + document = _json( + selected, api_version=DESCRIPTOR_VERSION, kind="PlatformDevPickerDescriptor" + ) + document = cls._parse_descriptor(selected, document, live=True) picker = cls(selected, document, hashlib.sha256(raw).digest()) picker._check_live() picker._read_generation() @@ -388,23 +575,35 @@ def from_descriptor(cls, path: str | Path) -> DevelopmentPicker: return picker @staticmethod - def _parse_descriptor(path: Path, document: Any) -> Mapping[str, Any]: + def _parse_descriptor(path: Path, document: Any, *, live: bool = False) -> Mapping[str, Any]: fields = { - "apiVersion", "kind", "runId", "persona", "origin", "sessionNamespace", - "issuedAt", "expiresAt", "generationRef", "products", "people", - "workloadConnectionRef", "workloads", + "apiVersion", + "kind", + "runId", + "persona", + "origin", + "sessionNamespace", + "issuedAt", + "expiresAt", + "generationFile", + "products", + "people", + "workloadConnectionFile", + "workloads", } - document = _object(document, fields=fields, name="picker descriptor") + required = fields - {"workloadConnectionFile"} + if not isinstance(document, dict) or not required <= set(document) <= fields: + raise PickerUnavailable("picker descriptor has unsupported or missing fields") if ( document["apiVersion"] != DESCRIPTOR_VERSION or document["kind"] != "PlatformDevPickerDescriptor" ): raise PickerUnavailable("descriptor has an unsupported format") run_id = _text(document["runId"], name="runId", maximum=32) - if not _RUN_ID.fullmatch(run_id) or path.parents[2].name != run_id: + if not _RUN_ID.fullmatch(run_id) or (live and path.parents[2].name != run_id): raise PickerUnavailable("descriptor run does not match its private run directory") persona = document["persona"] - if persona not in ("holder", "staff") or path.parent.name != persona: + if persona not in ("holder", "staff") or (live and path.parent.name != persona): raise PickerUnavailable("descriptor persona does not match its private directory") document["origin"] = _loopback_origin(document["origin"], name="origin") namespace = _text(document["sessionNamespace"], name="sessionNamespace", maximum=64) @@ -412,7 +611,7 @@ def _parse_descriptor(path: Path, document: Any) -> Mapping[str, Any]: raise PickerUnavailable("sessionNamespace must be opaque runner state") issued_at = _epoch(document["issuedAt"], name="issuedAt") expires_at = _epoch(document["expiresAt"], name="expiresAt") - if issued_at >= expires_at or expires_at <= int(time.time()): + if issued_at >= expires_at or (live and expires_at <= int(time.time())): raise PickerUnavailable("development run has expired") if not isinstance(document["products"], dict) or not document["products"]: raise PickerUnavailable("descriptor needs exact product endpoints") @@ -421,10 +620,12 @@ def _parse_descriptor(path: Path, document: Any) -> Mapping[str, Any]: if not isinstance(product, str) or not _LOCAL_NAME.fullmatch(product): raise PickerUnavailable("descriptor product name is malformed") raw = _object(raw, fields={"url", "resource"}, name=f"products.{product}") - products[product] = MappingProxyType({ - "url": _loopback_origin(raw["url"], name=f"products.{product}.url"), - "resource": _resource(raw["resource"], name=f"products.{product}.resource"), - }) + products[product] = MappingProxyType( + { + "url": _loopback_origin(raw["url"], name=f"products.{product}.url"), + "resource": _resource(raw["resource"], name=f"products.{product}.resource"), + } + ) document["products"] = MappingProxyType(products) raw_people = document["people"] if not isinstance(raw_people, list) or not 1 <= len(raw_people) <= 32: @@ -434,7 +635,14 @@ def _parse_descriptor(path: Path, document: Any) -> Mapping[str, Any]: for index, raw in enumerate(raw_people): raw = _object( raw, - fields={"selector", "label", "subject", "principal", "clientId", "credentials"}, + fields={ + "selector", + "label", + "subject", + "principal", + "clientId", + "credentials", + }, name=f"people[{index}]", ) selector = _text(raw["selector"], name="selector", maximum=128) @@ -460,19 +668,25 @@ def _parse_descriptor(path: Path, document: Any) -> Mapping[str, Any]: grant = _object( grant, fields={ - "tokenRef", "profile", "resource", "audiences", "scopes", + "tokenFile", + "profile", + "resource", + "audiences", + "scopes", "principalClaim", }, name=f"people[{index}].credentials.{product}", ) - token_ref = _text(grant["tokenRef"], name="tokenRef", maximum=128) - _relative_file(path.parent, token_ref, name="tokenRef") + token_ref = _text(grant["tokenFile"], name="tokenFile", maximum=128) + _relative_file(path.parent, token_ref, name="tokenFile") profile = _text(grant["profile"], name="profile", maximum=64) if not _LOCAL_NAME.fullmatch(profile): raise PickerUnavailable("person credential profile is malformed") resource = _resource(grant["resource"], name="resource") if resource != products[product]["resource"]: - raise PickerUnavailable("person credential resource differs from its run product") + raise PickerUnavailable( + "person credential resource differs from its run product" + ) audiences = grant["audiences"] if ( not isinstance(audiences, list) @@ -493,19 +707,26 @@ def _parse_descriptor(path: Path, document: Any) -> Mapping[str, Any]: _text(grant["principalClaim"], name="principalClaim", maximum=128), ) people[selector] = _Person( - selector, label, subject, principal, client_id, MappingProxyType(credentials) + selector, + label, + subject, + principal, + client_id, + MappingProxyType(credentials), ) document["people"] = MappingProxyType(people) - connection_reference = document["workloadConnectionRef"] + connection_reference = document.get("workloadConnectionFile") connection_path = None if connection_reference is not None: connection_path = _relative_file( path.parent, connection_reference, - name="workloadConnectionRef", + name="workloadConnectionFile", allow_parent=True, ) - run_root = path.parents[2] + run_root = ( + path.parents[2] if path.parent.parent.name == "python-picker" else path.parent + ) try: connection_path.relative_to(run_root) except ValueError as exc: @@ -513,14 +734,23 @@ def _parse_descriptor(path: Path, document: Any) -> Mapping[str, Any]: "workload connection is outside the development run" ) from exc document["workloadConnectionPath"] = connection_path - del document["workloadConnectionRef"] + document.pop("workloadConnectionFile", None) raw_workloads = document["workloads"] if not isinstance(raw_workloads, list) or len(raw_workloads) > 32: raise PickerUnavailable("descriptor workloads are malformed") workloads = {} workload_fields = { - "name", "product", "default", "url", "issuer", "subject", "clientId", - "profile", "resource", "scopes", "claims", + "name", + "product", + "default", + "url", + "issuer", + "subject", + "clientId", + "profile", + "resource", + "scopes", + "claims", } for index, raw in enumerate(raw_workloads): raw = _object(raw, fields=workload_fields, name=f"workloads[{index}]") @@ -557,6 +787,63 @@ def _parse_descriptor(path: Path, document: Any) -> Mapping[str, Any]: document["workloads"] = MappingProxyType(workloads) return MappingProxyType(document) + @classmethod + def check_descriptor(cls, path: str | Path, document: Any) -> None: + """Check one generated descriptor bundle without requiring a live run.""" + try: + selected = Path(path).resolve(strict=True) + except OSError as exc: + raise PickerUnavailable("descriptor is unavailable") from exc + parsed = cls._parse_descriptor(selected, document) + picker = cls(selected, parsed, b"") + try: + generation = picker._read_generation(private=False) + except PickerValidationError as exc: + exc.source = picker._generation_path + raise + for person in picker._people.values(): + for product, credential in person.credentials.items(): + token_path = _relative_file( + picker._picker_root, + credential.token_ref, + name="person token reference", + ) + try: + state = _json( + token_path, + api_version=TOKEN_VERSION, + kind="PlatformDevPickerToken", + private=False, + ) + state = _validate_token_document(state) + picker._check_person_token_state( + state, + person=person, + product=product, + credential=credential, + generation=generation, + descriptor_issued_at=picker._issued_at, + ) + except PickerValidationError as exc: + exc.source = token_path + raise + except PickerUnavailable as exc: + raise PickerValidationError( + "person token state is malformed", source=token_path + ) from exc + if "token" in state: + _private_file(token_path) + try: + picker._validate_workload_connection(private=False) + except PickerValidationError as exc: + exc.source = picker._workload_connection_path + raise + except PickerUnavailable as exc: + raise PickerValidationError( + "workload connection state is malformed", + source=picker._workload_connection_path, + ) from exc + @property def origin(self) -> str: return self._origin @@ -576,8 +863,7 @@ def pending_cookie(self) -> str: def choices(self) -> tuple[PickerChoice, ...]: self._check_live() return tuple( - PickerChoice(person.label, person.selector) - for person in self._people.values() + PickerChoice(person.label, person.selector) for person in self._people.values() ) def begin(self) -> PickerForm: @@ -587,9 +873,7 @@ def begin(self) -> PickerForm: csrf_token = secrets.token_urlsafe(32) with self._lock: self._pending = { - key: pending - for key, pending in self._pending.items() - if pending[1] > now + key: pending for key, pending in self._pending.items() if pending[1] > now } self._pending[pending_id] = (csrf_token, min(now + 300, self._expires_at)) return PickerForm(pending_id, csrf_token, self.choices()) @@ -685,9 +969,7 @@ def authorize_mutation( self, session_id: str, *, origin: str, csrf_token: str ) -> DevelopmentPerson: person = self.context(session_id) - if origin != self._origin or not hmac.compare_digest( - person.csrf_token, csrf_token - ): + if origin != self._origin or not hmac.compare_digest(person.csrf_token, csrf_token): raise CSRFError() return person @@ -747,28 +1029,18 @@ def _check_live(self) -> None: ): raise PickerUnavailable("descriptor is not owned by a ready live development run") - def _read_generation(self) -> Mapping[str, Any]: - state = _object( - _json(self._generation_path), - fields={ - "apiVersion", "kind", "status", "runId", "picker", "generation", - "runExpiresAt", - }, - name="person generation", + def _read_generation(self, *, private: bool = True) -> Mapping[str, Any]: + return _validate_generation_document( + _json( + self._generation_path, + api_version=GENERATION_VERSION, + kind="PlatformDevPickerGeneration", + private=private, + ), + run_id=self._run_id, + picker=self._persona, + run_expires_at=self._expires_at, ) - if ( - state["apiVersion"] != GENERATION_VERSION - or state["kind"] != "PlatformDevPickerGeneration" - or state["status"] not in ("ready", "stopped") - or state["runId"] != self._run_id - or state["picker"] != self._persona - or not isinstance(state["generation"], int) - or isinstance(state["generation"], bool) - or state["generation"] < 1 - or state["runExpiresAt"] != self._expires_at - ): - raise PickerUnavailable("person credential generation is malformed") - return state def _person_tokens(self, person: _Person, *, admission: bool) -> Mapping[str, str]: first = self._read_generation() @@ -779,12 +1051,15 @@ def _person_tokens(self, person: _Person, *, admission: bool) -> Mapping[str, st path = _relative_file( self._picker_root, credential.token_ref, name="person token reference" ) - state = _json(path) + state = _json(path, api_version=TOKEN_VERSION, kind="PlatformDevPickerToken") if not isinstance(state, dict) or state.get("generation") != first["generation"]: raise PickerUnavailable("person credentials rotated during admission") try: tokens[product] = self._person_token( - state, person=person, product=product, credential=credential, + state, + person=person, + product=product, + credential=credential, generation=first["generation"], ) except PickerUnavailable: @@ -805,13 +1080,29 @@ def _person_token( credential: _Credential, generation: int, ) -> str: - fields = { - "apiVersion", "kind", "runId", "picker", "persona", "selector", "product", - "issuer", "subject", "principal", "clientId", "profile", "resource", - "audiences", "scopes", "principalClaim", "generation", "issuedAt", - "expiresAt", "runExpiresAt", "token", - } - state = _object(state, fields=fields, name="person token") + state = _validate_token_document(state, current_time=True) + self._check_person_token_state( + state, + person=person, + product=product, + credential=credential, + generation={"status": "ready", "generation": generation}, + descriptor_issued_at=self._issued_at, + ) + if "token" not in state: + raise PickerUnavailable("person token is not ready") + return state["token"] + + def _check_person_token_state( + self, + state: Mapping[str, Any], + *, + person: _Person, + product: str, + credential: _Credential, + generation: Mapping[str, Any], + descriptor_issued_at: int, + ) -> None: expected = { "apiVersion": TOKEN_VERSION, "kind": "PlatformDevPickerToken", @@ -828,59 +1119,40 @@ def _person_token( "audiences": list(credential.audiences), "scopes": list(credential.scopes), "principalClaim": credential.principal_claim, - "generation": generation, + "generation": generation["generation"], "runExpiresAt": self._expires_at, } - if any(state.get(name) != value for name, value in expected.items()): - raise PickerUnavailable("person token differs from the declared run authority") - issuer = _resource(state["issuer"], name="person token issuer") - issued = _epoch(state["issuedAt"], name="person token issuedAt") - expires = _epoch(state["expiresAt"], name="person token expiresAt") - now = int(time.time()) - if ( - issued > now + 60 - or issued > expires - or expires - issued > 300 - or expires > self._expires_at - or now >= expires - ): - raise PickerUnavailable("person token is expired or has an invalid lifetime") - token = state["token"] - if ( - not isinstance(token, str) - or not token - or len(token) > 8192 - or any(character.isspace() for character in token) - or token.count(".") != 2 - ): - raise PickerUnavailable("person token is malformed") - claims = _b64_json(token.split(".")[1]) - audience = claims.get("aud") - token_audiences = [audience] if isinstance(audience, str) else audience - if ( - claims.get("iss") != issuer - or token_audiences != list(credential.audiences) - or claims.get("sub") != person.subject - or claims.get("client_id") != person.client_id - or claims.get("scope") != " ".join(sorted(credential.scopes)) - or claims.get(credential.principal_claim) != person.principal - or claims.get("registry_dev_persona") != self._persona - or claims.get("iat") != issued - or claims.get("exp") != expires - ): - raise PickerUnavailable("person token claims differ from the declared run authority") - return token + for name, value in expected.items(): + if state.get(name) != value: + raise PickerValidationError( + "person token differs from the declared run authority", path=f"/{name}" + ) + if state["issuedAt"] < descriptor_issued_at: + raise PickerValidationError("person token predates the picker run", path="/issuedAt") + expected_state = "token" if generation["status"] == "ready" else "status" + if expected_state not in state: + raise PickerValidationError("person token state differs from its generation") - def _validate_workload_connection(self) -> None: + def _validate_workload_connection(self, *, private: bool = True) -> None: if self._workload_connection_path is None: if self._workloads: raise PickerUnavailable("workload connection is incomplete for this picker run") return - document = _json(self._workload_connection_path) + document = _json( + self._workload_connection_path, + api_version=CONNECTION_VERSION, + kind="PlatformPythonConnection", + private=private, + ) if not isinstance(document, dict): raise PickerUnavailable("workload connection is malformed") required = { - "apiVersion", "kind", "service", "audience", "secretProviders", "bindings" + "apiVersion", + "kind", + "service", + "audience", + "secretProviders", + "bindings", } if ( set(document) != required @@ -896,7 +1168,11 @@ def _validate_workload_connection(self) -> None: observed = {} for raw in document["bindings"]: if not isinstance(raw, dict) or set(raw) != { - "name", "product", "url", "default", "credential" + "name", + "product", + "url", + "default", + "credential", }: raise PickerUnavailable("workload binding is malformed") name = raw.get("name") @@ -906,9 +1182,19 @@ def _validate_workload_connection(self) -> None: expected is None or not isinstance(credential, dict) or credential.get("type") != "runner-token" - or set(credential) != { - "type", "tokenRef", "runId", "binding", "issuer", "subject", - "clientId", "profile", "resource", "scopes", "claims", + or set(credential) + != { + "type", + "tokenRef", + "runId", + "binding", + "issuer", + "subject", + "clientId", + "profile", + "resource", + "scopes", + "claims", "runExpiresAt", } or raw.get("product") != expected["product"] @@ -938,8 +1224,7 @@ def _validate_workload_connection(self) -> None: def _parse_form(content_type: str, body: bytes) -> Mapping[str, str]: if ( - content_type.split(";", 1)[0].strip().lower() - != "application/x-www-form-urlencoded" + content_type.split(";", 1)[0].strip().lower() != "application/x-www-form-urlencoded" or not 1 <= len(body) <= _MAXIMUM_FORM_BYTES ): raise PickerAdmissionError() @@ -967,7 +1252,7 @@ def _picker_html(form: PickerForm) -> str: for choice in form.choices ) return ( - "Choose test person" + 'Choose test person' '
' f'' f'' @@ -977,8 +1262,14 @@ def _picker_html(form: PickerForm) -> str: def _clear_cookie(response: Any, name: str) -> None: response.set_cookie( - name, "", max_age=0, expires=0, secure=False, httponly=True, - samesite="strict", path="/", + name, + "", + max_age=0, + expires=0, + secure=False, + httponly=True, + samesite="strict", + path="/", ) @@ -1065,8 +1356,12 @@ def registry_dev_login(): form = picker.begin() response = Response(_picker_html(form), content_type="text/html; charset=utf-8") response.set_cookie( - picker.pending_cookie, form.pending_id, secure=False, httponly=True, - samesite="Strict", path="/auth/dev", + picker.pending_cookie, + form.pending_id, + secure=False, + httponly=True, + samesite="Strict", + path="/auth/dev", ) response.headers["Cache-Control"] = "no-store" return response @@ -1088,8 +1383,12 @@ def registry_dev_select(): return error(PickerAdmissionError.code, 403) response = redirect("/") response.set_cookie( - picker.session_cookie, session.session_id, secure=False, httponly=True, - samesite="Strict", path="/", + picker.session_cookie, + session.session_id, + secure=False, + httponly=True, + samesite="Strict", + path="/", ) _clear_cookie(response, picker.pending_cookie) response.headers["Cache-Control"] = "no-store" @@ -1190,9 +1489,7 @@ async def admit_request(request: Request, call_next: Callable): if request.method in ("GET", "HEAD", "OPTIONS") else await authorized_mutation(request) ) - request.state.registry_person = await asyncio.to_thread( - person_factory, context - ) + request.state.registry_person = await asyncio.to_thread(person_factory, context) except ReauthenticationRequired: return error(ReauthenticationRequired.code, 401) except (CSRFError, PickerAdmissionError): @@ -1202,21 +1499,21 @@ async def admit_request(request: Request, call_next: Callable): @app.get("/auth/dev") async def registry_dev_login(): form = await asyncio.to_thread(picker.begin) - response = HTMLResponse( - _picker_html(form), headers={"Cache-Control": "no-store"} - ) + response = HTMLResponse(_picker_html(form), headers={"Cache-Control": "no-store"}) response.set_cookie( - picker.pending_cookie, form.pending_id, secure=False, httponly=True, - samesite="strict", path="/auth/dev", + picker.pending_cookie, + form.pending_id, + secure=False, + httponly=True, + samesite="strict", + path="/auth/dev", ) return response @app.post("/auth/dev") async def registry_dev_select(request: Request): try: - values = _parse_form( - request.headers.get("content-type", ""), await request.body() - ) + values = _parse_form(request.headers.get("content-type", ""), await request.body()) if request.cookies.get(picker.pending_cookie) != values["pending_id"]: raise PickerAdmissionError() session = await asyncio.to_thread( @@ -1231,8 +1528,12 @@ async def registry_dev_select(request: Request): return error(PickerAdmissionError.code, 403) response = RedirectResponse("/", status_code=302) response.set_cookie( - picker.session_cookie, session.session_id, secure=False, httponly=True, - samesite="strict", path="/", + picker.session_cookie, + session.session_id, + secure=False, + httponly=True, + samesite="strict", + path="/", ) _clear_cookie(response, picker.pending_cookie) response.headers["Cache-Control"] = "no-store" diff --git a/crates/registry-stack-client-py/tests/test_dev_picker.py b/crates/registry-stack-client-py/tests/test_dev_picker.py index 152a3751db..54d2af6f65 100644 --- a/crates/registry-stack-client-py/tests/test_dev_picker.py +++ b/crates/registry-stack-client-py/tests/test_dev_picker.py @@ -4,9 +4,12 @@ import asyncio import base64 +from contextlib import redirect_stderr, redirect_stdout import fcntl import importlib +import io import json +import os from pathlib import Path import re import sys @@ -14,6 +17,7 @@ import time import types import unittest +from unittest import mock from fastapi import FastAPI, Request from flask import Flask, g, jsonify @@ -24,8 +28,10 @@ PACKAGE = "_registry_client_dev_picker_test" package = types.ModuleType(PACKAGE) package.__path__ = [str(SOURCE)] +package.__version__ = "0.46.1" sys.modules[PACKAGE] = package yaml_module = types.ModuleType(f"{PACKAGE}.yaml") +read_formats = [] class ConfigReadError(ValueError): @@ -35,6 +41,7 @@ def __init__(self, message, *, diagnostics=()): def read_document(contents, *, file, api_version, kind): + read_formats.append((api_version, kind)) try: value = json.loads(contents) except (UnicodeError, json.JSONDecodeError): @@ -55,9 +62,11 @@ def read_document(contents, *, file, api_version, kind): def _segment(value): - return base64.urlsafe_b64encode( - json.dumps(value, separators=(",", ":")).encode() - ).rstrip(b"=").decode() + return ( + base64.urlsafe_b64encode(json.dumps(value, separators=(",", ":")).encode()) + .rstrip(b"=") + .decode() + ) def _token(*, product, persona, generation, issued, expires, **changes): @@ -168,13 +177,15 @@ def _write_connection( "service": f"rstack-dev-{RUN_ID}", "audience": "service", "secretProviders": {"file": {"root": str(self.workload_root.resolve())}}, - "bindings": [{ - "name": "notices", - "product": "messaging", - "url": endpoint, - "default": True, - "credential": credential, - }], + "bindings": [ + { + "name": "notices", + "product": "messaging", + "url": endpoint, + "default": True, + "credential": credential, + } + ], }, ) @@ -188,44 +199,54 @@ def write_descriptor(self, **changes): "sessionNamespace": self.namespace, "issuedAt": self.now, "expiresAt": self.expires, - "generationRef": "generation.json", + "generationFile": "generation.json", "products": { "breg": {"url": "http://127.0.0.1:49199", "resource": "urn:test:breg"}, - "casework": {"url": "http://127.0.0.1:49200", "resource": "urn:test:casework"}, - "messaging": {"url": "http://127.0.0.1:49201", "resource": "urn:test:messaging"}, - }, - "people": [{ - "selector": self.selector, - "label": "Applicant One", - "subject": "person-one", - "principal": "person-one", - "clientId": "portal-client", - "credentials": { - product: { - "tokenRef": f"person-one-{product}.json", - "profile": "applicant" if product == "breg" else "requester", - "resource": f"urn:test:{product}", - "audiences": [f"urn:test:{product}"], - "scopes": [f"{product}:read"], - "principalClaim": "registry_principal", - } - for product in ("breg", "casework") + "casework": { + "url": "http://127.0.0.1:49200", + "resource": "urn:test:casework", }, - }], - "workloadConnectionRef": "../../python-workload/python-connection.json", - "workloads": [{ - "name": "notices", - "product": "messaging", - "default": True, - "url": "http://127.0.0.1:49201", - "issuer": "https://issuer.example.test", - "subject": "notice-service", - "clientId": "notice-client", - "profile": "service-sender", - "resource": "urn:test:messaging", - "scopes": ["messaging:send"], - "claims": {"registry_actor_kind": "service"}, - }], + "messaging": { + "url": "http://127.0.0.1:49201", + "resource": "urn:test:messaging", + }, + }, + "people": [ + { + "selector": self.selector, + "label": "Applicant One", + "subject": "person-one", + "principal": "person-one", + "clientId": "portal-client", + "credentials": { + product: { + "tokenFile": f"credential-0-{product}.json", + "profile": "applicant" if product == "breg" else "requester", + "resource": f"urn:test:{product}", + "audiences": [f"urn:test:{product}"], + "scopes": [f"{product}:read"], + "principalClaim": "registry_principal", + } + for product in ("breg", "casework") + }, + } + ], + "workloadConnectionFile": "../../python-workload/python-connection.json", + "workloads": [ + { + "name": "notices", + "product": "messaging", + "default": True, + "url": "http://127.0.0.1:49201", + "issuer": "https://issuer.example.test", + "subject": "notice-service", + "clientId": "notice-client", + "profile": "service-sender", + "resource": "urn:test:messaging", + "scopes": ["messaging:send"], + "claims": {"registry_actor_kind": "service"}, + } + ], } descriptor.update(changes) self._write_json(self.descriptor_path, descriptor) @@ -275,7 +296,7 @@ def write_token(self, product, generation, **changes): ), } state.update(changes) - self._write_json(self.picker_root / f"person-one-{product}.json", state) + self._write_json(self.picker_root / f"credential-0-{product}.json", state) class DevelopmentPickerTests(unittest.TestCase): @@ -314,7 +335,249 @@ def test_only_a_private_live_runner_descriptor_mounts(self): with self.assertRaisesRegex(dev_picker.PickerUnavailable, "live development run"): dev_picker.DevelopmentPicker.from_descriptor(self.live.descriptor_path) - def test_nonloopback_wrong_run_stopped_expired_and_copied_descriptors_are_refused(self): + def test_picker_state_uses_the_shared_typed_reader(self): + read_formats.clear() + self.select() + self.assertIn((dev_picker.DESCRIPTOR_VERSION, "PlatformDevPickerDescriptor"), read_formats) + self.assertIn((dev_picker.GENERATION_VERSION, "PlatformDevPickerGeneration"), read_formats) + self.assertIn((dev_picker.TOKEN_VERSION, "PlatformDevPickerToken"), read_formats) + + def test_descriptor_without_workloads_omits_connection_reference(self): + descriptor = json.loads(self.live.descriptor_path.read_text(encoding="utf-8")) + descriptor.pop("workloadConnectionFile") + descriptor["workloads"] = [] + self.live._write_json(self.live.descriptor_path, descriptor) + picker = self.picker() + self.assertEqual(picker._workloads, {}) + + def test_offline_picker_checker_routes_each_format_without_a_live_issuer(self): + checker = importlib.import_module(f"{PACKAGE}.check_dev_picker") + read_formats.clear() + for kind, path in ( + ("descriptor", self.live.descriptor_path), + ("generation", self.live.picker_root / "generation.json"), + ("token", self.live.picker_root / "credential-0-breg.json"), + ): + with self.subTest(kind=kind): + checker.check_file(path, kind=kind) + self.assertIn((dev_picker.DESCRIPTOR_VERSION, "PlatformDevPickerDescriptor"), read_formats) + self.assertIn((dev_picker.GENERATION_VERSION, "PlatformDevPickerGeneration"), read_formats) + self.assertIn((dev_picker.TOKEN_VERSION, "PlatformDevPickerToken"), read_formats) + with self.assertRaises(dev_picker.ConnectionError): + checker.check_file(self.live.picker_root / "generation.json", kind="token") + link = self.live.root / "picker-link.json" + link.symlink_to(self.live.descriptor_path) + with self.assertRaises(dev_picker.ConnectionError): + checker.check_file(link, kind="descriptor") + + def test_offline_descriptor_checks_run_authority_and_referenced_state(self): + checker = importlib.import_module(f"{PACKAGE}.check_dev_picker") + + descriptor = json.loads(self.live.descriptor_path.read_text(encoding="utf-8")) + descriptor["origin"] = "https://portal.example.test" + self.live._write_json(self.live.descriptor_path, descriptor) + with self.assertRaises(dev_picker.ConnectionError): + checker.check_file(self.live.descriptor_path, kind="descriptor") + + self.live.write_descriptor() + self.live.write_generation(1, run_id="f" * 32) + with self.assertRaises(dev_picker.ConnectionError): + checker.check_file(self.live.descriptor_path, kind="descriptor") + + self.live.write_generation(1) + self.live.write_token("breg", 1, subject="other") + with self.assertRaises(dev_picker.ConnectionError): + checker.check_file(self.live.descriptor_path, kind="descriptor") + + self.live.write_token( + "breg", 1, issuedAt=self.live.expires - 100, expiresAt=self.live.expires + 1 + ) + with self.assertRaises(dev_picker.ConnectionError): + checker.check_file(self.live.descriptor_path, kind="descriptor") + + self.live.write_token("breg", 1) + self.live._write_connection(endpoint="http://127.0.0.1:49999") + with self.assertRaises(dev_picker.ConnectionError): + checker.check_file(self.live.descriptor_path, kind="descriptor") + + def test_offline_live_bearer_requires_private_single_link_owner(self): + checker = importlib.import_module(f"{PACKAGE}.check_dev_picker") + token_path = self.live.picker_root / "credential-0-breg.json" + + token_path.chmod(0o644) + with self.assertRaisesRegex(dev_picker.ConnectionError, "refused") as refused: + checker.check_file(token_path, kind="token") + self.assertNotIn(self.live.selector, str(refused.exception)) + + token_path.chmod(0o600) + linked = self.live.picker_root / "credential-linked.json" + os.link(token_path, linked) + with self.assertRaises(dev_picker.ConnectionError): + checker.check_file(token_path, kind="token") + linked.unlink() + + with mock.patch.object(checker.os, "getuid", return_value=os.getuid() + 1): + with self.assertRaises(dev_picker.ConnectionError): + checker.check_file(token_path, kind="token") + + self.live.write_token("breg", 1, status="stopped") + stopped = json.loads(token_path.read_text(encoding="utf-8")) + stopped.pop("token") + self.live._write_json(token_path, stopped) + token_path.chmod(0o644) + checker.check_file(token_path, kind="token") + + def test_generation_and_token_references_cannot_escape_through_symlinks(self): + checker = importlib.import_module(f"{PACKAGE}.check_dev_picker") + outside = self.live.root / "outside-token.json" + outside.write_bytes((self.live.picker_root / "credential-0-breg.json").read_bytes()) + outside.chmod(0o600) + token_path = self.live.picker_root / "credential-0-breg.json" + token_path.unlink() + token_path.symlink_to(outside) + + with self.assertRaises(dev_picker.PickerUnavailable): + self.picker() + with self.assertRaises(dev_picker.ConnectionError): + checker.check_file(self.live.descriptor_path, kind="descriptor") + + def test_offline_checker_json_report_is_structured_and_value_free(self): + checker = importlib.import_module(f"{PACKAGE}.check_dev_picker") + self.live.write_generation(1, run_id="f" * 32) + output = io.StringIO() + with ( + mock.patch.object( + sys, + "argv", + [ + "check_dev_picker", + "--kind", + "descriptor", + os.fspath(self.live.descriptor_path), + "--format", + "json", + ], + ), + redirect_stdout(output), + ): + self.assertEqual(checker.main(), 1) + report = json.loads(output.getvalue()) + self.assertFalse(report["ok"]) + self.assertEqual(list(report)[:5], ["ok", "command", "status", "apiVersion", "kind"]) + self.assertEqual(report["command"], "dev-picker check") + self.assertEqual(report["status"], "domain-refusal") + self.assertEqual( + report["apiVersion"], + "id.registrystack.org/formats/platform/dev-picker-check-report/v1alpha1", + ) + self.assertEqual(report["kind"], "PlatformDevPickerCheckReport") + self.assertEqual(report["version"], "0.46.1") + self.assertEqual(report["diagnostics"][0]["code"], "config.invalid-value") + self.assertEqual( + report["diagnostics"][0]["source"]["file"], + os.fspath(self.live.picker_root / "generation.json"), + ) + self.assertEqual(report["diagnostics"][0]["path"], "/runId") + self.assertNotIn("f" * 32, output.getvalue()) + + self.live.write_generation(1) + output = io.StringIO() + with ( + mock.patch.object( + sys, + "argv", + [ + "check_dev_picker", + "--kind", + "descriptor", + os.fspath(self.live.descriptor_path), + "--format", + "json", + "--deny-warnings", + ], + ), + redirect_stdout(output), + ): + self.assertEqual(checker.main(), 0) + report = json.loads(output.getvalue()) + self.assertEqual(report["status"], "complete") + self.assertEqual(report["diagnostics"], []) + self.assertEqual(report["version"], "0.46.1") + + output = io.StringIO() + with ( + mock.patch.object( + sys, + "argv", + [ + "check_dev_picker", + "--kind", + "unsupported", + os.fspath(self.live.descriptor_path), + "--format", + "json", + ], + ), + redirect_stdout(output), + ): + self.assertEqual(checker.main(), 2) + report = json.loads(output.getvalue()) + self.assertEqual(report["status"], "usage-error") + self.assertFalse(report["ok"]) + self.assertEqual(report["version"], "0.46.1") + self.assertEqual(report["diagnostics"][0]["code"], "check-dev-picker.usage-error") + + def test_offline_checker_boundary_and_human_refusals_are_diagnostic(self): + checker = importlib.import_module(f"{PACKAGE}.check_dev_picker") + link = self.live.root / "picker-link.json" + link.symlink_to(self.live.descriptor_path) + output = io.StringIO() + with ( + mock.patch.object( + sys, + "argv", + [ + "check_dev_picker", + "--kind", + "descriptor", + os.fspath(link), + "--format", + "json", + ], + ), + redirect_stdout(output), + ): + self.assertEqual(checker.main(), 1) + report = json.loads(output.getvalue()) + self.assertTrue(report["diagnostics"]) + self.assertEqual(report["diagnostics"][0]["code"], "config.invalid-value") + + self.live.write_generation(1, run_id="f" * 32) + error = io.StringIO() + with ( + mock.patch.object( + sys, + "argv", + [ + "check_dev_picker", + "--kind", + "descriptor", + os.fspath(self.live.descriptor_path), + ], + ), + redirect_stderr(error), + ): + self.assertEqual(checker.main(), 1) + lines = error.getvalue().splitlines() + self.assertRegex(lines[0], r"^error\[config\.invalid-value\] .+generation\.json /runId$") + self.assertTrue(lines[1].startswith(" ")) + self.assertTrue(lines[2].startswith(" next: ")) + self.assertEqual(lines[-1], "1 error, 0 warnings in 1 file") + self.assertNotIn("f" * 32, error.getvalue()) + + def test_nonloopback_wrong_run_stopped_expired_and_copied_descriptors_are_refused( + self, + ): cases = ( {"origin": "https://portal.example.test"}, {"runId": "f" * 32}, @@ -341,7 +604,12 @@ def test_selection_is_opaque_csrf_bound_and_all_or_nothing(self): form = picker.begin() for selector, origin, host, csrf in ( ("person-one", self.live.origin, "127.0.0.1:43891", form.csrf_token), - (self.live.selector, "http://127.0.0.1:1", "127.0.0.1:43891", form.csrf_token), + ( + self.live.selector, + "http://127.0.0.1:1", + "127.0.0.1:43891", + form.csrf_token, + ), (self.live.selector, self.live.origin, "127.0.0.1:1", form.csrf_token), (self.live.selector, self.live.origin, "127.0.0.1:43891", "wrong"), ): @@ -366,7 +634,9 @@ def test_selection_is_opaque_csrf_bound_and_all_or_nothing(self): ) self.assertEqual(picker.session_count(), 0) - def test_complete_session_tracks_rotation_and_refuses_mismatch_stop_or_old_run(self): + def test_complete_session_tracks_rotation_and_refuses_mismatch_stop_or_old_run( + self, + ): picker, session = self.select() context = picker.context(session.session_id) self.assertEqual(context.subject, "person-one") @@ -414,13 +684,13 @@ def __init__(self, *args, **kwargs): person._context._token_for("breg"), ) casework = person.casework - self.assertEqual( - casework._CaseworkWorkload__client.args[0], "http://127.0.0.1:49200" - ) + self.assertEqual(casework._CaseworkWorkload__client.args[0], "http://127.0.0.1:49200") self.assertEqual(casework._CaseworkWorkload__profile, "requester") self.assertNotIn("http", repr(person)) - def test_tampered_identity_audience_client_or_missing_product_opens_no_session(self): + def test_tampered_identity_audience_client_or_missing_product_opens_no_session( + self, + ): mutations = ( ("breg", {"subject": "other"}), ("breg", {"clientId": "other-client"}), @@ -442,7 +712,7 @@ def test_tampered_identity_audience_client_or_missing_product_opens_no_session(s ) self.assertEqual(picker.session_count(), 0) self.live.write_token(product, 1) - (self.live.picker_root / "person-one-casework.json").unlink() + (self.live.picker_root / "credential-0-casework.json").unlink() with self.assertRaises(dev_picker.PickerUnavailable): self.picker() @@ -463,9 +733,7 @@ def test_workload_connection_is_same_run_runner_only_and_endpoint_bound(self): self.live._write_connection() connection_path = self.live.workload_root / "python-connection.json" connection = json.loads(connection_path.read_text(encoding="utf-8")) - connection["bindings"][0]["credential"]["claims"] = { - "registry_actor_kind": "human" - } + connection["bindings"][0]["credential"]["claims"] = {"registry_actor_kind": "human"} self.live._write_json(connection_path, connection) with self.assertRaisesRegex(dev_picker.PickerUnavailable, "workload"): self.picker().workloads @@ -511,13 +779,14 @@ def home(): self.assertNotIn(b"Bearer", login.data) form = self._form(login.data) refused = client.post( - "/auth/dev", base_url=base, data=form, headers={"Origin": "http://127.0.0.1:1"} + "/auth/dev", + base_url=base, + data=form, + headers={"Origin": "http://127.0.0.1:1"}, ) self.assertEqual(refused.status_code, 403) form = self._form(client.get("/auth/dev", base_url=base).data) - selected = client.post( - "/auth/dev", base_url=base, data=form, headers={"Origin": base} - ) + selected = client.post("/auth/dev", base_url=base, data=form, headers={"Origin": base}) self.assertEqual(selected.status_code, 302) self.assertIn(picker.session_cookie, selected.headers["Set-Cookie"]) self.assertNotIn(picker.pending_cookie, selected.headers["Set-Cookie"]) diff --git a/products/breg/generated/tools/project-dev.v1alpha1.schema.json b/products/breg/generated/tools/project-dev.v1alpha1.schema.json index 9dadef88f0..512bb571b3 100644 --- a/products/breg/generated/tools/project-dev.v1alpha1.schema.json +++ b/products/breg/generated/tools/project-dev.v1alpha1.schema.json @@ -212,7 +212,8 @@ "items": { "$ref": "#/$defs/Product" }, - "type": "array" + "type": "array", + "uniqueItems": true }, "workloads": { "default": [], @@ -664,10 +665,7 @@ }, "developmentPickers": { "$ref": "#/$defs/DevelopmentPickers", - "default": { - "holder": null, - "staff": null - }, + "default": {}, "description": "Explicit local person-picker services. Omit this map for normal production-style connections." }, "issuer": { diff --git a/products/identifiers/contracts/catalog-source.json b/products/identifiers/contracts/catalog-source.json index c21bee21d3..672dc9f52a 100644 --- a/products/identifiers/contracts/catalog-source.json +++ b/products/identifiers/contracts/catalog-source.json @@ -620,6 +620,30 @@ "compatibilityLine": "v1alpha1", "description": "Registry Stack local development workload token JSON Schema." }, + { + "glob": "products/platform/schemas/dev-picker-descriptor.v1alpha1.schema.json", + "sourcePath": "crates/registry-platform-yaml-py/src/formats.rs", + "owner": "platform", + "status": "active", + "compatibilityLine": "v1alpha1", + "description": "Registry Stack local development picker descriptor JSON Schema." + }, + { + "glob": "products/platform/schemas/dev-picker-token.v1alpha1.schema.json", + "sourcePath": "crates/registry-platform-yaml-py/src/formats.rs", + "owner": "platform", + "status": "active", + "compatibilityLine": "v1alpha1", + "description": "Registry Stack local development picker token JSON Schema." + }, + { + "glob": "products/platform/schemas/dev-picker-generation.v1alpha1.schema.json", + "sourcePath": "crates/registry-platform-yaml-py/src/formats.rs", + "owner": "platform", + "status": "active", + "compatibilityLine": "v1alpha1", + "description": "Registry Stack local development picker generation JSON Schema." + }, { "glob": "products/evidence/generated/oid4vci-runtime/*.schema.json", "sourcePath": "crates/registry-evidence-oid4vci/src/schema.rs", diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index 761617e326..3b8aae711e 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -4996,7 +4996,7 @@ }, "artifact": { "path": "products/breg/generated/tools/project-dev.v1alpha1.schema.json", - "sha256": "bcc5ba9b634220dbadfca00a5f630d1d645b2b1e16299dad461365da142b154c", + "sha256": "5da4995d2ec0dc8007bacada75ed4f8599daaa26890dd014c4bb138b26a1bbfe", "mediaType": "application/schema+json" } }, @@ -5918,6 +5918,60 @@ "mediaType": "application/schema+json" } }, + { + "uri": "https://id.registrystack.org/schemas/platform/dev-picker-descriptor/dev-picker-descriptor.v1alpha1.schema.json", + "kind": "schema", + "status": "active", + "compatibilityLine": "v1alpha1", + "owner": "platform", + "title": "DevPickerDescriptor", + "description": "Registry Stack local development picker descriptor JSON Schema.", + "source": { + "path": "crates/registry-platform-yaml-py/src/formats.rs", + "sha256": "48e7f8f4dbe5c7e9a8289b6c5ef3379c82a8e93d951eb18b1b49b19c4151d2e8" + }, + "artifact": { + "path": "products/platform/schemas/dev-picker-descriptor.v1alpha1.schema.json", + "sha256": "0af9229be9a322dd6c23fed8527c3d65a09ac4538a1880fc5978c7ca290dc8a3", + "mediaType": "application/schema+json" + } + }, + { + "uri": "https://id.registrystack.org/schemas/platform/dev-picker-generation/dev-picker-generation.v1alpha1.schema.json", + "kind": "schema", + "status": "active", + "compatibilityLine": "v1alpha1", + "owner": "platform", + "title": "DevPickerGeneration", + "description": "Registry Stack local development picker generation JSON Schema.", + "source": { + "path": "crates/registry-platform-yaml-py/src/formats.rs", + "sha256": "48e7f8f4dbe5c7e9a8289b6c5ef3379c82a8e93d951eb18b1b49b19c4151d2e8" + }, + "artifact": { + "path": "products/platform/schemas/dev-picker-generation.v1alpha1.schema.json", + "sha256": "8480e2ff92cf609a29b4d6e768ee68551c36de6241137b7379c12f2db776b70f", + "mediaType": "application/schema+json" + } + }, + { + "uri": "https://id.registrystack.org/schemas/platform/dev-picker-token/dev-picker-token.v1alpha1.schema.json", + "kind": "schema", + "status": "active", + "compatibilityLine": "v1alpha1", + "owner": "platform", + "title": "DevPickerToken", + "description": "Registry Stack local development picker token JSON Schema.", + "source": { + "path": "crates/registry-platform-yaml-py/src/formats.rs", + "sha256": "48e7f8f4dbe5c7e9a8289b6c5ef3379c82a8e93d951eb18b1b49b19c4151d2e8" + }, + "artifact": { + "path": "products/platform/schemas/dev-picker-token.v1alpha1.schema.json", + "sha256": "48d7b5e126091c6eb47b3525d76f592ac6446ebc9dff218988c03c853257d7ed", + "mediaType": "application/schema+json" + } + }, { "uri": "https://id.registrystack.org/schemas/platform/dev-workload-token/dev-workload-token.v1alpha1.schema.json", "kind": "schema", @@ -5928,7 +5982,7 @@ "description": "Registry Stack local development workload token JSON Schema.", "source": { "path": "crates/registry-platform-yaml-py/src/formats.rs", - "sha256": "ffb0a64c7a943bdf86357f81dbb5dabb324d42b2856a237ab27be90f3e5def59" + "sha256": "48e7f8f4dbe5c7e9a8289b6c5ef3379c82a8e93d951eb18b1b49b19c4151d2e8" }, "artifact": { "path": "products/platform/schemas/dev-workload-token.v1alpha1.schema.json", @@ -6000,7 +6054,7 @@ "description": "Registry Stack Python service connection JSON Schema.", "source": { "path": "crates/registry-platform-yaml-py/src/formats.rs", - "sha256": "ffb0a64c7a943bdf86357f81dbb5dabb324d42b2856a237ab27be90f3e5def59" + "sha256": "48e7f8f4dbe5c7e9a8289b6c5ef3379c82a8e93d951eb18b1b49b19c4151d2e8" }, "artifact": { "path": "products/platform/schemas/python-connection.v1alpha1.schema.json", diff --git a/products/messaging/examples/formats/ctl-report.json b/products/messaging/examples/formats/ctl-report.json index 4bcc21e82a..df394dfa0d 100644 --- a/products/messaging/examples/formats/ctl-report.json +++ b/products/messaging/examples/formats/ctl-report.json @@ -7,8 +7,8 @@ "version": "0.44.0-dev", "accessProfiles": [ { - "actsAs": "sender", "actorKind": "service", + "actsAs": "sender", "id": "case-notices", "principalClaim": "sub", "requesterClients": [ @@ -19,8 +19,8 @@ ] }, { - "actsAs": "operator", "actorKind": null, + "actsAs": "operator", "id": "operations", "principalClaim": "sub", "requesterClients": [ diff --git a/products/platform/config-conventions-exceptions.yaml b/products/platform/config-conventions-exceptions.yaml index 4eed3c9820..9ea507a120 100644 --- a/products/platform/config-conventions-exceptions.yaml +++ b/products/platform/config-conventions-exceptions.yaml @@ -937,3 +937,15 @@ exceptions: class: exchange-model reason: "The development runner atomically writes the short-lived bearer only into its private mode-0600 state file, while the operator-authored connection holds a SecretReference to that file. The Python workload reader checks the run authority, expiry, and monotonic generation before each protected call." resolution: "Permanent for the dev-workload-token v1alpha1 producer-consumer contract. Remove this exception when a later format version no longer serializes the bearer in read-back state." +- rule: CFG-SEC-1 + format: platform/dev-picker-descriptor + location: products/platform/schemas/dev-picker-descriptor.v1alpha1.schema.json#/$defs/DevPickerCredential/properties/tokenFile + class: exchange-model + reason: "The generated descriptor names a bearer file relative to the owner-only picker directory. The Python picker checks file ownership, run confinement, live supervisor authority, and token claims before use; this relative file name is not an operator-authored SecretReference." + resolution: "Permanent for the dev-picker-descriptor v1alpha1 producer-consumer contract. Remove this exception when the format no longer names a private bearer file." +- rule: CFG-SEC-1 + format: platform/dev-picker-token + location: products/platform/schemas/dev-picker-token.v1alpha1.schema.json#/properties/token + class: exchange-model + reason: "The development runner atomically writes the short-lived bearer only to a private mode-0600 picker file. The Python picker checks the live run, exact person grant, expiry, and a consistent generation snapshot when admitting each protected request." + resolution: "Permanent for the dev-picker-token v1alpha1 producer-consumer contract. Remove this exception when a later format version no longer serializes the bearer in read-back state." diff --git a/products/platform/config-formats.yaml b/products/platform/config-formats.yaml index 076d227cdb..e8746a3549 100644 --- a/products/platform/config-formats.yaml +++ b/products/platform/config-formats.yaml @@ -3693,6 +3693,263 @@ formats: whenOmitted: closed restrictingMembers: [/product, /profile, /resource, /scopes, /claims, /expiresAt, /runExpiresAt] + - id: platform/dev-picker-descriptor + product: platform + title: Development picker descriptor + files: [picker.json] + syntax: json + audience: generated + stability: experimental + current: + apiVersion: id.registrystack.org/formats/platform/dev-picker-descriptor/v1alpha1 + kind: PlatformDevPickerDescriptor + checkedBy: + file: crates/registry-platform-yaml-py/src/formats.rs + symbol: DEV_PICKER_DESCRIPTOR_API_VERSION + target: + apiVersion: id.registrystack.org/formats/platform/dev-picker-descriptor/v1alpha1 + kind: PlatformDevPickerDescriptor + schema: + path: products/platform/schemas/dev-picker-descriptor.v1alpha1.schema.json + id: https://id.registrystack.org/schemas/platform/dev-picker-descriptor/dev-picker-descriptor.v1alpha1.schema.json + origin: generated + generator: cargo run -p registry-platform-yaml-py --features schema --example python-formats-schema -- --output products/platform/schemas + driftCheck: crates/registry-platform-yaml-py/src/tests.rs + reader: + crate: registry-platform-yaml-py + file: crates/registry-platform-yaml-py/src/formats.rs + function: read_dev_picker_descriptor + type: DevPickerDescriptor + check: python -m registry_client.check_dev_picker --kind descriptor {file} + example: products/platform/examples/dev-picker/picker.json + conformance: + requiredText: /runId + optionalText: none + integer: /issuedAt + boolean: none + idList: none + set: /people/0/credentials/breg/scopes + reference: none + relativePath: /generationFile + operand: none + securityMembers: + - pointer: /runId + whenOmitted: refused + - pointer: /persona + whenOmitted: refused + - pointer: /origin + whenOmitted: refused + - pointer: /sessionNamespace + whenOmitted: refused + - pointer: /issuedAt + whenOmitted: refused + - pointer: /expiresAt + whenOmitted: refused + - pointer: /generationFile + whenOmitted: refused + - pointer: /products/*/url + whenOmitted: refused + - pointer: /products/*/resource + whenOmitted: refused + - pointer: /people/*/selector + whenOmitted: refused + - pointer: /people/*/subject + whenOmitted: refused + - pointer: /people/*/principal + whenOmitted: refused + - pointer: /people/*/clientId + whenOmitted: refused + - pointer: /people/*/credentials/*/tokenFile + whenOmitted: refused + - pointer: /people/*/credentials/*/profile + whenOmitted: refused + - pointer: /people/*/credentials/*/resource + whenOmitted: refused + - pointer: /people/*/credentials/*/audiences + whenOmitted: refused + - pointer: /people/*/credentials/*/scopes + whenOmitted: refused + - pointer: /people/*/credentials/*/principalClaim + whenOmitted: refused + - pointer: /workloadConnectionFile + whenOmitted: closed + - pointer: /workloads/*/product + whenOmitted: refused + - pointer: /workloads/*/default + whenOmitted: refused + - pointer: /workloads/*/url + whenOmitted: refused + - pointer: /workloads/*/issuer + whenOmitted: refused + - pointer: /workloads/*/subject + whenOmitted: refused + - pointer: /workloads/*/clientId + whenOmitted: refused + - pointer: /workloads/*/profile + whenOmitted: refused + - pointer: /workloads/*/resource + whenOmitted: refused + - pointer: /workloads/*/scopes + whenOmitted: refused + - pointer: /workloads/*/claims + whenOmitted: refused + restrictingMembers: [/persona, /origin, /expiresAt, /products/*/resource, /people/*/credentials/*/profile, /people/*/credentials/*/resource, /people/*/credentials/*/audiences, /people/*/credentials/*/scopes, /people/*/credentials/*/principalClaim, /workloadConnectionFile, /workloads/*/product, /workloads/*/profile, /workloads/*/resource, /workloads/*/scopes, /workloads/*/claims] + + - id: platform/dev-picker-token + product: platform + title: Development picker person token state + files: ['credential-*.json'] + syntax: json + audience: generated + stability: experimental + current: + apiVersion: id.registrystack.org/formats/platform/dev-picker-token/v1alpha1 + kind: PlatformDevPickerToken + checkedBy: + file: crates/registry-platform-yaml-py/src/formats.rs + symbol: DEV_PICKER_TOKEN_API_VERSION + target: + apiVersion: id.registrystack.org/formats/platform/dev-picker-token/v1alpha1 + kind: PlatformDevPickerToken + schema: + path: products/platform/schemas/dev-picker-token.v1alpha1.schema.json + id: https://id.registrystack.org/schemas/platform/dev-picker-token/dev-picker-token.v1alpha1.schema.json + origin: generated + generator: cargo run -p registry-platform-yaml-py --features schema --example python-formats-schema -- --output products/platform/schemas + driftCheck: crates/registry-platform-yaml-py/src/tests.rs + reader: + crate: registry-platform-yaml-py + file: crates/registry-platform-yaml-py/src/formats.rs + function: read_dev_picker_token + type: DevPickerToken + check: python -m registry_client.check_dev_picker --kind token {file} + example: products/platform/examples/dev-picker/credential-0-breg.json + conformance: + requiredText: /runId + optionalText: none + integer: /generation + boolean: none + idList: none + set: /scopes + reference: none + operand: none + securityMembers: + - pointer: /runId + whenOmitted: refused + - pointer: /picker + whenOmitted: refused + - pointer: /persona + whenOmitted: refused + - pointer: /selector + whenOmitted: refused + - pointer: /product + whenOmitted: refused + - pointer: /issuer + whenOmitted: refused + - pointer: /subject + whenOmitted: refused + - pointer: /principal + whenOmitted: refused + - pointer: /clientId + whenOmitted: refused + - pointer: /profile + whenOmitted: refused + - pointer: /resource + whenOmitted: refused + - pointer: /audiences + whenOmitted: refused + - pointer: /scopes + whenOmitted: refused + - pointer: /principalClaim + whenOmitted: refused + - pointer: /generation + whenOmitted: refused + - pointer: /issuedAt + whenOmitted: refused + - pointer: /expiresAt + whenOmitted: refused + - pointer: /runExpiresAt + whenOmitted: refused + - pointer: /status + whenOmitted: open + - pointer: /token + whenOmitted: closed + restrictingMembers: [/persona, /product, /profile, /resource, /audiences, /scopes, /principalClaim, /expiresAt, /runExpiresAt] + + - id: platform/dev-picker-generation + product: platform + title: Development picker credential generation state + files: [generation.json] + syntax: json + audience: generated + stability: experimental + current: + apiVersion: id.registrystack.org/formats/platform/dev-picker-generation/v1alpha1 + kind: PlatformDevPickerGeneration + checkedBy: + file: crates/registry-platform-yaml-py/src/formats.rs + symbol: DEV_PICKER_GENERATION_API_VERSION + target: + apiVersion: id.registrystack.org/formats/platform/dev-picker-generation/v1alpha1 + kind: PlatformDevPickerGeneration + schema: + path: products/platform/schemas/dev-picker-generation.v1alpha1.schema.json + id: https://id.registrystack.org/schemas/platform/dev-picker-generation/dev-picker-generation.v1alpha1.schema.json + origin: generated + generator: cargo run -p registry-platform-yaml-py --features schema --example python-formats-schema -- --output products/platform/schemas + driftCheck: crates/registry-platform-yaml-py/src/tests.rs + reader: + crate: registry-platform-yaml-py + file: crates/registry-platform-yaml-py/src/formats.rs + function: read_dev_picker_generation + type: DevPickerGeneration + check: python -m registry_client.check_dev_picker --kind generation {file} + example: products/platform/examples/dev-picker/generation.json + conformance: + requiredText: /runId + optionalText: none + integer: /generation + boolean: none + idList: none + set: none + reference: none + operand: none + securityMembers: + - pointer: /status + whenOmitted: refused + - pointer: /runId + whenOmitted: refused + - pointer: /picker + whenOmitted: refused + - pointer: /generation + whenOmitted: refused + - pointer: /runExpiresAt + whenOmitted: refused + restrictingMembers: [/status, /generation, /runExpiresAt] + + - id: platform/dev-picker-check-report + product: platform + title: Development picker offline check report + files: [] + syntax: json + audience: generated + stability: experimental + current: + apiVersion: id.registrystack.org/formats/platform/dev-picker-check-report/v1alpha1 + kind: PlatformDevPickerCheckReport + checkedBy: none + target: + apiVersion: id.registrystack.org/formats/platform/dev-picker-check-report/v1alpha1 + kind: PlatformDevPickerCheckReport + schema: none + reader: none + emittedBy: none + check: none + example: products/platform/examples/dev-picker/check-report.json + conformance: none + securityMembers: [] + restrictingMembers: [] + - id: platform/package-sums product: platform title: Package SHA256SUMS diff --git a/products/platform/examples/dev-picker/check-report.json b/products/platform/examples/dev-picker/check-report.json new file mode 100644 index 0000000000..bbf7cdfb4f --- /dev/null +++ b/products/platform/examples/dev-picker/check-report.json @@ -0,0 +1,12 @@ +{ + "ok": true, + "command": "dev-picker check", + "status": "complete", + "apiVersion": "id.registrystack.org/formats/platform/dev-picker-check-report/v1alpha1", + "kind": "PlatformDevPickerCheckReport", + "version": "0.46.1", + "filesChecked": 1, + "errors": 0, + "warnings": 0, + "diagnostics": [] +} diff --git a/products/platform/examples/dev-picker/credential-0-breg.json b/products/platform/examples/dev-picker/credential-0-breg.json new file mode 100644 index 0000000000..cb3c5416df --- /dev/null +++ b/products/platform/examples/dev-picker/credential-0-breg.json @@ -0,0 +1,27 @@ +{ + "apiVersion": "id.registrystack.org/formats/platform/dev-picker-token/v1alpha1", + "kind": "PlatformDevPickerToken", + "runId": "0123456789abcdef0123456789abcdef", + "picker": "holder", + "persona": "holder", + "selector": "abcdef0123456789abcdef0123456789", + "product": "breg", + "issuer": "https://issuer.example.test", + "subject": "person-one", + "principal": "person-one", + "clientId": "portal-client", + "profile": "applicant", + "resource": "urn:test:breg", + "audiences": [ + "urn:test:breg" + ], + "scopes": [ + "breg:read" + ], + "principalClaim": "registry_principal", + "generation": 1, + "issuedAt": 1700000000, + "expiresAt": 1700000300, + "runExpiresAt": 1700000600, + "status": "stopped" +} diff --git a/products/platform/examples/dev-picker/generation.json b/products/platform/examples/dev-picker/generation.json new file mode 100644 index 0000000000..6450a763cd --- /dev/null +++ b/products/platform/examples/dev-picker/generation.json @@ -0,0 +1,9 @@ +{ + "apiVersion": "id.registrystack.org/formats/platform/dev-picker-generation/v1alpha1", + "kind": "PlatformDevPickerGeneration", + "status": "stopped", + "runId": "0123456789abcdef0123456789abcdef", + "picker": "holder", + "generation": 1, + "runExpiresAt": 1700000600 +} diff --git a/products/platform/examples/dev-picker/picker.json b/products/platform/examples/dev-picker/picker.json new file mode 100644 index 0000000000..537250afa0 --- /dev/null +++ b/products/platform/examples/dev-picker/picker.json @@ -0,0 +1,41 @@ +{ + "apiVersion": "id.registrystack.org/formats/platform/dev-picker-descriptor/v1alpha1", + "kind": "PlatformDevPickerDescriptor", + "runId": "0123456789abcdef0123456789abcdef", + "persona": "holder", + "origin": "http://127.0.0.1:41000", + "sessionNamespace": "0123456789abcdef0123456789abcdef", + "issuedAt": 1700000000, + "expiresAt": 1700000600, + "generationFile": "generation.json", + "products": { + "breg": { + "url": "http://127.0.0.1:41001", + "resource": "urn:test:breg" + } + }, + "people": [ + { + "selector": "abcdef0123456789abcdef0123456789", + "label": "applicant", + "subject": "person-one", + "principal": "person-one", + "clientId": "portal-client", + "credentials": { + "breg": { + "tokenFile": "credential-0-breg.json", + "profile": "applicant", + "resource": "urn:test:breg", + "audiences": [ + "urn:test:breg" + ], + "scopes": [ + "breg:read" + ], + "principalClaim": "registry_principal" + } + } + } + ], + "workloads": [] +} diff --git a/products/platform/schemas/dev-picker-descriptor.v1alpha1.schema.json b/products/platform/schemas/dev-picker-descriptor.v1alpha1.schema.json new file mode 100644 index 0000000000..f14c4fd0d3 --- /dev/null +++ b/products/platform/schemas/dev-picker-descriptor.v1alpha1.schema.json @@ -0,0 +1,302 @@ +{ + "$defs": { + "DevPickerCredential": { + "additionalProperties": false, + "properties": { + "audiences": { + "items": { + "$ref": "#/$defs/ExternalId" + }, + "maxItems": 4, + "minItems": 1, + "type": "array", + "uniqueItems": true + }, + "principalClaim": { + "$ref": "#/$defs/ExternalId" + }, + "profile": { + "$ref": "#/$defs/ExternalId" + }, + "resource": { + "$ref": "#/$defs/ExternalId" + }, + "scopes": { + "items": { + "$ref": "#/$defs/ExternalId" + }, + "maxItems": 32, + "minItems": 1, + "type": "array", + "uniqueItems": true + }, + "tokenFile": { + "$ref": "#/$defs/ExternalId" + } + }, + "required": [ + "tokenFile", + "profile", + "resource", + "audiences", + "scopes", + "principalClaim" + ], + "type": "object" + }, + "DevPickerPerson": { + "additionalProperties": false, + "properties": { + "clientId": { + "$ref": "#/$defs/ExternalId" + }, + "credentials": { + "additionalProperties": { + "$ref": "#/$defs/DevPickerCredential" + }, + "maxProperties": 2, + "minProperties": 1, + "propertyNames": { + "$ref": "#/$defs/ExternalId", + "enum": [ + "breg", + "casework" + ] + }, + "type": "object" + }, + "label": { + "maxLength": 128, + "minLength": 1, + "type": "string" + }, + "principal": { + "$ref": "#/$defs/ExternalId" + }, + "selector": { + "maxLength": 128, + "minLength": 20, + "pattern": "^[A-Za-z0-9_-]{20,128}$", + "type": "string" + }, + "subject": { + "$ref": "#/$defs/ExternalId" + } + }, + "required": [ + "selector", + "label", + "subject", + "principal", + "clientId", + "credentials" + ], + "type": "object" + }, + "DevPickerPersona": { + "enum": [ + "holder", + "staff" + ], + "type": "string" + }, + "DevPickerProductTarget": { + "additionalProperties": false, + "properties": { + "resource": { + "$ref": "#/$defs/ExternalId" + }, + "url": { + "$ref": "#/$defs/Url" + } + }, + "required": [ + "url", + "resource" + ], + "type": "object" + }, + "DevPickerWorkload": { + "additionalProperties": false, + "properties": { + "claims": { + "additionalProperties": true, + "maxProperties": 64, + "propertyNames": { + "$ref": "#/$defs/ExternalId" + }, + "type": "object", + "x-registry-passthrough": "Claim values are written into the workload token as declared." + }, + "clientId": { + "$ref": "#/$defs/ExternalId" + }, + "default": { + "type": "boolean" + }, + "issuer": { + "$ref": "#/$defs/Url" + }, + "name": { + "pattern": "^[a-z][a-z0-9-]{0,63}$", + "type": "string" + }, + "product": { + "$ref": "#/$defs/DevPickerWorkloadProduct" + }, + "profile": { + "$ref": "#/$defs/ExternalId" + }, + "resource": { + "$ref": "#/$defs/ExternalId" + }, + "scopes": { + "items": { + "$ref": "#/$defs/ExternalId" + }, + "maxItems": 32, + "minItems": 1, + "type": "array", + "uniqueItems": true + }, + "subject": { + "$ref": "#/$defs/ExternalId" + }, + "url": { + "$ref": "#/$defs/Url" + } + }, + "required": [ + "name", + "product", + "default", + "url", + "issuer", + "subject", + "clientId", + "profile", + "resource", + "scopes", + "claims" + ], + "type": "object" + }, + "DevPickerWorkloadProduct": { + "enum": [ + "breg", + "messaging" + ], + "type": "string" + }, + "ExternalId": { + "description": "An identifier another system issues, written exactly as its issuer gives it.", + "maxLength": 512, + "minLength": 1, + "pattern": "^[^\\u0000-\\u001F\\u007F-\\u009F]+$", + "type": "string" + }, + "Url": { + "description": "An absolute http or https URL with a host preserved as written, no user information, and no backslash, whitespace or control character. DNS case and equivalent IPv6 literals are permitted.", + "format": "uri", + "maxLength": 2048, + "pattern": "^[Hh][Tt][Tt][Pp][Ss]?://[^/?#@\\u005C\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000]+([/?#][^\\u005C\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000]*)?$", + "type": "string" + } + }, + "$id": "https://id.registrystack.org/schemas/platform/dev-picker-descriptor/dev-picker-descriptor.v1alpha1.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "apiVersion": { + "const": "id.registrystack.org/formats/platform/dev-picker-descriptor/v1alpha1", + "type": "string" + }, + "expiresAt": { + "format": "uint64", + "maximum": 18446744073709551615, + "minimum": 1, + "type": "integer" + }, + "generationFile": { + "$ref": "#/$defs/ExternalId" + }, + "issuedAt": { + "format": "uint64", + "maximum": 18446744073709551615, + "minimum": 1, + "type": "integer" + }, + "kind": { + "const": "PlatformDevPickerDescriptor", + "type": "string" + }, + "origin": { + "$ref": "#/$defs/Url" + }, + "people": { + "items": { + "$ref": "#/$defs/DevPickerPerson" + }, + "maxItems": 32, + "minItems": 1, + "type": "array" + }, + "persona": { + "$ref": "#/$defs/DevPickerPersona" + }, + "products": { + "additionalProperties": { + "$ref": "#/$defs/DevPickerProductTarget" + }, + "maxProperties": 3, + "minProperties": 1, + "propertyNames": { + "$ref": "#/$defs/ExternalId", + "enum": [ + "breg", + "casework", + "messaging" + ] + }, + "type": "object" + }, + "runId": { + "maxLength": 32, + "minLength": 32, + "pattern": "^[0-9a-f]{32}$", + "type": "string" + }, + "sessionNamespace": { + "maxLength": 128, + "minLength": 20, + "pattern": "^[A-Za-z0-9_-]{20,128}$", + "type": "string" + }, + "workloadConnectionFile": { + "$ref": "#/$defs/ExternalId" + }, + "workloads": { + "items": { + "$ref": "#/$defs/DevPickerWorkload" + }, + "maxItems": 32, + "type": "array" + } + }, + "required": [ + "apiVersion", + "kind", + "runId", + "persona", + "origin", + "sessionNamespace", + "issuedAt", + "expiresAt", + "generationFile", + "products", + "people", + "workloads" + ], + "title": "DevPickerDescriptor", + "type": "object" +} diff --git a/products/platform/schemas/dev-picker-generation.v1alpha1.schema.json b/products/platform/schemas/dev-picker-generation.v1alpha1.schema.json new file mode 100644 index 0000000000..bae6d6f73d --- /dev/null +++ b/products/platform/schemas/dev-picker-generation.v1alpha1.schema.json @@ -0,0 +1,66 @@ +{ + "$defs": { + "DevPickerGenerationStatus": { + "enum": [ + "ready", + "stopped" + ], + "type": "string" + }, + "DevPickerPersona": { + "enum": [ + "holder", + "staff" + ], + "type": "string" + } + }, + "$id": "https://id.registrystack.org/schemas/platform/dev-picker-generation/dev-picker-generation.v1alpha1.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "apiVersion": { + "const": "id.registrystack.org/formats/platform/dev-picker-generation/v1alpha1", + "type": "string" + }, + "generation": { + "format": "uint64", + "maximum": 18446744073709551615, + "minimum": 1, + "type": "integer" + }, + "kind": { + "const": "PlatformDevPickerGeneration", + "type": "string" + }, + "picker": { + "$ref": "#/$defs/DevPickerPersona" + }, + "runExpiresAt": { + "format": "uint64", + "maximum": 18446744073709551615, + "minimum": 1, + "type": "integer" + }, + "runId": { + "maxLength": 32, + "minLength": 32, + "pattern": "^[0-9a-f]{32}$", + "type": "string" + }, + "status": { + "$ref": "#/$defs/DevPickerGenerationStatus" + } + }, + "required": [ + "apiVersion", + "kind", + "status", + "runId", + "picker", + "generation", + "runExpiresAt" + ], + "title": "DevPickerGeneration", + "type": "object" +} diff --git a/products/platform/schemas/dev-picker-token.v1alpha1.schema.json b/products/platform/schemas/dev-picker-token.v1alpha1.schema.json new file mode 100644 index 0000000000..07c7444ee7 --- /dev/null +++ b/products/platform/schemas/dev-picker-token.v1alpha1.schema.json @@ -0,0 +1,190 @@ +{ + "$defs": { + "DevPickerPersonProduct": { + "enum": [ + "breg", + "casework" + ], + "type": "string" + }, + "DevPickerPersona": { + "enum": [ + "holder", + "staff" + ], + "type": "string" + }, + "DevPickerTokenStatus": { + "enum": [ + "stopped" + ], + "type": "string" + }, + "ExternalId": { + "description": "An identifier another system issues, written exactly as its issuer gives it.", + "maxLength": 512, + "minLength": 1, + "pattern": "^[^\\u0000-\\u001F\\u007F-\\u009F]+$", + "type": "string" + }, + "Url": { + "description": "An absolute http or https URL with a host preserved as written, no user information, and no backslash, whitespace or control character. DNS case and equivalent IPv6 literals are permitted.", + "format": "uri", + "maxLength": 2048, + "pattern": "^[Hh][Tt][Tt][Pp][Ss]?://[^/?#@\\u005C\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000]+([/?#][^\\u005C\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000]*)?$", + "type": "string" + } + }, + "$id": "https://id.registrystack.org/schemas/platform/dev-picker-token/dev-picker-token.v1alpha1.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "oneOf": [ + { + "not": { + "required": [ + "status" + ] + }, + "required": [ + "token" + ] + }, + { + "not": { + "required": [ + "token" + ] + }, + "required": [ + "status" + ] + } + ], + "properties": { + "apiVersion": { + "const": "id.registrystack.org/formats/platform/dev-picker-token/v1alpha1", + "type": "string" + }, + "audiences": { + "items": { + "$ref": "#/$defs/ExternalId" + }, + "maxItems": 4, + "minItems": 1, + "type": "array", + "uniqueItems": true + }, + "clientId": { + "$ref": "#/$defs/ExternalId" + }, + "expiresAt": { + "format": "uint64", + "maximum": 18446744073709551615, + "minimum": 1, + "type": "integer" + }, + "generation": { + "format": "uint64", + "maximum": 18446744073709551615, + "minimum": 1, + "type": "integer" + }, + "issuedAt": { + "format": "uint64", + "maximum": 18446744073709551615, + "minimum": 1, + "type": "integer" + }, + "issuer": { + "$ref": "#/$defs/Url" + }, + "kind": { + "const": "PlatformDevPickerToken", + "type": "string" + }, + "persona": { + "$ref": "#/$defs/DevPickerPersona" + }, + "picker": { + "$ref": "#/$defs/DevPickerPersona" + }, + "principal": { + "$ref": "#/$defs/ExternalId" + }, + "principalClaim": { + "$ref": "#/$defs/ExternalId" + }, + "product": { + "$ref": "#/$defs/DevPickerPersonProduct" + }, + "profile": { + "$ref": "#/$defs/ExternalId" + }, + "resource": { + "$ref": "#/$defs/ExternalId" + }, + "runExpiresAt": { + "format": "uint64", + "maximum": 18446744073709551615, + "minimum": 1, + "type": "integer" + }, + "runId": { + "maxLength": 32, + "minLength": 32, + "pattern": "^[0-9a-f]{32}$", + "type": "string" + }, + "scopes": { + "items": { + "$ref": "#/$defs/ExternalId" + }, + "maxItems": 32, + "minItems": 1, + "type": "array", + "uniqueItems": true + }, + "selector": { + "maxLength": 128, + "minLength": 20, + "pattern": "^[A-Za-z0-9_-]{20,128}$", + "type": "string" + }, + "status": { + "$ref": "#/$defs/DevPickerTokenStatus" + }, + "subject": { + "$ref": "#/$defs/ExternalId" + }, + "token": { + "maxLength": 8192, + "minLength": 1, + "pattern": "^\\S+$", + "type": "string" + } + }, + "required": [ + "apiVersion", + "kind", + "runId", + "picker", + "persona", + "selector", + "product", + "issuer", + "subject", + "principal", + "clientId", + "profile", + "resource", + "audiences", + "scopes", + "principalClaim", + "generation", + "issuedAt", + "expiresAt", + "runExpiresAt" + ], + "title": "DevPickerToken", + "type": "object" +} diff --git a/release/scripts/test_build_linux_python_client.py b/release/scripts/test_build_linux_python_client.py index 298f58e16e..14fb76ef32 100755 --- a/release/scripts/test_build_linux_python_client.py +++ b/release/scripts/test_build_linux_python_client.py @@ -189,7 +189,7 @@ def test_rejects_retired_relay_before_build(self) -> None: result = self.run_build(client="relay") self.assertEqual(result.returncode, 2) self.assertIn( - "client must be discovery, evidence, breg, casework, messaging, scheduling, coordinator, or render", + "client must be discovery, evidence, breg, casework, messaging, scheduling, coordinator, render, oidc, or yaml", result.stderr, ) self.assertFalse(self.log.exists()) From 3ec9c43a5449ab72404efaaea087c1bb4d2cb5ab Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 06:49:08 +0700 Subject: [PATCH 15/34] fix(platform): bind Python checker reports to their source Signed-off-by: Jeremi Joslin --- products/platform/config-formats.yaml | 8 +++-- .../scripts/check-config-conventions.py | 32 +++++++++++++++++-- .../scripts/test_check_config_conventions.py | 23 +++++++++++++ 3 files changed, 59 insertions(+), 4 deletions(-) diff --git a/products/platform/config-formats.yaml b/products/platform/config-formats.yaml index e8746a3549..ad30fd8623 100644 --- a/products/platform/config-formats.yaml +++ b/products/platform/config-formats.yaml @@ -3937,13 +3937,17 @@ formats: current: apiVersion: id.registrystack.org/formats/platform/dev-picker-check-report/v1alpha1 kind: PlatformDevPickerCheckReport - checkedBy: none + checkedBy: + file: crates/registry-stack-client-py/python/registry_client/check_dev_picker.py + symbol: REPORT_API_VERSION target: apiVersion: id.registrystack.org/formats/platform/dev-picker-check-report/v1alpha1 kind: PlatformDevPickerCheckReport schema: none reader: none - emittedBy: none + emittedBy: + file: crates/registry-stack-client-py/python/registry_client/check_dev_picker.py + symbol: _report check: none example: products/platform/examples/dev-picker/check-report.json conformance: none diff --git a/products/platform/scripts/check-config-conventions.py b/products/platform/scripts/check-config-conventions.py index 1e5e91d4b5..1344abacf2 100644 --- a/products/platform/scripts/check-config-conventions.py +++ b/products/platform/scripts/check-config-conventions.py @@ -1242,8 +1242,26 @@ def check_symbol(self, fid: str, label: str, reference: object) -> str | None: if text is None: self.error(f"{fid}: {label} file {reference['file']} does not exist") return None - code = conformance.code_only(text) - if not re.search(rf"\b(?:const|static|fn)\s+{re.escape(str(reference['symbol']))}\b", code): + symbol = str(reference["symbol"]) + if str(reference["file"]).endswith(".py"): + try: + nodes = ast.parse(text).body + except SyntaxError: + self.error(f"{fid}: {label} {reference['file']} does not parse as Python") + return None + names = set() + for node in nodes: + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + names.add(node.name) + elif isinstance(node, ast.Assign): + names.update(target.id for target in node.targets if isinstance(target, ast.Name)) + elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): + names.add(node.target.id) + defined = symbol in names + else: + code = conformance.code_only(text) + defined = re.search(rf"\b(?:const|static|fn)\s+{re.escape(symbol)}\b", code) is not None + if not defined: self.error(f"{fid}: {label} {reference['file']} does not define {reference['symbol']}") return None return text @@ -1274,6 +1292,16 @@ def check_current(self, fid: str, entry: dict) -> None: literal = re.search(rf"\b(?:const|static)\s+{symbol}\s*:[^=]*=\s*\"([^\"]*)\"\s*;", text) if literal and literal.group(1) not in values: self.error(f"{fid}: checkedBy {current['checkedBy']['symbol']} is {literal.group(1)!r}, not a current header value") + if str(current["checkedBy"]["file"]).endswith(".py"): + for node in ast.parse(text).body: + if ( + isinstance(node, ast.Assign) + and any(isinstance(target, ast.Name) and target.id == current["checkedBy"]["symbol"] for target in node.targets) + and isinstance(node.value, ast.Constant) + and isinstance(node.value.value, str) + and node.value.value not in values + ): + self.error(f"{fid}: checkedBy {current['checkedBy']['symbol']} is not a current header value") def check_target(self, fid: str, entry: dict, kinds: dict[str, list[str]]) -> None: target = entry["target"] diff --git a/products/platform/scripts/test_check_config_conventions.py b/products/platform/scripts/test_check_config_conventions.py index e998a8aedb..0a65bc4b76 100644 --- a/products/platform/scripts/test_check_config_conventions.py +++ b/products/platform/scripts/test_check_config_conventions.py @@ -574,6 +574,29 @@ def test_cfg_schema_1_refuses_checked_by_symbol_the_file_does_not_define(self) - self.repo.fmt()["current"]["checkedBy"]["symbol"] = "MISSING_VERSION" self.assertError(self.repo.run(), "does not define MISSING_VERSION") + def test_cfg_schema_1_binds_python_checker_and_emitter_symbols(self) -> None: + source = "tools/check_report.py" + self.repo.write( + source, + 'REPORT_API_VERSION = "id.registrystack.org/formats/casework/check-report/v1alpha1"\n' + 'REPORT_KIND = "CaseworkCheckReport"\n' + "def report():\n return REPORT_API_VERSION\n", + ) + report_format = self.repo.fmt(R) + report_format["current"]["checkedBy"] = {"file": source, "symbol": "REPORT_API_VERSION"} + report_format["emittedBy"] = {"file": source, "symbol": "report"} + self.assertEqual(self.repo.run().errors, []) + report_format["current"]["checkedBy"]["symbol"] = "MISSING_VERSION" + self.assertError(self.repo.run(), "does not define MISSING_VERSION") + report_format["current"]["checkedBy"]["symbol"] = "REPORT_API_VERSION" + self.repo.write( + source, + 'REPORT_API_VERSION = "id.registrystack.org/formats/casework/other/v1alpha1"\n' + 'REPORT_KIND = "CaseworkCheckReport"\n' + "def report():\n return REPORT_API_VERSION\n", + ) + self.assertError(self.repo.run(), "is not a current header value") + def test_cfg_schema_1_refuses_checked_by_file_without_the_header_value(self) -> None: self.repo.fmt()["current"]["apiVersion"] = "registry.registrystack.org/casework/v1alpha1" self.assertError(self.repo.run(), "does not contain the current header") From 8e8990c31c2c2e5ac1966c542a4de7c0971721b7 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 06:50:52 +0700 Subject: [PATCH 16/34] fix(platform): require literal Python format headers Signed-off-by: Jeremi Joslin --- .../scripts/check-config-conventions.py | 18 +++++++++++------- .../scripts/test_check_config_conventions.py | 14 ++++++++++++++ 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/products/platform/scripts/check-config-conventions.py b/products/platform/scripts/check-config-conventions.py index 1344abacf2..ead60f56ce 100644 --- a/products/platform/scripts/check-config-conventions.py +++ b/products/platform/scripts/check-config-conventions.py @@ -1293,15 +1293,19 @@ def check_current(self, fid: str, entry: dict) -> None: if literal and literal.group(1) not in values: self.error(f"{fid}: checkedBy {current['checkedBy']['symbol']} is {literal.group(1)!r}, not a current header value") if str(current["checkedBy"]["file"]).endswith(".py"): + named = str(current["checkedBy"]["symbol"]) + assignments = [] for node in ast.parse(text).body: - if ( - isinstance(node, ast.Assign) - and any(isinstance(target, ast.Name) and target.id == current["checkedBy"]["symbol"] for target in node.targets) - and isinstance(node.value, ast.Constant) - and isinstance(node.value.value, str) - and node.value.value not in values + if isinstance(node, ast.Assign) and any( + isinstance(target, ast.Name) and target.id == named for target in node.targets ): - self.error(f"{fid}: checkedBy {current['checkedBy']['symbol']} is not a current header value") + assignments.append(node.value) + elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.target.id == named: + assignments.append(node.value) + if len(assignments) != 1 or not isinstance(assignments[0], ast.Constant) or not isinstance(assignments[0].value, str): + self.error(f"{fid}: checkedBy {named} is not a literal current header value") + elif assignments[0].value not in values: + self.error(f"{fid}: checkedBy {named} is not a current header value") def check_target(self, fid: str, entry: dict, kinds: dict[str, list[str]]) -> None: target = entry["target"] diff --git a/products/platform/scripts/test_check_config_conventions.py b/products/platform/scripts/test_check_config_conventions.py index 0a65bc4b76..17b07a749a 100644 --- a/products/platform/scripts/test_check_config_conventions.py +++ b/products/platform/scripts/test_check_config_conventions.py @@ -596,6 +596,20 @@ def test_cfg_schema_1_binds_python_checker_and_emitter_symbols(self) -> None: "def report():\n return REPORT_API_VERSION\n", ) self.assertError(self.repo.run(), "is not a current header value") + self.repo.write( + source, + "REPORT_API_VERSION = make_version()\n" + 'REPORT_KIND = "CaseworkCheckReport"\n' + "def report():\n return REPORT_API_VERSION\n", + ) + self.assertError(self.repo.run(), "is not a literal current header value") + self.repo.write( + source, + 'REPORT_API_VERSION: str = "id.registrystack.org/formats/casework/check-report/v1alpha1"\n' + 'REPORT_KIND = "CaseworkCheckReport"\n' + "def report():\n return REPORT_API_VERSION\n", + ) + self.assertEqual(self.repo.run().errors, []) def test_cfg_schema_1_refuses_checked_by_file_without_the_header_value(self) -> None: self.repo.fmt()["current"]["apiVersion"] = "registry.registrystack.org/casework/v1alpha1" From 61475c9fd2d3b40ddb116a7fd043c1020cf373c5 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 07:18:17 +0700 Subject: [PATCH 17/34] fix(platform): retain Python AST import in merged checks Signed-off-by: Jeremi Joslin --- .../scripts/check-config-conventions.py | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/products/platform/scripts/check-config-conventions.py b/products/platform/scripts/check-config-conventions.py index ead60f56ce..bfd5f7e96a 100644 --- a/products/platform/scripts/check-config-conventions.py +++ b/products/platform/scripts/check-config-conventions.py @@ -46,6 +46,7 @@ import importlib.util import json import re +import ast as python_ast import subprocess import sys import tomllib @@ -1245,17 +1246,17 @@ def check_symbol(self, fid: str, label: str, reference: object) -> str | None: symbol = str(reference["symbol"]) if str(reference["file"]).endswith(".py"): try: - nodes = ast.parse(text).body + nodes = python_ast.parse(text).body except SyntaxError: self.error(f"{fid}: {label} {reference['file']} does not parse as Python") return None names = set() for node in nodes: - if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + if isinstance(node, (python_ast.FunctionDef, python_ast.AsyncFunctionDef, python_ast.ClassDef)): names.add(node.name) - elif isinstance(node, ast.Assign): - names.update(target.id for target in node.targets if isinstance(target, ast.Name)) - elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): + elif isinstance(node, python_ast.Assign): + names.update(target.id for target in node.targets if isinstance(target, python_ast.Name)) + elif isinstance(node, python_ast.AnnAssign) and isinstance(node.target, python_ast.Name): names.add(node.target.id) defined = symbol in names else: @@ -1295,14 +1296,14 @@ def check_current(self, fid: str, entry: dict) -> None: if str(current["checkedBy"]["file"]).endswith(".py"): named = str(current["checkedBy"]["symbol"]) assignments = [] - for node in ast.parse(text).body: - if isinstance(node, ast.Assign) and any( - isinstance(target, ast.Name) and target.id == named for target in node.targets + for node in python_ast.parse(text).body: + if isinstance(node, python_ast.Assign) and any( + isinstance(target, python_ast.Name) and target.id == named for target in node.targets ): assignments.append(node.value) - elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.target.id == named: + elif isinstance(node, python_ast.AnnAssign) and isinstance(node.target, python_ast.Name) and node.target.id == named: assignments.append(node.value) - if len(assignments) != 1 or not isinstance(assignments[0], ast.Constant) or not isinstance(assignments[0].value, str): + if len(assignments) != 1 or not isinstance(assignments[0], python_ast.Constant) or not isinstance(assignments[0].value, str): self.error(f"{fid}: checkedBy {named} is not a literal current header value") elif assignments[0].value not in values: self.error(f"{fid}: checkedBy {named} is not a current header value") From baa0727d1d355605f3661289bd42fd2a5bac8568 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 07:19:59 +0700 Subject: [PATCH 18/34] fix(platform): refresh picker identifiers after schema bounds Signed-off-by: Jeremi Joslin --- products/identifiers/generated/catalog.v1.json | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index 3b8aae711e..d036fad038 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -5928,11 +5928,11 @@ "description": "Registry Stack local development picker descriptor JSON Schema.", "source": { "path": "crates/registry-platform-yaml-py/src/formats.rs", - "sha256": "48e7f8f4dbe5c7e9a8289b6c5ef3379c82a8e93d951eb18b1b49b19c4151d2e8" + "sha256": "243a5d94ee9059d15287d2872b67983f77ae39e1c6e3e533fdb0a24dc31edf52" }, "artifact": { "path": "products/platform/schemas/dev-picker-descriptor.v1alpha1.schema.json", - "sha256": "0af9229be9a322dd6c23fed8527c3d65a09ac4538a1880fc5978c7ca290dc8a3", + "sha256": "b8de601e84c2678ff52e1cb9da2f305097d2e238ea3160734e0c37be1ba13409", "mediaType": "application/schema+json" } }, @@ -5946,7 +5946,7 @@ "description": "Registry Stack local development picker generation JSON Schema.", "source": { "path": "crates/registry-platform-yaml-py/src/formats.rs", - "sha256": "48e7f8f4dbe5c7e9a8289b6c5ef3379c82a8e93d951eb18b1b49b19c4151d2e8" + "sha256": "243a5d94ee9059d15287d2872b67983f77ae39e1c6e3e533fdb0a24dc31edf52" }, "artifact": { "path": "products/platform/schemas/dev-picker-generation.v1alpha1.schema.json", @@ -5964,11 +5964,11 @@ "description": "Registry Stack local development picker token JSON Schema.", "source": { "path": "crates/registry-platform-yaml-py/src/formats.rs", - "sha256": "48e7f8f4dbe5c7e9a8289b6c5ef3379c82a8e93d951eb18b1b49b19c4151d2e8" + "sha256": "243a5d94ee9059d15287d2872b67983f77ae39e1c6e3e533fdb0a24dc31edf52" }, "artifact": { "path": "products/platform/schemas/dev-picker-token.v1alpha1.schema.json", - "sha256": "48d7b5e126091c6eb47b3525d76f592ac6446ebc9dff218988c03c853257d7ed", + "sha256": "2cd7593ef090855baffb9db91d827120976a241a51c3f01a988909d9e98ed71c", "mediaType": "application/schema+json" } }, @@ -5982,7 +5982,7 @@ "description": "Registry Stack local development workload token JSON Schema.", "source": { "path": "crates/registry-platform-yaml-py/src/formats.rs", - "sha256": "48e7f8f4dbe5c7e9a8289b6c5ef3379c82a8e93d951eb18b1b49b19c4151d2e8" + "sha256": "243a5d94ee9059d15287d2872b67983f77ae39e1c6e3e533fdb0a24dc31edf52" }, "artifact": { "path": "products/platform/schemas/dev-workload-token.v1alpha1.schema.json", @@ -6054,7 +6054,7 @@ "description": "Registry Stack Python service connection JSON Schema.", "source": { "path": "crates/registry-platform-yaml-py/src/formats.rs", - "sha256": "48e7f8f4dbe5c7e9a8289b6c5ef3379c82a8e93d951eb18b1b49b19c4151d2e8" + "sha256": "243a5d94ee9059d15287d2872b67983f77ae39e1c6e3e533fdb0a24dc31edf52" }, "artifact": { "path": "products/platform/schemas/python-connection.v1alpha1.schema.json", From 0c5503a5c460937991472d7dc8d26160bdade8fe Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 07:53:56 +0700 Subject: [PATCH 19/34] ci: retain Linux Python wheel for runtime acceptance Signed-off-by: Jeremi Joslin --- .github/workflows/ci.yml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3a936444ac..b3da041e0e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -3449,6 +3449,15 @@ jobs: working-directory: products/coordinator/examples/reviewed-notice run: uv run --locked python -m unittest discover -s tests -v + - name: Retain Linux Python client candidate for runtime acceptance + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: python-client-linux-x64-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ env.REGISTRY_CLIENT_PY_WHEEL }} + if-no-files-found: error + retention-days: 2 + compression-level: 0 + release-linux-node-clients: name: Release Linux native clients (${{ matrix.asset }}) needs: changes From d86e9bcb117dc51c3d8a06aec5baa8ae67e57e8d Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 08:15:56 +0700 Subject: [PATCH 20/34] test(platform): acknowledge JSON configuration formats Signed-off-by: Jeremi Joslin --- .../platform/conformance/yaml/expected-failures.yaml | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/products/platform/conformance/yaml/expected-failures.yaml b/products/platform/conformance/yaml/expected-failures.yaml index aa1fc6c9af..8116333995 100644 --- a/products/platform/conformance/yaml/expected-failures.yaml +++ b/products/platform/conformance/yaml/expected-failures.yaml @@ -69,6 +69,16 @@ unreachedFormats: reason: syntax json; the corpus mutates YAML text - format: messaging/template-contracts reason: syntax json; the corpus mutates YAML text +- format: platform/dev-picker-descriptor + reason: syntax json; the corpus mutates YAML text +- format: platform/dev-picker-generation + reason: syntax json; the corpus mutates YAML text +- format: platform/dev-picker-token + reason: syntax json; the corpus mutates YAML text +- format: platform/dev-workload-token + reason: syntax json; the corpus mutates YAML text +- format: platform/python-connection + reason: syntax json; the corpus mutates YAML text - format: platform/thunderid-session reason: syntax json; the corpus mutates YAML text inapplicableCases: [] From 6debf41a25218e87b4c85296b0e26d2c551d492d Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 09:41:13 +0700 Subject: [PATCH 21/34] docs: include Python grants command in CLI catalog Signed-off-by: Jeremi Joslin --- crates/registry-cli-docs/catalog.json | 81 +++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) diff --git a/crates/registry-cli-docs/catalog.json b/crates/registry-cli-docs/catalog.json index 6443e2b77b..25c84bd598 100644 --- a/crates/registry-cli-docs/catalog.json +++ b/crates/registry-cli-docs/catalog.json @@ -25943,6 +25943,87 @@ } ] }, + { + "name": "grants", + "invocation": "rstack grants", + "about": "Report configured bindings and known profile facts without certifying live grants", + "long_about": null, + "usage": "rstack grants [OPTIONS] ", + "arguments": [ + { + "display": "", + "description": "Python service connection file", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "options": [ + { + "display": "--facts ", + "description": "Product identity facts file; repeat for each known product", + "always_required": false, + "repeatable": true, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--format ", + "description": "Report encoding. Defaults to human even when stdout is piped. Evidence test and fixtures run also accept junit", + "always_required": false, + "repeatable": true, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "--install-root ", + "description": "Installation generation storage directory", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--bin-dir ", + "description": "Directory for the single public rstack executable link", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--asset-dir ", + "description": "Directory of already downloaded, verified release assets", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [], + "subcommands": [] + }, { "name": "dev", "invocation": "rstack dev", From 2f7d74059bd3d10fc39b8eaf40f87b53a49e5bd9 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 10:14:40 +0700 Subject: [PATCH 22/34] fix(coordinator): bind external job receipts to verified callers Signed-off-by: Jeremi Joslin --- products/coordinator/SECURITY-MODEL.md | 9 + .../examples/external-job/README.md | 26 ++- .../examples/external-job/service.py | 208 +++++++++++++++--- .../external-job/tests/acceptance_server.py | 9 +- .../tests/test_acceptance_server.py | 29 ++- .../external-job/tests/test_postgres.py | 169 +++++++++++++- .../external-job/tests/test_service.py | 141 ++++++++---- 7 files changed, 483 insertions(+), 108 deletions(-) diff --git a/products/coordinator/SECURITY-MODEL.md b/products/coordinator/SECURITY-MODEL.md index cba42f8797..b0ecf7551c 100644 --- a/products/coordinator/SECURITY-MODEL.md +++ b/products/coordinator/SECURITY-MODEL.md @@ -188,6 +188,15 @@ The `examples/external-job` Python provider protects both admission and status routes with a separate service connection's machine verifier before reading its application store. Its checked-in Coordinator connection requests an exact service resource and scopes; a browser cookie grants neither route authority. +The application binds the verifier's issuer, resource, subject, client, profile +and persona into an opaque owner digest. Durable admission is unique by that +owner, the stable application operation and the Coordinator command key; the +same input key from another admitted caller cannot recover or conflict with the +first caller's receipt. Status lookup reapplies the owner digest and returns the +same `job-not-found` response for a missing job and another caller's job. The +table stores no raw caller identity. A legacy example table with rows fails +startup because those rows have no provable caller binding; only an empty table +is upgraded in place. An operator running this example must supply a matching issuer registration, service admission policy and assembled Python client. The loopback fixture and synthetic request tests do not prove a live issuer or deployed HTTPS boundary. diff --git a/products/coordinator/examples/external-job/README.md b/products/coordinator/examples/external-job/README.md index b62f435d36..0b3d42d754 100644 --- a/products/coordinator/examples/external-job/README.md +++ b/products/coordinator/examples/external-job/README.md @@ -46,10 +46,12 @@ cannot stop an external job. There is no callback contract. [`service.py`](service.py) is deliberately application code, not a client-library helper. Its PostgreSQL `jobs` row contains the command key, canonical request digest, application work, -stable receipt, and current state. `JobStore.admit` inserts the job and receipt in one database -transaction. Concurrent duplicates contend on the unique key and return the committed receipt. -The same key with another request is a conflict and never selects the earlier receipt as if it -belonged to the changed command. +stable receipt, current state, stable operation and an opaque digest of the verified machine +caller. `JobStore.admit` inserts the job and receipt in one database transaction. Concurrent +duplicates from the same verified caller contend on its caller-operation-key tuple and return the +committed receipt. The same caller and key with another request is a conflict and never selects +the earlier receipt as if it belonged to the changed command. Two admitted callers may choose the +same input key without colliding or receiving each other's receipt. The commit completes before response encoding. If the process stops, the connection drops, or encoding fails after commit, Coordinator sees an uncertain command. Repeating the same command @@ -63,6 +65,15 @@ reading the job store. `JobApplication` passes only the WSGI `Authorization` val missing, malformed, expired or policy-mismatched bearer returns the value-free `authentication.refused` response. A verifier outage returns `authentication.unavailable`. Neither response reaches application work or observation. +The admitted context's issuer, resource, subject, client, profile and persona form the opaque +caller digest. GET applies that same digest to the job lookup, so another admitted caller receives +the ordinary `job-not-found` response rather than the job's existence or state. The raw identity +members are not stored in the application table. + +An older example table has no caller binding. Startup upgrades it only when it is empty. If rows +remain, startup fails closed and tells the operator to keep the old service until those jobs are +terminal, then empty the example table before restarting. It never assigns existing receipts to a +guessed caller. Run the local fixture against a dedicated PostgreSQL database: @@ -101,9 +112,10 @@ admission connection. Copy runtime configuration outside the package and follow Offline scenarios prove the accepted, declared-refusal, uncertain, recovery, terminal and timeout routes through the pinned Functions. The Python unit test covers machine admission on both HTTP routes, no cookie authority, refusal and verifier outage before the store, durable duplicate -semantics, exact observation, and a post-commit encoding failure. Its PostgreSQL test covers -concurrent duplicate admission, crash after commit, stable correlation and terminal state. Run it -only with an explicitly disposable database: +semantics, caller-separated admission and observation, exact observation, and a post-commit +encoding failure. Its PostgreSQL test covers concurrent duplicate admission, crash after commit, +caller separation, stable correlation and terminal state. Run it only with an explicitly +disposable database: ```sh EXTERNAL_JOB_TEST_DATABASE_URL=postgresql://... \ diff --git a/products/coordinator/examples/external-job/service.py b/products/coordinator/examples/external-job/service.py index 130211741c..d74acdd2c0 100644 --- a/products/coordinator/examples/external-job/service.py +++ b/products/coordinator/examples/external-job/service.py @@ -22,6 +22,7 @@ _SCHEMA = re.compile(r"[a-z][a-z0-9_]{0,62}\Z") _STATES = frozenset(("queued", "running", "succeeded", "failed")) +_OPERATION = "external-job.admit/v1" _MAX_BODY_BYTES = 16 * 1024 _MAX_KEY_BYTES = 200 @@ -58,12 +59,14 @@ def migrate(self) -> None: """Create this example's application-owned table.""" from psycopg import sql + schema = sql.Identifier(self._schema) statement = sql.SQL( """ - CREATE SCHEMA IF NOT EXISTS {}; CREATE TABLE IF NOT EXISTS {}.jobs ( job_id uuid PRIMARY KEY, - admission_key varchar(200) NOT NULL UNIQUE, + owner_id char(64) NOT NULL, + operation text NOT NULL CHECK (operation = 'external-job.admit/v1'), + admission_key varchar(200) NOT NULL, request_digest bytea NOT NULL, request_body jsonb NOT NULL, receipt jsonb NOT NULL, @@ -71,15 +74,39 @@ def migrate(self) -> None: CHECK (state IN ('queued', 'running', 'succeeded', 'failed')), created_at timestamptz NOT NULL DEFAULT clock_timestamp(), updated_at timestamptz NOT NULL DEFAULT clock_timestamp(), - CHECK (receipt = jsonb_build_object('jobId', job_id::text)) + CHECK (receipt = jsonb_build_object('jobId', job_id::text)), + CONSTRAINT caller_operation_key_unique + UNIQUE (owner_id, operation, admission_key) ) """ - ).format(sql.Identifier(self._schema), sql.Identifier(self._schema)) + ).format(schema) with self._connect() as connection: + connection.execute(sql.SQL("CREATE SCHEMA IF NOT EXISTS {}").format(schema)) + relation = connection.execute( + "SELECT to_regclass(%s)", (f"{self._schema}.jobs",) + ).fetchone() + if relation is not None and relation[0] is not None: + columns = { + row[0] + for row in connection.execute( + """ + SELECT attname + FROM pg_attribute + WHERE attrelid = %s::regclass + AND attnum > 0 + AND NOT attisdropped + """, + (f"{self._schema}.jobs",), + ) + } + caller_columns = {"owner_id", "operation"} + if not caller_columns.issubset(columns): + self._migrate_empty_legacy_table(connection) connection.execute(statement) def admit( self, + caller: _MachineContext, key: str, request: Mapping[str, object], *, @@ -87,6 +114,7 @@ def admit( ) -> JobReceipt: """Commit the job and its stable receipt in one application transaction.""" self._validate_key(key) + owner_id = _owner_id(caller) request_bytes = _canonical_json(request) request_digest = hashlib.sha256(request_bytes).digest() job_id = str(uuid.uuid4()) @@ -97,14 +125,19 @@ def admit( insert = sql.SQL( """ INSERT INTO {}.jobs - (job_id, admission_key, request_digest, request_body, receipt) - VALUES (%s, %s, %s, %s::jsonb, %s::jsonb) - ON CONFLICT (admission_key) DO NOTHING + (job_id, owner_id, operation, admission_key, request_digest, + request_body, receipt) + VALUES (%s, %s, %s, %s, %s, %s::jsonb, %s::jsonb) + ON CONFLICT (owner_id, operation, admission_key) DO NOTHING RETURNING receipt """ ).format(sql.Identifier(self._schema)) existing = sql.SQL( - "SELECT request_digest, receipt FROM {}.jobs WHERE admission_key = %s" + """ + SELECT request_digest, receipt + FROM {}.jobs + WHERE owner_id = %s AND operation = %s AND admission_key = %s + """ ).format(sql.Identifier(self._schema)) with self._connect() as connection: @@ -113,6 +146,8 @@ def admit( insert, ( job_id, + owner_id, + _OPERATION, key, request_digest, request_bytes.decode("utf-8"), @@ -121,7 +156,7 @@ def admit( ) row = cursor.fetchone() if row is None: - cursor.execute(existing, (key,)) + cursor.execute(existing, (owner_id, _OPERATION, key)) row = cursor.fetchone() if row is None: raise RuntimeError("duplicate admission has no durable receipt") @@ -136,20 +171,21 @@ def admit( after_commit(receipt) return receipt - def status(self, job_id: str) -> str | None: - """Read the current state of one exact durable job.""" + def status(self, caller: _MachineContext, job_id: str) -> str | None: + """Read one exact durable job only for its verified caller.""" try: uuid.UUID(job_id) except (ValueError, AttributeError): return None from psycopg import sql - statement = sql.SQL("SELECT state FROM {}.jobs WHERE job_id = %s").format( - sql.Identifier(self._schema) - ) + owner_id = _owner_id(caller) + statement = sql.SQL( + "SELECT state FROM {}.jobs WHERE owner_id = %s AND job_id = %s" + ).format(sql.Identifier(self._schema)) with self._connect() as connection: with connection.cursor() as cursor: - cursor.execute(statement, (job_id,)) + cursor.execute(statement, (owner_id, job_id)) row = cursor.fetchone() return None if row is None else row[0] @@ -179,6 +215,53 @@ def _connect(self): return psycopg.connect(self._database_url) + def _migrate_empty_legacy_table(self, connection) -> None: + """Upgrade only an empty pre-caller-binding example table.""" + from psycopg import sql + + table = sql.SQL("{}.jobs").format(sql.Identifier(self._schema)) + connection.execute( + sql.SQL("LOCK TABLE {} IN ACCESS EXCLUSIVE MODE").format(table) + ) + columns = { + row[0] + for row in connection.execute( + """ + SELECT attname + FROM pg_attribute + WHERE attrelid = %s::regclass + AND attnum > 0 + AND NOT attisdropped + """, + (f"{self._schema}.jobs",), + ) + } + if {"owner_id", "operation"}.issubset(columns): + return + row = connection.execute( + sql.SQL("SELECT EXISTS (SELECT 1 FROM {})").format(table) + ).fetchone() + if row is None or row[0]: + raise RuntimeError( + "existing external-job rows have no verified caller binding; " + "keep the old example service until they are terminal, then empty " + "the example table before restarting" + ) + connection.execute( + sql.SQL( + """ + ALTER TABLE {} + DROP CONSTRAINT jobs_admission_key_key, + ADD COLUMN owner_id char(64) NOT NULL, + ADD COLUMN operation text NOT NULL, + ADD CONSTRAINT jobs_operation_check + CHECK (operation = 'external-job.admit/v1'), + ADD CONSTRAINT caller_operation_key_unique + UNIQUE (owner_id, operation, admission_key) + """ + ).format(table) + ) + @staticmethod def _validate_key(key: str) -> None: if ( @@ -192,13 +275,27 @@ def _validate_key(key: str) -> None: class _Store(Protocol): - def admit(self, key: str, request: dict[str, object]) -> JobReceipt: ... + def admit( + self, + caller: _MachineContext, + key: str, + request: dict[str, object], + ) -> JobReceipt: ... - def status(self, job_id: str) -> str | None: ... + def status(self, caller: _MachineContext, job_id: str) -> str | None: ... + + +class _MachineContext(Protocol): + issuer: str + resource: str + subject: str + client_id: str + profile: str + persona: str class _MachineAdmission(Protocol): - def admit(self, request_values: Mapping[str, Any]) -> object: ... + def admit(self, request_values: Mapping[str, Any]) -> _MachineContext: ... class JobApplication: @@ -223,15 +320,19 @@ def __call__( method = environ.get("REQUEST_METHOD") path = environ.get("PATH_INFO") if method == "POST" and path == "/jobs": - refused = self._admit_machine(environ, start_response) + caller, refused = self._admit_machine(environ, start_response) if refused is not None: return refused - return self._admit(environ, start_response) + if caller is None: + raise RuntimeError("machine admission returned no caller") + return self._admit(caller, environ, start_response) if method == "GET" and path == "/jobs/status": - refused = self._admit_machine(environ, start_response) + caller, refused = self._admit_machine(environ, start_response) if refused is not None: return refused - return self._status(environ, start_response) + if caller is None: + raise RuntimeError("machine admission returned no caller") + return self._status(caller, environ, start_response) return self._response( start_response, HTTPStatus.NOT_FOUND, {"reason": "route-not-found"} ) @@ -240,30 +341,37 @@ def _admit_machine( self, environ: Mapping[str, Any], start_response: Callable[[str, list[tuple[str, str]]], None], - ) -> Iterable[bytes] | None: + ) -> tuple[_MachineContext | None, Iterable[bytes] | None]: try: - self._machine_admission.admit( + caller = self._machine_admission.admit( {"authorization": environ.get("HTTP_AUTHORIZATION")} ) except Exception as error: code = getattr(error, "code", None) if code == "authentication.refused": - return self._response( - start_response, - HTTPStatus.UNAUTHORIZED, - {"code": "authentication.refused"}, + return ( + None, + self._response( + start_response, + HTTPStatus.UNAUTHORIZED, + {"code": "authentication.refused"}, + ), ) if code == "authentication.unavailable": - return self._response( - start_response, - HTTPStatus.SERVICE_UNAVAILABLE, - {"code": "authentication.unavailable"}, + return ( + None, + self._response( + start_response, + HTTPStatus.SERVICE_UNAVAILABLE, + {"code": "authentication.unavailable"}, + ), ) raise - return None + return caller, None def _admit( self, + caller: _MachineContext, environ: Mapping[str, Any], start_response: Callable[[str, list[tuple[str, str]]], None], ) -> Iterable[bytes]: @@ -295,7 +403,7 @@ def _admit( {"reason": "invalid-job"}, ) try: - receipt = self._store.admit(key, body) + receipt = self._store.admit(caller, key, body) except AdmissionConflict: return self._response( start_response, @@ -312,6 +420,7 @@ def _admit( def _status( self, + caller: _MachineContext, environ: Mapping[str, Any], start_response: Callable[[str, list[tuple[str, str]]], None], ) -> Iterable[bytes]: @@ -332,7 +441,7 @@ def _status( HTTPStatus.BAD_REQUEST, {"reason": "invalid-job-reference"}, ) - state = self._store.status(job_id) + state = self._store.status(caller, job_id) if state is None: return self._response( start_response, @@ -376,6 +485,31 @@ def _canonical_json(value: Mapping[str, object]) -> bytes: raise ValueError("invalid job request") from error +def _owner_id(caller: _MachineContext) -> str: + values = { + "issuer": caller.issuer, + "resource": caller.resource, + "subject": caller.subject, + "client": caller.client_id, + "profile": caller.profile, + "persona": caller.persona, + } + for name, value in values.items(): + _bounded_text(value, name, maximum_bytes=512) + return hashlib.sha256(_canonical_json(values)).hexdigest() + + +def _bounded_text(value: str, name: str, *, maximum_bytes: int) -> None: + if ( + not isinstance(value, str) + or not value + or value.strip() != value + or len(value.encode("utf-8")) > maximum_bytes + or any(ord(character) < 33 or ord(character) == 127 for character in value) + ): + raise RuntimeError(f"verified caller {name} must be bounded text") + + def _encode_json(value: object) -> bytes: return json.dumps(value, separators=(",", ":")).encode("utf-8") @@ -401,7 +535,9 @@ def _valid_job(value: object) -> bool: isinstance(reference, str) and 1 <= len(reference) <= 64 and reference.strip() == reference - and not any(ord(character) < 32 or ord(character) == 127 for character in reference) + and not any( + ord(character) < 32 or ord(character) == 127 for character in reference + ) ) diff --git a/products/coordinator/examples/external-job/tests/acceptance_server.py b/products/coordinator/examples/external-job/tests/acceptance_server.py index 0e52acc7c5..b02be577cc 100644 --- a/products/coordinator/examples/external-job/tests/acceptance_server.py +++ b/products/coordinator/examples/external-job/tests/acceptance_server.py @@ -117,19 +117,20 @@ def __init__(self, store: Any, fault: str): self._store = store self._fault = fault - def admit(self, key: str, request: dict[str, object]) -> JobReceipt: + def admit(self, caller: Any, key: str, request: dict[str, object]) -> JobReceipt: if self._fault == "declared-refusal": raise ValueError("synthetic declared refusal") if self._fault == "process-exit-after-commit": return self._store.admit( + caller, key, request, after_commit=lambda _receipt: os._exit(POST_COMMIT_EXIT_CODE), ) - return self._store.admit(key, request) + return self._store.admit(caller, key, request) - def status(self, job_id: str) -> str | None: - return self._store.status(job_id) + def status(self, caller: Any, job_id: str) -> str | None: + return self._store.status(caller, job_id) def transition(self, job_id: str, state: str) -> None: self._store.transition(job_id, state) diff --git a/products/coordinator/examples/external-job/tests/test_acceptance_server.py b/products/coordinator/examples/external-job/tests/test_acceptance_server.py index 8e7f781502..39f07b390a 100644 --- a/products/coordinator/examples/external-job/tests/test_acceptance_server.py +++ b/products/coordinator/examples/external-job/tests/test_acceptance_server.py @@ -1,6 +1,7 @@ from __future__ import annotations from contextlib import redirect_stderr +from dataclasses import dataclass from http.client import RemoteDisconnected from io import StringIO import json @@ -19,16 +20,23 @@ import acceptance_server # noqa: E402 +@dataclass(frozen=True) +class Caller: + subject: str + + class MemoryStore: def __init__(self) -> None: - self.admissions: dict[str, tuple[dict[str, object], object]] = {} + self.admissions: dict[tuple[str, str], tuple[dict[str, object], object]] = {} self.states: dict[str, str] = {} + self.owners: dict[str, str] = {} self.calls = 0 self.transition_calls = 0 - def admit(self, key, request, *, after_commit=None): + def admit(self, caller, key, request, *, after_commit=None): self.calls += 1 - existing = self.admissions.get(key) + owner_key = (caller.subject, key) + existing = self.admissions.get(owner_key) if existing is not None: original, receipt = existing if original != request: @@ -37,13 +45,16 @@ def admit(self, key, request, *, after_commit=None): receipt = acceptance_server.JobReceipt( f"00000000-0000-0000-0000-{len(self.admissions) + 1:012d}" ) - self.admissions[key] = (dict(request), receipt) + self.admissions[owner_key] = (dict(request), receipt) self.states[receipt.job_id] = "queued" + self.owners[receipt.job_id] = caller.subject if after_commit is not None: after_commit(receipt) return receipt - def status(self, job_id): + def status(self, caller, job_id): + if self.owners.get(job_id) != caller.subject: + return None return self.states.get(job_id) def transition(self, job_id, state): @@ -62,7 +73,7 @@ def snapshot(self): "request": request, "receipt": receipt.as_json(), } - for key, (request, receipt) in self.admissions.items() + for (_, key), (request, receipt) in self.admissions.items() ] @@ -270,7 +281,11 @@ def test_snapshot_requires_machine_admission_before_store_access(self): def test_snapshot_refuses_more_than_sixteen_jobs(self): store = MemoryStore() for index in range(17): - store.admit(f"command-{index}", {"reference": f"case-{index}"}) + store.admit( + Caller("coordinator-service"), + f"command-{index}", + {"reference": f"case-{index}"}, + ) server = acceptance_server.AcceptanceServer(store) server.start() self.addCleanup(server.stop) diff --git a/products/coordinator/examples/external-job/tests/test_postgres.py b/products/coordinator/examples/external-job/tests/test_postgres.py index a3783d0677..7477667816 100644 --- a/products/coordinator/examples/external-job/tests/test_postgres.py +++ b/products/coordinator/examples/external-job/tests/test_postgres.py @@ -1,10 +1,13 @@ from __future__ import annotations from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass import os from pathlib import Path import sys +import threading import unittest +from unittest.mock import patch import uuid @@ -17,6 +20,16 @@ DATABASE_URL = os.environ.get("EXTERNAL_JOB_TEST_DATABASE_URL") +@dataclass(frozen=True) +class MachineContext: + subject: str + client_id: str = "coordinator-client" + profile: str = "coordinator-invoker" + issuer: str = "https://issuer.example.invalid/" + resource: str = "urn:example:external-job" + persona: str = "service" + + @unittest.skipUnless( DATABASE_URL, "EXTERNAL_JOB_TEST_DATABASE_URL must name a disposable PostgreSQL database", @@ -26,11 +39,16 @@ def setUp(self) -> None: self.schema = f"external_job_test_{uuid.uuid4().hex}" self.store = JobStore(DATABASE_URL, schema=self.schema) self.store.migrate() + self.caller = MachineContext("coordinator-a") - def test_concurrent_duplicate_admission_commits_one_job_and_one_receipt(self) -> None: + def test_concurrent_duplicate_admission_commits_one_job_and_one_receipt( + self, + ) -> None: def admit(_: int): return self.store.admit( - "coordinator-command-001", {"reference": "case-001"} + self.caller, + "coordinator-command-001", + {"reference": "case-001"}, ) with ThreadPoolExecutor(max_workers=8) as pool: @@ -49,6 +67,7 @@ def stop_after_commit(receipt): with self.assertRaisesRegex(RuntimeError, "after commit"): self.store.admit( + self.caller, "coordinator-command-001", {"reference": "case-001"}, after_commit=stop_after_commit, @@ -56,38 +75,122 @@ def stop_after_commit(receipt): restarted = JobStore(DATABASE_URL, schema=self.schema) recovered = restarted.admit( - "coordinator-command-001", {"reference": "case-001"} + self.caller, + "coordinator-command-001", + {"reference": "case-001"}, ) self.assertEqual(recovered, committed) self.assertEqual(self._job_count(), 1) def test_duplicate_key_cannot_select_a_different_job(self) -> None: original = self.store.admit( - "coordinator-command-001", {"reference": "case-001"} + self.caller, + "coordinator-command-001", + {"reference": "case-001"}, ) with self.assertRaises(AdmissionConflict): self.store.admit( - "coordinator-command-001", {"reference": "case-002"} + self.caller, "coordinator-command-001", {"reference": "case-002"} ) - self.assertEqual(self.store.status(original.job_id), "queued") + self.assertEqual(self.store.status(self.caller, original.job_id), "queued") self.assertEqual(self._job_count(), 1) def test_worker_state_is_durable_and_terminal(self) -> None: receipt = self.store.admit( - "coordinator-command-001", {"reference": "case-001"} + self.caller, + "coordinator-command-001", + {"reference": "case-001"}, ) - self.assertEqual(self.store.status(receipt.job_id), "queued") + self.assertEqual(self.store.status(self.caller, receipt.job_id), "queued") self.store.transition(receipt.job_id, "running") - self.assertEqual(self.store.status(receipt.job_id), "running") + self.assertEqual(self.store.status(self.caller, receipt.job_id), "running") self.store.transition(receipt.job_id, "succeeded") self.assertEqual( - JobStore(DATABASE_URL, schema=self.schema).status(receipt.job_id), + JobStore(DATABASE_URL, schema=self.schema).status( + self.caller, receipt.job_id + ), "succeeded", ) with self.assertRaisesRegex(ValueError, "invalid job transition"): self.store.transition(receipt.job_id, "failed") + def test_verified_callers_have_separate_keys_and_cannot_cross_read(self) -> None: + first_caller = MachineContext("coordinator-a") + second_caller = MachineContext("coordinator-b") + + first = self.store.admit( + first_caller, + "shared-command", + {"reference": "case-shared"}, + ) + second = self.store.admit( + second_caller, + "shared-command", + {"reference": "case-shared"}, + ) + + self.assertNotEqual(first, second) + self.assertEqual(self.store.status(first_caller, first.job_id), "queued") + self.assertIsNone(self.store.status(first_caller, second.job_id)) + self.assertIsNone(self.store.status(second_caller, first.job_id)) + self.assertEqual(self.store.status(second_caller, second.job_id), "queued") + self.assertEqual(self._job_count(), 2) + + def test_empty_legacy_table_upgrades_without_guessing_an_owner(self) -> None: + schema = f"external_job_legacy_empty_{uuid.uuid4().hex}" + self._create_legacy_table(schema) + store = JobStore(DATABASE_URL, schema=schema) + + store.migrate() + receipt = store.admit( + self.caller, + "coordinator-command-001", + {"reference": "case-001"}, + ) + + self.assertEqual(store.status(self.caller, receipt.job_id), "queued") + + def test_concurrent_empty_legacy_upgrade_rechecks_after_the_table_lock( + self, + ) -> None: + schema = f"external_job_legacy_concurrent_{uuid.uuid4().hex}" + self._create_legacy_table(schema) + stores = [ + JobStore(DATABASE_URL, schema=schema), + JobStore(DATABASE_URL, schema=schema), + ] + entered = threading.Barrier(2) + migrate_legacy = JobStore._migrate_empty_legacy_table + + def synchronized_migration(store, connection): + entered.wait(timeout=5) + return migrate_legacy(store, connection) + + with patch.object( + JobStore, + "_migrate_empty_legacy_table", + synchronized_migration, + ): + with ThreadPoolExecutor(max_workers=2) as pool: + list(pool.map(lambda store: store.migrate(), stores)) + + receipt = stores[0].admit( + self.caller, + "coordinator-command-001", + {"reference": "case-001"}, + ) + self.assertEqual(stores[1].status(self.caller, receipt.job_id), "queued") + + def test_populated_legacy_table_fails_closed_without_an_owner_binding(self) -> None: + schema = f"external_job_legacy_populated_{uuid.uuid4().hex}" + self._create_legacy_table(schema, populated=True) + + with self.assertRaisesRegex( + RuntimeError, "rows have no verified caller binding" + ): + JobStore(DATABASE_URL, schema=schema).migrate() + def _job_count(self) -> int: import psycopg from psycopg import sql @@ -103,6 +206,52 @@ def _job_count(self) -> int: assert row is not None return row[0] + @staticmethod + def _create_legacy_table(schema: str, *, populated: bool = False) -> None: + import psycopg + from psycopg import sql + + statement = sql.SQL( + """ + CREATE TABLE {}.jobs ( + job_id uuid PRIMARY KEY, + admission_key varchar(200) NOT NULL UNIQUE, + request_digest bytea NOT NULL, + request_body jsonb NOT NULL, + receipt jsonb NOT NULL, + state text NOT NULL DEFAULT 'queued' + CHECK (state IN ('queued', 'running', 'succeeded', 'failed')), + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + updated_at timestamptz NOT NULL DEFAULT clock_timestamp(), + CHECK (receipt = jsonb_build_object('jobId', job_id::text)) + ) + """ + ).format(sql.Identifier(schema)) + with psycopg.connect(DATABASE_URL) as connection: + connection.execute( + sql.SQL("CREATE SCHEMA {}").format(sql.Identifier(schema)) + ) + connection.execute(statement) + if populated: + job_id = uuid.uuid4() + connection.execute( + sql.SQL( + """ + INSERT INTO {}.jobs ( + job_id, admission_key, request_digest, + request_body, receipt + ) VALUES (%s, %s, %s, %s::jsonb, %s::jsonb) + """ + ).format(sql.Identifier(schema)), + ( + job_id, + "legacy-command", + b"legacy-digest", + '{"reference":"legacy"}', + f'{{"jobId":"{job_id}"}}', + ), + ) + if __name__ == "__main__": unittest.main() diff --git a/products/coordinator/examples/external-job/tests/test_service.py b/products/coordinator/examples/external-job/tests/test_service.py index 0dc705754d..2c7b878792 100644 --- a/products/coordinator/examples/external-job/tests/test_service.py +++ b/products/coordinator/examples/external-job/tests/test_service.py @@ -1,5 +1,6 @@ from __future__ import annotations +from dataclasses import dataclass from io import BytesIO import json from pathlib import Path @@ -15,27 +16,30 @@ class MemoryStore: def __init__(self) -> None: - self.admissions: dict[str, tuple[dict[str, object], JobReceipt]] = {} - self.states: dict[str, str] = {} + self.admissions: dict[ + tuple[str, str], tuple[dict[str, object], JobReceipt] + ] = {} + self.states: dict[tuple[str, str], str] = {} self.calls = 0 self.status_calls = 0 - def admit(self, key: str, request: dict[str, object]) -> JobReceipt: + def admit(self, caller, key: str, request: dict[str, object]) -> JobReceipt: self.calls += 1 - existing = self.admissions.get(key) + owner_key = (caller.subject, key) + existing = self.admissions.get(owner_key) if existing is not None: original, receipt = existing if original != request: raise AdmissionConflict() return receipt receipt = JobReceipt(job_id=f"job-{len(self.admissions) + 1}") - self.admissions[key] = (request, receipt) - self.states[receipt.job_id] = "queued" + self.admissions[owner_key] = (request, receipt) + self.states[(caller.subject, receipt.job_id)] = "queued" return receipt - def status(self, job_id: str) -> str | None: + def status(self, caller, job_id: str) -> str | None: self.status_calls += 1 - return self.states.get(job_id) + return self.states.get((caller.subject, job_id)) class AdmissionFailure(ValueError): @@ -54,12 +58,26 @@ def admit(self, values: dict[str, object]) -> object: self.calls.append(values) authorization = values.get("authorization") if authorization == "Bearer coordinator": - return object() + return MachineContext("coordinator") + if authorization == "Bearer coordinator-a": + return MachineContext("coordinator-a") + if authorization == "Bearer coordinator-b": + return MachineContext("coordinator-b") if authorization == "Bearer unavailable-canary": raise AdmissionUnavailable() raise AdmissionFailure() +@dataclass(frozen=True) +class MachineContext: + subject: str + client_id: str = "coordinator-client" + profile: str = "coordinator-invoker" + issuer: str = "https://issuer.example.invalid/" + resource: str = "urn:example:external-job" + persona: str = "service" + + def request( app: JobApplication, method: str, @@ -99,13 +117,36 @@ def start_response(status: str, headers: list[tuple[str, str]]) -> None: ) +def get_url(app, url, *, authorization): + path, _, query = url.partition("?") + captured = {} + + def start_response(status, headers): + captured["status"] = status + captured["headers"] = dict(headers) + + environ = { + "REQUEST_METHOD": "GET", + "PATH_INFO": path, + "QUERY_STRING": query, + "CONTENT_LENGTH": "0", + "wsgi.input": BytesIO(), + } + if authorization is not None: + environ["HTTP_AUTHORIZATION"] = authorization + payload = b"".join(app(environ, start_response)) + return captured["status"], captured["headers"], json.loads(payload) + + class JobApplicationTests(unittest.TestCase): def setUp(self) -> None: self.store = MemoryStore() self.admission = MachineAdmission() self.app = JobApplication(self.store, self.admission) - def test_post_requires_machine_admission_before_reading_or_storing_work(self) -> None: + def test_post_requires_machine_admission_before_reading_or_storing_work( + self, + ) -> None: for authorization, cookie in ( (None, None), (None, "session=Bearer coordinator"), @@ -137,9 +178,7 @@ def test_post_requires_machine_admission_before_reading_or_storing_work(self) -> ) def test_get_requires_machine_admission_before_observing_a_job(self) -> None: - status, _, body = self._request_url( - "/jobs/status?id=job-1", authorization=None - ) + status, _, body = self._request_url("/jobs/status?id=job-1", authorization=None) self.assertEqual(status, "401 Unauthorized") self.assertEqual(body, {"code": "authentication.refused"}) @@ -218,7 +257,7 @@ def test_status_reads_the_exact_admitted_job(self) -> None: body={"reference": "case-001"}, ) job_id = receipt["jobId"] - self.store.states[job_id] = "running" + self.store.states[("coordinator", job_id)] = "running" environ_path = f"/jobs/status?id={job_id}" status, _, body = self._request_url(environ_path) @@ -237,20 +276,20 @@ def test_invalid_work_is_refused_before_admission(self) -> None: ("coordinator-command-001", {"reference": "case-001", "extra": True}), ]: with self.subTest(key=key, body=body): - status, _, _ = request( - self.app, "POST", "/jobs", key=key, body=body - ) + status, _, _ = request(self.app, "POST", "/jobs", key=key, body=body) self.assertIn(status.split(" ", 1)[0], ("400", "422")) self.assertEqual(self.store.calls, 0) - def test_response_encoding_failure_leaves_the_committed_receipt_recoverable(self) -> None: + def test_response_encoding_failure_leaves_the_committed_receipt_recoverable( + self, + ) -> None: def broken_encoder(_: object) -> bytes: raise UnicodeError("synthetic response encoding failure") - broken = JobApplication( - self.store, self.admission, encode_json=broken_encoder - ) - with self.assertRaisesRegex(UnicodeError, "synthetic response encoding failure"): + broken = JobApplication(self.store, self.admission, encode_json=broken_encoder) + with self.assertRaisesRegex( + UnicodeError, "synthetic response encoding failure" + ): request( broken, "POST", @@ -270,34 +309,48 @@ def broken_encoder(_: object) -> bytes: self.assertEqual(body, {"jobId": "job-1"}) self.assertEqual(len(self.store.admissions), 1) + def test_verified_caller_namespaces_admission_and_status(self) -> None: + first = request( + self.app, + "POST", + "/jobs", + key="shared-command", + body={"reference": "case-shared"}, + authorization="Bearer coordinator-a", + ) + second = request( + self.app, + "POST", + "/jobs", + key="shared-command", + body={"reference": "case-shared"}, + authorization="Bearer coordinator-b", + ) + + self.assertEqual(first[0], "201 Created") + self.assertEqual(second[0], "201 Created") + self.assertNotEqual(first[2], second[2]) + hidden = get_url( + self.app, + f"/jobs/status?id={first[2]['jobId']}", + authorization="Bearer coordinator-b", + ) + visible = get_url( + self.app, + f"/jobs/status?id={first[2]['jobId']}", + authorization="Bearer coordinator-a", + ) + self.assertEqual(hidden[0], "404 Not Found") + self.assertEqual(hidden[2], {"reason": "job-not-found"}) + self.assertEqual(visible[2], {**first[2], "state": "queued"}) + def _request_url( self, url: str, *, authorization: str | None = "Bearer coordinator", ) -> tuple[str, dict[str, str], object]: - path, _, query = url.partition("?") - captured: dict[str, object] = {} - - def start_response(status: str, headers: list[tuple[str, str]]) -> None: - captured["status"] = status - captured["headers"] = dict(headers) - - environ = { - "REQUEST_METHOD": "GET", - "PATH_INFO": path, - "QUERY_STRING": query, - "CONTENT_LENGTH": "0", - "wsgi.input": BytesIO(), - } - if authorization is not None: - environ["HTTP_AUTHORIZATION"] = authorization - payload = b"".join(self.app(environ, start_response)) - return ( - captured["status"], - captured["headers"], - json.loads(payload), - ) + return get_url(self.app, url, authorization=authorization) if __name__ == "__main__": From 7c2491df6e69eb977431b225b3259c2e09e87b23 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 10:14:51 +0700 Subject: [PATCH 23/34] feat(platform): add FastAPI machine service and lifecycle guidance Signed-off-by: Jeremi Joslin --- .../examples/python-composition/README.md | 8 +- .../examples/python-machine-service/README.md | 86 +++- .../python-machine-service/pyproject.toml | 20 +- .../python-machine-service/service.py | 136 +++++- .../tests/test_service.py | 320 +++++++++++++- .../examples/python-machine-service/uv.lock | 398 +++++++++++++++++- .../platform/examples/python-portal/README.md | 42 +- .../platform/examples/python-script/README.md | 25 ++ 8 files changed, 1003 insertions(+), 32 deletions(-) diff --git a/products/platform/examples/python-composition/README.md b/products/platform/examples/python-composition/README.md index d4ced18858..fb06493f4f 100644 --- a/products/platform/examples/python-composition/README.md +++ b/products/platform/examples/python-composition/README.md @@ -32,10 +32,10 @@ application calls `connect()` and uses the default `stack.breg` and `stack.messaging` bindings; it does not construct either client or handle their bearer tokens. -Casework deliberately remains on its existing path in this L1 migration. Its -URL and token provider remain in the application config, and every Casework call -still supplies that provider's bearer. For this remaining provider, a -`privateKeyJwt` object uses the released canonical helper's `token_endpoint`, +Casework deliberately remains on its existing explicit token-provider path in +this example. Its URL and token provider remain in the application config, and +every Casework call still supplies that provider's bearer. A `privateKeyJwt` +object uses the released canonical helper's `token_endpoint`, `client_id`, `client_key`, `resource`, and `scopes` settings instead of a `headerFile`. Its optional `audience` identifies the OAuth token endpoint as the client assertion's recipient. It is distinct from `resource`, which requests diff --git a/products/platform/examples/python-machine-service/README.md b/products/platform/examples/python-machine-service/README.md index 3ddcc5ebea..7bffa1bc50 100644 --- a/products/platform/examples/python-machine-service/README.md +++ b/products/platform/examples/python-machine-service/README.md @@ -1,6 +1,6 @@ # Keyed Python machine-service effect -This reference shows a Flask machine endpoint performing one keyed Registry Messaging effect through the `registry-stack-client` wheel. +This reference shows Flask and FastAPI machine endpoints performing one keyed Registry Messaging effect through the `registry-stack-client` wheel. It separates the verified Coordinator caller from the service's Messaging workload authority, keeps recipients and templates in protected application state, and recovers an uncertain submission without sending it again. It targets the candidate Python service APIs in this checkout. It is not a published capability until the assembled wheel and release evidence say so. @@ -12,7 +12,7 @@ The endpoint accepts only this caller command: ``` It does not accept a bearer for Messaging, recipient, template, binding, URL, subject, scope, or workload profile. -The Flask adapter verifies the service caller and supplies an immutable `MachineContext`. +Each framework adapter verifies the service caller and supplies an immutable `MachineContext`. `registry_client.connect()` selects the default or declared named Messaging binding and supplies its workload credential internally. ## Effect and recovery contract @@ -44,26 +44,29 @@ The response is deliberately small: | `422` | `refused` | Input or a typed Messaging problem established that this command caused no effect. | | `429` | `not-processed` | Local submission capacity was unavailable before this command started a native effect. | -An unusable response after Messaging accepted the command remains recoverable because the receipt is committed before Flask encodes the response. +An unusable response after Messaging accepted the command remains recoverable because the receipt is committed before either framework encodes the response. The Coordinator `external.command/v1` interpreter should declare only the `200 accepted`, `422 refused`, and `429 not-processed` shapes. Every other status or shape remains uncertain. -`MessageEffect` emits one structured application audit event for each returned command result and changed-command conflict. Its fields are the operation, a deployment-keyed HMAC caller reference, the configured workload-authority fingerprint, the recovery reference, and the outcome. Recipients, templates, request bodies, credentials, and exception messages are absent. `create_app` requires an injected audit sink; the environment factory writes each bounded JSON event to stderr, which the deployment must capture. Keep the audit key stable for cross-command correlation; rotating it changes only the audit reference, not command recovery. This example does not provide durable, append-only audit storage. Messaging's own audit remains the product record of native acceptance and delivery. +`MessageEffect` emits one structured application audit event for each returned command result and changed-command conflict. Its fields are the operation, a deployment-keyed HMAC caller reference, the configured workload-authority fingerprint, the recovery reference, and the outcome. Recipients, templates, request bodies, credentials, and exception messages are absent. Both application factories require an injected audit sink; the environment factories write each bounded JSON event to stderr, which the deployment must capture. Keep the audit key stable for cross-command correlation; rotating it changes only the audit reference, not command recovery. This example does not provide durable, append-only audit storage. Messaging's own audit remains the product record of native acceptance and delivery. ## Configure the service Use Python 3.11 or later and the assembled `registry-stack-client` wheel from the same Registry Stack source or release as the services. The source facade directory is not a substitute for that wheel. -Install Flask from this project's lock, then supply the matching wheel explicitly: +Install the Flask server from this project's lock, then supply the matching wheel explicitly: ```sh -uv sync --locked +uv sync --locked --no-dev --extra flask sdk='registry-stack-client==' # Prepared source candidates may use an absolute wheel path instead. -uv run --locked --with "$sdk" python service.py +uv run --locked --no-dev --extra flask --with "$sdk" python service.py ``` +That last command starts the loopback Flask development runner. For FastAPI, +use the worker factory in [Run after the server forks](#run-after-the-server-forks). + Set these variables before starting the process: - `REGISTRY_STACK_CONNECTION` names the owner-only service connection consumed by `connect()`. @@ -87,13 +90,72 @@ The non-secret fingerprint covers the product and the connection's declared issu It deliberately excludes the binding alias, endpoint URL, token endpoint, and client-key reference. Renaming an alias, moving an endpoint, or rotating a key while retaining the same authority therefore preserves receipt recovery. Changing any covered declaration changes the fingerprint and makes a stale target mapping fail application construction, before any effect is attempted under another declared identity. -The connection does not inspect bearer bytes, so this proves continuity of the closed operator declaration, not that an issuer emitted matching claims. -A live issuer and Messaging recovery check remains required before claiming effective issuer/subject continuity under L2-04. +The connection does not inspect bearer bytes, so this proves continuity of the +closed operator declaration, not that an issuer emitted matching claims. +A live issuer and Messaging recovery check remains required before claiming +continuity of the effective issuer and subject. + +## Durable jobs use a separate recovery boundary + +The [Coordinator external-job example](../../../coordinator/examples/external-job/README.md) +admits an application-owned job and its stable receipt in one PostgreSQL +transaction. Coordinator repeats only the frozen admission command after an +uncertain response, then observes the saved job ID through `external.get/v1` +within a bounded wait. Admission means the job exists; an observation timeout +does not mean it failed or was cancelled. Use that pattern for work that should +outlive one HTTP request. This Messaging example demonstrates recovery of one +immediate keyed product effect. + +## Run after the server forks Construct the application inside each server worker after fork. -The module imports no native client at import time, and `create_app_from_environment()` calls `connect()` during application construction. +The module imports no native client at import time. Both environment factories +call `connect()` during application construction. The built-in `app.run` path is a loopback development runner, not the production server recipe. +The `flask` extra includes Gunicorn. Use the application factory without +Gunicorn's preload mode: + +```sh +uv run --locked --no-dev --extra flask --with "$sdk" gunicorn --bind 127.0.0.1:9011 --workers 2 \ + 'service:create_app_from_environment()' +``` + +The separate `fastapi` extra includes Uvicorn. Install it and use factory mode: + +```sh +uv sync --locked --no-dev --extra fastapi +uv run --locked --no-dev --extra fastapi --with "$sdk" uvicorn --factory \ + service:create_fastapi_app_from_environment \ + --host 127.0.0.1 --port 9011 +``` + +Keep the listener on a protected network or behind the deployment's TLS edge. +Do not add Gunicorn's `--preload` option: constructing the application in the +master would call `connect()` before worker fork. +Worker replacement constructs a new connection and native clients inside the +replacement worker. + +## Request budgets and blocking calls + +Both framework factories install a two-second request budget by default. +The workload wrapper checks this budget before each Registry Stack native call +and refuses to start another call after the budget ends. +The budget does not cancel a native call that already started, stop application +database work or arbitrary network calls, or guarantee that the handler returns +within two seconds. +A native call may therefore finish after the budget. +If the response to a Messaging submission is lost, preserve the stored `unknown` +state and recover the original receipt with the same key and request. +Do not submit a replacement command. + +Registry Stack native calls are synchronous. +The Flask and FastAPI effect routes therefore use synchronous handlers. +In another FastAPI route, use a synchronous `def` handler or explicitly call the +native operation through `asyncio.to_thread`; a direct native call on the +event-loop thread raises an error instead of blocking silently. +The FastAPI adapter already offloads caller admission. + ## Populate protected notice state `MessageEffectStore.put_notice` represents an earlier application transaction. @@ -107,7 +169,7 @@ A multi-host deployment should implement the same transitions in its application ## Verify -Run the pure-Python recovery and Flask boundary tests: +Run the pure-Python recovery and both framework boundary tests: ```sh uv run --locked python -W error::ResourceWarning -m unittest discover -s tests -p 'test_*.py' -v @@ -115,7 +177,7 @@ ruff format --check . ruff check . ``` -The tests cover exact protected-request forwarding, bounded duplicate-free JSON input, two configured bindings, caller-separated keys, changed-command conflicts, concurrent duplicates, native declared refusal, unknown outcome, process stop after acceptance, restart recovery, response-encoding failure, authority rename versus replacement, expired receipt behavior, machine admission, the pre-effect-only `429` rule, and minimized application audit correlation. +The tests cover exact protected-request forwarding, bounded duplicate-free JSON input, oversized streamed FastAPI bodies, two configured bindings, caller-separated keys, changed-command conflicts, concurrent duplicates, native declared refusal, unknown outcome, process stop after acceptance, restart recovery, response-encoding failure, authority rename versus replacement, expired receipt behavior, machine admission, the pre-effect-only `429` rule, and minimized application audit correlation. They use protocol doubles and do not establish a real issuer, Messaging, Coordinator, built-wheel, Linux, or multi-host result. Complete acceptance still needs the matching assembled wheel, a real machine token, two real workload bindings, Messaging product denials and receipts, and Coordinator's actual `external.command/v1` interpretation and same-command recovery path. diff --git a/products/platform/examples/python-machine-service/pyproject.toml b/products/platform/examples/python-machine-service/pyproject.toml index 6f98dcedad..ee3c7dac4b 100644 --- a/products/platform/examples/python-machine-service/pyproject.toml +++ b/products/platform/examples/python-machine-service/pyproject.toml @@ -2,9 +2,27 @@ name = "registry-python-machine-service" version = "0.1.0" requires-python = ">=3.11" -dependencies = [ +dependencies = [] + +[project.optional-dependencies] +flask = [ "flask==3.1.2", + "gunicorn>=23,<24", +] +fastapi = [ + "fastapi>=0.115,<1", + "uvicorn>=0.34,<1", ] [tool.uv] package = false + +[dependency-groups] +dev = [ + "fastapi>=0.115,<1", + "flask==3.1.2", + "gunicorn>=23,<24", + "httpx>=0.28,<1", + "ruff==0.14.3", + "uvicorn>=0.34,<1", +] diff --git a/products/platform/examples/python-machine-service/service.py b/products/platform/examples/python-machine-service/service.py index 048f4e0390..c0aa307683 100644 --- a/products/platform/examples/python-machine-service/service.py +++ b/products/platform/examples/python-machine-service/service.py @@ -1,6 +1,4 @@ -"""Flask machine endpoint for the keyed Messaging effect example.""" - -from __future__ import annotations +"""Flask and FastAPI endpoints for the keyed Messaging effect example.""" import json import os @@ -84,8 +82,90 @@ def message_effect(): return app +def create_fastapi_app( + *, + database_path: str | Path, + service_namespace: str, + audit_key: bytes, + audit_sink: Callable[[Mapping[str, str]], None], + targets: Mapping[str, str | None], + stack: Any | None = None, + request_seconds: float = 2.0, + maximum_inflight_submissions: int = 32, +): + """Construct clients after worker start and protect FastAPI routes by default.""" + from fastapi import Depends, FastAPI, Request + from fastapi.responses import JSONResponse + from registry_client import connect, fastapi_adapter, web + + if stack is None: + stack = connect() + if not callable(audit_sink): + raise ValueError("audit_sink must be callable") + store = MessageEffectStore(database_path) + store.migrate() + effect = MessageEffect( + store, + MessagingTargets(stack, targets), + service_namespace=service_namespace, + audit_key=audit_key, + audit_sink=audit_sink, + maximum_inflight_submissions=maximum_inflight_submissions, + ) + app = FastAPI() + app.state.registry_message_effect_store = store + + @app.get("/healthz") + @web.public + def healthz(): + return _fastapi_response(JSONResponse, 200, {"status": "ok"}) + + async def command_body(request: Request): + return await _read_fastapi_command(request) + + @app.post("/v1/message-effects") + def message_effect(request: Request, body: Any = Depends(command_body)): + if not _valid_command(body): + return _fastapi_response( + JSONResponse, + 422, + {"state": "refused", "code": "invalid-command"}, + ) + try: + result = effect.execute( + request.state.registry_context, + body["key"], + body["noticeId"], + ) + except NoticeNotFound: + return _fastapi_response( + JSONResponse, + 422, + {"state": "refused", "code": "notice-not-found"}, + ) + except CommandConflict as error: + return _fastapi_response( + JSONResponse, + 409, + {"state": "uncertain", "recovery": error.recovery}, + ) + return _fastapi_response(JSONResponse, result.status, result.body) + + fastapi_adapter.install(app, stack, request_seconds=request_seconds) + return app + + def create_app_from_environment(): """Load non-secret example settings; `connect()` owns credential references.""" + return create_app(**_environment_arguments()) + + +def create_fastapi_app_from_environment(): + """Load settings and construct one FastAPI worker after process startup.""" + return create_fastapi_app(**_environment_arguments()) + + +def _environment_arguments() -> dict[str, Any]: database_path = os.environ.get("MESSAGE_EFFECT_DATABASE") service_namespace = os.environ.get("MESSAGE_EFFECT_SERVICE_NAMESPACE") raw_audit_key = os.environ.get("MESSAGE_EFFECT_AUDIT_KEY_HEX") @@ -118,13 +198,13 @@ def create_app_from_environment(): raise RuntimeError( "MESSAGE_EFFECT_TARGETS must map authority IDs to binding names or null" ) - return create_app( - database_path=database_path, - service_namespace=service_namespace, - audit_key=audit_key, - audit_sink=_stderr_audit, - targets=targets, - ) + return { + "database_path": database_path, + "service_namespace": service_namespace, + "audit_key": audit_key, + "audit_sink": _stderr_audit, + "targets": targets, + } def _stderr_audit(event: Mapping[str, str]) -> None: @@ -162,7 +242,36 @@ def _read_command(request) -> Any: raw = request.get_data(cache=False) if len(raw) != length: return None + return _decode_command(raw) + + +async def _read_fastapi_command(request) -> Any: + lengths = request.headers.getlist("content-length") + if len(lengths) != 1: + return None + try: + length = int(lengths[0]) + except (TypeError, ValueError): + return None + if ( + request.headers.get("content-type", "").split(";", 1)[0].strip().lower() + != "application/json" + or not 1 <= length <= _MAXIMUM_COMMAND_BYTES + ): + return None + raw = bytearray() + async for chunk in request.stream(): + if len(chunk) > length - len(raw) or len(chunk) > _MAXIMUM_COMMAND_BYTES - len( + raw + ): + return None + raw.extend(chunk) + if len(raw) != length: + return None + return _decode_command(bytes(raw)) + +def _decode_command(raw: bytes) -> Any: def unique_members(pairs): value = {} for name, member in pairs: @@ -186,5 +295,12 @@ def _response(jsonify, status: int, body: Mapping[str, Any]): return response +def _fastapi_response(response_type, status: int, body: Mapping[str, Any]): + headers = {"Cache-Control": "no-store"} + if status == 429: + headers["Retry-After"] = "1" + return response_type(body, status_code=status, headers=headers) + + if __name__ == "__main__": create_app_from_environment().run(host="127.0.0.1", port=9011, debug=False) diff --git a/products/platform/examples/python-machine-service/tests/test_service.py b/products/platform/examples/python-machine-service/tests/test_service.py index 8420590aa4..a21ace1c5f 100644 --- a/products/platform/examples/python-machine-service/tests/test_service.py +++ b/products/platform/examples/python-machine-service/tests/test_service.py @@ -1,5 +1,6 @@ from __future__ import annotations +import asyncio from contextlib import redirect_stderr import importlib from io import StringIO @@ -8,10 +9,14 @@ from pathlib import Path import sys import tempfile +import threading +import tomllib import types import unittest from unittest.mock import patch +import httpx + EXAMPLE = Path(__file__).resolve().parents[1] TESTS = Path(__file__).resolve().parent @@ -23,7 +28,12 @@ sys.path.insert(0, str(TESTS)) from effect import MessageEffectStore # noqa: E402 -from service import create_app, create_app_from_environment # noqa: E402 +from service import ( # noqa: E402 + create_app, + create_app_from_environment, + create_fastapi_app, + create_fastapi_app_from_environment, +) from test_effect import Authority, FakeMessaging, FakeMessagingError, message # noqa: E402 @@ -39,7 +49,10 @@ def load_client_module(name: str): machine = load_client_module("machine") +fastapi_adapter = load_client_module("fastapi_adapter") flask_adapter = load_client_module("flask_adapter") +web = load_client_module("web") +workload = load_client_module("workload") class Stack: @@ -89,6 +102,30 @@ def authority(self, product): return self.primary_authority +class PackagingTests(unittest.TestCase): + def test_framework_servers_are_separate_extras_and_dev_installs_both(self) -> None: + with (EXAMPLE / "pyproject.toml").open("rb") as source: + project = tomllib.load(source) + + metadata = project["project"] + self.assertEqual(metadata.get("dependencies", []), []) + extras = metadata["optional-dependencies"] + self.assertEqual(set(extras), {"fastapi", "flask"}) + self.assertEqual( + set(extras["flask"]), + {"flask==3.1.2", "gunicorn>=23,<24"}, + ) + self.assertEqual( + set(extras["fastapi"]), + {"fastapi>=0.115,<1", "uvicorn>=0.34,<1"}, + ) + dev = set(project["dependency-groups"]["dev"]) + self.assertTrue(set(extras["flask"]).issubset(dev)) + self.assertTrue(set(extras["fastapi"]).issubset(dev)) + self.assertIn("httpx>=0.28,<1", dev) + self.assertIn("ruff==0.14.3", dev) + + class MachineServiceTests(unittest.TestCase): def setUp(self) -> None: self.temporary = tempfile.TemporaryDirectory() @@ -385,5 +422,286 @@ def fail_accepted(value, **kwargs): self.assertEqual(len(self.stack.primary.submit_calls), 1) +class FastAPIMachineServiceTests(unittest.TestCase): + def setUp(self) -> None: + self.temporary = tempfile.TemporaryDirectory() + self.database = Path(self.temporary.name) / "effects.sqlite3" + self.stack = Stack() + self.connect_calls = 0 + + registry_client = types.ModuleType("registry_client") + + def connect(): + self.connect_calls += 1 + return self.stack + + registry_client.connect = connect + registry_client.fastapi_adapter = fastapi_adapter + registry_client.web = web + self.prior_registry_client = sys.modules.get("registry_client") + sys.modules["registry_client"] = registry_client + + self.audit = [] + self.app = create_fastapi_app( + database_path=self.database, + service_namespace="urn:example:service:renewal-notices", + audit_key=b"A" * 32, + audit_sink=self.audit.append, + targets={ + "a" * 64: None, + "b" * 64: "secondary", + }, + ) + self.store: MessageEffectStore = self.app.state.registry_message_effect_store + self.context = machine.MachineContext( + "caller-a", + "coordinator-client", + "coordinator-invoker", + "https://issuer.example.invalid/", + "urn:registry:python:test", + ) + + def tearDown(self) -> None: + if self.prior_registry_client is None: + sys.modules.pop("registry_client", None) + else: + sys.modules["registry_client"] = self.prior_registry_client + self.temporary.cleanup() + + def seed(self, notice_id, payload, authority="a" * 64): + self.store.put_notice( + self.context, + notice_id, + authority, + payload, + service_namespace="urn:example:service:renewal-notices", + ) + + async def request(self, method, path, **kwargs): + transport = httpx.ASGITransport(app=self.app) + async with httpx.AsyncClient( + transport=transport, + base_url="http://testserver", + ) as client: + return await client.request(method, path, **kwargs) + + def post(self, body, *, bearer="caller-a"): + return asyncio.run( + self.request( + "POST", + "/v1/message-effects", + json=body, + headers={"Authorization": f"Bearer {bearer}"}, + ) + ) + + def test_factory_uses_connect_and_sync_handler_for_native_effect(self) -> None: + self.seed("notice-1", message("person@example.invalid")) + effect_thread = [] + request_deadline = [] + running_loop = [] + original_submit = self.stack.primary.submit + + def observe_submit(key, payload): + effect_thread.append(threading.get_ident()) + request_deadline.append(workload._deadline.get()) + workload._require_sync() + try: + asyncio.get_running_loop() + except RuntimeError: + running_loop.append(False) + else: + running_loop.append(True) + return original_submit(key, payload) + + self.stack.primary.submit = observe_submit + + async def exercise(): + loop_thread = threading.get_ident() + response = await self.request( + "POST", + "/v1/message-effects", + json={"key": "command-1", "noticeId": "notice-1"}, + headers={"Authorization": "Bearer caller-a"}, + ) + return response, loop_thread + + response, loop_thread = asyncio.run(exercise()) + + self.assertEqual(self.connect_calls, 1) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()["state"], "accepted") + self.assertEqual(response.headers["Cache-Control"], "no-store") + self.assertEqual(running_loop, [False]) + self.assertIsInstance(request_deadline[0], float) + self.assertNotEqual(effect_thread, [loop_thread]) + self.assertEqual( + self.stack.admission_calls[-1], + {"authorization": ["Bearer caller-a"]}, + ) + + def test_missing_or_invalid_bearer_is_refused_before_effect(self) -> None: + self.seed("notice-1", message("person@example.invalid")) + command = {"key": "command-1", "noticeId": "notice-1"} + + missing = asyncio.run(self.request("POST", "/v1/message-effects", json=command)) + cookie = asyncio.run( + self.request( + "POST", + "/v1/message-effects", + json=command, + headers={"Cookie": "session=canary"}, + ) + ) + invalid = asyncio.run( + self.request( + "POST", + "/v1/message-effects", + json=command, + headers={"Authorization": "Bearer invalid-canary"}, + ) + ) + + self.assertEqual(missing.status_code, 401) + self.assertEqual(cookie.status_code, 401) + self.assertEqual(invalid.status_code, 401) + self.assertEqual( + invalid.json(), + {"code": "authentication.refused"}, + ) + self.assertEqual(invalid.headers["Cache-Control"], "no-store") + self.assertEqual(self.stack.primary.submit_calls, []) + + def test_public_liveness_exception_is_explicit(self) -> None: + response = asyncio.run(self.request("GET", "/healthz")) + + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json(), {"status": "ok"}) + self.assertEqual(response.headers["Cache-Control"], "no-store") + self.assertEqual(self.stack.admission_calls, []) + + def test_duplicate_oversized_or_lookalike_command_is_refused(self) -> None: + self.seed("notice-1", message("protected@example.invalid")) + headers = { + "Authorization": "Bearer caller-a", + "Content-Type": "application/json", + } + duplicate = asyncio.run( + self.request( + "POST", + "/v1/message-effects", + content=b'{"key":"first","key":"second","noticeId":"notice-1"}', + headers=headers, + ) + ) + valid = b'{"key":"command-1","noticeId":"notice-1"}' + duplicate_length = asyncio.run( + self.request( + "POST", + "/v1/message-effects", + content=valid, + headers=[ + ("Authorization", "Bearer caller-a"), + ("Content-Type", "application/json"), + ("Content-Length", str(len(valid))), + ("Content-Length", str(len(valid))), + ], + ) + ) + oversized = asyncio.run( + self.request( + "POST", + "/v1/message-effects", + content=json.dumps( + { + "key": "command-1", + "noticeId": "notice-1", + "padding": "x" * 5000, + } + ), + headers=headers, + ) + ) + lookalike = self.post( + { + "key": "command-1", + "noticeId": "notice-1", + "token": "secret-canary", + } + ) + + self.assertEqual(duplicate.status_code, 422) + self.assertEqual(duplicate_length.status_code, 422) + self.assertEqual(oversized.status_code, 422) + self.assertEqual(lookalike.status_code, 422) + self.assertEqual(self.stack.primary.submit_calls, []) + + def test_streamed_body_stops_when_declared_length_is_exceeded(self) -> None: + self.seed("notice-1", message("protected@example.invalid")) + declared = b'{"key":"command-1","noticeId":"notice-1"}' + chunks_requested = [] + + async def body(): + chunks_requested.append(1) + yield declared + chunks_requested.append(2) + yield b"x" + raise AssertionError("bounded reader requested another body chunk") + + response = asyncio.run( + self.request( + "POST", + "/v1/message-effects", + content=body(), + headers={ + "Authorization": "Bearer caller-a", + "Content-Type": "application/json", + "Content-Length": str(len(declared)), + }, + ) + ) + + self.assertEqual(response.status_code, 422) + self.assertEqual(chunks_requested, [1, 2]) + self.assertEqual(self.stack.primary.submit_calls, []) + + def test_response_contract_preserves_refusal_and_uncertainty(self) -> None: + self.seed("refused", message("one@example.invalid")) + self.stack.primary.submit_error = FakeMessagingError( + "template.not-found", status=422, outcome_unknown=False + ) + refused = self.post({"key": "command-1", "noticeId": "refused"}) + + self.seed("unknown", message("two@example.invalid")) + self.stack.primary.submit_error = FakeMessagingError( + "service.unavailable", status=503, outcome_unknown=True + ) + uncertain = self.post({"key": "command-2", "noticeId": "unknown"}) + + self.assertEqual(refused.status_code, 422) + self.assertEqual( + refused.json(), + {"state": "refused", "code": "template.not-found"}, + ) + self.assertEqual(uncertain.status_code, 202) + self.assertEqual(uncertain.json()["state"], "uncertain") + self.assertIn("recovery", uncertain.json()) + + def test_environment_factory_constructs_fastapi_worker(self) -> None: + settings = { + "MESSAGE_EFFECT_DATABASE": str(self.database), + "MESSAGE_EFFECT_SERVICE_NAMESPACE": "urn:example:service:renewal-notices", + "MESSAGE_EFFECT_TARGETS": json.dumps({"a" * 64: None}), + "MESSAGE_EFFECT_AUDIT_KEY_HEX": "a" * 64, + } + + with patch.dict(os.environ, settings, clear=True): + app = create_fastapi_app_from_environment() + + self.assertIsInstance( + app.state.registry_message_effect_store, MessageEffectStore + ) + + if __name__ == "__main__": unittest.main() diff --git a/products/platform/examples/python-machine-service/uv.lock b/products/platform/examples/python-machine-service/uv.lock index cd2cd01cef..132be2c6cd 100644 --- a/products/platform/examples/python-machine-service/uv.lock +++ b/products/platform/examples/python-machine-service/uv.lock @@ -2,6 +2,37 @@ version = 1 revision = 3 requires-python = ">=3.11" +[[package]] +name = "annotated-doc" +version = "0.0.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/0f/6e/a61e86e43bb6039b31a33a8f5fba76fe1cdacf3661e7b9756d4ff1b28cdc/annotated_doc-0.0.6.tar.gz", hash = "sha256:7969bb69912085b2285849c0dcac0b4b374fd180c13cf10a87f284ffcf347bbf", size = 10767, upload-time = "2026-11-10T18:17:11.28Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cd/f5/3dd85d583e55be76cd02b1fc9bbec771b12d63124b01661d9535ccf8721f/annotated_doc-0.0.6-py3-none-any.whl", hash = "sha256:361ca0950cc7082f53fa69e9328409f40a62c61e57e0a47e1825a08078a58a53", size = 5293, upload-time = "2026-11-10T18:17:10.249Z" }, +] + +[[package]] +name = "annotated-types" +version = "0.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/5f/56/a8120250d128bed162cd73c76d45f6ef9991f3e068f62a8ee060afa3104a/annotated_types-0.8.0.tar.gz", hash = "sha256:13b2beaad985e05e2d6407ee4c4f35590b11f8d693a258a561055cac8f64cab7", size = 15893, upload-time = "2026-07-23T20:16:13.995Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/99/91/8acff4f5e50511b911bbccb72b8628a49c68ce14148cd9f6431094859a90/annotated_types-0.8.0-py3-none-any.whl", hash = "sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0", size = 13427, upload-time = "2026-07-23T20:16:12.938Z" }, +] + +[[package]] +name = "anyio" +version = "4.16.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "idna" }, + { name = "typing-extensions", marker = "python_full_version < '3.15'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a1/98/7e457a3b014976887a050561955c0b76e1e7e2d6e27b78ecef2ef80518f2/anyio-4.16.0.tar.gz", hash = "sha256:59bb03251907983d1603d27c3087ddb1e93299ea2163adcdba37899a4fb12ffb", size = 310971, upload-time = "2026-11-01T11:20:07.282Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a9/16/7757fb84c819accc7d7e9af5291b261e4abb8627ee040f99e7d35ef2457a/anyio-4.16.0-py3-none-any.whl", hash = "sha256:c66ae634e0b8228396b801741beb3294326d4b6102f7bba4041c0dfb58c29026", size = 134521, upload-time = "2026-11-01T11:20:05.59Z" }, +] + [[package]] name = "blinker" version = "1.9.0" @@ -11,6 +42,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/10/cb/f2ad4230dc2eb1a74edf38f1a38b9b52277f75bef262d8908e60d957e13c/blinker-1.9.0-py3-none-any.whl", hash = "sha256:ba0efaa9080b619ff2f3459d1d500c57bddea4a6b424b60a91141db6fd2f08bc", size = 8458, upload-time = "2024-11-08T17:25:46.184Z" }, ] +[[package]] +name = "certifi" +version = "2026.10.23" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, +] + [[package]] name = "click" version = "8.5.1" @@ -20,6 +60,24 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/31/7d/164b7ffc8624fe9efb4221bf9af485d5c1e41b9ae118045d2b6dc5457d8b/click-8.5.1-py3-none-any.whl", hash = "sha256:8bb5376d2006950386f8c6427613334a2acadc5f559cb80e638d00b4df957e37", size = 126163, upload-time = "2026-11-06T17:36:59.287Z" }, ] +[[package]] +name = "fastapi" +version = "0.162.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "annotated-doc" }, + { name = "anyio" }, + { name = "opentelemetry-api" }, + { name = "pydantic" }, + { name = "starlette" }, + { name = "typing-extensions" }, + { name = "typing-inspection" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/4e/7b/ae546e10f153fcf9a6afd8b9fe4730bdfeb8fdcb93178d54122973ef3f4c/fastapi-0.162.5.tar.gz", hash = "sha256:1ca37f64f61c99cebd38636e67525fb721c5e8c1169f07f2a35d73b0a63265d4", size = 531785, upload-time = "2026-11-11T22:29:53.177Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/10/19/5b9abfa67a29b862e509911eef40f4901f78aa48de32ad1f939b5c2b165e/fastapi-0.162.5-py3-none-any.whl", hash = "sha256:5303c67415fde762889ca337db79d27b755b8bd09cef314fa7a4340bb30bfd2b", size = 151782, upload-time = "2026-11-11T22:29:51.47Z" }, +] + [[package]] name = "flask" version = "3.1.2" @@ -37,6 +95,64 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/ec/f9/7f9263c5695f4bd0023734af91bedb2ff8209e8de6ead162f35d8dc762fd/flask-3.1.2-py3-none-any.whl", hash = "sha256:ca1d8112ec8a6158cc29ea4858963350011b5c846a414cdb7a954aa9e967d03c", size = 103308, upload-time = "2025-08-19T21:03:19.499Z" }, ] +[[package]] +name = "gunicorn" +version = "23.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "packaging" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/34/72/9614c465dc206155d93eff0ca20d42e1e35afc533971379482de953521a4/gunicorn-23.0.0.tar.gz", hash = "sha256:f014447a0101dc57e294f6c18ca6b40227a4c90e9bdb586042628030cba004ec", size = 375031, upload-time = "2024-08-10T20:25:27.378Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cb/7d/6dac2a6e1eba33ee43f318edbed4ff29151a49b5d37f080aad1e6469bca4/gunicorn-23.0.0-py3-none-any.whl", hash = "sha256:ec400d38950de4dfd418cff8328b2c8faed0edb0d517d3394e457c317908ca4d", size = 85029, upload-time = "2024-08-10T20:25:24.996Z" }, +] + +[[package]] +name = "h11" +version = "0.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/01/ee/02a2c011bdab74c6fb3c75474d40b3052059d95df7e73351460c8588d963/h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1", size = 101250, upload-time = "2025-04-24T03:35:25.427Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" }, +] + +[[package]] +name = "httpcore" +version = "1.0.9" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "h11" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484, upload-time = "2025-04-24T22:06:22.219Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" }, +] + +[[package]] +name = "httpx" +version = "0.28.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "certifi" }, + { name = "httpcore" }, + { name = "idna" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406, upload-time = "2024-12-06T15:37:23.222Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" }, +] + +[[package]] +name = "idna" +version = "3.20" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f5/08/8eea9d4b8302028f3abb2c0813953f7aec26d33b7a8960ed760e65ff29fa/idna-3.20.tar.gz", hash = "sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44", size = 216463, upload-time = "2026-09-17T14:11:04.752Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl", hash = "sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c", size = 69583, upload-time = "2026-09-17T14:11:03.168Z" }, +] + [[package]] name = "itsdangerous" version = "2.2.0" @@ -186,16 +302,294 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/92/f9/ecbde7149e95b8a0f18e16d5d747f7dc06049d5da2e4f77f6f5e4a1f46a8/markupsafe-3.0.4-cp315-cp315t-win_arm64.whl", hash = "sha256:39dbacefc411633db5b4378b066a9aca70a3d7e2922c9e578d825f844026eeba", size = 14417, upload-time = "2026-10-02T23:06:56.246Z" }, ] +[[package]] +name = "opentelemetry-api" +version = "1.45.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, +] + +[[package]] +name = "packaging" +version = "26.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7d/fa/3944b40b07da9ce895c0e6303a5ab7d53da063554f534556b134a54d6093/packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", size = 313412, upload-time = "2026-08-04T18:15:28.737Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" }, +] + +[[package]] +name = "pydantic" +version = "2.14.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "annotated-types" }, + { name = "pydantic-core" }, + { name = "typing-extensions" }, + { name = "typing-inspection" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b4/fc/1203d011145c98ddce3cd2f505bb54375ef8d43223053df6bfcf3c746f46/pydantic-2.14.3.tar.gz", hash = "sha256:1054f237f4d4733e5a30e1e2333bd33a2004ab9ab1510bd053a9a31bb48e232d", size = 925636, upload-time = "2026-11-05T09:17:04.686Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/72/b8/b864503789ef5c58597d2a7b4adbee62c26440ab1e682581fc6838df8947/pydantic-2.14.3-py3-none-any.whl", hash = "sha256:3f7b347782ab7e4cf4c798496ae3a82787d9f21ec12676a9c564355eeef8daa8", size = 494071, upload-time = "2026-11-05T09:17:02.426Z" }, +] + +[[package]] +name = "pydantic-core" +version = "2.50.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9c/0f/34f9ce4ba701dd0b815033ef94d99b56f66200e578ee6052aa3ac26f064e/pydantic_core-2.50.4.tar.gz", hash = "sha256:aead3b74b68396bf0feab5d57e050b730ded7df55853c1e048a87e00aaf033c6", size = 522249, upload-time = "2026-11-05T09:15:26.774Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/df/00/85e80811834d7cbd9bc228f9b5cdf8ec0edd69b55351ad720aac8c412d8c/pydantic_core-2.50.4-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:3e547ceec1da7382f01f9e13963023e53367a71802c88778b21b9645a077cbdf", size = 2170584, upload-time = "2026-11-05T09:11:41.139Z" }, + { url = "https://files.pythonhosted.org/packages/a3/f1/438de1fb99d717dcc6521922478dc16ef7b757302d4fc1f7faba3aaeac09/pydantic_core-2.50.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c813ada7a651193acda85b6bc1cf12abd4b37cd25c7c6a75d7183512cc374969", size = 2128471, upload-time = "2026-11-05T09:11:42.65Z" }, + { url = "https://files.pythonhosted.org/packages/b7/74/f21ab568c6d3f315988b40e53f809c95b63fafc5403332963aa6dfc2c054/pydantic_core-2.50.4-cp311-cp311-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:57fa0a9490785139f1a4e4f43891830d55dfe4408845c0c9cb5eff4aeaf75f69", size = 2281509, upload-time = "2026-11-05T09:11:44.359Z" }, + { url = "https://files.pythonhosted.org/packages/a1/42/24ed3ea8e2fb6463c9ba5b8b1f089e69040905c7fd81dcfa6f52fcc692d5/pydantic_core-2.50.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:30d4dc35bc0eea52202a90b3820445ee0072c820241bfa710a623a078c9b267b", size = 2128064, upload-time = "2026-11-05T09:11:46.01Z" }, + { url = "https://files.pythonhosted.org/packages/d6/d1/44f541b2c18a46df6f18281a557acefeb5bbf0733a0b80b0a5e835e10ee4/pydantic_core-2.50.4-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:789f88dea57841cdebef392b5d6e90444d767117e9ff2e0d9172df5c9de6690c", size = 2214472, upload-time = "2026-11-05T09:11:47.503Z" }, + { url = "https://files.pythonhosted.org/packages/bd/1b/e9a9ad8733e8051abca9e4acce37ba3ddd13930fd3b8730f4c7816fa979a/pydantic_core-2.50.4-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:d690121e80ab16e623415351ab24713534d4e500b3cadff216409cb6826063d4", size = 2401153, upload-time = "2026-11-05T09:11:49.403Z" }, + { url = "https://files.pythonhosted.org/packages/79/84/d88e8e6aa42d4d677666d6625db9177ad6851be9e7564a25aeb0b0cbcaf2/pydantic_core-2.50.4-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:b42f64825f5d750228f08318a9bf4d723b7ecb4c472aedcb3013c3ec2dc1f949", size = 2453307, upload-time = "2026-11-05T09:11:51.118Z" }, + { url = "https://files.pythonhosted.org/packages/56/51/cbb7a1bc0196ff94d3478d265eed7449f811759988eb760d41f4edd0893b/pydantic_core-2.50.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:0574866e05f6adeecc520d87e87dd06210c0a51706341f6ef8421572f5a64444", size = 2253434, upload-time = "2026-11-05T09:11:52.997Z" }, + { url = "https://files.pythonhosted.org/packages/9e/04/206b4881d631033ae88f005da6e11bd610c850e1850217342c03053d253b/pydantic_core-2.50.4-cp311-cp311-manylinux_2_31_riscv64.whl", hash = "sha256:dcf2c7eaaa4cafe8e49b017e5bb49e76e084ab6f0cd712ee4019c812b5cf68b8", size = 2279365, upload-time = "2026-11-05T09:11:54.822Z" }, + { url = "https://files.pythonhosted.org/packages/a1/7c/d815b5a3f83069b283d3b6a2e61de6e14baac3b20c6cd3418e9e629551cf/pydantic_core-2.50.4-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:3b8ee2589a082739c522c1fe4be227412fcf108b903abb6672ae2f5570558882", size = 2319407, upload-time = "2026-11-05T09:11:56.46Z" }, + { url = "https://files.pythonhosted.org/packages/ee/00/c9a483276d1052d5142e1e01eccac97d939f83a3a3fd94c4766495a9b807/pydantic_core-2.50.4-cp311-cp311-musllinux_1_1_armv7l.whl", hash = "sha256:aec3c2d741a8e3ee993de7f95f37afb51e31b169c95dbd29da4cf6688f340914", size = 2489900, upload-time = "2026-11-05T09:11:58.102Z" }, + { url = "https://files.pythonhosted.org/packages/2d/b5/8cd8ee29a1d63ad47f95593384df92476cef6896c644f280db0748b8e76b/pydantic_core-2.50.4-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:8923fcd49f875e8a0448d7223d1fdf1a9973ae2d1f20d4158753ceb8909facd2", size = 2497732, upload-time = "2026-11-05T09:11:59.928Z" }, + { url = "https://files.pythonhosted.org/packages/60/31/050a48c0c373df16442ac07f3fa167414bb0e22f54a3e886f6d6cb7ad1d4/pydantic_core-2.50.4-cp311-cp311-win32.whl", hash = "sha256:fc04affef30be98c1f36f0c422a4061ef618fdc1dde79f5ad5458dd496fecffa", size = 2132347, upload-time = "2026-11-05T09:12:01.928Z" }, + { url = "https://files.pythonhosted.org/packages/c6/06/cebeeb7a8e87b42a3d8bc189d0d400e47df5d1736cb326764bae8a74c433/pydantic_core-2.50.4-cp311-cp311-win_amd64.whl", hash = "sha256:15bece43a02ad543c621c8305e67dedb5f27d378c5ba741e5a2c36523f8ef37f", size = 2255970, upload-time = "2026-11-05T09:12:03.888Z" }, + { url = "https://files.pythonhosted.org/packages/46/db/5b4bf14347da658c994483043fbabffedcab98929c41c261ec168c3c1f87/pydantic_core-2.50.4-cp311-cp311-win_arm64.whl", hash = "sha256:e498900bfbf7ddddd862f810440c09e9b81674739e8a11d619b40906dccd4a9a", size = 2196799, upload-time = "2026-11-05T09:12:05.389Z" }, + { url = "https://files.pythonhosted.org/packages/10/bf/d1f6b81709538f831ebe1c42f50fb89db3dfda06f9e9b1ea24e90fc69209/pydantic_core-2.50.4-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:32a991aebd165f227b7c7c60bb9d66c2c7de9c24308552da264c9938fde0f8d6", size = 2231444, upload-time = "2026-11-05T09:12:06.969Z" }, + { url = "https://files.pythonhosted.org/packages/c1/39/6618e541658d5a687a8d4962fc304350073a8f322bc4c62e8ed4c2d514d6/pydantic_core-2.50.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1e20cbde2b6deb33a51d08cd168454dd9044ec7d4474056f4d98d63f51578783", size = 2108048, upload-time = "2026-11-05T09:12:08.85Z" }, + { url = "https://files.pythonhosted.org/packages/d9/54/1c941fffa4e14bfc9ab0cd4977075f0e03201447856130d08a33cd45e47b/pydantic_core-2.50.4-cp312-cp312-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:8cceae48ae7f94990c2f4e36291e9ec9868735e8b0f19e4489a17b0422338466", size = 2256866, upload-time = "2026-11-05T09:12:10.495Z" }, + { url = "https://files.pythonhosted.org/packages/61/a0/8028ef3e014be522ce43060aeac82a5be2288215e660866f5e6260acc123/pydantic_core-2.50.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:16902a147b3da4840612164a5e67947104d63e978f7a57c395877a5e26690b9c", size = 2125682, upload-time = "2026-11-05T09:12:12.278Z" }, + { url = "https://files.pythonhosted.org/packages/c3/f2/b98bb73b1734ec4e42e786a766abc24f3c89620a0ddbaf8aa14e4b4c628c/pydantic_core-2.50.4-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:d6e3485a5e5c01fb5339c1ee3d4b9e21e2135a2a9d44caafb71acd994487ee7c", size = 2197108, upload-time = "2026-11-05T09:12:13.873Z" }, + { url = "https://files.pythonhosted.org/packages/f1/d1/7a7142786781400143e8806633fe5b65e2d407c311041fc9494490f05b18/pydantic_core-2.50.4-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:629eae995185540406e3635df5d5cf1d44f19ea240840b835d3f44541ff694d8", size = 2380521, upload-time = "2026-11-05T09:12:15.539Z" }, + { url = "https://files.pythonhosted.org/packages/b5/34/cf710ca48d4498b04a3ea605d45892675dc2b14a94a25121a8d03f56d3e9/pydantic_core-2.50.4-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:41b2cd8b29dbb5a4c9828a70f50d1abfc92011115c813213d3a91205c6f731b3", size = 2457436, upload-time = "2026-11-05T09:12:17.447Z" }, + { url = "https://files.pythonhosted.org/packages/91/23/e0c6e3cd09a0ac809953fea698c816b9f03bf0b35b6820c9553e4f5d85a8/pydantic_core-2.50.4-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c81d98e27d9d9261909dcccab1ba5d6ea1c98b0bb9470e368604614fd1d36ddd", size = 2261727, upload-time = "2026-11-05T09:12:19.097Z" }, + { url = "https://files.pythonhosted.org/packages/f9/00/292a0ed96d5d2d6edb49468ef481336e5b7e54f13435d73b7c912c891c23/pydantic_core-2.50.4-cp312-cp312-manylinux_2_31_riscv64.whl", hash = "sha256:ca83a32b2b41653d89f09a3d22b770bca96da72273bef8f7a68136bdd1e8b823", size = 2262071, upload-time = "2026-11-05T09:12:20.78Z" }, + { url = "https://files.pythonhosted.org/packages/f8/36/d4690faf8c082eacf7754e52ab6bebe1bc73b167272e28699c00480ee908/pydantic_core-2.50.4-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:817953730e4a73a09008b010c4a42396cefe799616a22df2ac21d3927b3080cf", size = 2298931, upload-time = "2026-11-05T09:12:22.614Z" }, + { url = "https://files.pythonhosted.org/packages/21/17/b180af6d17cf6c8e0d3d2661fc501a4a40959744ca4947d6ad0db81b1416/pydantic_core-2.50.4-cp312-cp312-musllinux_1_1_armv7l.whl", hash = "sha256:664e74848c2f5fc27db8505fe24e1ecd3ac669412913bf73d176916f86cc08e2", size = 2474285, upload-time = "2026-11-05T09:12:24.842Z" }, + { url = "https://files.pythonhosted.org/packages/6e/bb/7e44d4ac6e1292f1859384c688713045bdf5448e0635c49c003d2be3bb6c/pydantic_core-2.50.4-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:219114f8dcdcbe4720d82ef016b1287ce5a0a67d7c69ca61524eb72e82aac344", size = 2498172, upload-time = "2026-11-05T09:12:26.434Z" }, + { url = "https://files.pythonhosted.org/packages/d8/84/5101f35294579c4bef7dc32fd4f097d91eedac2e195894266bdabc1e6dfd/pydantic_core-2.50.4-cp312-cp312-win32.whl", hash = "sha256:67f7cc397e1d5556a801d1cba74de0d27d827eb242e6c036c0ca273c745414f1", size = 2119592, upload-time = "2026-11-05T09:12:27.971Z" }, + { url = "https://files.pythonhosted.org/packages/82/88/d438a8fcf3738e9ff2670f724047ca3893ec899bcd5cdfc077a2aab133c6/pydantic_core-2.50.4-cp312-cp312-win_amd64.whl", hash = "sha256:ea2f61b0bc12f3592288503961b764579dea0658852d96a0b3d823614d808821", size = 2264064, upload-time = "2026-11-05T09:12:29.538Z" }, + { url = "https://files.pythonhosted.org/packages/77/d4/4a0c73dc3ef9e50b122b8c3527afcded15a44838f1c9668d2d4b72cc09f0/pydantic_core-2.50.4-cp312-cp312-win_arm64.whl", hash = "sha256:32d6dda86383645ec428ea64dfc277036f5cbc60a72238eab28b91a3fdb9a113", size = 2167792, upload-time = "2026-11-05T09:12:31.103Z" }, + { url = "https://files.pythonhosted.org/packages/1b/21/39f8d97e7ea8e3083606ee9bb1d7f3ec70ded780bb6a872aad76c7eb08b2/pydantic_core-2.50.4-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:0f87ae9db5ba8d8de40dcb93982cf8dd544e6552a80d3345af51941cc2146b80", size = 2232841, upload-time = "2026-11-05T09:12:32.617Z" }, + { url = "https://files.pythonhosted.org/packages/90/a9/fc89a632331882c4cb91b949003418e6f5085ddcf2c9b875d499682bca91/pydantic_core-2.50.4-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:1239daaf063e62213ca1f34d96663900bd7510c42a786e843fd328af70e46445", size = 2108326, upload-time = "2026-11-05T09:12:34.419Z" }, + { url = "https://files.pythonhosted.org/packages/5d/6d/4f6d00e9e4ba2a7bfb206ae49cb32a3ea90c4d658e62f8775277d75e8291/pydantic_core-2.50.4-cp313-cp313-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:1afefe44ec042fbabfb4483ea258c04cf75ff4ff328d754f09b321fdaa232aca", size = 2256276, upload-time = "2026-11-05T09:12:36.212Z" }, + { url = "https://files.pythonhosted.org/packages/b3/b8/936cb0d85a4082e902c7397db0f05c4372eac08372c8bd2d0b43088fcf17/pydantic_core-2.50.4-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:a9ee990bf2cfbd81574c5d4f9f6c9d480a14b5b43d2c4f2ca13f4c6f48089394", size = 2125469, upload-time = "2026-11-05T09:12:37.913Z" }, + { url = "https://files.pythonhosted.org/packages/66/a1/f3b551ce233dcac73286b8b2ae45c23232a9f41c68663e2dcce4bb2dbcfa/pydantic_core-2.50.4-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:ab2822bcdcefb54d1e8ca29f5e3ec3afe160fb794bb3a3a73b09d11ed2671104", size = 2196397, upload-time = "2026-11-05T09:12:39.725Z" }, + { url = "https://files.pythonhosted.org/packages/3d/93/a8a6e7e20826567a73e6f52416667698aa3de704804d7a49d25272246af4/pydantic_core-2.50.4-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:0001d6920e3a5d92758cda460d6dc9f918a78ad6d5d092f1c8b5395e6b775356", size = 2380442, upload-time = "2026-11-05T09:12:41.196Z" }, + { url = "https://files.pythonhosted.org/packages/aa/ba/921d90c9d8ddfa653a35a92f2bbdcd650a9493f5c43f39cdfe4c56659cfa/pydantic_core-2.50.4-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:ad92d255a165cde5f9882ff69699eaf5495e0a1f32e97566bbbb80f11e46781f", size = 2457747, upload-time = "2026-11-05T09:12:42.723Z" }, + { url = "https://files.pythonhosted.org/packages/2b/c0/1c8f2c8f1b03d3fe2fdd7962df8f5a744fe48c90b4c49615e4eb77d04141/pydantic_core-2.50.4-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:fb2bb5b557080da398b866408117d98fe9731a12334afd0cdff221b458cdc5dc", size = 2260946, upload-time = "2026-11-05T09:12:44.185Z" }, + { url = "https://files.pythonhosted.org/packages/07/ab/5b78a78f0c0f11c8b54fac214ed49cbb4795c34881aa5e5a15715917936f/pydantic_core-2.50.4-cp313-cp313-manylinux_2_31_riscv64.whl", hash = "sha256:92f8f63df729061bb14558ed740e7a222f6e2aa6c2e6a5bcfb4e706676562049", size = 2261921, upload-time = "2026-11-05T09:12:45.706Z" }, + { url = "https://files.pythonhosted.org/packages/b3/e8/dd5d154cf3401f836d8754fdc1b82ecadd37944e4355d855e5b54c7d8ae5/pydantic_core-2.50.4-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:2a60ec2a57ac3ef3767e526e9bf706ec75aa3d79c4ea134d9d4fcf7c62a297a7", size = 2298475, upload-time = "2026-11-05T09:12:47.183Z" }, + { url = "https://files.pythonhosted.org/packages/b7/49/af059d9c4483cba168b17e5f84f1090a3e4547a02fc7698ebc231d48298a/pydantic_core-2.50.4-cp313-cp313-musllinux_1_1_armv7l.whl", hash = "sha256:a2f8716344bbbd10443391be0b1f2003b34949e3c4e6883005c2bc498ab6b64b", size = 2473226, upload-time = "2026-11-05T09:12:48.785Z" }, + { url = "https://files.pythonhosted.org/packages/71/ba/4e8cc3064e8bc2ea272cf80dfc57fa4e455f6835c1def21609a9b4f94135/pydantic_core-2.50.4-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:b300a30304c4c6aeab03ed06809819d9eceacdd58441d3c7dffe41edfd006091", size = 2498764, upload-time = "2026-11-05T09:12:50.316Z" }, + { url = "https://files.pythonhosted.org/packages/bf/96/0878499cfa88eb0b07762b488d3cc1b64cb156a4905db99a0d12096b2e17/pydantic_core-2.50.4-cp313-cp313-win32.whl", hash = "sha256:ef8a9ddb2e2a4eae4abb72dc0710eca6c2726779b0664bd10c3ce9fcfaed8c4e", size = 2119158, upload-time = "2026-11-05T09:12:51.834Z" }, + { url = "https://files.pythonhosted.org/packages/e7/e0/95b651213e79ffe0cbee855590bf5cfdf8e3a0d90a7fc73a080e63f7cc38/pydantic_core-2.50.4-cp313-cp313-win_amd64.whl", hash = "sha256:4c29b8f2d6417069bb1f257e6b9113f5d64dc2f554cc200ea90b4fe2c5cdb733", size = 2262887, upload-time = "2026-11-05T09:12:53.282Z" }, + { url = "https://files.pythonhosted.org/packages/08/d3/c3801dc75844a0b13d000bd575bf1b3b3a8aca9f63d19e1809f69c9c5121/pydantic_core-2.50.4-cp313-cp313-win_arm64.whl", hash = "sha256:a0c5210d038418a115e7cf8706bfa611bd14add2f5787274dba45aadca3155e0", size = 2167878, upload-time = "2026-11-05T09:12:54.677Z" }, + { url = "https://files.pythonhosted.org/packages/ee/ed/c9a4982ac3bbc78f27498d9efb85b3dabd739a1724db53c35cc4c018e1de/pydantic_core-2.50.4-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:5c074454dc6d4f6f4ba6561a56bf33a14db7651d882a5a5321ba3ae8868e082d", size = 2236841, upload-time = "2026-11-05T09:12:56.111Z" }, + { url = "https://files.pythonhosted.org/packages/56/32/92c174c17bfc5fc52d0c064e6a7969a727731e25829ede752fba8bacce0f/pydantic_core-2.50.4-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:a4bb174bd65f795c39ad6642d9d5bdc43351b306b7d0a654ab0d0abb38be245f", size = 2108348, upload-time = "2026-11-05T09:12:57.638Z" }, + { url = "https://files.pythonhosted.org/packages/cb/cb/9f637d424a04d3edce7dd527da941950cce05a74b025eef3d54427b86c8e/pydantic_core-2.50.4-cp314-cp314-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:0ec20aca2b067369913716847f7dfe5f4dddf16a46965b7a70bbad5defaaba86", size = 2261331, upload-time = "2026-11-05T09:12:59.154Z" }, + { url = "https://files.pythonhosted.org/packages/91/ff/1117a3cccabb67305bd98d992a84eaf275939a9a043b4f14126ed7252e4f/pydantic_core-2.50.4-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:70dbc9f83c41f37a4faa62dae5203853847223a891da446f48ef2efcfd5df806", size = 2128667, upload-time = "2026-11-05T09:13:00.614Z" }, + { url = "https://files.pythonhosted.org/packages/93/45/6de1b4a6e8c415cd547f90d1408a711e7975116423e3eb3046061c62d7c7/pydantic_core-2.50.4-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:3de6c2a4df2af0ac9ab4dc1488746fe8b1a90e27955d870d9edda3187d20092b", size = 2198183, upload-time = "2026-11-05T09:13:02.259Z" }, + { url = "https://files.pythonhosted.org/packages/d0/bd/c6e64c315d35cc0783a0ea033a3dca062bc368905d0217eab6f6f63007de/pydantic_core-2.50.4-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:3a48a5254d15a0ad050318bfc7a9566d4ec740118187e8f303e47a6840287eb7", size = 2386279, upload-time = "2026-11-05T09:13:03.988Z" }, + { url = "https://files.pythonhosted.org/packages/33/ab/0d56280c89d3841381e9c699c3fa80e3dd3288edf5e7fe4d149136835dca/pydantic_core-2.50.4-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:0af56dbf8822ba9f4efcbbfdc15478f8b6fb08f1609860cb50aa2cc8476b3c34", size = 2464343, upload-time = "2026-11-05T09:13:05.98Z" }, + { url = "https://files.pythonhosted.org/packages/56/9c/621ad8f88590a92a086b1168dce09369d9c5e079e2e635e6646d248af55b/pydantic_core-2.50.4-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f1d62fb172db35c6478c9323da34ff37d1f3d37d7d44337a9d94ba8c583e5730", size = 2265388, upload-time = "2026-11-05T09:13:07.808Z" }, + { url = "https://files.pythonhosted.org/packages/f3/7b/cef68a667bf29b86e293a80a601d488a84c8f45508915ad6201fcfe1a798/pydantic_core-2.50.4-cp314-cp314-manylinux_2_31_riscv64.whl", hash = "sha256:5c1013647be741647895c102831dcf79c34209662dbb683df9efb864417ed7d5", size = 2267012, upload-time = "2026-11-05T09:13:09.273Z" }, + { url = "https://files.pythonhosted.org/packages/4b/9f/3ae4d163d8feda2b52de88b5cd96b1c40f79d11503003b061136d2ece6ab/pydantic_core-2.50.4-cp314-cp314-musllinux_1_1_aarch64.whl", hash = "sha256:aeb2e123cbf978a905e9f55155c1b8316fbbfa7cf64d04521fe174bab302d100", size = 2300478, upload-time = "2026-11-05T09:13:10.758Z" }, + { url = "https://files.pythonhosted.org/packages/e8/72/41881d31f6452430ed6792679c5391795910f0a27a6aebd424683e504ed6/pydantic_core-2.50.4-cp314-cp314-musllinux_1_1_armv7l.whl", hash = "sha256:523466eba8ee10f7480f3c2057563145978011c583130d2cc01fb1e7af808e25", size = 2474874, upload-time = "2026-11-05T09:13:12.188Z" }, + { url = "https://files.pythonhosted.org/packages/05/ef/099874dd6d5ca1e49987dea87eecc05610183249450b1fff883d87f1e8eb/pydantic_core-2.50.4-cp314-cp314-musllinux_1_1_x86_64.whl", hash = "sha256:c9e70012926e97069cdd09221861aff412aa94e4cac2e019055cdb79485b150c", size = 2502771, upload-time = "2026-11-05T09:13:13.981Z" }, + { url = "https://files.pythonhosted.org/packages/c6/07/a7d8615b8677bf69e24666bbce431299850c95a7b084649342582a1c3210/pydantic_core-2.50.4-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:e6da138a1ecc1341c8b788a5ee822670b03788e1f5decf7af9d461de6e508b8e", size = 1496509, upload-time = "2026-11-05T09:13:15.704Z" }, + { url = "https://files.pythonhosted.org/packages/ab/71/fdf2c25c3a4f89968263c1d896c933809ca8d2fb13443626648a17b2e296/pydantic_core-2.50.4-cp314-cp314-win32.whl", hash = "sha256:13b6dd62b5279f5b9d72f3bf918a35443ee8bd549241d9dc52d79a2c3b6d7016", size = 2122015, upload-time = "2026-11-05T09:13:17.09Z" }, + { url = "https://files.pythonhosted.org/packages/3a/9f/3554f0148b01ddaa5e678bf5fbce4679873534e5c0985cdf6c59c41dc9a9/pydantic_core-2.50.4-cp314-cp314-win_amd64.whl", hash = "sha256:b0cdb655fbd1562c2dfc9986f9103a106f7058cd0915afc6e656d4b1d73f3387", size = 2265109, upload-time = "2026-11-05T09:13:18.702Z" }, + { url = "https://files.pythonhosted.org/packages/ed/3c/196ef237d9ec5cca5ea9b773911dee1a387b9b1d4bfea05625b3e191a338/pydantic_core-2.50.4-cp314-cp314-win_arm64.whl", hash = "sha256:df1c174796cd63eb6b139f7daf783affe1f3ed659605850e843b24764c21bfc5", size = 2165745, upload-time = "2026-11-05T09:13:20.245Z" }, + { url = "https://files.pythonhosted.org/packages/36/12/0ee82a41a3995f0b531cf14e0b823dc2365ba4a22330670fccaa72753f12/pydantic_core-2.50.4-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:edbca8789fd10f0de534b660a6b4c71f1fd18039679c918dad392ab044bb37e4", size = 2223917, upload-time = "2026-11-05T09:13:21.623Z" }, + { url = "https://files.pythonhosted.org/packages/90/2c/592f8404abbcc65a70e6a802d1dc8f11412af44913e5146cf5c345370074/pydantic_core-2.50.4-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:33b21f69540a12c2053cd1d95766d8bd9667a3897f7c712a642de8aa37eb0865", size = 2087372, upload-time = "2026-11-05T09:13:23.16Z" }, + { url = "https://files.pythonhosted.org/packages/ea/1d/c7111757c84b5b8c19b1e39ceb5e131e6e48e14169ec6004e0f8f28f43f3/pydantic_core-2.50.4-cp314-cp314t-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:ffb616d8d55965839670301dc3bae3abacff560a7e137a89056058a8a9da4d96", size = 2275190, upload-time = "2026-11-05T09:13:24.634Z" }, + { url = "https://files.pythonhosted.org/packages/3d/ae/6c49cc9b8e66e61adee782d1763894bf64a357cddae82f725059b85bdc98/pydantic_core-2.50.4-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:6c5687b59b6ba0f663c4f2f15470f68507d6b45ccd3a19ee6d224f95cbee70d8", size = 2110343, upload-time = "2026-11-05T09:13:26.168Z" }, + { url = "https://files.pythonhosted.org/packages/ed/39/0ee5261d1daa9ad526371181c13696add0565251b2823f6e00a9a9af397d/pydantic_core-2.50.4-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:c733087ecf7dde06b1d071679bfd5f3ba03266ba77814c1c7253bc48c9adedd9", size = 2207887, upload-time = "2026-11-05T09:13:27.681Z" }, + { url = "https://files.pythonhosted.org/packages/ac/b5/a0652c0e99590107e111088b6d059044380a787da9ffdd0b458ab4cd9453/pydantic_core-2.50.4-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:94733cb447c37b0ce6f71b39ca1288d5f966a084023a5617b4cc35a852586859", size = 2404171, upload-time = "2026-11-05T09:13:29.864Z" }, + { url = "https://files.pythonhosted.org/packages/a3/85/d49f0b8e09a0ffc40dcefb604f9e6020e0d61b51a5f64a504f382fa84c39/pydantic_core-2.50.4-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:b26f39a5be3cd91a2035818be3d0ffdf5282c3e1f5f53d3b80b7024021acee52", size = 2466049, upload-time = "2026-11-05T09:13:31.658Z" }, + { url = "https://files.pythonhosted.org/packages/e6/76/f2b04d7c53edfd8136053c812ea49914fbf4091196cb7baf9ea326fa2ff8/pydantic_core-2.50.4-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c856e439a9d54d514e81a7131229ba151cdf81df7c408e0f6c89340e5003dfe2", size = 2262062, upload-time = "2026-11-05T09:13:33.806Z" }, + { url = "https://files.pythonhosted.org/packages/24/60/016f14cea883adc33df90b8df220df934de49ded9640f45c8e92bb298494/pydantic_core-2.50.4-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:cbf0777d54672990b10cb8ca9b0523499e182d7e2ea39f86b138519a902aa601", size = 2263713, upload-time = "2026-11-05T09:13:35.337Z" }, + { url = "https://files.pythonhosted.org/packages/f1/3f/b05828e978512973e7e215bab69e65e70d223d6309a17bf48084a50692f4/pydantic_core-2.50.4-cp314-cp314t-musllinux_1_1_aarch64.whl", hash = "sha256:edc17549ab592e33cfcaf285f047bb75fcd98f608aa9309af1187fd736ce9641", size = 2305044, upload-time = "2026-11-05T09:13:37.043Z" }, + { url = "https://files.pythonhosted.org/packages/91/c1/fca6c5f623ac45ba284713c614b30173aa0794899a0a457f866fa6f5e886/pydantic_core-2.50.4-cp314-cp314t-musllinux_1_1_armv7l.whl", hash = "sha256:23a9ba564b2db709ff16eca990992ba95a19069972b34bff87c81d4b473cd755", size = 2483506, upload-time = "2026-11-05T09:13:40.524Z" }, + { url = "https://files.pythonhosted.org/packages/94/c2/ec41f68d1208e53e1a73ead940c050c4316bbb555ba42676a5e949fd529e/pydantic_core-2.50.4-cp314-cp314t-musllinux_1_1_x86_64.whl", hash = "sha256:41f4f8ae714e4fea1d635880f8a1af715ecf080eed4d13c5b04a0f3210f9c61a", size = 2512832, upload-time = "2026-11-05T09:13:43.361Z" }, + { url = "https://files.pythonhosted.org/packages/43/22/58583b86309f70cce854e0e77c412839a56ac6c682d6060f5794afeff315/pydantic_core-2.50.4-cp314-cp314t-win32.whl", hash = "sha256:601fce6cea9ddeaa85329e12e7f351def38d233075f42a3012b9c48071b02941", size = 2101977, upload-time = "2026-11-05T09:13:45.735Z" }, + { url = "https://files.pythonhosted.org/packages/6b/28/193bc0994f7fe15f2874c1dfe2f3bc7872aed8283ffda2cf05fb9a5a06b4/pydantic_core-2.50.4-cp314-cp314t-win_amd64.whl", hash = "sha256:22e874666bdbd96d6bf629d32cd8ab376fedf1fd62585b52a42b9fa9fa6c20b6", size = 2240461, upload-time = "2026-11-05T09:13:48.38Z" }, + { url = "https://files.pythonhosted.org/packages/00/ed/5615cfdd5620a4926440eb1a2b73db0dc895824ba565ccaa8d9eb3a8e974/pydantic_core-2.50.4-cp314-cp314t-win_arm64.whl", hash = "sha256:71395a43da5584bb70556f380387e15f845c0dcf76373c1afbfa0025737576ac", size = 2168505, upload-time = "2026-11-05T09:13:50.762Z" }, + { url = "https://files.pythonhosted.org/packages/6d/9f/e6673535165d965a11c1d5339f53995f90234019827eaecb41a57e6e463d/pydantic_core-2.50.4-cp315-cp315-macosx_10_12_x86_64.whl", hash = "sha256:7ac2769a7ddd661e07e26c12220adc31b17014c48234b2a5a88993b8d4109e09", size = 2241950, upload-time = "2026-11-05T09:13:53.055Z" }, + { url = "https://files.pythonhosted.org/packages/6f/02/65951efadbf7826e6a270843f97e3da2ef726de2b6d9cd7c5dfa4c48807e/pydantic_core-2.50.4-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:930ad463d3fb7a340d323bcc496ec32dae469ec9974c29ff569f19806b6b03b4", size = 2112412, upload-time = "2026-11-05T09:13:55.309Z" }, + { url = "https://files.pythonhosted.org/packages/c9/d3/4fb6e2e4a9e4951f1e05b198366ed5330e0874e83d52077e8b985350fe0e/pydantic_core-2.50.4-cp315-cp315-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:b867f9fd183d76977f810c626d539265183c25b2284762893a31e8d6cacc81c0", size = 2263220, upload-time = "2026-11-05T09:13:57.555Z" }, + { url = "https://files.pythonhosted.org/packages/63/83/42e70436c523357b49393b73f161f2741acf36003c8efd2f941d2be56bae/pydantic_core-2.50.4-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:49eb1241a969a5994db6880c18c012b6cbe2340343d8f529721571806583e500", size = 2134716, upload-time = "2026-11-05T09:13:59.413Z" }, + { url = "https://files.pythonhosted.org/packages/36/66/ed9b87f4751fd07e472c62cfe151f575abdf4c452fab943d35ba8efdc6c4/pydantic_core-2.50.4-cp315-cp315-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:477af785d1846e4e96bf56983b92ea7553aaeccdeb8acdaa55c7cee9eda0ae32", size = 2201901, upload-time = "2026-11-05T09:14:01.472Z" }, + { url = "https://files.pythonhosted.org/packages/2b/21/ff2e6ac7202b6d326e9f007c6082f6e6f3aaa063790ea2a355bdc985addc/pydantic_core-2.50.4-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:29358a8ca74e7d81158d14e2b10c904bd18773293ae3788716c0626fe0342347", size = 2389670, upload-time = "2026-11-05T09:14:03.431Z" }, + { url = "https://files.pythonhosted.org/packages/b9/34/e9348bc13d549641791a51843ed140fbb311d9066628e27477343412d5ad/pydantic_core-2.50.4-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:300753f71c73302e218124baf995f00058e085cd01869bd9610bcbd0bd4500c1", size = 2468951, upload-time = "2026-11-05T09:14:05.028Z" }, + { url = "https://files.pythonhosted.org/packages/ac/5e/145a02bf2b9f66981108caf6cc9e78917e31e4caca14d1e3ccd3ff2c7293/pydantic_core-2.50.4-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:26cb012c4b8ca9f847bd0ac15978bd3d0f55b050bfbe6c47355edfc7e945029b", size = 2272957, upload-time = "2026-11-05T09:14:06.587Z" }, + { url = "https://files.pythonhosted.org/packages/fd/38/b71c5b245e923f6cf144e948ed2a9d6b7fb97d8905784db8d860f5176b8b/pydantic_core-2.50.4-cp315-cp315-manylinux_2_31_riscv64.whl", hash = "sha256:9be1cfe715ecaa060ffd5d599ef410b94ef2697a0eed4cee562f788a2aa2175b", size = 2275028, upload-time = "2026-11-05T09:14:08.219Z" }, + { url = "https://files.pythonhosted.org/packages/ba/71/2504dacdc5cd3ea3ec5e68c9b6e097c979500bcff220b97046cc8ea3c1ad/pydantic_core-2.50.4-cp315-cp315-musllinux_1_1_aarch64.whl", hash = "sha256:c81e35862aced259177a537ce1a6264c3a97bae1ced184ca9dc10ea754563688", size = 2305447, upload-time = "2026-11-05T09:14:09.795Z" }, + { url = "https://files.pythonhosted.org/packages/2c/90/904233a6c148bcac9f30bb96a2761e5fb52682d0d6de31a40c74a3714ceb/pydantic_core-2.50.4-cp315-cp315-musllinux_1_1_armv7l.whl", hash = "sha256:b2f2d13239487cecaae98c9f4d5904ad0737643cdf8873c88ec6a78b12214f20", size = 2477852, upload-time = "2026-11-05T09:14:11.443Z" }, + { url = "https://files.pythonhosted.org/packages/72/33/1cbdcbf343ca23b507e967b21dddc4c8bf17a74c8b5cad59228c85ba4efc/pydantic_core-2.50.4-cp315-cp315-musllinux_1_1_x86_64.whl", hash = "sha256:e6b4b08d09054310a4dc389fa61ee22a7a5a292cb23ab8a985136ca8828bf924", size = 2506352, upload-time = "2026-11-05T09:14:13.165Z" }, + { url = "https://files.pythonhosted.org/packages/91/24/3ad9ea0876e6624c90967e5f1446e751b275cfdfaaf798a0d8e0b30025bc/pydantic_core-2.50.4-cp315-cp315-win32.whl", hash = "sha256:6619d49a89a15cd04334f76fec530c155923bfc60da74ff5d815a52629e1aa6c", size = 2127780, upload-time = "2026-11-05T09:14:17.52Z" }, + { url = "https://files.pythonhosted.org/packages/c0/3c/0582532b90a12492471977bdbca1317eca5144f6342ea581d2cee73ccd35/pydantic_core-2.50.4-cp315-cp315-win_amd64.whl", hash = "sha256:e5bd109d095aaae989a0463d5ef0fcc43e9ddd5de125e656d3c119a79e466380", size = 2270596, upload-time = "2026-11-05T09:14:20.955Z" }, + { url = "https://files.pythonhosted.org/packages/6c/50/967cfe4f7043a993c0c80cd3563c598b5281d2276aa775d0f6ff7f714271/pydantic_core-2.50.4-cp315-cp315-win_arm64.whl", hash = "sha256:6118e5a5550e36582e19bac1a403711a748f9f18251b054c326d3db02aaa7a18", size = 2170880, upload-time = "2026-11-05T09:14:24.822Z" }, + { url = "https://files.pythonhosted.org/packages/9e/71/3ec5bd8a82f792482f16d79fdbe8ce85aa71bf7147e556c5fc5f8546818d/pydantic_core-2.50.4-cp315-cp315t-macosx_10_12_x86_64.whl", hash = "sha256:d8201c9f9035520cdcc7dcad383b039ec8123969b87e01cf27c3dd883c02313b", size = 2233053, upload-time = "2026-11-05T09:14:27.942Z" }, + { url = "https://files.pythonhosted.org/packages/6e/2e/614dc37aedf8e9f811c1f2eedaf8eb09a7c196e2d137fe82bcc9d5662ca2/pydantic_core-2.50.4-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:1de7be9a66fc8536770481ab64a05aae5067c725f2b29a09543af00e6a417b97", size = 2090776, upload-time = "2026-11-05T09:14:30.281Z" }, + { url = "https://files.pythonhosted.org/packages/f9/14/aefc14e3e05013070ee959fc0b8703f6860a2776ed6e75b9c748f61aced0/pydantic_core-2.50.4-cp315-cp315t-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:789a6453e5ffd18a7ab6b8c3a0dd8403053829197ec258ecb90c604c21ffcc99", size = 2272481, upload-time = "2026-11-05T09:14:32.578Z" }, + { url = "https://files.pythonhosted.org/packages/13/c9/d56999aa7236dc9303091db2b1ef7303f0b022baf25ebf33cd200c0cb933/pydantic_core-2.50.4-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:6348ad12fa741bcc9c2f173e99fbf27cbc038826d8c31a4a7d836eca27878ba2", size = 2113069, upload-time = "2026-11-05T09:14:34.69Z" }, + { url = "https://files.pythonhosted.org/packages/b7/d5/a62da9e72f272f198f6118c5457332bbd4b9fdc4b77858448120569756de/pydantic_core-2.50.4-cp315-cp315t-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:d49127f137f871cde3c5650af33bbbdcee02679dae76e020902fa106f522b8ae", size = 2202754, upload-time = "2026-11-05T09:14:36.49Z" }, + { url = "https://files.pythonhosted.org/packages/37/4a/e7f21577f96e42ac3082cd014df398c1c913d482afac1c8ef17b9e039198/pydantic_core-2.50.4-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:2f5cc5bcb94063fbbdfd285a2b302da34af07491337c10bb35de1d5220fa1583", size = 2411472, upload-time = "2026-11-05T09:14:38.63Z" }, + { url = "https://files.pythonhosted.org/packages/38/ad/c57c5e13bbfd3404ec1af519764aadbc52ee01e39f9f9ae9d28317f982f2/pydantic_core-2.50.4-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:b99bed995ed7c41515c11fe2beb86f8a6cc298e5537cae2f736de2f982f74ef0", size = 2475330, upload-time = "2026-11-05T09:14:40.519Z" }, + { url = "https://files.pythonhosted.org/packages/6e/63/65cf0e1f1fd8cfaafee3c005712b8020e063b0f3e3571493ea68db5ec44f/pydantic_core-2.50.4-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:faa4e96385c820ce9d7f7a623486e23d4134ae3c9ba2071e44e0ab5a5a5002c4", size = 2265718, upload-time = "2026-11-05T09:14:42.379Z" }, + { url = "https://files.pythonhosted.org/packages/72/5d/fd9fdec9b25e2ef1f788970a84f749f0e28f166573c87654fd5387d8e5ce/pydantic_core-2.50.4-cp315-cp315t-manylinux_2_31_riscv64.whl", hash = "sha256:d6a166978f22f10cb91413f70519861605219346decf65bc79008f9257c94afe", size = 2273454, upload-time = "2026-11-05T09:14:44.286Z" }, + { url = "https://files.pythonhosted.org/packages/34/8c/19705c6d5eb72ff8c25006df8a375da7466176a5968781789e5415384f65/pydantic_core-2.50.4-cp315-cp315t-musllinux_1_1_aarch64.whl", hash = "sha256:a70d5effebd81ebd8e15a8aabdc7980832367b2b00c36543bac378977004cc80", size = 2314862, upload-time = "2026-11-05T09:14:45.97Z" }, + { url = "https://files.pythonhosted.org/packages/b8/fb/acefa27031aba2646b0d3026c4a1602e526489d39395ab17bc47f03234e3/pydantic_core-2.50.4-cp315-cp315t-musllinux_1_1_armv7l.whl", hash = "sha256:f8fd23653a252cefabea11cd041efd7b80bdf403e43a36dea53f9cb0aaa21f0f", size = 2479073, upload-time = "2026-11-05T09:14:47.526Z" }, + { url = "https://files.pythonhosted.org/packages/ef/e1/db08fa1e5edf1779fa0612f8d09f9030bdc513f593687c883cb781b86caa/pydantic_core-2.50.4-cp315-cp315t-musllinux_1_1_x86_64.whl", hash = "sha256:7646353a5a7c553c04167aca628e2550b538f492765b03ccf34321a560acc43c", size = 2521328, upload-time = "2026-11-05T09:14:49.042Z" }, + { url = "https://files.pythonhosted.org/packages/0d/51/bf1ec5b96c076d8d514b08f3bcffb3397df7a0fcc729eb960838a8bbe27f/pydantic_core-2.50.4-cp315-cp315t-win32.whl", hash = "sha256:65376dbe1ab4dbc768ca2b72b7c13993562c035f5925fd3bc7ff9c8c585c515d", size = 2107629, upload-time = "2026-11-05T09:14:50.891Z" }, + { url = "https://files.pythonhosted.org/packages/18/32/43d5db1824ec2314f737ff8d9962ff59954a74616d8656a8cc78790e45f1/pydantic_core-2.50.4-cp315-cp315t-win_amd64.whl", hash = "sha256:f08ee8248aad2d054e5bc4c73554d4505464698f6d754f16198dbc5764e9821d", size = 2244906, upload-time = "2026-11-05T09:14:53.056Z" }, + { url = "https://files.pythonhosted.org/packages/3a/c0/38c505004969c4641c3a077a8e72e354f02d5c06d8f51d7a103699704772/pydantic_core-2.50.4-cp315-cp315t-win_arm64.whl", hash = "sha256:da779ae50b46f3f7d1e1b5f362fdc0ad376a49fd55f6f3122dc2b6149936cdf7", size = 2179018, upload-time = "2026-11-05T09:14:54.448Z" }, + { url = "https://files.pythonhosted.org/packages/9a/18/2f6a25e9104d5af713d16671711927601da1f0db74e785be67bd590385c9/pydantic_core-2.50.4-graalpy312-graalpy250_312_native-macosx_10_12_x86_64.whl", hash = "sha256:c04e9d920e2674f54651fd260a15c5d2843526c73d5242ee4311325ddc9573b3", size = 2212591, upload-time = "2026-11-05T09:14:56.262Z" }, + { url = "https://files.pythonhosted.org/packages/4c/1b/ba8b721af10a7659e7fbbef320ff8eb55462557a72607858af5a9bd22cb1/pydantic_core-2.50.4-graalpy312-graalpy250_312_native-macosx_11_0_arm64.whl", hash = "sha256:5bc1811ef2b4d4ba63e8e452f6e332b6374bd1d2cbbfdf66826c8cb1f71dd10d", size = 2048167, upload-time = "2026-11-05T09:14:57.681Z" }, + { url = "https://files.pythonhosted.org/packages/48/42/3f8638e7d90bdd9a7c7f3e5084723af59e7f43f15a292e242d35624073ce/pydantic_core-2.50.4-graalpy312-graalpy250_312_native-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:0b059a7968b1911be5a2d9a8234827ab0bef9d1e465d4b42da525894143550e8", size = 2119548, upload-time = "2026-11-05T09:14:59.317Z" }, + { url = "https://files.pythonhosted.org/packages/e0/8d/4bfbacaf191f7939893d165e18eb301731fa3366c59a6e57336c4f168fbd/pydantic_core-2.50.4-graalpy312-graalpy250_312_native-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:bee28aab5a580eec673f7b68dfa8dece3dd37bd207ef8d22fafe23a8e9837296", size = 2279952, upload-time = "2026-11-05T09:15:00.907Z" }, + { url = "https://files.pythonhosted.org/packages/9e/3a/d405a50e02ea81cd95e93fc97f43d351eeaa1707c28aa6fb58a9f1c1efa9/pydantic_core-2.50.4-graalpy313-graalpy253_313_native-macosx_11_0_arm64.whl", hash = "sha256:71e03d2ea1a221d020cfc5b6cc8bbbedef23a06704c70fcf4d0afb42965b22d1", size = 2049324, upload-time = "2026-11-05T09:15:02.379Z" }, + { url = "https://files.pythonhosted.org/packages/8f/3b/03e7992115e17cae4131ecd71aadb8fd5e4a04cc2aead72c3c27e9b453d1/pydantic_core-2.50.4-graalpy313-graalpy253_313_native-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:09450778e3ab58d3f565899fcfbf6c82926e31af29e28e799d1d50941316e0cb", size = 2119802, upload-time = "2026-11-05T09:15:03.901Z" }, + { url = "https://files.pythonhosted.org/packages/e3/d5/b76fc647e473377ca6e693c21549ee3a4a7677e4962c28ae4659337c5114/pydantic_core-2.50.4-graalpy313-graalpy253_313_native-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:4eb15be588407148ef5937dc8d9256a71f6b115e6cddadb7aa20b6ee384680dc", size = 2280639, upload-time = "2026-11-05T09:15:05.374Z" }, + { url = "https://files.pythonhosted.org/packages/d8/18/3ca5b3b8ce7a540305e6856d013e9c6b9c0fef93258fef6038db0beb233a/pydantic_core-2.50.4-pp311-pypy311_pp73-macosx_10_12_x86_64.whl", hash = "sha256:39f489ce31272073e6e146f6781690f9c1ee8c126836e6403361ef91154d89fe", size = 2166960, upload-time = "2026-11-05T09:15:06.902Z" }, + { url = "https://files.pythonhosted.org/packages/a3/60/65d725001bffcde0170f6d37ae8bccce715e5311122eb6127f698115957e/pydantic_core-2.50.4-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:5b26e5f1793b96cdc60242bf38da86ff24a27a708aa396214cac9b534bf571c7", size = 2085636, upload-time = "2026-11-05T09:15:08.395Z" }, + { url = "https://files.pythonhosted.org/packages/ac/12/934cf1d44a3fee3c47231d4690dddee19264150c3aa59a3ddf66fa43454d/pydantic_core-2.50.4-pp311-pypy311_pp73-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:7210398a1607ad607dc73196e575b3148b00a333cbb602ddbe1b60ba54554f43", size = 2284621, upload-time = "2026-11-05T09:15:09.82Z" }, + { url = "https://files.pythonhosted.org/packages/c4/91/52248eee98d76f8d9239166d24928f805292df16729109f4f189cdb59be4/pydantic_core-2.50.4-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:2f42584e5785385f681163a42506cab0d51295e17599a648396c52a7046c1372", size = 2277673, upload-time = "2026-11-05T09:15:11.236Z" }, + { url = "https://files.pythonhosted.org/packages/9f/89/900a7970ef19843aa79522a95b461e9c365b7fedd7ee80ef28a84dae9a41/pydantic_core-2.50.4-pp311-pypy311_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:2039e323acee9abfec1fb5f661776e8965fe5928f3b7f8431900a774cba5c317", size = 2297354, upload-time = "2026-11-05T09:15:12.798Z" }, + { url = "https://files.pythonhosted.org/packages/de/ec/053d829437f70070cdd7116a0257cc0da651103328ff1e9e82954c45efd6/pydantic_core-2.50.4-pp311-pypy311_pp73-musllinux_1_1_armv7l.whl", hash = "sha256:71ade6d2e445839350d589ff99bbddfde16f3f32db28da5c894a09f99c8b2a03", size = 2469913, upload-time = "2026-11-05T09:15:14.319Z" }, + { url = "https://files.pythonhosted.org/packages/80/af/207c821cb0813e16d630660e0073491e3ab07370efaa6fa0b8b10fffb7b6/pydantic_core-2.50.4-pp311-pypy311_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:d7d406709ae924cf0b08b8282ca2f0e1c90526911d93bc040557cbc83b74c55f", size = 2503746, upload-time = "2026-11-05T09:15:15.736Z" }, + { url = "https://files.pythonhosted.org/packages/e7/ca/8a053f24e22d8150349cabaecb2f35c89dcf07fbaadb5e48295184dd0e5b/pydantic_core-2.50.4-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:7472c39480ccc11dda69a196d1b7c7a6b48eb6594b77f05d945599d3e47f731c", size = 2333540, upload-time = "2026-11-05T09:15:17.883Z" }, + { url = "https://files.pythonhosted.org/packages/ac/9d/41b374c62cdb87f84081e2ef2963a115eacc6284a26dbc96bb83568e83ec/pydantic_core-2.50.4-pp311-pypy311_pp80-macosx_10_12_x86_64.whl", hash = "sha256:b67d38e8bb0ade7e6e84575e4bb153fab35b122458077273aeb08fdf12be9d2c", size = 2166962, upload-time = "2026-11-05T09:15:20.276Z" }, + { url = "https://files.pythonhosted.org/packages/9a/4f/51ef440ee346d4388a2c4a3ac4b271fcc7b1d3ff68be8da2ed2be4d488b0/pydantic_core-2.50.4-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:4eda7e3fdef382b7d4492745988a5baaf6953923a337f8b9dde5f76fa8afde20", size = 2085634, upload-time = "2026-11-05T09:15:21.953Z" }, + { url = "https://files.pythonhosted.org/packages/4b/5f/c9ed62b96beb9050db221d29e81856b6e28f277db601f8b0c3a08f8cf913/pydantic_core-2.50.4-pp311-pypy311_pp80-manylinux_2_28_x86_64.whl", hash = "sha256:474f7e598c7902165662a5d5160d3fce31037890a2975a9871ebf7c05862300b", size = 2277804, upload-time = "2026-11-05T09:15:23.836Z" }, + { url = "https://files.pythonhosted.org/packages/63/bd/b912a5e251ef10ed7be5e543a2bfbeebb0c79bf6302bee786f8dc3bf4341/pydantic_core-2.50.4-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:3e0b395648c6cb871bceb2906907f255dc876ec425f2d5b024e129985cea8519", size = 2333539, upload-time = "2026-11-05T09:15:25.354Z" }, +] + [[package]] name = "registry-python-machine-service" version = "0.1.0" source = { virtual = "." } -dependencies = [ + +[package.optional-dependencies] +fastapi = [ + { name = "fastapi" }, + { name = "uvicorn" }, +] +flask = [ + { name = "flask" }, + { name = "gunicorn" }, +] + +[package.dev-dependencies] +dev = [ + { name = "fastapi" }, { name = "flask" }, + { name = "gunicorn" }, + { name = "httpx" }, + { name = "ruff" }, + { name = "uvicorn" }, ] [package.metadata] -requires-dist = [{ name = "flask", specifier = "==3.1.2" }] +requires-dist = [ + { name = "fastapi", marker = "extra == 'fastapi'", specifier = ">=0.115,<1" }, + { name = "flask", marker = "extra == 'flask'", specifier = "==3.1.2" }, + { name = "gunicorn", marker = "extra == 'flask'", specifier = ">=23,<24" }, + { name = "uvicorn", marker = "extra == 'fastapi'", specifier = ">=0.34,<1" }, +] +provides-extras = ["flask", "fastapi"] + +[package.metadata.requires-dev] +dev = [ + { name = "fastapi", specifier = ">=0.115,<1" }, + { name = "flask", specifier = "==3.1.2" }, + { name = "gunicorn", specifier = ">=23,<24" }, + { name = "httpx", specifier = ">=0.28,<1" }, + { name = "ruff", specifier = "==0.14.3" }, + { name = "uvicorn", specifier = ">=0.34,<1" }, +] + +[[package]] +name = "ruff" +version = "0.14.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/75/62/50b7727004dfe361104dfbf898c45a9a2fdfad8c72c04ae62900224d6ecf/ruff-0.14.3.tar.gz", hash = "sha256:4ff876d2ab2b161b6de0aa1f5bd714e8e9b4033dc122ee006925fbacc4f62153", size = 5558687, upload-time = "2025-10-31T00:26:26.878Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ce/8e/0c10ff1ea5d4360ab8bfca4cb2c9d979101a391f3e79d2616c9bf348cd26/ruff-0.14.3-py3-none-linux_armv6l.whl", hash = "sha256:876b21e6c824f519446715c1342b8e60f97f93264012de9d8d10314f8a79c371", size = 12535613, upload-time = "2025-10-31T00:25:44.302Z" }, + { url = "https://files.pythonhosted.org/packages/d3/c8/6724f4634c1daf52409fbf13fefda64aa9c8f81e44727a378b7b73dc590b/ruff-0.14.3-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:b6fd8c79b457bedd2abf2702b9b472147cd860ed7855c73a5247fa55c9117654", size = 12855812, upload-time = "2025-10-31T00:25:47.793Z" }, + { url = "https://files.pythonhosted.org/packages/de/03/db1bce591d55fd5f8a08bb02517fa0b5097b2ccabd4ea1ee29aa72b67d96/ruff-0.14.3-py3-none-macosx_11_0_arm64.whl", hash = "sha256:71ff6edca490c308f083156938c0c1a66907151263c4abdcb588602c6e696a14", size = 11944026, upload-time = "2025-10-31T00:25:49.657Z" }, + { url = "https://files.pythonhosted.org/packages/0b/75/4f8dbd48e03272715d12c87dc4fcaaf21b913f0affa5f12a4e9c6f8a0582/ruff-0.14.3-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:786ee3ce6139772ff9272aaf43296d975c0217ee1b97538a98171bf0d21f87ed", size = 12356818, upload-time = "2025-10-31T00:25:51.949Z" }, + { url = "https://files.pythonhosted.org/packages/ec/9b/506ec5b140c11d44a9a4f284ea7c14ebf6f8b01e6e8917734a3325bff787/ruff-0.14.3-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:cd6291d0061811c52b8e392f946889916757610d45d004e41140d81fb6cd5ddc", size = 12336745, upload-time = "2025-10-31T00:25:54.248Z" }, + { url = "https://files.pythonhosted.org/packages/c7/e1/c560d254048c147f35e7f8131d30bc1f63a008ac61595cf3078a3e93533d/ruff-0.14.3-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a497ec0c3d2c88561b6d90f9c29f5ae68221ac00d471f306fa21fa4264ce5fcd", size = 13101684, upload-time = "2025-10-31T00:25:56.253Z" }, + { url = "https://files.pythonhosted.org/packages/a5/32/e310133f8af5cd11f8cc30f52522a3ebccc5ea5bff4b492f94faceaca7a8/ruff-0.14.3-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:e231e1be58fc568950a04fbe6887c8e4b85310e7889727e2b81db205c45059eb", size = 14535000, upload-time = "2025-10-31T00:25:58.397Z" }, + { url = "https://files.pythonhosted.org/packages/a2/a1/7b0470a22158c6d8501eabc5e9b6043c99bede40fa1994cadf6b5c2a61c7/ruff-0.14.3-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:469e35872a09c0e45fecf48dd960bfbce056b5db2d5e6b50eca329b4f853ae20", size = 14156450, upload-time = "2025-10-31T00:26:00.889Z" }, + { url = "https://files.pythonhosted.org/packages/0a/96/24bfd9d1a7f532b560dcee1a87096332e461354d3882124219bcaff65c09/ruff-0.14.3-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:3d6bc90307c469cb9d28b7cfad90aaa600b10d67c6e22026869f585e1e8a2db0", size = 13568414, upload-time = "2025-10-31T00:26:03.291Z" }, + { url = "https://files.pythonhosted.org/packages/a7/e7/138b883f0dfe4ad5b76b58bf4ae675f4d2176ac2b24bdd81b4d966b28c61/ruff-0.14.3-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0e2f8a0bbcffcfd895df39c9a4ecd59bb80dca03dc43f7fb63e647ed176b741e", size = 13315293, upload-time = "2025-10-31T00:26:05.708Z" }, + { url = "https://files.pythonhosted.org/packages/33/f4/c09bb898be97b2eb18476b7c950df8815ef14cf956074177e9fbd40b7719/ruff-0.14.3-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:678fdd7c7d2d94851597c23ee6336d25f9930b460b55f8598e011b57c74fd8c5", size = 13539444, upload-time = "2025-10-31T00:26:08.09Z" }, + { url = "https://files.pythonhosted.org/packages/9c/aa/b30a1db25fc6128b1dd6ff0741fa4abf969ded161599d07ca7edd0739cc0/ruff-0.14.3-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:1ec1ac071e7e37e0221d2f2dbaf90897a988c531a8592a6a5959f0603a1ecf5e", size = 12252581, upload-time = "2025-10-31T00:26:10.297Z" }, + { url = "https://files.pythonhosted.org/packages/da/13/21096308f384d796ffe3f2960b17054110a9c3828d223ca540c2b7cc670b/ruff-0.14.3-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:afcdc4b5335ef440d19e7df9e8ae2ad9f749352190e96d481dc501b753f0733e", size = 12307503, upload-time = "2025-10-31T00:26:12.646Z" }, + { url = "https://files.pythonhosted.org/packages/cb/cc/a350bac23f03b7dbcde3c81b154706e80c6f16b06ff1ce28ed07dc7b07b0/ruff-0.14.3-py3-none-musllinux_1_2_i686.whl", hash = "sha256:7bfc42f81862749a7136267a343990f865e71fe2f99cf8d2958f684d23ce3dfa", size = 12675457, upload-time = "2025-10-31T00:26:15.044Z" }, + { url = "https://files.pythonhosted.org/packages/cb/76/46346029fa2f2078826bc88ef7167e8c198e58fe3126636e52f77488cbba/ruff-0.14.3-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:a65e448cfd7e9c59fae8cf37f9221585d3354febaad9a07f29158af1528e165f", size = 13403980, upload-time = "2025-10-31T00:26:17.81Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a4/35f1ef68c4e7b236d4a5204e3669efdeefaef21f0ff6a456792b3d8be438/ruff-0.14.3-py3-none-win32.whl", hash = "sha256:f3d91857d023ba93e14ed2d462ab62c3428f9bbf2b4fbac50a03ca66d31991f7", size = 12500045, upload-time = "2025-10-31T00:26:20.503Z" }, + { url = "https://files.pythonhosted.org/packages/03/15/51960ae340823c9859fb60c63301d977308735403e2134e17d1d2858c7fb/ruff-0.14.3-py3-none-win_amd64.whl", hash = "sha256:d7b7006ac0756306db212fd37116cce2bd307e1e109375e1c6c106002df0ae5f", size = 13594005, upload-time = "2025-10-31T00:26:22.533Z" }, + { url = "https://files.pythonhosted.org/packages/b7/73/4de6579bac8e979fca0a77e54dec1f1e011a0d268165eb8a9bc0982a6564/ruff-0.14.3-py3-none-win_arm64.whl", hash = "sha256:26eb477ede6d399d898791d01961e16b86f02bc2486d0d1a7a9bb2379d055dc1", size = 12590017, upload-time = "2025-10-31T00:26:24.52Z" }, +] + +[[package]] +name = "starlette" +version = "1.10.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/48/bb/3d8757f21e9a53d9035c9eb039a777047139a16bfdbedfc7a58241c3d914/starlette-1.10.0.tar.gz", hash = "sha256:b8399098d4c1e3522734f7235dc79b1fc967f96cf139c81e0fa30479e0685f9b", size = 2734356, upload-time = "2026-10-24T15:04:12.342Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/88/2e/947cfe02def9371c07cd5bf5b6b61c829e9aecb9904db02a66cfafbc1eec/starlette-1.10.0-py3-none-any.whl", hash = "sha256:478c0ab3b4ced6e82719849c118fa406f0278a3499c1a898cd15cd31bdc38ce4", size = 80571, upload-time = "2026-10-24T15:04:10.371Z" }, +] + +[[package]] +name = "typing-extensions" +version = "4.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, +] + +[[package]] +name = "typing-inspection" +version = "0.4.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ff/50/0195198eb1d75bab716bb0a813abea4cc394bfa17a92a189f021a34859af/typing_inspection-0.4.5.tar.gz", hash = "sha256:7f16c411e7930dc79596d42ab44672a3fe5f60eb34b781a1647e7872363120c7", size = 81194, upload-time = "2026-11-04T14:13:23.774Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/de/0c/ea2544850a7c135e15033a5c7a8e7211136184b7ae63e2239d557c2b3019/typing_inspection-0.4.5-py3-none-any.whl", hash = "sha256:bc210535442b39e1bf2805e0c7a17dfd6a4ace760c84c7f7d16245d23a6b1c39", size = 14874, upload-time = "2026-11-04T14:13:22.616Z" }, +] + +[[package]] +name = "uvicorn" +version = "0.54.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "h11" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/da/34/30e9280707135d2cfc589dfff3cb796bd07a3aeb1a3e415ba09dd89d7bb4/uvicorn-0.54.0.tar.gz", hash = "sha256:a2e33cbfaa0306f8e6b0c13e0cb89d7d7a2da3e62b90c66e18c33d9807b28620", size = 112283, upload-time = "2026-09-25T06:52:37.601Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/38/0c/b54a4fdd7f90a3af8b02ebc9ce6712c2c208b7926a2f7bad95c33ebbe943/uvicorn-0.54.0-py3-none-any.whl", hash = "sha256:505bdb0f318731d45f1f712071fc781a8981f6847a31c902c9f5e652d4f67faf", size = 87427, upload-time = "2026-09-25T06:52:35.829Z" }, +] [[package]] name = "werkzeug" diff --git a/products/platform/examples/python-portal/README.md b/products/platform/examples/python-portal/README.md index f0f4b2762e..04c7fd5e43 100644 --- a/products/platform/examples/python-portal/README.md +++ b/products/platform/examples/python-portal/README.md @@ -84,7 +84,7 @@ contract exported by BReg. Its synthetic reviewer uses the `licensing-auditor` client with matched BReg `auditor` and Casework `reviewer` grants. The local picker and native product journey have been exercised with synthetic credentials; real issuer tokens and browser renewal still require -separate acceptance before treating L3 or L4 as complete. +separate acceptance before treating holder or staff portal support as complete. ## Secrets and database @@ -103,6 +103,44 @@ Use a dedicated PostgreSQL database and least-privilege role for portal session state. Do not share the product databases. Supply secrets with the deployment platform or `op run`; do not commit an environment file. +## Session and request lifecycle + +`sessionSeconds` is an absolute portal-session lifetime measured from the final +successful product-grant callback. +Refreshing a product access token does not extend this lifetime. +`pendingSeconds` limits each pending authorization step; an expired callback is +refused and creates no session. +The example sets both services to a 900-second session and each pending step to +300 seconds. + +Before a protected route runs, the portal refreshes any product grant that has +30 seconds or less remaining. +The refresh must preserve the configured issuer, client, subject, principal, +persona, resource, profile, scopes and required claims. +If refresh fails, changes identity or authority, or finishes after the absolute +session expiry, the server deletes that session and the adapter returns +`401 authentication.reauthentication-required`. +It never converts expired person authority into a workload grant or +automatically replays a mutating handler. + +Logout and account switch delete local session state before attempting issuer +logout. +The browser cookie is cleared even if the issuer does not provide a usable +end-session response. +PostgreSQL keeps valid encrypted sessions across worker replacement and server +restart; a memory session store would intentionally lose them on restart. + +`requestSeconds` bounds the start of Registry Stack native work during one +request. +It does not cancel an already-started product call, application database work or +the Python handler. +The FastAPI routes in this example use synchronous `def` handlers, which the +framework offloads from its event-loop thread. +A direct native call from an asynchronous event-loop handler is refused; +explicitly use `asyncio.to_thread` when an asynchronous handler must make one. +If a mutating request loses its response, retain the original idempotency key +and inputs and reconcile the product result before attempting more work. + ## Install and start Use Python 3.11 or later. `sdk` must name the matching assembled or released @@ -225,4 +263,4 @@ dedicated PostgreSQL fixture, real products and a browser. Run one holder throug both frameworks, one staff service, two people with row/history denials, access token expiry and renewal, logout, account replacement, restart, two-worker refresh, encryption rotation, source reads and the full Casework staff journey. -Do not describe the source test as real sign-in or L3/L4 completion. +Do not describe the source test as real holder or staff sign-in proof. diff --git a/products/platform/examples/python-script/README.md b/products/platform/examples/python-script/README.md index a7a5651bad..00a159930e 100644 --- a/products/platform/examples/python-script/README.md +++ b/products/platform/examples/python-script/README.md @@ -60,6 +60,31 @@ Passing this command against a live runner demonstrates the runtime behavior. The source test below proves only that the same connection is retained and the second protected call is made; it cannot prove that a token file rotated. +## Recover after local expiry + +Runner rotation keeps a live run usable, but it never extends the run's TTL. +When the run expires or is stopped, its connection and token-state files are +removed. +Do not retry with the old `Connection`, copy its generated files, or lengthen a +token lifetime. +Start a new run with the commands in +[Start the prepared project](#start-the-prepared-project), export the new +`connection_file`, and rerun the script. + +If the supervisor was lost before cleanup completed, inspect the recorded run +and recover only that run against the PostgreSQL cluster used to start it: + +```sh +rstack dev status "$RUN_ID" --json +rstack dev stop "$RUN_ID" --recover +``` + +Use plain `rstack dev stop "$RUN_ID"` while the supervisor is still running. +Recovery refuses a different PostgreSQL cluster or maintenance database and +reports any resources that still need attention. +After recovery reports the run stopped, start a new run rather than reusing the +expired connection. + ## Verify the source example ```sh From 1f11790de7a978948197e0b3643c114a24e4a61b Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 10:40:53 +0700 Subject: [PATCH 24/34] fix(platform): document machine service admission authority Signed-off-by: Jeremi Joslin --- .../examples/python-machine-service/README.md | 73 +++++++ .../tests/test_service.py | 202 ++++++++++++++++++ 2 files changed, 275 insertions(+) diff --git a/products/platform/examples/python-machine-service/README.md b/products/platform/examples/python-machine-service/README.md index 7bffa1bc50..f1328547eb 100644 --- a/products/platform/examples/python-machine-service/README.md +++ b/products/platform/examples/python-machine-service/README.md @@ -75,6 +75,79 @@ Set these variables before starting the process: - `MESSAGE_EFFECT_AUDIT_KEY_HEX` is a secret, independently generated 32-byte audit key encoded as 64 hexadecimal characters; inject it at process start through the operator's secret manager, without writing it into the connection or fixture. - `MESSAGE_EFFECT_TARGETS` is a JSON object mapping checked workload-authority fingerprints to a named Messaging binding, or to `null` for the default. +The connection must declare two separate authorities. The `bindings` entry is +the service's outbound Messaging workload identity. The top-level `admission` +entry is the exact inbound Coordinator identity allowed to call protected +routes. An outbound-only connection remains valid for scripts that do not +admit callers, but it is not a machine-service configuration for either web +factory. + +This closed synthetic example names every required field. Its example domains, +client registrations and key reference are not a live deployment. Replace +them with one issuer's registered Coordinator client and this service's +separately registered Messaging workload client. Keep the inbound resource, +client, profile, scopes and claims aligned with the token the Coordinator is +actually issued. + + + +```json +{ + "apiVersion": "id.registrystack.org/formats/platform/python-connection/v1alpha1", + "kind": "PlatformPythonConnection", + "service": "renewal-notice-service", + "audience": "service", + "secretProviders": { + "file": { + "root": "/run/secrets/renewal-service" + } + }, + "bindings": [ + { + "name": "approval-notices", + "product": "messaging", + "url": "https://messaging.example.org/", + "default": true, + "credential": { + "type": "private-key-jwt", + "issuer": "https://identity.example.org/", + "subject": "renewal-notice-service", + "tokenEndpoint": "https://identity.example.org/oauth/token", + "clientId": "renewal-notice-messaging", + "profile": "service-sender", + "clientKeyRef": "secret:file/messaging-client.jwk", + "resource": "urn:example:messaging", + "scopes": [ + "messaging:send" + ], + "claims": { + "registry_actor_kind": "service" + } + } + } + ], + "admission": { + "issuer": "https://identity.example.org/", + "resource": "urn:example:renewal-notice-service", + "clientId": "renewal-notice-coordinator", + "profile": "coordinator-invoker", + "requiredScopes": [ + "renewal-notices:invoke" + ], + "requiredClaims": { + "registry_actor_kind": "service" + }, + "algorithm": "RS256", + "accessTokenType": "at+jwt", + "maximumAccessTokenLifetimeSeconds": 300, + "jwksUri": "https://identity.example.org/.well-known/jwks.json", + "clockSkewSeconds": 60 + } +} +``` + + + For example: ```sh diff --git a/products/platform/examples/python-machine-service/tests/test_service.py b/products/platform/examples/python-machine-service/tests/test_service.py index a21ace1c5f..6bbb6a8ca2 100644 --- a/products/platform/examples/python-machine-service/tests/test_service.py +++ b/products/platform/examples/python-machine-service/tests/test_service.py @@ -126,6 +126,208 @@ def test_framework_servers_are_separate_extras_and_dev_installs_both(self) -> No self.assertIn("ruff==0.14.3", dev) +class RealConnectionFactoryTests(unittest.TestCase): + def setUp(self) -> None: + self.temporary = tempfile.TemporaryDirectory() + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + self.prior_modules = { + name: module + for name, module in sys.modules.items() + if name == "registry_client" or name.startswith("registry_client.") + } + for name in self.prior_modules: + sys.modules.pop(name, None) + + package = types.ModuleType("registry_client") + package.__path__ = [str(CLIENT_SOURCE)] + sys.modules["registry_client"] = package + + yaml_module = types.ModuleType("registry_client.yaml") + + class ConfigReadError(ValueError): + def __init__(self, message, *, diagnostics=None): + super().__init__(message) + self.diagnostics = diagnostics or () + + def read_document(contents, *, file, api_version, kind): + del file + + def unique_members(pairs): + value = {} + for name, member in pairs: + if name in value: + raise ConfigReadError("duplicate mapping key") + value[name] = member + return value + + try: + value = json.loads(contents, object_pairs_hook=unique_members) + except (UnicodeError, json.JSONDecodeError): + raise ConfigReadError("invalid connection document") from None + if value.get("apiVersion") != api_version or value.get("kind") != kind: + raise ConfigReadError("wrong connection envelope") + return value + + yaml_module.ConfigReadError = ConfigReadError + yaml_module.read_document = read_document + sys.modules["registry_client.yaml"] = yaml_module + + oidc_module = types.ModuleType("registry_client.oidc") + + class VerificationFailure(ValueError): + kind = "verification" + + class AccessTokenVerifier: + instances = [] + results = {} + + def __init__(self, *args, **options): + self.args = args + self.options = options + self.__class__.instances.append(self) + + def verify(self, token): + result = self.__class__.results.get(token) + if result is None: + raise VerificationFailure("synthetic token refused") + return result + + oidc_module.AccessTokenVerifier = AccessTokenVerifier + sys.modules["registry_client.oidc"] = oidc_module + + self.connection = importlib.import_module("registry_client.connection") + package.connect = self.connection.connect + package.flask_adapter = importlib.import_module("registry_client.flask_adapter") + self.AccessTokenVerifier = AccessTokenVerifier + self.addCleanup(self.restore_modules) + + def restore_modules(self) -> None: + for name in tuple(sys.modules): + if name == "registry_client" or name.startswith("registry_client."): + sys.modules.pop(name, None) + sys.modules.update(self.prior_modules) + + def documented_connection(self) -> dict[str, object]: + readme = (EXAMPLE / "README.md").read_text(encoding="utf-8") + section = readme.split("", 1)[ + 1 + ].split("", 1)[0] + source = section.split("```json", 1)[1].split("```", 1)[0] + return json.loads(source) + + def verified(self, admission, *, scopes=None, claims=None): + return types.SimpleNamespace( + kind="access", + issuer=admission["issuer"], + audiences=(admission["resource"],), + subject="synthetic-coordinator-run", + client_id=admission["clientId"], + scopes=tuple(scopes or admission["requiredScopes"]), + claims=dict(claims or admission["requiredClaims"]), + ) + + def test_documented_connection_reaches_real_machine_admission(self) -> None: + document = self.documented_connection() + secrets = self.root / "secrets" + secrets.mkdir(mode=0o700) + document["secretProviders"]["file"]["root"] = str(secrets) + connection_path = self.root / "connection.json" + + outbound_only = json.loads(json.dumps(document)) + outbound_only.pop("admission") + connection_path.write_text(json.dumps(outbound_only), encoding="utf-8") + script_stack = self.connection.connect(path=connection_path) + self.assertEqual(script_stack.authority("messaging").product, "messaging") + with self.assertRaisesRegex( + self.connection.ConnectionError, + "machine admission is not configured", + ): + script_stack.admit({"authorization": ["Bearer admitted"]}) + + connection_path.write_text(json.dumps(document), encoding="utf-8") + + admission = document["admission"] + self.AccessTokenVerifier.results = { + "admitted": self.verified(admission), + "wrong-scope": self.verified(admission, scopes=("other:invoke",)), + "wrong-claim": self.verified( + admission, + claims={"registry_actor_kind": "person"}, + ), + } + stack = self.connection.connect(path=connection_path) + fingerprint = stack.authority("messaging").fingerprint + context = stack.admit({"authorization": ["Bearer admitted"]}) + self.assertEqual(context.client_id, admission["clientId"]) + self.assertEqual(context.profile, admission["profile"]) + self.assertEqual(context.issuer, admission["issuer"]) + self.assertEqual(context.resource, admission["resource"]) + settings = { + "REGISTRY_STACK_CONNECTION": str(connection_path), + "MESSAGE_EFFECT_DATABASE": str(self.root / "effects.sqlite3"), + "MESSAGE_EFFECT_SERVICE_NAMESPACE": "urn:example:service:renewal-notices", + "MESSAGE_EFFECT_TARGETS": json.dumps({fingerprint: None}), + "MESSAGE_EFFECT_AUDIT_KEY_HEX": "a" * 64, + } + + with patch.dict(os.environ, settings, clear=True): + app = create_app_from_environment() + app.testing = True + client = app.test_client() + refused = client.post( + "/v1/message-effects", + json={"key": "command-1", "noticeId": "notice-1"}, + headers={"Authorization": "Bearer wrong-scope"}, + ) + wrong_claim = client.post( + "/v1/message-effects", + json={"key": "command-1", "noticeId": "notice-1"}, + headers={"Authorization": "Bearer wrong-claim"}, + ) + admitted = client.post( + "/v1/message-effects", + json={"key": "command-1", "noticeId": "notice-1"}, + headers={"Authorization": "Bearer admitted"}, + ) + + self.assertEqual(refused.status_code, 401) + self.assertEqual(refused.json, {"code": "authentication.refused"}) + self.assertEqual(wrong_claim.status_code, 401) + self.assertEqual(wrong_claim.json, {"code": "authentication.refused"}) + self.assertEqual(admitted.status_code, 422) + self.assertEqual( + admitted.json, + {"state": "refused", "code": "notice-not-found"}, + ) + self.assertEqual(len(self.AccessTokenVerifier.instances), 2) + for verifier in self.AccessTokenVerifier.instances: + self.assertEqual( + verifier.args, + ( + admission["issuer"], + admission["resource"], + admission["clientId"], + ), + ) + self.assertEqual(verifier.options["algorithm"], admission["algorithm"]) + self.assertEqual( + verifier.options["access_token_type"], admission["accessTokenType"] + ) + self.assertEqual( + verifier.options["maximum_access_token_lifetime_seconds"], + admission["maximumAccessTokenLifetimeSeconds"], + ) + self.assertEqual( + verifier.options["claim_names"], + tuple(admission["requiredClaims"]), + ) + self.assertEqual(verifier.options["jwks_uri"], admission["jwksUri"]) + self.assertEqual( + verifier.options["clock_skew_seconds"], admission["clockSkewSeconds"] + ) + + class MachineServiceTests(unittest.TestCase): def setUp(self) -> None: self.temporary = tempfile.TemporaryDirectory() From 0196b18ffe8abf5c531e080e77ff2aba999d7e05 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 10:41:17 +0700 Subject: [PATCH 25/34] test(coordinator): run external job acceptance in CI Signed-off-by: Jeremi Joslin --- .github/scripts/ci_changes.py | 1 + .github/scripts/test_ci_changes.py | 51 ++++++++++++++++++- .github/workflows/ci.yml | 47 ++++++++++++++++- products/coordinator/AGENTS.md | 1 + products/coordinator/README.md | 9 ++-- products/coordinator/scripts/test-postgres.sh | 12 ++++- 6 files changed, 114 insertions(+), 7 deletions(-) diff --git a/.github/scripts/ci_changes.py b/.github/scripts/ci_changes.py index 0c7d750697..2a55bd5adf 100644 --- a/.github/scripts/ci_changes.py +++ b/.github/scripts/ci_changes.py @@ -1521,6 +1521,7 @@ def classify( "products/platform/examples/python-composition/", "products/platform/examples/python-machine-service/", "products/platform/examples/python-portal/", + "products/coordinator/examples/external-job/", "products/coordinator/examples/reviewed-notice/", )) for path in changed_paths) ) diff --git a/.github/scripts/test_ci_changes.py b/.github/scripts/test_ci_changes.py index c07ebf9fb0..215b0b7fec 100644 --- a/.github/scripts/test_ci_changes.py +++ b/.github/scripts/test_ci_changes.py @@ -1410,12 +1410,14 @@ def test_coordinator_postgres_proof_has_its_own_database_job(self) -> None: self.assertIn("COORDINATOR_TEST_DATABASE_URL", proof["env"]) self.assertIn("COORDINATOR_MESSAGING_TEST_DATABASE_URL", proof["env"]) self.assertIn("COORDINATOR_SCHEDULING_TEST_DATABASE_URL", proof["env"]) + self.assertIn("EXTERNAL_JOB_TEST_DATABASE_URL", proof["env"]) database_urls = ( proof["env"]["COORDINATOR_TEST_DATABASE_URL"], proof["env"]["COORDINATOR_MESSAGING_TEST_DATABASE_URL"], proof["env"]["COORDINATOR_SCHEDULING_TEST_DATABASE_URL"], + proof["env"]["EXTERNAL_JOB_TEST_DATABASE_URL"], ) - self.assertEqual(len(set(database_urls)), 3) + self.assertEqual(len(set(database_urls)), 4) database_preparation = "\n".join( step.get("run", "") for step in job["steps"] ) @@ -1423,12 +1425,59 @@ def test_coordinator_postgres_proof_has_its_own_database_job(self) -> None: self.assertIn("createdb coordinator_messaging", database_preparation) self.assertTrue(database_urls[2].endswith("/coordinator_scheduling")) self.assertIn("createdb coordinator_scheduling", database_preparation) + self.assertTrue(database_urls[3].endswith("/coordinator_external_job")) + self.assertIn("createdb coordinator_external_job", database_preparation) script = Path("products/coordinator/scripts/test-postgres.sh").read_text() self.assertRegex(script, r"cargo test --locked -p registry-coordinator[^\n]*--lib") self.assertIn("--test messaging_integration", script) self.assertIn("--test process_restart", script) self.assertIn("--test deployment_postgres", script) self.assertIn("cargo build --locked -p registry-messaging -p registry-messagingctl", script) + self.assertIn("external-job/tests/test_service.py", script) + self.assertIn("external-job/tests/test_postgres.py", script) + self.assertIn( + "uv run --project products/coordinator/examples/external-job", script + ) + + def test_external_job_routes_postgres_and_installed_wheel_acceptance(self) -> None: + outputs = classify( + self.workspace, + ("products/coordinator/examples/external-job/service.py",), + ) + self.assertTrue(outputs["coordinator"]) + self.assertTrue(outputs["client_bindings"]) + self.assertFalse( + classify( + self.workspace, + ("products/coordinator/examples/delayed-follow-up/workflow.yaml",), + )["client_bindings"] + ) + + job = self.workflow_jobs["client-bindings"] + self.assertIn("postgres", job.get("services", {})) + acceptance = next( + step + for step in job["steps"] + if step.get("name") == "Test installed-wheel Coordinator external job" + ) + self.assertIn("COORDINATOR_TEST_DATABASE_URL", acceptance["env"]) + self.assertIn("EXTERNAL_JOB_TEST_DATABASE_URL", acceptance["env"]) + self.assertNotEqual( + acceptance["env"]["COORDINATOR_TEST_DATABASE_URL"], + acceptance["env"]["EXTERNAL_JOB_TEST_DATABASE_URL"], + ) + self.assertIn("test_acceptance_server.py", acceptance["run"]) + self.assertEqual( + acceptance["run"].count( + 'uv run --with "${REGISTRY_CLIENT_PY_WHEEL}"' + ), + 2, + ) + self.assertIn( + "installed_python_job_recovers_the_original_command_after_commit", + acceptance["run"], + ) + self.assertIn("--ignored", acceptance["run"]) def test_shared_review_protocol_selects_casework_and_breg_consumers(self) -> None: outputs = classify( diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b3da041e0e..aa6f4756ab 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1463,8 +1463,14 @@ jobs: cache-targets: false save-if: ${{ github.ref == 'refs/heads/main' }} + - name: Install uv + uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2 + with: + version: "0.11.16" + # The suite composes with real Messaging and Scheduling runtimes, which - # each need a database of their own beside the Coordinator's. + # each need a database of their own beside the Coordinator's. The + # application-owned external job keeps its receipt in a fourth database. - name: Prepare the product test databases env: PGHOST: 127.0.0.1 @@ -1474,11 +1480,13 @@ jobs: run: | createdb coordinator_messaging createdb coordinator_scheduling + createdb coordinator_external_job - name: Verify coordinator restart, fencing, and native product recovery env: COORDINATOR_TEST_DATABASE_URL: postgresql://coordinator:coordinator_test@127.0.0.1:${{ job.services.postgres.ports['5432'] }}/coordinator COORDINATOR_MESSAGING_TEST_DATABASE_URL: postgresql://coordinator:coordinator_test@127.0.0.1:${{ job.services.postgres.ports['5432'] }}/coordinator_messaging COORDINATOR_SCHEDULING_TEST_DATABASE_URL: postgresql://coordinator:coordinator_test@127.0.0.1:${{ job.services.postgres.ports['5432'] }}/coordinator_scheduling + EXTERNAL_JOB_TEST_DATABASE_URL: postgresql://coordinator:coordinator_test@127.0.0.1:${{ job.services.postgres.ports['5432'] }}/coordinator_external_job run: products/coordinator/scripts/test-postgres.sh messaging-smtp: @@ -3275,6 +3283,20 @@ jobs: if: needs.changes.outputs.client_bindings == 'true' runs-on: ubuntu-24.04 timeout-minutes: 45 + services: + postgres: + image: docker.io/library/postgres:17.11@sha256:67f41722b7a8cbdb868a44a4995c846eddfdc2973bccb291ce937dce88ad5675 + env: + POSTGRES_DB: client_bindings + POSTGRES_USER: client_bindings + POSTGRES_PASSWORD: client_bindings_test + options: >- + --health-cmd "pg_isready -U client_bindings -d client_bindings" + --health-interval 10s + --health-timeout 5s + --health-retries 5 + ports: + - 5432/tcp steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 @@ -3449,6 +3471,29 @@ jobs: working-directory: products/coordinator/examples/reviewed-notice run: uv run --locked python -m unittest discover -s tests -v + - name: Test installed-wheel Coordinator external job + working-directory: products/coordinator/examples/external-job + shell: bash + env: + COORDINATOR_TEST_DATABASE_URL: postgresql://client_bindings:client_bindings_test@127.0.0.1:${{ job.services.postgres.ports['5432'] }}/client_bindings + EXTERNAL_JOB_TEST_DATABASE_URL: postgresql://client_bindings:client_bindings_test@127.0.0.1:${{ job.services.postgres.ports['5432'] }}/client_bindings_external_job + EXTERNAL_JOB_PYTHON: python + PGHOST: 127.0.0.1 + PGPORT: ${{ job.services.postgres.ports['5432'] }} + PGUSER: client_bindings + PGPASSWORD: client_bindings_test + run: | + set -euo pipefail + createdb client_bindings_external_job + uv run --with "${REGISTRY_CLIENT_PY_WHEEL}" \ + python -W error::ResourceWarning -m unittest \ + tests/test_acceptance_server.py -v + uv run --with "${REGISTRY_CLIENT_PY_WHEEL}" \ + cargo test --locked -p registry-coordinator \ + --features postgres-test --test external_wait_postgres \ + installed_python_job_recovers_the_original_command_after_commit \ + -- --ignored --nocapture + - name: Retain Linux Python client candidate for runtime acceptance uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: diff --git a/products/coordinator/AGENTS.md b/products/coordinator/AGENTS.md index 3d392c6f84..921266cf0c 100644 --- a/products/coordinator/AGENTS.md +++ b/products/coordinator/AGENTS.md @@ -77,6 +77,7 @@ cargo test --locked -p registry-coordinator-client -p registry-stack-client COORDINATOR_TEST_DATABASE_URL= \ COORDINATOR_MESSAGING_TEST_DATABASE_URL= \ COORDINATOR_SCHEDULING_TEST_DATABASE_URL= \ +EXTERNAL_JOB_TEST_DATABASE_URL= \ products/coordinator/scripts/test-postgres.sh ``` diff --git a/products/coordinator/README.md b/products/coordinator/README.md index 53c5470a01..7fc4b898bb 100644 --- a/products/coordinator/README.md +++ b/products/coordinator/README.md @@ -580,11 +580,13 @@ The schema check generates temporary outputs and compares them with the committe OpenAPI document. It does not rewrite tracked artifacts; regenerate changed artifacts explicitly with their owning generators. -With three dedicated disposable PostgreSQL 17+ databases configured, use +With four dedicated disposable PostgreSQL 17+ databases configured, use `scripts/test-postgres.sh` for the maintained durable-state, encrypted-custody, restart, deployment/router, review waits, standalone review, bounded external waits, and -Messaging and Scheduling integration checks. The three URLs must name distinct databases owned -by the test identity. That script first builds the independent Messaging and Scheduling services +Messaging and Scheduling integration checks. The four URLs must name distinct databases owned +by the test identity. The external-job example runs its Python WSGI and PostgreSQL +tests in the fourth database before the Rust suites. The script then builds the +independent Messaging and Scheduling services and operator executables, then supplies `COORDINATOR_MESSAGING_BIN`, `COORDINATOR_MESSAGINGCTL_BIN`, `COORDINATOR_SCHEDULING_BIN`, and `COORDINATOR_SCHEDULINGCTL_BIN` to the tests. The integration fixtures compose through the @@ -595,6 +597,7 @@ runtimes as test dependencies. COORDINATOR_TEST_DATABASE_URL= \ COORDINATOR_MESSAGING_TEST_DATABASE_URL= \ COORDINATOR_SCHEDULING_TEST_DATABASE_URL= \ +EXTERNAL_JOB_TEST_DATABASE_URL= \ products/coordinator/scripts/test-postgres.sh ``` diff --git a/products/coordinator/scripts/test-postgres.sh b/products/coordinator/scripts/test-postgres.sh index 364c48f7ff..fa59131298 100755 --- a/products/coordinator/scripts/test-postgres.sh +++ b/products/coordinator/scripts/test-postgres.sh @@ -5,10 +5,14 @@ set -euo pipefail : "${COORDINATOR_TEST_DATABASE_URL:?set the disposable local coordinator database URL}" : "${COORDINATOR_MESSAGING_TEST_DATABASE_URL:?set a separate disposable local Messaging database URL}" : "${COORDINATOR_SCHEDULING_TEST_DATABASE_URL:?set a separate disposable local Scheduling database URL}" +: "${EXTERNAL_JOB_TEST_DATABASE_URL:?set a separate disposable external-job database URL}" if [[ "$COORDINATOR_TEST_DATABASE_URL" == "$COORDINATOR_MESSAGING_TEST_DATABASE_URL" || "$COORDINATOR_TEST_DATABASE_URL" == "$COORDINATOR_SCHEDULING_TEST_DATABASE_URL" || - "$COORDINATOR_MESSAGING_TEST_DATABASE_URL" == "$COORDINATOR_SCHEDULING_TEST_DATABASE_URL" ]]; then - printf '%s\n' "Coordinator, Messaging, and Scheduling tests require distinct disposable databases." >&2 + "$COORDINATOR_TEST_DATABASE_URL" == "$EXTERNAL_JOB_TEST_DATABASE_URL" || + "$COORDINATOR_MESSAGING_TEST_DATABASE_URL" == "$COORDINATOR_SCHEDULING_TEST_DATABASE_URL" || + "$COORDINATOR_MESSAGING_TEST_DATABASE_URL" == "$EXTERNAL_JOB_TEST_DATABASE_URL" || + "$COORDINATOR_SCHEDULING_TEST_DATABASE_URL" == "$EXTERNAL_JOB_TEST_DATABASE_URL" ]]; then + printf '%s\n' "Coordinator, Messaging, Scheduling, and external-job tests require distinct disposable databases." >&2 exit 1 fi @@ -16,6 +20,10 @@ cd "$(dirname "$0")/../../.." export CARGO_INCREMENTAL=0 export CARGO_PROFILE_DEV_DEBUG=0 export CARGO_PROFILE_TEST_DEBUG=0 +uv run --project products/coordinator/examples/external-job \ + python -W error::ResourceWarning -m unittest \ + products/coordinator/examples/external-job/tests/test_service.py \ + products/coordinator/examples/external-job/tests/test_postgres.py -v # Compose through independently built product executables, never runtime # dev-dependencies. Tests refuse missing binaries rather than skipping coverage. cargo build --locked -p registry-messaging -p registry-messagingctl \ From 575bda3dee36c53e0fcf30c9a06490aca9567a3a Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 10:41:28 +0700 Subject: [PATCH 26/34] test(release): qualify Python wheels without publishing Signed-off-by: Jeremi Joslin --- .../python-release-wheel-qualification.yml | 197 ++++++++++++++++++ .../test_release_workflow_structure.py | 130 +++++++++++- 2 files changed, 326 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/python-release-wheel-qualification.yml diff --git a/.github/workflows/python-release-wheel-qualification.yml b/.github/workflows/python-release-wheel-qualification.yml new file mode 100644 index 0000000000..2a87d32b42 --- /dev/null +++ b/.github/workflows/python-release-wheel-qualification.yml @@ -0,0 +1,197 @@ +name: Qualify release-profile Python wheel +run-name: Qualify release-profile Python wheel at ${{ github.event.pull_request.head.sha || github.sha }} + +on: + workflow_dispatch: + pull_request: + branches: + - main + - release/1.0 + types: [labeled, synchronize] + +permissions: + contents: read + +concurrency: + group: python-release-wheel-${{ github.event.pull_request.head.sha || github.sha }} + cancel-in-progress: false + +env: + CARGO_INCREMENTAL: "0" + CARGO_PROFILE_DEV_DEBUG: "0" + CARGO_PROFILE_TEST_DEBUG: "0" + +jobs: + qualify: + name: Release-profile Python wheel (${{ matrix.asset }}) + if: github.event_name == 'workflow_dispatch' || contains(github.event.pull_request.labels.*.name, 'ci:python-release-wheel') + runs-on: ${{ matrix.runner }} + timeout-minutes: 45 + permissions: + contents: read + env: + RUSTUP_TOOLCHAIN: "1.95.0" + CARGO_TARGET_DIR: ${{ github.workspace }}/target/python-release-wheel-qualification + AWS_LC_FIPS_SYS_STATIC: "1" + QUALIFICATION_SOURCE_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + strategy: + fail-fast: false + matrix: + include: + - runner: ubuntu-24.04 + asset: linux-amd64-glibc + napi_platform: linux-x64-gnu + wheel_tag: cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64 + - runner: ubuntu-24.04-arm + asset: linux-arm64-glibc + napi_platform: linux-arm64-gnu + wheel_tag: cp311-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64 + steps: + - name: Checkout exact qualification source + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ env.QUALIFICATION_SOURCE_SHA }} + fetch-depth: 1 + persist-credentials: false + submodules: false + + - name: Install Go for the AWS-LC-FIPS source build + uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version: 1.27.2 + cache: false + + - name: Install uv + uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2 + with: + version: "0.11.16" + + - name: Build release-profile unified wheel + shell: bash + run: | + set -euo pipefail + rustup toolchain install 1.95.0 --profile minimal + uv venv "${RUNNER_TEMP}/maturin" + uv pip install --python "${RUNNER_TEMP}/maturin/bin/python" \ + --require-hashes --only-binary :all: \ + --requirement "${GITHUB_WORKSPACE}/release/requirements/maturin-1.9.6.txt" + version="$(python3 -c 'import tomllib; print(tomllib.load(open("crates/registry-stack-client-py/pyproject.toml", "rb"))["project"]["version"])')" + output_dir="${RUNNER_TEMP}/python-release-wheel" + python3 release/scripts/assemble-registry-client-packages.py \ + --artifacts python \ + --napi-platform "${{ matrix.napi_platform }}" \ + --version "${version}" \ + --python-profile release \ + --output-dir "${output_dir}" \ + --work-dir "${RUNNER_TEMP}/python-release-wheel-assembly" \ + --maturin "${RUNNER_TEMP}/maturin/bin/maturin" \ + --zig-python "${RUNNER_TEMP}/maturin/bin/python" + wheel="${output_dir}/registry_stack_client-${version}-${{ matrix.wheel_tag }}.whl" + test -f "${wheel}" + test "$(find "${output_dir}" -maxdepth 1 -type f -name '*.whl' | wc -l)" -eq 1 + evidence_dir="${RUNNER_TEMP}/python-release-wheel-evidence" + mkdir -p "${evidence_dir}" + cp "${wheel}" "${evidence_dir}/" + wheel_name="$(basename "${wheel}")" + ( + cd "${evidence_dir}" + sha256sum "${wheel_name}" >SHA256SUMS + ) + { + printf 'QUALIFICATION_VERSION=%s\n' "${version}" + printf 'QUALIFICATION_WHEEL=%s\n' "${wheel}" + printf 'QUALIFICATION_EVIDENCE_DIR=%s\n' "${evidence_dir}" + } >>"${GITHUB_ENV}" + + - name: Exercise clean installed-wheel modes + shell: bash + run: | + set -euo pipefail + for mode in core flask fastapi human-flask human-fastapi; do + environment="${RUNNER_TEMP}/client-${mode}" + uv venv "${environment}" + case "${mode}" in + core) + uv pip install --python "${environment}/bin/python" \ + --no-deps "${QUALIFICATION_WHEEL}" + "${environment}/bin/python" -I \ + release/scripts/smoke-registry-client-package.py + ;; + flask) + uv pip install --python "${environment}/bin/python" \ + "${QUALIFICATION_WHEEL}[flask]" + ;; + fastapi) + uv pip install --python "${environment}/bin/python" \ + "${QUALIFICATION_WHEEL}[fastapi]" httpx==0.28.1 + ;; + human-flask) + uv pip install --python "${environment}/bin/python" \ + "${QUALIFICATION_WHEEL}[human,flask,postgres]" + ;; + human-fastapi) + uv pip install --python "${environment}/bin/python" \ + "${QUALIFICATION_WHEEL}[human,fastapi,postgres]" + ;; + esac + "${environment}/bin/python" -I \ + release/scripts/smoke-registry-client-extras.py "${mode}" + done + service_environment="${RUNNER_TEMP}/client-service-smoke" + uv venv "${service_environment}" + uv pip install --python "${service_environment}/bin/python" \ + "${QUALIFICATION_WHEEL}[human,flask,fastapi,postgres]" httpx==0.28.1 + "${service_environment}/bin/python" -I \ + release/scripts/smoke-registry-client-service.py + + - name: Record qualification evidence + shell: bash + env: + QUALIFICATION_ASSET: ${{ matrix.asset }} + QUALIFICATION_WHEEL_TAG: ${{ matrix.wheel_tag }} + run: | + set -euo pipefail + python3 - "${QUALIFICATION_EVIDENCE_DIR}/qualification.json" <<'PY' + import json + import os + from pathlib import Path + + output = Path(__import__("sys").argv[1]) + output.write_text( + json.dumps( + { + "schema_version": "registry-stack.python-wheel-qualification.v1", + "source_sha": os.environ["QUALIFICATION_SOURCE_SHA"], + "version": os.environ["QUALIFICATION_VERSION"], + "asset": os.environ["QUALIFICATION_ASSET"], + "wheel_tag": os.environ["QUALIFICATION_WHEEL_TAG"], + "profile": "release", + "checks": { + "package_smoke": "passed", + "clean_install_modes": [ + "core", + "flask", + "fastapi", + "human-flask", + "human-fastapi", + ], + "installed_service_smoke": "passed", + }, + }, + indent=2, + sort_keys=True, + ) + + "\n", + encoding="utf-8", + ) + PY + + - name: Retain wheel and qualification evidence + if: ${{ always() && env.QUALIFICATION_WHEEL != '' }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: python-release-wheel-${{ matrix.asset }}-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ env.QUALIFICATION_EVIDENCE_DIR }} + if-no-files-found: error + retention-days: 8 + compression-level: 0 diff --git a/release/scripts/test_release_workflow_structure.py b/release/scripts/test_release_workflow_structure.py index c900ef3d42..5e53c3251c 100644 --- a/release/scripts/test_release_workflow_structure.py +++ b/release/scripts/test_release_workflow_structure.py @@ -369,6 +369,129 @@ def test_publishes_one_unique_prerelease_and_prints_its_curl_command(self) -> No self.assertNotIn(forbidden, text) +class PythonReleaseWheelQualificationWorkflowTest(unittest.TestCase): + WORKFLOW = "python-release-wheel-qualification.yml" + + def test_activation_is_deliberate_and_the_matrix_is_linux_only(self) -> None: + _, document = workflow(self.WORKFLOW) + triggers = document[True] + self.assertIn("workflow_dispatch", triggers) + self.assertEqual( + triggers["pull_request"], + { + "branches": ["main", "release/1.0"], + "types": ["labeled", "synchronize"], + }, + ) + self.assertEqual(document["permissions"], {"contents": "read"}) + + job = document["jobs"]["qualify"] + self.assertEqual( + job["if"], + "github.event_name == 'workflow_dispatch' || " + "contains(github.event.pull_request.labels.*.name, " + "'ci:python-release-wheel')", + ) + self.assertEqual(job["permissions"], {"contents": "read"}) + self.assertEqual(job["timeout-minutes"], 45) + self.assertEqual( + job["strategy"]["matrix"]["include"], + [ + { + "runner": "ubuntu-24.04", + "asset": "linux-amd64-glibc", + "napi_platform": "linux-x64-gnu", + "wheel_tag": "cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64", + }, + { + "runner": "ubuntu-24.04-arm", + "asset": "linux-arm64-glibc", + "napi_platform": "linux-arm64-gnu", + "wheel_tag": "cp311-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64", + }, + ], + ) + + def test_builds_and_exercises_the_release_profile_wheel(self) -> None: + _, document = workflow(self.WORKFLOW) + job = document["jobs"]["qualify"] + assert_pinned_go(self, document, "qualify") + self.assertEqual(job["env"]["RUSTUP_TOOLCHAIN"], "1.95.0") + self.assertEqual(job["env"]["AWS_LC_FIPS_SYS_STATIC"], "1") + self.assertEqual( + job["env"]["CARGO_TARGET_DIR"], + "${{ github.workspace }}/target/python-release-wheel-qualification", + ) + checkout = next( + step + for step in job["steps"] + if step.get("name") == "Checkout exact qualification source" + ) + self.assertEqual(checkout["with"]["ref"], "${{ env.QUALIFICATION_SOURCE_SHA }}") + self.assertFalse(checkout["with"]["persist-credentials"]) + + build = step_run(document, "qualify", "Build release-profile unified wheel") + self.assertIn("release/requirements/maturin-1.9.6.txt", build) + self.assertIn('uv venv "${RUNNER_TEMP}/maturin"', build) + self.assertIn('uv pip install --python "${RUNNER_TEMP}/maturin/bin/python"', build) + self.assertIn("--require-hashes --only-binary :all:", build) + self.assertNotIn("python3 -m venv", build) + self.assertNotIn("/bin/pip", build) + self.assertIn("release/scripts/assemble-registry-client-packages.py", build) + self.assertIn("--artifacts python", build) + self.assertIn('--napi-platform "${{ matrix.napi_platform }}"', build) + self.assertIn("--python-profile release", build) + self.assertIn('--maturin "${RUNNER_TEMP}/maturin/bin/maturin"', build) + self.assertIn('--zig-python "${RUNNER_TEMP}/maturin/bin/python"', build) + self.assertIn("sha256sum", build) + self.assertNotIn("--include-render", build) + + smoke = step_run(document, "qualify", "Exercise clean installed-wheel modes") + self.assertIn("release/scripts/smoke-registry-client-package.py", smoke) + self.assertIn("release/scripts/smoke-registry-client-service.py", smoke) + for mode in ("core", "flask", "fastapi", "human-flask", "human-fastapi"): + self.assertIn(mode, smoke) + self.assertIn("--no-deps", smoke) + self.assertIn('"${environment}/bin/python" -I', smoke) + self.assertIn('"${service_environment}/bin/python" -I', smoke) + + evidence = step_run(document, "qualify", "Record qualification evidence") + self.assertIn("qualification.json", evidence) + self.assertIn("QUALIFICATION_SOURCE_SHA", evidence) + upload = next( + step + for step in job["steps"] + if step.get("name") == "Retain wheel and qualification evidence" + ) + self.assertEqual( + upload["if"], "${{ always() && env.QUALIFICATION_WHEEL != '' }}" + ) + self.assertEqual(upload["with"]["retention-days"], 8) + self.assertEqual(upload["with"]["compression-level"], 0) + self.assertEqual(upload["with"]["if-no-files-found"], "error") + + def test_has_no_publication_or_registry_write_capability(self) -> None: + text, document = workflow(self.WORKFLOW) + job = document["jobs"]["qualify"] + self.assertFalse(any("attest" in str(step).lower() for step in job["steps"])) + for forbidden in ( + "packages: write", + "contents: write", + "id-token: write", + "attestations: write", + "npm publish", + "maturin publish", + "twine upload", + "gh release", + "git tag", + "git push", + "docker push", + "oras ", + "ghcr.io", + ): + self.assertNotIn(forbidden, text) + + class CandidateWorkflowStructureTest(unittest.TestCase): def test_pins_go_for_every_host_native_artifact_build(self) -> None: _, document = workflow("release-candidate.yml") @@ -2942,6 +3065,7 @@ def test_every_go_setup_pins_the_supported_toolchain(self) -> None: ("macos-contributor.yml", "direct-cargo-binaries"), ("nightly-release.yml", "arm64"), ("nightly-release.yml", "macos"), + ("python-release-wheel-qualification.yml", "qualify"), ("release-candidate.yml", "build-macos-platforms"), ("release-candidate.yml", "build-platforms"), ("release-candidate.yml", "clients"), @@ -3877,7 +4001,11 @@ def test_the_roster_includes_the_breg_services_from_a_named_first_release( ) PYTHON_WHEEL_ABI_TAG_PATTERN = re.compile(r"cp3\d+-abi3") PYTHON_STABLE_ABI_FEATURE_PATTERN = re.compile(r"abi3-py3\d+") -PYTHON_WHEEL_WORKFLOWS = ("evidence-dev.yml", "release-candidate.yml") +PYTHON_WHEEL_WORKFLOWS = ( + "evidence-dev.yml", + "python-release-wheel-qualification.yml", + "release-candidate.yml", +) def load_release_script(name: str): From bb5550a6cac23f6c1d66b4eee74974bdbb700145 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 10:53:34 +0700 Subject: [PATCH 27/34] test(platform): exercise machine admission in FastAPI Signed-off-by: Jeremi Joslin --- .../tests/test_service.py | 40 ++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/products/platform/examples/python-machine-service/tests/test_service.py b/products/platform/examples/python-machine-service/tests/test_service.py index 6bbb6a8ca2..b5a4dfb375 100644 --- a/products/platform/examples/python-machine-service/tests/test_service.py +++ b/products/platform/examples/python-machine-service/tests/test_service.py @@ -300,7 +300,45 @@ def test_documented_connection_reaches_real_machine_admission(self) -> None: admitted.json, {"state": "refused", "code": "notice-not-found"}, ) - self.assertEqual(len(self.AccessTokenVerifier.instances), 2) + + with patch.dict(os.environ, settings, clear=True): + fastapi_app = create_fastapi_app_from_environment() + + async def exercise_fastapi(): + transport = httpx.ASGITransport(app=fastapi_app) + async with httpx.AsyncClient( + transport=transport, + base_url="http://testserver", + ) as fastapi_client: + command = {"key": "command-1", "noticeId": "notice-1"} + denied_scope = await fastapi_client.post( + "/v1/message-effects", + json=command, + headers={"Authorization": "Bearer wrong-scope"}, + ) + denied_claim = await fastapi_client.post( + "/v1/message-effects", + json=command, + headers={"Authorization": "Bearer wrong-claim"}, + ) + allowed = await fastapi_client.post( + "/v1/message-effects", + json=command, + headers={"Authorization": "Bearer admitted"}, + ) + return denied_scope, denied_claim, allowed + + denied_scope, denied_claim, allowed = asyncio.run(exercise_fastapi()) + self.assertEqual(denied_scope.status_code, 401) + self.assertEqual(denied_scope.json(), {"code": "authentication.refused"}) + self.assertEqual(denied_claim.status_code, 401) + self.assertEqual(denied_claim.json(), {"code": "authentication.refused"}) + self.assertEqual(allowed.status_code, 422) + self.assertEqual( + allowed.json(), + {"state": "refused", "code": "notice-not-found"}, + ) + self.assertEqual(len(self.AccessTokenVerifier.instances), 3) for verifier in self.AccessTokenVerifier.instances: self.assertEqual( verifier.args, From acf2c9fc13dc2f76cb5611005b6629d84b08e176 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 11:12:57 +0700 Subject: [PATCH 28/34] test(coordinator): prove durable Python job recovery Signed-off-by: Jeremi Joslin --- .../tests/external_wait_postgres.rs | 336 +++++++++++++++++- .../examples/external-job/README.md | 28 +- 2 files changed, 347 insertions(+), 17 deletions(-) diff --git a/crates/registry-coordinator/tests/external_wait_postgres.rs b/crates/registry-coordinator/tests/external_wait_postgres.rs index 7968acc9a5..f8e0c97c22 100644 --- a/crates/registry-coordinator/tests/external_wait_postgres.rs +++ b/crates/registry-coordinator/tests/external_wait_postgres.rs @@ -4,10 +4,11 @@ #![cfg(feature = "postgres-test")] use std::{ - io::{BufRead, BufReader}, + io::{BufRead, BufReader, Read}, process::{Child, Command, Stdio}, sync::{mpsc, Arc}, - time::Duration, + thread::JoinHandle, + time::{Duration, Instant}, }; use async_trait::async_trait; @@ -31,18 +32,24 @@ const PYTHON_ACCEPTANCE_TOKEN: &str = "external-job-acceptance-token"; struct PythonService { child: Child, + stderr_reader: Option>, + reaped: bool, base_url: String, } impl PythonService { fn start(fault: &str) -> Self { + let schema = format!("external_job_{}", Uuid::new_v4().simple()); + Self::start_in_schema(fault, &schema) + } + + fn start_in_schema(fault: &str, schema: &str) -> Self { let python = std::env::var("EXTERNAL_JOB_PYTHON") .expect("EXTERNAL_JOB_PYTHON must name the installed-wheel Python interpreter"); let database = std::env::var("EXTERNAL_JOB_TEST_DATABASE_URL") .expect("EXTERNAL_JOB_TEST_DATABASE_URL must name a separate disposable database"); let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) .join("../../products/coordinator/examples/external-job/tests/acceptance_server.py"); - let schema = format!("external_job_{}", Uuid::new_v4().simple()); let child = Command::new(python) .arg(script) .arg("--fault") @@ -51,13 +58,23 @@ impl PythonService { .arg(schema) .env("EXTERNAL_JOB_DATABASE_URL", database) .stdout(Stdio::piped()) - .stderr(Stdio::inherit()) + .stderr(Stdio::piped()) .spawn() .expect("start the installed-wheel Python acceptance host"); let mut service = Self { child, + stderr_reader: None, + reaped: false, base_url: String::new(), }; + let mut stderr = service.child.stderr.take().unwrap(); + service.stderr_reader = Some(std::thread::spawn(move || { + let mut output = String::new(); + stderr + .read_to_string(&mut output) + .expect("read Python acceptance stderr"); + output + })); let stdout = service.child.stdout.take().unwrap(); let (sender, receiver) = mpsc::channel(); let reader = std::thread::spawn(move || { @@ -77,14 +94,59 @@ impl PythonService { .to_owned(); service } -} -impl Drop for PythonService { - fn drop(&mut self) { + fn wait_for_exit(&mut self, expected_code: i32) { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + match self.child.try_wait().expect("read Python acceptance exit") { + Some(status) => { + assert_eq!(status.code(), Some(expected_code)); + self.reaped = true; + return; + } + None if Instant::now() < deadline => { + std::thread::sleep(Duration::from_millis(10)); + } + None => panic!("Python acceptance host did not exit within 10 seconds"), + } + } + } + + fn take_stderr(&mut self) -> String { + assert!(self.reaped, "reap the Python acceptance host first"); + self.stderr_reader + .take() + .expect("Python acceptance stderr is available") + .join() + .expect("Python acceptance stderr reader exited") + } + + fn stop_and_take_stderr(&mut self) -> String { let _ = self.child.kill(); self.child .wait() .expect("reap the Python acceptance host after the journey"); + self.reaped = true; + self.take_stderr() + } +} + +impl Drop for PythonService { + fn drop(&mut self) { + if !self.reaped { + let _ = self.child.kill(); + self.child + .wait() + .expect("reap the Python acceptance host after the journey"); + self.reaped = true; + } + if self.stderr_reader.is_some() { + let stderr = self.take_stderr(); + assert!( + stderr.is_empty(), + "Python acceptance host wrote unexpected stderr" + ); + } } } @@ -283,6 +345,34 @@ impl Harness { Worker::new(self.store.clone(), self.adapters.clone()) } + fn bind_python(&mut self, service: &PythonService) { + let mut config: ExternalHttpConfig = serde_json::from_value(json!({ + "baseUrl":service.base_url, + "paths":["jobs/status"], + "queryParameters":["id"], + "commandPath":"jobs", + "responseSchema":{"type":"object"} + })) + .unwrap(); + config.authorization = Some( + serde_json::from_value(json!({ + "tokenEndpoint":"http://127.0.0.1:9999/token", + "clientId":"coordinator-external-job", + "signingKeyRef":"secret:file/external-job-client-jwk", + "resource":"urn:example:external-job", + "scopes":["external-job:admit","external-job:observe"] + })) + .unwrap(), + ); + self.adapters = Arc::new(ExternalAdapter( + ExternalHttpConnection::new( + &config, + Some(Arc::new(StaticToken::new(PYTHON_ACCEPTANCE_TOKEN).unwrap())), + ) + .unwrap(), + )); + } + async fn begin_wait(&self) -> Uuid { self.admitted("running").await; let run = self.start().await; @@ -432,6 +522,238 @@ async fn installed_python_job_recovers_the_original_command_after_commit() { assert!(terminal.waits.is_empty()); } +#[tokio::test] +#[ignore = "requires separate disposable Coordinator and external-job databases plus an installed-wheel Python interpreter"] +async fn installed_python_job_survives_process_death_after_commit_and_restart() { + let schema = format!("external_job_{}", Uuid::new_v4().simple()); + let mut service = PythonService::start_in_schema("process-exit-after-commit", &schema); + let mut h = Harness::new().await; + h.bind_python(&service); + + let run = h.start().await; + h.drain(&h.worker()).await; + let held = h + .store + .inspect(run, h.adapters.binding_digest()) + .await + .unwrap(); + assert_eq!(held.run.state, "attention"); + assert!(held.run.uncertain); + assert_eq!( + serde_json::to_value(&held.effects[0]).unwrap()["state"], + "unknown" + ); + assert!(held.recovery.retry_allowed); + assert_eq!( + held.recovery.operation, + Some(Operation::ExternalCommand.identity()) + ); + service.wait_for_exit(86); + assert!(service.take_stderr().is_empty()); + drop(service); + + let service = PythonService::start_in_schema("none", &schema); + h.bind_python(&service); + h.store + .retry_same(run, h.adapters.binding_digest()) + .await + .unwrap(); + h.drain(&h.worker()).await; + let recovered = h + .store + .inspect(run, h.adapters.binding_digest()) + .await + .unwrap(); + assert_eq!(recovered.run.step, "await-terminal"); + assert_eq!(recovered.effects.len(), 1); + assert_eq!(recovered.waits.len(), 1); + + let client = reqwest::Client::builder() + .timeout(Duration::from_secs(10)) + .build() + .unwrap(); + let snapshot: Value = client + .get(format!("{}/test/snapshot", service.base_url)) + .bearer_auth(PYTHON_ACCEPTANCE_TOKEN) + .send() + .await + .unwrap() + .error_for_status() + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(snapshot["jobCount"], 1); + assert_eq!( + snapshot["jobs"][0]["request"], + json!({"reference":"case-001"}) + ); + let job_id = snapshot["jobs"][0]["receipt"]["jobId"] + .as_str() + .unwrap() + .to_owned(); + + for state in ["running", "succeeded"] { + client + .post(format!("{}/test/transition", service.base_url)) + .bearer_auth(PYTHON_ACCEPTANCE_TOKEN) + .json(&json!({"jobId":job_id,"state":state})) + .send() + .await + .unwrap() + .error_for_status() + .unwrap(); + } + h.advance().await; + h.drain(&h.worker()).await; + let terminal = h + .store + .inspect(run, h.adapters.binding_digest()) + .await + .unwrap(); + assert_eq!(terminal.run.state, "finished"); + assert_eq!(terminal.run.outcome.as_deref(), Some("job-result")); + assert_eq!( + terminal.run.output, + Some(json!({"state":"complete","result":{"jobId":job_id}})) + ); +} + +#[tokio::test] +#[ignore = "requires separate disposable Coordinator and external-job databases plus an installed-wheel Python interpreter"] +async fn installed_python_encoding_failure_keeps_the_committed_job_recoverable() { + let mut service = PythonService::start("encoding-error-after-commit"); + let mut h = Harness::new().await; + h.bind_python(&service); + + let run = h.start().await; + h.drain(&h.worker()).await; + let held = h + .store + .inspect(run, h.adapters.binding_digest()) + .await + .unwrap(); + assert_eq!(held.run.state, "attention"); + assert!(held.run.uncertain); + assert_eq!( + serde_json::to_value(&held.effects[0]).unwrap()["state"], + "unknown" + ); + assert!(held.recovery.retry_allowed); + assert_eq!( + held.recovery.operation, + Some(Operation::ExternalCommand.identity()) + ); + + let client = reqwest::Client::builder() + .timeout(Duration::from_secs(10)) + .build() + .unwrap(); + let snapshot_url = format!("{}/test/snapshot", service.base_url); + let first_snapshot: Value = client + .get(&snapshot_url) + .bearer_auth(PYTHON_ACCEPTANCE_TOKEN) + .send() + .await + .unwrap() + .error_for_status() + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(first_snapshot["jobCount"], 1); + + h.store + .retry_same(run, h.adapters.binding_digest()) + .await + .unwrap(); + h.drain(&h.worker()).await; + let recovered = h + .store + .inspect(run, h.adapters.binding_digest()) + .await + .unwrap(); + assert_eq!(recovered.run.step, "await-terminal"); + assert_eq!(recovered.effects.len(), 1); + assert_eq!(recovered.waits.len(), 1); + let recovered_snapshot: Value = client + .get(&snapshot_url) + .bearer_auth(PYTHON_ACCEPTANCE_TOKEN) + .send() + .await + .unwrap() + .error_for_status() + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(recovered_snapshot, first_snapshot); + let stderr = service.stop_and_take_stderr(); + assert!(stderr.contains("UnicodeError: synthetic response encoding failure")); +} + +#[tokio::test] +async fn command_rate_limit_retries_without_claiming_an_unknown_effect() { + let h = Harness::new().await; + Mock::given(method("POST")) + .and(path("/jobs")) + .and(header_exists("idempotency-key")) + .and(body_json(json!({"reference":"case-001"}))) + .respond_with(ResponseTemplate::new(429).insert_header("retry-after", "1")) + .expect(1) + .mount(&h.server) + .await; + + let run = h.start().await; + h.drain(&h.worker()).await; + let rate_limited = h + .store + .inspect(run, h.adapters.binding_digest()) + .await + .unwrap(); + assert_eq!(rate_limited.run.state, "running"); + assert!(!rate_limited.run.uncertain); + assert!(rate_limited.effects.is_empty()); + assert!(!rate_limited.recovery.retry_allowed); + assert_eq!( + rate_limited.recovery.operation, + Some(Operation::ExternalCommand.identity()) + ); + let first_requests = h.server.received_requests().await.unwrap(); + assert_eq!(first_requests.len(), 1); + let first_key = first_requests[0].headers["idempotency-key"] + .to_str() + .unwrap() + .to_owned(); + + // Replace the 429 responder before the scheduled retry, so this attempt + // must reach a distinct accepted response. + h.admitted("running").await; + h.advance().await; + h.drain(&h.worker()).await; + let accepted = h + .store + .inspect(run, h.adapters.binding_digest()) + .await + .unwrap(); + assert_eq!(accepted.run.step, "await-terminal"); + assert!(!accepted.run.uncertain); + assert_eq!(accepted.effects.len(), 1); + assert_eq!( + serde_json::to_value(&accepted.effects[0]).unwrap()["state"], + "accepted" + ); + let retried_requests = h.server.received_requests().await.unwrap(); + let retried_post = retried_requests + .iter() + .find(|request| request.method.as_str() == "POST") + .unwrap(); + assert_eq!( + retried_post.headers["idempotency-key"].to_str().unwrap(), + first_key + ); +} + #[tokio::test] async fn declared_admission_refusal_takes_the_authored_no_effect_route() { let h = Harness::new().await; diff --git a/products/coordinator/examples/external-job/README.md b/products/coordinator/examples/external-job/README.md index 0b3d42d754..30ea2a28d0 100644 --- a/products/coordinator/examples/external-job/README.md +++ b/products/coordinator/examples/external-job/README.md @@ -127,11 +127,12 @@ EXTERNAL_JOB_TEST_DATABASE_URL=postgresql://... \ `crates/registry-coordinator/tests/external_wait_postgres.rs` drives the maintained project through the real external command and GET adapters, durable Coordinator store and worker. It covers accepted and declared-refused admission, unusable post-effect responses, same-command recovery, -restart, correlation, pending/success/declared job failure, observation exhaustion, timeout, -cancellation and deadline. A skipped database test is not evidence for either durable store. +command-side rate limiting, restart, correlation, pending/success/declared job failure, +observation exhaustion, timeout, cancellation and deadline. A skipped database test is not +evidence for either durable store. -An opt-in test in that target composes the Coordinator worker with the actual Python example -application and its separate PostgreSQL store. It requires the assembled Python wheel to be +Three opt-in tests in that target compose the Coordinator worker with the actual Python example +application and its separate PostgreSQL store. They require the assembled Python wheel to be installed in the selected interpreter: ```sh @@ -139,11 +140,18 @@ COORDINATOR_TEST_DATABASE_URL= \ EXTERNAL_JOB_TEST_DATABASE_URL= \ EXTERNAL_JOB_PYTHON= \ cargo test --locked -p registry-coordinator --features postgres-test \ - --test external_wait_postgres installed_python_job_recovers_the_original_command_after_commit \ - -- --ignored + --test external_wait_postgres installed_python_ -- --include-ignored ``` -The test-only loopback host uses synthetic machine admission. It asserts that a malformed -response after application commit leaves Coordinator uncertain, then `retry-same` reuses the -original saved command and receipt before observing terminal success. It does not prove live -issuer token exchange or institutional deployment. +The test-only loopback host uses synthetic machine admission. The tests assert that malformed +response bytes and an actual response-encoding failure after application commit leave Coordinator +uncertain with its pinned recovery operation, then `retry-same` reuses the original saved command +and receipt. A third test lets the Python process exit after commit, asserts its exit status, +starts a fresh process over the same application schema, and reaches terminal success without a +second job. They do not prove live issuer token exchange or institutional deployment. + +The Python reference application has no rate-limiting policy or 429 response path. The PostgreSQL +target proves that Coordinator treats a configured upstream 429 as known not processed and retries +the frozen command without recording an unknown effect. Proving that the reference application +itself emits 429 only before admission remains open until its application-level rate-limiting +policy is defined. From cc46f89f9f9370e227463d16152e7ac50b8f64c8 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 11:15:49 +0700 Subject: [PATCH 29/34] test(release): qualify macOS Python wheel on pull requests Signed-off-by: Jeremi Joslin --- .../python-release-wheel-qualification.yml | 26 +++++++++++++++++-- .../test_release_workflow_structure.py | 22 +++++++++++++++- 2 files changed, 45 insertions(+), 3 deletions(-) diff --git a/.github/workflows/python-release-wheel-qualification.yml b/.github/workflows/python-release-wheel-qualification.yml index 2a87d32b42..5c625ff836 100644 --- a/.github/workflows/python-release-wheel-qualification.yml +++ b/.github/workflows/python-release-wheel-qualification.yml @@ -46,6 +46,10 @@ jobs: asset: linux-arm64-glibc napi_platform: linux-arm64-gnu wheel_tag: cp311-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64 + - runner: macos-26 + asset: macos-arm64 + napi_platform: darwin-arm64 + wheel_tag: cp311-abi3-macosx_11_0_arm64 steps: - name: Checkout exact qualification source uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -76,6 +80,12 @@ jobs: --require-hashes --only-binary :all: \ --requirement "${GITHUB_WORKSPACE}/release/requirements/maturin-1.9.6.txt" version="$(python3 -c 'import tomllib; print(tomllib.load(open("crates/registry-stack-client-py/pyproject.toml", "rb"))["project"]["version"])')" + IFS=. read -r client_major client_minor _ <<<"${version}" + if [[ "${RUNNER_OS}" == macOS ]] && + (( client_major > 0 || client_minor >= 33 )); then + export AWS_LC_FIPS_SYS_STATIC=0 + export MACOSX_DEPLOYMENT_TARGET=11.0 + fi output_dir="${RUNNER_TEMP}/python-release-wheel" python3 release/scripts/assemble-registry-client-packages.py \ --artifacts python \ @@ -88,14 +98,19 @@ jobs: --zig-python "${RUNNER_TEMP}/maturin/bin/python" wheel="${output_dir}/registry_stack_client-${version}-${{ matrix.wheel_tag }}.whl" test -f "${wheel}" - test "$(find "${output_dir}" -maxdepth 1 -type f -name '*.whl' | wc -l)" -eq 1 + wheels=("${output_dir}"/*.whl) + test "${#wheels[@]}" -eq 1 evidence_dir="${RUNNER_TEMP}/python-release-wheel-evidence" mkdir -p "${evidence_dir}" cp "${wheel}" "${evidence_dir}/" wheel_name="$(basename "${wheel}")" ( cd "${evidence_dir}" - sha256sum "${wheel_name}" >SHA256SUMS + if command -v sha256sum >/dev/null 2>&1; then + sha256sum -- "${wheel_name}" >SHA256SUMS + else + shasum -a 256 -- "${wheel_name}" >SHA256SUMS + fi ) { printf 'QUALIFICATION_VERSION=%s\n' "${version}" @@ -107,6 +122,13 @@ jobs: shell: bash run: | set -euo pipefail + unset DYLD_LIBRARY_PATH DYLD_FALLBACK_LIBRARY_PATH DYLD_INSERT_LIBRARIES + if [[ "${RUNNER_OS}" == macOS ]]; then + build_root="${CARGO_TARGET_DIR}" + hidden_build_root="${build_root}.smoke-hidden" + mv -- "${build_root}" "${hidden_build_root}" + trap 'mv -- "${hidden_build_root}" "${build_root}"' EXIT + fi for mode in core flask fastapi human-flask human-fastapi; do environment="${RUNNER_TEMP}/client-${mode}" uv venv "${environment}" diff --git a/release/scripts/test_release_workflow_structure.py b/release/scripts/test_release_workflow_structure.py index 5e53c3251c..4affb4ecaf 100644 --- a/release/scripts/test_release_workflow_structure.py +++ b/release/scripts/test_release_workflow_structure.py @@ -372,7 +372,7 @@ def test_publishes_one_unique_prerelease_and_prints_its_curl_command(self) -> No class PythonReleaseWheelQualificationWorkflowTest(unittest.TestCase): WORKFLOW = "python-release-wheel-qualification.yml" - def test_activation_is_deliberate_and_the_matrix_is_linux_only(self) -> None: + def test_activation_is_deliberate_and_the_matrix_matches_release_targets(self) -> None: _, document = workflow(self.WORKFLOW) triggers = document[True] self.assertIn("workflow_dispatch", triggers) @@ -409,6 +409,12 @@ def test_activation_is_deliberate_and_the_matrix_is_linux_only(self) -> None: "napi_platform": "linux-arm64-gnu", "wheel_tag": "cp311-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64", }, + { + "runner": "macos-26", + "asset": "macos-arm64", + "napi_platform": "darwin-arm64", + "wheel_tag": "cp311-abi3-macosx_11_0_arm64", + }, ], ) @@ -443,10 +449,24 @@ def test_builds_and_exercises_the_release_profile_wheel(self) -> None: self.assertIn("--python-profile release", build) self.assertIn('--maturin "${RUNNER_TEMP}/maturin/bin/maturin"', build) self.assertIn('--zig-python "${RUNNER_TEMP}/maturin/bin/python"', build) + self.assertIn('[[ "${RUNNER_OS}" == macOS ]] &&', build) + self.assertIn("client_major > 0 || client_minor >= 33", build) + self.assertIn("export AWS_LC_FIPS_SYS_STATIC=0", build) + self.assertIn("export MACOSX_DEPLOYMENT_TARGET=11.0", build) self.assertIn("sha256sum", build) + self.assertIn("shasum -a 256", build) + self.assertNotIn("-maxdepth", build) self.assertNotIn("--include-render", build) smoke = step_run(document, "qualify", "Exercise clean installed-wheel modes") + self.assertIn( + "unset DYLD_LIBRARY_PATH DYLD_FALLBACK_LIBRARY_PATH DYLD_INSERT_LIBRARIES", + smoke, + ) + self.assertIn('mv -- "${build_root}" "${hidden_build_root}"', smoke) + self.assertIn( + 'trap \'mv -- "${hidden_build_root}" "${build_root}"\' EXIT', smoke + ) self.assertIn("release/scripts/smoke-registry-client-package.py", smoke) self.assertIn("release/scripts/smoke-registry-client-service.py", smoke) for mode in ("core", "flask", "fastapi", "human-flask", "human-fastapi"): From 3693ad873e40ff50f57cc9506e10d2ecc15ced56 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 11:25:44 +0700 Subject: [PATCH 30/34] test(coordinator): select durable Python recovery in CI Signed-off-by: Jeremi Joslin --- .github/scripts/test_ci_changes.py | 26 +++++++++-- .github/workflows/ci.yml | 3 +- .../tests/external_wait_postgres.rs | 45 +++++++++++++------ 3 files changed, 55 insertions(+), 19 deletions(-) diff --git a/.github/scripts/test_ci_changes.py b/.github/scripts/test_ci_changes.py index 215b0b7fec..6fb1918af3 100644 --- a/.github/scripts/test_ci_changes.py +++ b/.github/scripts/test_ci_changes.py @@ -1473,11 +1473,31 @@ def test_external_job_routes_postgres_and_installed_wheel_acceptance(self) -> No ), 2, ) + installed_acceptance = Path( + "crates/registry-coordinator/tests/external_wait_postgres.rs" + ).read_text(encoding="utf-8") + installed_tests = set( + re.findall( + r'#\[ignore = "[^"]*installed-wheel Python interpreter"\]\s*' + r"async fn (installed_python_[a-z0-9_]+)\(", + installed_acceptance, + ) + ) + self.assertEqual( + installed_tests, + { + "installed_python_encoding_failure_keeps_the_committed_job_recoverable", + "installed_python_job_recovers_the_original_command_after_commit", + "installed_python_job_survives_process_death_after_commit_and_restart", + }, + ) + normalized_acceptance = " ".join( + acceptance["run"].replace("\\\n", " ").split() + ) self.assertIn( - "installed_python_job_recovers_the_original_command_after_commit", - acceptance["run"], + "--test external_wait_postgres -- --include-ignored --nocapture", + normalized_acceptance, ) - self.assertIn("--ignored", acceptance["run"]) def test_shared_review_protocol_selects_casework_and_breg_consumers(self) -> None: outputs = classify( diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index aa6f4756ab..acc546ac9d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -3491,8 +3491,7 @@ jobs: uv run --with "${REGISTRY_CLIENT_PY_WHEEL}" \ cargo test --locked -p registry-coordinator \ --features postgres-test --test external_wait_postgres \ - installed_python_job_recovers_the_original_command_after_commit \ - -- --ignored --nocapture + -- --include-ignored --nocapture - name: Retain Linux Python client candidate for runtime acceptance uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 diff --git a/crates/registry-coordinator/tests/external_wait_postgres.rs b/crates/registry-coordinator/tests/external_wait_postgres.rs index f8e0c97c22..16b5cb6a7b 100644 --- a/crates/registry-coordinator/tests/external_wait_postgres.rs +++ b/crates/registry-coordinator/tests/external_wait_postgres.rs @@ -554,6 +554,33 @@ async fn installed_python_job_survives_process_death_after_commit_and_restart() let service = PythonService::start_in_schema("none", &schema); h.bind_python(&service); + let client = reqwest::Client::builder() + .timeout(Duration::from_secs(10)) + .build() + .unwrap(); + let snapshot_url = format!("{}/test/snapshot", service.base_url); + let committed_snapshot: Value = client + .get(&snapshot_url) + .bearer_auth(PYTHON_ACCEPTANCE_TOKEN) + .send() + .await + .unwrap() + .error_for_status() + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(committed_snapshot["jobCount"], 1); + let committed_job = &committed_snapshot["jobs"][0]; + assert_eq!(committed_job["request"], json!({"reference":"case-001"})); + assert!(committed_job["key"] + .as_str() + .is_some_and(|key| !key.is_empty())); + let job_id = committed_job["receipt"]["jobId"] + .as_str() + .expect("the restarted application read the committed receipt") + .to_owned(); + h.store .retry_same(run, h.adapters.binding_digest()) .await @@ -567,13 +594,8 @@ async fn installed_python_job_survives_process_death_after_commit_and_restart() assert_eq!(recovered.run.step, "await-terminal"); assert_eq!(recovered.effects.len(), 1); assert_eq!(recovered.waits.len(), 1); - - let client = reqwest::Client::builder() - .timeout(Duration::from_secs(10)) - .build() - .unwrap(); - let snapshot: Value = client - .get(format!("{}/test/snapshot", service.base_url)) + let recovered_snapshot: Value = client + .get(&snapshot_url) .bearer_auth(PYTHON_ACCEPTANCE_TOKEN) .send() .await @@ -583,15 +605,10 @@ async fn installed_python_job_survives_process_death_after_commit_and_restart() .json() .await .unwrap(); - assert_eq!(snapshot["jobCount"], 1); assert_eq!( - snapshot["jobs"][0]["request"], - json!({"reference":"case-001"}) + recovered_snapshot, committed_snapshot, + "retry-same preserved the original application key, request and receipt" ); - let job_id = snapshot["jobs"][0]["receipt"]["jobId"] - .as_str() - .unwrap() - .to_owned(); for state in ["running", "succeeded"] { client From dd339e45849a499e7660aa43d7ff0b1aa0a79697 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 11:27:08 +0700 Subject: [PATCH 31/34] test(platform): pin machine service workload authority Signed-off-by: Jeremi Joslin --- .../tests/test_effect.py | 66 +++++++++++++++++++ .../tests/test_service.py | 34 +++++++--- 2 files changed, 92 insertions(+), 8 deletions(-) diff --git a/products/platform/examples/python-machine-service/tests/test_effect.py b/products/platform/examples/python-machine-service/tests/test_effect.py index ee03eca5f9..3da2d75c64 100644 --- a/products/platform/examples/python-machine-service/tests/test_effect.py +++ b/products/platform/examples/python-machine-service/tests/test_effect.py @@ -451,6 +451,72 @@ def test_declared_no_effect_problem_is_terminal_and_not_retried(self) -> None: self.assertEqual(len(self.messaging.submit_calls), 1) self.assertEqual(self.messaging.receipt_calls, []) + def test_missing_authority_binding_is_uncertain_until_exact_binding_returns( + self, + ) -> None: + self.seed("notice-1", message("person@example.invalid"), authority="b" * 64) + + result = self.effect.execute(self.context, "command-1", "notice-1") + + self.assertEqual(result.status, 202) + self.assertEqual(result.body["state"], "uncertain") + self.assertRegex(result.body["recovery"], r"\A[0-9a-f]{64}\Z") + self.assertEqual(self.messaging.submit_calls, []) + self.assertEqual(self.messaging.receipt_calls, []) + + restored_client = FakeMessaging() + restored = MessageEffect( + MessageEffectStore(self.database), + MessagingTargets( + FakeStack(restored_client, authority=Authority("b" * 64)), + {"b" * 64: None}, + ), + service_namespace="urn:example:service:renewal-notices", + audit_key=b"A" * 32, + ).execute(self.context, "command-1", "notice-1") + + self.assertEqual(restored.status, 200) + self.assertEqual(restored.body["recovery"], result.body["recovery"]) + self.assertEqual(len(restored_client.submit_calls), 1) + + def test_product_403_is_terminal_without_identity_fallback(self) -> None: + primary = FakeMessaging() + secondary = FakeMessaging() + primary.submit_error = FakeMessagingError( + "operation.not-authorized", status=403, outcome_unknown=False + ) + stack = FakeStack( + primary, + {"secondary": secondary}, + authority=Authority("a" * 64), + authorities={"secondary": Authority("b" * 64)}, + ) + effect = MessageEffect( + self.store, + MessagingTargets( + stack, + {"a" * 64: None, "b" * 64: "secondary"}, + ), + service_namespace="urn:example:service:renewal-notices", + audit_key=b"A" * 32, + ) + self.seed("notice-1", message("person@example.invalid")) + + refused = effect.execute(self.context, "command-1", "notice-1") + repeated = effect.execute(self.context, "command-1", "notice-1") + + self.assertEqual(refused.status, 422) + self.assertEqual( + refused.body, + {"state": "refused", "code": "operation.not-authorized"}, + ) + self.assertEqual(repeated, refused) + self.assertEqual(len(primary.submit_calls), 1) + self.assertEqual(primary.receipt_calls, []) + self.assertEqual(secondary.submit_calls, []) + self.assertEqual(secondary.receipt_calls, []) + self.assertEqual(stack.selections, ["secondary"]) + def test_alias_can_change_for_same_authority_but_authority_cannot_change( self, ) -> None: diff --git a/products/platform/examples/python-machine-service/tests/test_service.py b/products/platform/examples/python-machine-service/tests/test_service.py index b5a4dfb375..6cd2134093 100644 --- a/products/platform/examples/python-machine-service/tests/test_service.py +++ b/products/platform/examples/python-machine-service/tests/test_service.py @@ -54,6 +54,18 @@ def load_client_module(name: str): web = load_client_module("web") workload = load_client_module("workload") +_REQUEST_AUTHORITY_SUBSTITUTIONS = ( + ("binding", "secondary"), + ("url", "https://other.example.invalid"), + ("ur\u2113", "https://other.example.invalid"), + ("subject", "other-service"), + ("subj\u0435ct", "other-service"), + ("scope", "admin"), + ("sc\u03bfpe", "admin"), + ("recipient", "substitute@example.invalid"), + ("token", "secret-canary"), +) + class Stack: def __init__(self) -> None: @@ -541,17 +553,11 @@ def test_cookie_or_missing_bearer_cannot_reach_the_effect(self) -> None: self.assertEqual(cookie.status_code, 401) self.assertEqual(self.stack.primary.submit_calls, []) - def test_request_cannot_select_binding_url_scope_recipient_or_token(self) -> None: + def test_request_cannot_substitute_workload_authority_or_recipient(self) -> None: self.seed("notice-1", message("protected@example.invalid")) base = {"key": "command-1", "noticeId": "notice-1"} - for field, value in [ - ("binding", "secondary"), - ("url", "https://other.example.invalid"), - ("scope", "admin"), - ("recipient", "substitute@example.invalid"), - ("token", "secret-canary"), - ]: + for field, value in _REQUEST_AUTHORITY_SUBSTITUTIONS: with self.subTest(field=field): response = self.post({**base, field: value}) self.assertEqual(response.status_code, 422) @@ -876,6 +882,18 @@ def test_duplicate_oversized_or_lookalike_command_is_refused(self) -> None: self.assertEqual(lookalike.status_code, 422) self.assertEqual(self.stack.primary.submit_calls, []) + def test_request_cannot_substitute_workload_authority_or_recipient(self) -> None: + self.seed("notice-1", message("protected@example.invalid")) + base = {"key": "command-1", "noticeId": "notice-1"} + + for field, value in _REQUEST_AUTHORITY_SUBSTITUTIONS: + with self.subTest(field=field): + response = self.post({**base, field: value}) + self.assertEqual(response.status_code, 422) + + self.assertEqual(self.stack.primary.submit_calls, []) + self.assertEqual(self.stack.secondary.submit_calls, []) + def test_streamed_body_stops_when_declared_length_is_exceeded(self) -> None: self.seed("notice-1", message("protected@example.invalid")) declared = b'{"key":"command-1","noticeId":"notice-1"}' From 6ead81fe3761d9afc7a0459183027c14594b0bb6 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 11:33:36 +0700 Subject: [PATCH 32/34] test(ci): route Coordinator wheel acceptance edits Signed-off-by: Jeremi Joslin --- .github/scripts/ci_changes.py | 6 ++++++ .github/scripts/test_ci_changes.py | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/.github/scripts/ci_changes.py b/.github/scripts/ci_changes.py index 2a55bd5adf..d4a023eb16 100644 --- a/.github/scripts/ci_changes.py +++ b/.github/scripts/ci_changes.py @@ -1517,6 +1517,12 @@ def classify( or unified_client_changed or "release/scripts/smoke-registry-client-service.py" in changed_paths or "release/scripts/smoke-registry-client-extras.py" in changed_paths + # This target's installed-wheel cases are ignored by the ordinary + # Coordinator PostgreSQL job and run in client-bindings instead. + or ( + "crates/registry-coordinator/tests/external_wait_postgres.rs" + in changed_paths + ) or any(path.startswith(( "products/platform/examples/python-composition/", "products/platform/examples/python-machine-service/", diff --git a/.github/scripts/test_ci_changes.py b/.github/scripts/test_ci_changes.py index 6fb1918af3..791ca37bac 100644 --- a/.github/scripts/test_ci_changes.py +++ b/.github/scripts/test_ci_changes.py @@ -1446,6 +1446,12 @@ def test_external_job_routes_postgres_and_installed_wheel_acceptance(self) -> No ) self.assertTrue(outputs["coordinator"]) self.assertTrue(outputs["client_bindings"]) + acceptance_test_outputs = classify( + self.workspace, + ("crates/registry-coordinator/tests/external_wait_postgres.rs",), + ) + self.assertTrue(acceptance_test_outputs["coordinator"]) + self.assertTrue(acceptance_test_outputs["client_bindings"]) self.assertFalse( classify( self.workspace, From 2f85ea660aa646b5fc723708c9b9d7d0b6306891 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 12:45:23 +0700 Subject: [PATCH 33/34] test(platform): pin machine recovery to original authority and request Signed-off-by: Jeremi Joslin --- .../python-machine-service/tests/test_effect.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/products/platform/examples/python-machine-service/tests/test_effect.py b/products/platform/examples/python-machine-service/tests/test_effect.py index 3da2d75c64..97c2e0faf3 100644 --- a/products/platform/examples/python-machine-service/tests/test_effect.py +++ b/products/platform/examples/python-machine-service/tests/test_effect.py @@ -133,12 +133,13 @@ def using(self, name): def authority_fingerprint( *, subject: str = "notice-service", + client_id: str = "notice-client", profile: str = "service-sender", claims: dict[str, object] | None = None, ) -> str: identity = { "claims": claims or {"registry_actor_kind": "service"}, - "clientId": "notice-client", + "clientId": client_id, "issuer": "https://issuer.example.invalid/", "product": "messaging", "profile": profile, @@ -375,12 +376,18 @@ def test_issuer_and_resource_changes_separate_protected_effects(self) -> None: def test_process_stop_after_acceptance_recovers_without_resubmission(self) -> None: payload = message("person@example.invalid") + original = json.loads(json.dumps(payload)) self.seed("notice-1", payload) self.messaging.stop_after_accept = True with self.assertRaises(SyntheticProcessStop): self.effect.execute(self.context, "command-1", "notice-1") + payload["to"] = {"email": "changed@example.invalid"} + payload["template"] = {"id": "renewal", "version": "2"} + with self.assertRaisesRegex(ValueError, "immutable"): + self.seed("notice-1", payload) + recovered_client = FakeMessaging(self.messaging.effects) restarted = MessageEffect( MessageEffectStore(self.database), @@ -394,7 +401,7 @@ def test_process_stop_after_acceptance_recovers_without_resubmission(self) -> No self.assertEqual(result.body["state"], "accepted") self.assertEqual(recovered_client.submit_calls, []) self.assertEqual(len(recovered_client.receipt_calls), 1) - self.assertEqual(recovered_client.receipt_calls[0][1], payload) + self.assertEqual(recovered_client.receipt_calls[0][1], original) def test_unknown_reply_uses_receipt_recovery_and_never_submit_again(self) -> None: self.seed("notice-1", message("person@example.invalid")) @@ -573,7 +580,7 @@ def test_alias_can_change_for_same_authority_but_authority_cannot_change( ) self.assertEqual(unavailable_client.submit_calls, []) - def test_subject_profile_or_claim_change_cannot_recover_old_unknown_command( + def test_subject_client_profile_or_claim_change_cannot_recover_old_unknown_command( self, ) -> None: original = authority_fingerprint() @@ -599,6 +606,7 @@ def test_subject_profile_or_claim_change_cannot_recover_old_unknown_command( changes = { "subject": authority_fingerprint(subject="other-service"), + "client": authority_fingerprint(client_id="other-client"), "profile": authority_fingerprint(profile="other-sender"), "claims": authority_fingerprint(claims={"registry_actor_kind": "human"}), } From 4b1d2904ef3035e5d172b31625d33c75ac8d6664 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 13:02:02 +0700 Subject: [PATCH 34/34] test(platform): match Messaging receipt expiry contract Signed-off-by: Jeremi Joslin --- .../examples/python-machine-service/tests/test_effect.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/products/platform/examples/python-machine-service/tests/test_effect.py b/products/platform/examples/python-machine-service/tests/test_effect.py index 97c2e0faf3..3dea34d9df 100644 --- a/products/platform/examples/python-machine-service/tests/test_effect.py +++ b/products/platform/examples/python-machine-service/tests/test_effect.py @@ -429,7 +429,7 @@ def test_later_denial_or_expired_receipt_keeps_the_outcome_uncertain(self) -> No for code, status in [ ("operation.not-authorized", 403), - ("idempotency.expired", 410), + ("receipt.unresolved", 409), ]: with self.subTest(code=code): self.messaging.receipt_error = FakeMessagingError(