From 4b1aa4991182fe21d722e6335bf572d0d6416774 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 8 Nov 2026 06:16:10 +1300 Subject: [PATCH 01/29] Compose isolated Account login and first-invoice receiving --- .../account-service/api-contracts.md | 8 +- .../account-service/configuration.md | 10 +- .../account-service/operations.md | 4 +- .../account-service/runtime-and-data.md | 2 + .../account-service/stripe-integration.md | 6 +- .../subscription-management.md | 2 +- .../system-architecture-authz-route-matrix.md | 2 +- ...ystem-architecture-authz-route-matrix.yaml | 28 +- .../system-architecture-gateway.md | 6 + .../player-access-and-session.md | 8 +- .../v1/control_ui_authentication.proto | 43 ++ services/account-service/build.gradle.kts | 25 + .../AccountControlUiAccountAuthority.java | 276 ++++++++ .../AccountControlUiAuthority.java | 251 +------ ...AccountCheckoutReceivingConfiguration.java | 312 +++++++++ .../AccountCheckoutReceivingProperties.java | 37 + ...countProtectedJwksSourceConfiguration.java | 70 ++ .../AccountHostingFirstInvoiceController.java | 31 +- ...tHostingFirstInvoiceWebhookController.java | 84 +++ .../AccountCheckoutHttpAuthInterceptor.java | 93 +++ ...untControlUiAuthenticationGrpcService.java | 94 +++ .../session/AccountControlUiActorService.java | 24 +- .../AccountControlUiIssuanceService.java | 24 +- .../AccountControlUiRegistryReader.java | 20 +- .../AccountRecentReauthenticationService.java | 5 +- .../src/main/resources/openapi.yaml | 36 +- ...nonicalHostingSubscriptionTestFixture.java | 61 +- ...teredReceivingPostgresIntegrationTest.java | 658 ++++++++++++++++++ .../AccountControlUiAccountAuthorityTest.java | 38 + .../AccountControlUiAuthorityTest.java | 2 +- ...untCheckoutReceivingConfigurationTest.java | 72 ++ ...ountHostingFirstInvoiceControllerTest.java | 12 + ...tingFirstInvoiceWebhookControllerTest.java | 79 +++ ...ccountCheckoutHttpAuthInterceptorTest.java | 135 ++++ ...ontrolUiAuthenticationGrpcServiceTest.java | 128 ++++ .../AccountControlUiIssuanceWorkflowTest.java | 41 ++ .../AccountControlUiRegistryReaderTest.java | 12 + .../AccountControlUiSigningAndActorTest.java | 27 + .../AccountControlUiOriginalOrderFixture.java | 24 +- .../common/grpc/GrpcChannelFactory.java | 22 +- .../grpc/GrpcChannelFactoryNoRetryTest.java | 62 ++ ...countControlUiAuthenticationGrpcCodec.java | 249 +++++++ ...tControlUiAuthenticationGrpcCodecTest.java | 132 ++++ .../client/AccountCheckoutHttpClient.java | 255 +++++++ .../AccountControlUiAuthenticationClient.java | 151 ++++ ...AccountCheckoutReceivingConfiguration.java | 195 ++++++ .../AccountCheckoutReceivingProperties.java | 78 +++ .../config/GatewayRateLimiterConfig.java | 57 ++ .../AccountCheckoutGatewayController.java | 335 +++++++++ .../src/main/resources/openapi.yaml | 120 ++++ .../AccountCheckoutHttpClientTlsTest.java | 348 +++++++++ ...ControlUiAuthenticationClientMtlsTest.java | 216 ++++++ ...untCheckoutReceivingConfigurationTest.java | 238 +++++++ .../config/GatewayRateLimiterConfigTest.java | 71 ++ .../AccountCheckoutGatewayControllerTest.java | 295 ++++++++ web-client/package.json | 2 +- web-client/src/App.tsx | 27 +- .../src/account/AccountCheckoutRoute.test.tsx | 329 +++++++++ .../src/account/AccountCheckoutRoute.tsx | 403 +++++++++++ .../src/account/controlUiSession.test.ts | 335 +++++++++ web-client/src/account/controlUiSession.ts | 529 ++++++++++++++ web-client/src/api/accountControlUi.test.ts | 197 ++++++ web-client/src/api/accountControlUi.ts | 220 ++++++ .../billing/HostingFirstInvoiceCheckout.tsx | 7 +- 64 files changed, 7362 insertions(+), 301 deletions(-) create mode 100644 protos/account/v1/control_ui_authentication.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAccountAuthority.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountCheckoutReceivingConfiguration.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountCheckoutReceivingProperties.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountProtectedJwksSourceConfiguration.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceWebhookController.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountCheckoutHttpAuthInterceptor.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcService.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountCheckoutRegisteredReceivingPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAccountAuthorityTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountCheckoutReceivingConfigurationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceWebhookControllerTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountCheckoutHttpAuthInterceptorTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcServiceTest.java create mode 100644 services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/grpc/GrpcChannelFactoryNoRetryTest.java create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/account/auth/AccountControlUiAuthenticationGrpcCodec.java create mode 100644 services/common-security/src/test/java/unit/net/firedevops/firemud/common/account/auth/AccountControlUiAuthenticationGrpcCodecTest.java create mode 100644 services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/client/AccountCheckoutHttpClient.java create mode 100644 services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/client/AccountControlUiAuthenticationClient.java create mode 100644 services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfiguration.java create mode 100644 services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingProperties.java create mode 100644 services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/controller/AccountCheckoutGatewayController.java create mode 100644 services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/client/AccountCheckoutHttpClientTlsTest.java create mode 100644 services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/client/AccountControlUiAuthenticationClientMtlsTest.java create mode 100644 services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfigurationTest.java create mode 100644 services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/controller/AccountCheckoutGatewayControllerTest.java create mode 100644 web-client/src/account/AccountCheckoutRoute.test.tsx create mode 100644 web-client/src/account/AccountCheckoutRoute.tsx create mode 100644 web-client/src/account/controlUiSession.test.ts create mode 100644 web-client/src/account/controlUiSession.ts create mode 100644 web-client/src/api/accountControlUi.test.ts create mode 100644 web-client/src/api/accountControlUi.ts diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 22367dc674..1d96c601ad 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -512,7 +512,11 @@ The private self-service game-creation reauthentication owner binds exact origin ### Hosting First-Invoice Checkout -The Account-owned HTTPS owner surface is `/billing/hosting/subscriptions/{subscriptionId}/first-invoice`, externally prefixed by `/api/account`. It is an account-scoped billing-owner operation, not tenant-role authority: the exact current `control-ui` Account subject must own the subscription and selected instrument. Billing suspension does not remove this recovery surface. The prepared controller is deliberately unregistered; the [Stripe owner contract](./stripe-integration.md#first-invoice-confirmation-and-completion) and existing retention, deletion, backup, custody and registration gates remain binding. +The isolated receiving login is public `POST /api/account/auth/login` at Gateway. Its bounded JSON body is `{requestId, callerContextId, email, secret}`, with non-nil request/context UUIDs and one enabled ordinary primary secret. Gateway authenticates Account's exact same-namespace URI SAN before releasing credentials over the narrow mTLS `AccountControlUiAuthenticationService/AuthLogin` RPC. Account permits only the exact same-namespace Gateway workload and delegates to its durable Account-only issuer and current-actor owners. Success is `{status: SUCCESS, data: {accountId, authToken, expiresAt}}`, with no-store headers. Exact retries retain the same issuance; changed input conflicts. The direct legacy Account HTTP login is rejected in this isolated mode and cannot provide a checkout fallback. Production legacy-login drift elsewhere remains unchanged. + +The first-party `/account/subscriptions/{subscriptionId}/checkout` route obtains its bearer only from that login, holds it in memory, restricts authenticated requests to the exact owner endpoints, and unmounts checkout on expiry, local sign-out, session replacement or route departure. Local sign-out clears this UI's credentials; it does not claim server-side token revocation. Navigation, Back/Forward, reload and remount never authorize a provider command. + +The Account-owned HTTPS owner surface is `/billing/hosting/subscriptions/{subscriptionId}/first-invoice`, externally prefixed by `/api/account`. It is an account-scoped billing-owner operation, not tenant-role authority: the exact current `control-ui` Account subject must own the subscription and selected instrument. Billing suspension does not remove this recovery surface. The controller is registered only by the explicitly isolated, default-off receiving composition; the [Stripe owner contract](./stripe-integration.md#first-invoice-confirmation-and-completion) and existing retention, deletion, backup, custody and registration gates remain binding. - `GET` returns the exact existing invoice, PaymentIntent, selected instrument, amount, currency, immutable `tupleDigest`, expected current subscription row version, expiry, nullable retained `confirmationRequestId`, current `authorizationVersion` (zero before first consent) and `AWAITING_PAYMENT` or `COMMITTED` state. `amount` is a positive decimal integer string in Stripe minor units, not a floating-point or major-unit amount. No client secret appears in status, URLs, logs or audit. - `POST /reauthenticate` takes distinct stable `requestId` and `confirmationRequestId` plus one enabled ordinary login secret over HTTPS. It returns an opaque `evidenceId` from actual primary authentication for `HOSTING_FIRST_INVOICE_PAYMENT`. `SELF_SERVICE_GAME_CREATION` evidence is rejected for payment. @@ -521,6 +525,8 @@ The Account-owned HTTPS owner surface is `/billing/hosting/subscriptions/{subscr - The narrowly authorized owner response returns provider status and a client secret only for `requires_action`, with `Cache-Control: no-store`. Stripe.js `handleNextAction` completes provider authentication for that existing intent. A browser result never completes Account fulfillment; the owner polls status until the signed server completion has committed and independently read back. - Transport or provider failures are uncertain, not evidence that no payment occurred. `FIRST_INVOICE_PROVIDER_UNCERTAIN` and `FIRST_INVOICE_EVIDENCE_REFUSED` preserve the original operation; clients must not create a replacement request or charge to escape an unknown result. +The separate `POST /billing/hosting/webhook` adapter accepts only a single bounded `Stripe-Signature` header and the exact raw UTF-8 JSON body, at most 256 KiB, over actual HTTPS. It accepts no browser bearer as provider authority. Signature validation, immutable intake, retained invoice linkage, fresh provider observations and Account completion remain independent predicates. Only independently read-back `COMMITTED` completion is acknowledged with HTTP 200; retained `RECONCILING` state returns 503 so the same signed event can be redelivered without another payment command. Gateway forwards only this exact signed-event path and the four owner operations over verified HTTPS without automatic retries or redirects; forwarded scheme or identity headers cannot establish transport security. + ### Sensitive Actions and Gameplay Handoff - Account identity/factor changes, new real-money charges, saved payment-instrument changes, global deletion, billing-owner transfer, and global administration are HTTPS-only account/control operations. Clients may be web, native, or CLI, but a Telnet gameplay connection cannot complete them or receive elevated authority. diff --git a/design/architecture/microservices/account-service/configuration.md b/design/architecture/microservices/account-service/configuration.md index 4865027487..23ac9d35c7 100644 --- a/design/architecture/microservices/account-service/configuration.md +++ b/design/architecture/microservices/account-service/configuration.md @@ -69,6 +69,12 @@ The source-only Control-UI issuance preparation reads the configured margin thro The gRPC schemas for this service live in [`protos/account/v1`](../../../../protos/account/v1). Use `./gradlew generateProto` to regenerate Java stubs when the definitions change. -### Held first-invoice checkout configuration +## Isolated First-Invoice Receiving Configuration -The prepared [first-invoice owner](./stripe-integration.md#first-invoice-confirmation-and-completion) has no enabling flag or automatically registered bean/controller. Explicit composition requires the Account Stripe client, a protected webhook signing secret (`firemud.payment.hosting-webhook-secret`), a public Stripe publishable key for the provider-authentication client, finite provider transport limits and genuine current Account/control-ui owners. Secrets must not be logged or exposed through property diagnostics. Separate versioned billing-purpose reauthentication policies and exact commercial billing-policy rows are required; absent rows refuse and no migration seeds a default. Configuration alone does not clear registration or custody gates. +The [first-invoice owner](./stripe-integration.md#first-invoice-confirmation-and-completion) is registered only with the `isolated-checkout-receiving` profile and `firemud.account.checkout-receiving.enabled=true`. Combining that profile with `prod` or `production` refuses startup. This selects an isolated receiving composition, not live activation or privacy qualification. Default production configuration registers none of its new handlers. + +Account requires explicit `firemud.grpc.workload-namespace`, `firemud.account.checkout-receiving.private-signer-root`, `public-signer-root` and `control-ui-keyring-root`; the dedicated control-ui keyring must remain separate from signer roots. The shared explicit-import `AccountProtectedJwksSourceConfiguration` owns the single API-binding, ConfigMap-client and trusted-source graph, including the existing protected path and namespace/incarnation checks. Checkout does not provision or duplicate those sources. Delivered named isolated inputs are `accountCheckoutIsolatedCoordinationUri`, `accountCheckoutIsolatedAcknowledgements` and `accountCheckoutIsolatedStripeClient`; the real Lettuce pinned provider and existing Stripe SDK owners consume them. Explicit hosting catalog, reconciliation limits/recovery policy and the protected webhook signing secret (`firemud.payment.hosting-webhook-secret`) are also required. No live SDK transport or credential is provisioned. + +Gateway uses the same isolated profile/selector plus `firemud.account.checkout-receiving.workload-namespace`, `account-https-base-url` and `account-ca-cert-path`; its ordinary gRPC endpoint and file-backed mTLS client configuration identify Account independently. Both incoming HTTP listeners must actually use TLS. Gateway forwards neither identity headers nor an asserted secure scheme. The frontend uses the current HTTPS origin and explicitly supplied public Stripe key; missing provider-authentication configuration refuses checkout. + +Separate versioned billing-purpose reauthentication policies and exact commercial policy rows remain necessary; absent rows refuse and migrations seed no defaults. Category-specific privacy/finance-approved finite retention, minimization, deletion, backup/provider consequences and deployed source custody remain unqualified activation obligations. No boolean in this receiving composition supplies those approvals. diff --git a/design/architecture/microservices/account-service/operations.md b/design/architecture/microservices/account-service/operations.md index 646959d085..d8fea9563d 100644 --- a/design/architecture/microservices/account-service/operations.md +++ b/design/architecture/microservices/account-service/operations.md @@ -86,4 +86,6 @@ See [System Architecture Testing](../../system-architecture-testing.md) for the Use the [first-invoice owner contract](./stripe-integration.md#first-invoice-confirmation-and-completion) for payment and completion. Preserve the original invoice, PaymentIntent, consent, provider idempotency key, event intake and reservation after an uncertain provider response, expired client session or failed Account commit. Never repair an uncertain charge by provisioning a replacement or changing the selected method. Read-only signed-success reconciliation must not authorize new provider work. An owner may explicitly renew unchanged consent and primary reauthentication on the original operation through the owner contract. A durable command claim, including an uncertain claim/response or crash after claim but before POST, never permits another provider command; keep it nonterminal for exact observation or audited remediation. Paid-but-unfulfilled and policy/authority conflicts remain explicit unresolved billing work and continue to block deletion. -Before registering this held source, execute physical migration/current-owner, crash/retry, signed tuple-mismatch, HTTPS owner isolation and provider next-action/SCA proof, together with the existing category-specific retention/minimization/deletion/backup and protected source-custody gates. Compiled Docker-backed definitions, skipped cases and controlled active-subscription fixtures are not proof of those boundaries. No live provider or financial action is authorized by this preparation. +Before any non-isolated activation, execute physical migration/current-owner, crash/retry, signed tuple-mismatch, HTTPS owner isolation and provider next-action/SCA proof, together with the existing category-specific retention/minimization/deletion/backup and protected source-custody gates. Compiled Docker-backed definitions, skipped cases and controlled active-subscription fixtures are not proof of those boundaries. No live provider or financial action is authorized by this preparation. + +The isolated registered composition and its controlled receiving proof are described in [configuration](./configuration.md#isolated-first-invoice-receiving-configuration). The proof starts with an explicitly controlled existing `AWAITING_PAYMENT` operation; it does not open `CreateSubscription`, onboard a payer or qualify live provider behavior. Its standard MVC/WebFlux mappings include real authentication middleware, mTLS login and TLS hops rather than a custom handler-recognition override. Test definitions and compilation must be reported separately from physical execution. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 9f48ebbeeb..70d7e1f2c6 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -406,3 +406,5 @@ V1003 preserves canonical predecessor SQL and retained owner rows; it never back ### First-invoice completion ownership The [Stripe owner contract](./stripe-integration.md#first-invoice-confirmation-and-completion) owns the immutable provider-linked first invoice, explicit billing consent, signed success and separate completion journal. `provisioning`/`AWAITING_PAYMENT` is never positive runtime authority. The first authorizing receipt must carry exact signed paid-invoice fulfillment; its receipt, audit, billing outbox and tenant authority outbox commit atomically and require independent current-source readback. The webhook inbox remains immutable intake and is not a processing ledger. Retention, minimization, deletion, backup and source-custody registration holds continue to apply. + +The isolated [receiving composition](./configuration.md#isolated-first-invoice-receiving-configuration) registers the actual Account issuer/current-actor and first-invoice handlers over the existing durable owners. Account-only source capture has no tenant, membership or hosted-terms collaborator; tenant-capable consumers retain their explicit source type. This does not add a production policy writer, onboarding producer, retention erasure implementation or live deployment qualification. diff --git a/design/architecture/microservices/account-service/stripe-integration.md b/design/architecture/microservices/account-service/stripe-integration.md index 7d1963c8cb..527a1dec1e 100644 --- a/design/architecture/microservices/account-service/stripe-integration.md +++ b/design/architecture/microservices/account-service/stripe-integration.md @@ -21,7 +21,7 @@ The future direction in [ADR 0179](../../decisions/adr-0179-firemud-managed-crea The verified event inbox contains complete provider payloads that may contain personal data. Registering its intake requires a category-specific finite schedule and minimization/erasure behavior under [ADR 0050's canonical retention registry](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md#canonical-retention-registry), including permitted retention, access, legal holds, account deletion and backup treatment. [Account erasure](../../decisions/adr-0043-global-account-lifecycle-and-bounded-erasure-workflow.md) preserves only the authorized minimum billing evidence; account deletion must not blindly delete unresolved provider evidence. -The current append-only inbox has no processing terminal, guarded payload minimization/erasure path or approved retention schedule. Intake remains unregistered until those owner paths and their physical proof exist. Its immutable raw-payload retention is an unresolved preparation boundary, not an indefinite production retention policy; no TTL or deletion bypass is inferred from this slice. +The current append-only inbox has no processing terminal, guarded payload minimization/erasure path or approved retention schedule. Production intake remains closed until those owner paths and their physical proof exist; the isolated receiving composition below does not qualify them. Its immutable raw-payload retention is an unresolved preparation boundary, not an indefinite production retention policy; no TTL or deletion bypass is inferred from this slice. The billing-customer and saved-method owners have the same prerequisite. Their append-only observation histories retain provider bindings and versioned card-display metadata; customer and instrument rows also retain Account references that currently block deletion. Before registering these sources, their exact categories require approved finite retention schedules, guarded minimization or erasure, and explicit account-deletion and backup treatment in the same canonical retention registry. Card-display history is not automatically necessary settlement evidence. Minimize or erase it when its authorized purpose ends, retaining only the minimum billing evidence authorized by ADR 0043 and any applicable legal hold. The owner must preserve unresolved provider and subscription obligations while completing the Account erasure workflow; neither indefinite Account retention nor bypassing a foreign-key or immutability guard is an acceptable deletion policy. The current owners remain unregistered until these paths and their physical proof exist. @@ -38,12 +38,14 @@ These gates do not authorize caching or a longer freshness window. Any separatel ## Implementation Status -The hosting-subscription, provider-reconciliation, and account-deletion billing-owner precondition contracts below are canonical target-state behavior. Account now has an unregistered verified Stripe event inbox, durable billing-customer intent and first-dispatch claim, and saved-method confirmation bound to the exact customer. The inbox is event intake only; the customer and instrument owners have controlled Stripe SDK/readback source and PostgreSQL proof, not a live provider or registered route. Current payment code records payment transactions, donations, refunds, platform fees, and creator shares, but still needs subscription webhook lifecycle processing, durable idempotent hosting-billing fulfillment/reconciliation, caller-stable subscription create retry evidence, active-subscription deletion guards, and end-to-end entitlement enforcement. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs now fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the underlying provider-mutating service methods remain unsupported substrate. Only separately typed hosting-billing operations may mutate Stripe. `purchase_entitlement` and paid-but-unfulfilled compensation are reserved for a separately accepted future marketplace path under [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md), and remain unsupported until its launch gates are implemented and proved. +The hosting-subscription, provider-reconciliation, and account-deletion billing-owner precondition contracts below are canonical target-state behavior. Account now has verified Stripe event-inbox source, durable billing-customer intent and first-dispatch claim, and saved-method confirmation bound to the exact customer. The inbox is event intake only; the customer and instrument owners have controlled Stripe SDK/readback source and PostgreSQL proof, not a live provider or registered route. Current payment code records payment transactions, donations, refunds, platform fees, and creator shares, but still needs subscription webhook lifecycle processing, durable idempotent hosting-billing fulfillment/reconciliation, caller-stable subscription create retry evidence, active-subscription deletion guards, and end-to-end entitlement enforcement. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs now fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the underlying provider-mutating service methods remain unsupported substrate. Only separately typed hosting-billing operations may mutate Stripe. `purchase_entitlement` and paid-but-unfulfilled compensation are reserved for a separately accepted future marketplace path under [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md), and remain unsupported until its launch gates are implemented and proved. The account-owned wallet contracts are also target state. Per-subscription instrument binding, replacement-before-detach, the single-use transfer proof and database transfer fence, immutable predecessor-provider history, and the audited `cross_tenant_billing_safe` ownership-transfer route remain absent or partial until the corresponding routes and enforcement are implemented; the [Authorization Route Matrix](../../system-architecture-authz-route-matrix.md) records that coverage drift. ## First-Invoice Confirmation and Completion +The [isolated receiving composition](./configuration.md#isolated-first-invoice-receiving-configuration) registers the existing owner through actual Gateway/Account HTTPS and genuine Account-session authentication, plus a separate exact-byte signed-event adapter. This source-level integration does not qualify a live provider, supply approved retention values or activate production billing. + `DEFAULT_INCOMPLETE` creation and subscription polling do not confirm the initial PaymentIntent. Account first retains the exact existing first invoice, its sole existing PaymentIntent, canonical provider subscription/customer, explicitly selected saved instrument and reserved version, provider method, versioned commercial policy/quote, positive minor-unit amount, currency and provider mode. Provider linkage remains `provisioning` with durable `AWAITING_PAYMENT` work and grants no hosting authority. The instrument reservation remains held through Stripe's original 23-hour incomplete-subscription boundary and until explicit terminal cleanup; expiry never creates a replacement subscription, PaymentIntent or Checkout Session. The current commercial owner supports only an exact positive first-invoice amount/currency/quantity matching an explicitly installed versioned billing policy and the sole fully read invoice line's original quote price/quantity. Invoice total and due must agree, the starting balance is zero, and an unpaid invoice must retain its full amount remaining. A credit, balance adjustment, tax, discount, split payment or currency difference that changes that exact tuple is refused rather than inferred or absorbed into a permissive policy. The policy relations contain no seeded default. A policy change cannot rewrite a retained invoice or silently authorize another amount. diff --git a/design/architecture/microservices/account-service/subscription-management.md b/design/architecture/microservices/account-service/subscription-management.md index 26118eebd2..ede9ed0a84 100644 --- a/design/architecture/microservices/account-service/subscription-management.md +++ b/design/architecture/microservices/account-service/subscription-management.md @@ -87,7 +87,7 @@ Before the billing lifecycle states below, creation uses two durable provisionin - `pending` – Account has committed the subscription operation, pending subscription row, billing-owner/instrument binding, captured and locally revalidated owner authority version/generation, observed instrument version reservation, customer-operation reference, stable creation-operation provider idempotency identity, separate cleanup/cancellation-operation identity, and outbox work item before any customer reconciliation or provider call; provider creation has not been claimed. - `provisioning` – A worker has confirmed the customer operation, then atomically revalidated instrument ownership, the exact reserved version, matching customer, and attachability before claiming the outbox item and creating or reconciling the provider subscription. Creation retries reuse the creation-operation identity; terminal cleanup uses the separate cleanup/cancellation identity while retaining the creation identity for provider-object lookup. This state grants no hosting entitlement and cannot be billed. -Provider linkage is necessary but not first-payment authority. An incomplete provider subscription remains non-authorizing while Account owns the exact awaiting-payment invoice and intent. Any initial authorizing receipt (`trialing`, `active`, `past_due` or `grace`) additionally requires the signed exact first-invoice completion and atomic Account fulfillment described in [Stripe Integration](./stripe-integration.md#first-invoice-confirmation-and-completion); creation, polling and browser/SCA results alone cannot supply it. +The [isolated receiving composition](./configuration.md#isolated-first-invoice-receiving-configuration) can consume an explicitly controlled existing awaiting-payment operation; it supplies no authenticated subscription-creation producer and leaves `CreateSubscription` closed. Provider linkage is necessary but not first-payment authority. An incomplete provider subscription remains non-authorizing while Account owns the exact awaiting-payment invoice and intent. Any initial authorizing receipt (`trialing`, `active`, `past_due` or `grace`) additionally requires the signed exact first-invoice completion and atomic Account fulfillment described in [Stripe Integration](./stripe-integration.md#first-invoice-confirmation-and-completion); creation, polling and browser/SCA results alone cannot supply it. A positive unpaid first invoice cannot gain authority through `trialing`; zero/free-trial onboarding remains unsupported by this paid-checkout component. Only a confirmed provider subscription ID may transition the row from `pending`/`provisioning` into `trialing` or `active`. A timeout or lost provider response is reconciled with the creation-operation identity before another create is attempted; if the provider resource exists but the local ID is missing, the creation lookup repairs the reference without creating a duplicate. diff --git a/design/architecture/system-architecture-authz-route-matrix.md b/design/architecture/system-architecture-authz-route-matrix.md index 48fd75aa53..29fbe98bec 100644 --- a/design/architecture/system-architecture-authz-route-matrix.md +++ b/design/architecture/system-architecture-authz-route-matrix.md @@ -296,6 +296,6 @@ The matrix should be expanded as service API surfaces evolve. Service docs may i ### Held Account first-invoice checkout -The four prepared HTTPS owner routes `GET /billing/hosting/subscriptions/{subscriptionId}/first-invoice`, `POST .../reauthenticate` `POST .../confirm` and `POST .../renew` are `account_scoped`, bound to the exact current subscription billing owner and selected Account instrument, rather than a tenant-admin role. They preserve billing recovery when gameplay is unavailable and confer no tenant or gameplay authority. The [Account API contract](./microservices/account-service/api-contracts.md#hosting-first-invoice-checkout) owns request, explicit consent and no-store client-secret semantics. The controller remains unregistered, all four matrix entries are `target_not_currently_routable`, and activation gates remain held. +The four prepared HTTPS owner routes `GET /billing/hosting/subscriptions/{subscriptionId}/first-invoice`, `POST .../reauthenticate` `POST .../confirm` and `POST .../renew` are `account_scoped`, bound to the exact current subscription billing owner and selected Account instrument, rather than a tenant-admin role. They preserve billing recovery when gameplay is unavailable and confer no tenant or gameplay authority. The [Account API contract](./microservices/account-service/api-contracts.md#hosting-first-invoice-checkout) owns request, explicit consent and no-store client-secret semantics. The explicit isolated receiving composition registers these four exact handlers while production remains closed; their production matrix status stays `target_not_currently_routable` and activation gates remain held. Its login RPC accepts only the certificate-derived same-namespace Gateway peer, and its separate signed webhook adapter accepts provider signature authority rather than an end-user token. These routes require two distinct Account-owned live checks. `current_subscription_owner` re-reads the exact subscription's current billing owner and requires it to match the authenticated Account subject. `exact_reserved_instrument` re-reads the Account instrument reserved for that first invoice and requires the same instrument identity and reserved version; a customer default or replacement is not a substitute. These checks are not gameplay `binding_ownership` or the weaker payment-instrument `explicit_per_subscription_binding`. The existing matrix validator requires both checks on each of the four held routes, with focused regression vectors for every route/check pair. diff --git a/design/architecture/system-architecture-authz-route-matrix.yaml b/design/architecture/system-architecture-authz-route-matrix.yaml index d07bacd0f5..6286598b22 100644 --- a/design/architecture/system-architecture-authz-route-matrix.yaml +++ b/design/architecture/system-architecture-authz-route-matrix.yaml @@ -1759,6 +1759,26 @@ routes: known_drift: - current_issuance_uses_legacy_scope_duplicated_session_keys_instead_of_single_token_registry required_live_checks: [account_state_login_eligible] + - service: account-service + route: AccountControlUiAuthenticationService/AuthLogin + transport: grpc + scope: account + classification: internal_workload + route_status: target_not_currently_routable + accepted_token_profiles: [] + token_type: none + token_issuer: none + token_audience: none + method_policy: exact_declared_route + allowed_callers: + any_of: [spring-cloud-gateway] + mtls_callers: + any_of: ["spiffe://firemud/ns/{namespace}/sa/spring-cloud-gateway"] + end_user_token_required: false + required_live_checks: [account_state_login_eligible] + implementation_status: + known_drift: + - Registered only by explicit isolated checkout receiving; production remains closed. - service: account-service route: PlayerBootstrapLogin http_route: POST /auth/player-bootstrap @@ -3225,7 +3245,7 @@ routes: mutation_contract: current_owner_exact_subscription_and_instrument implementation_status: known_drift: - - Prepared owner controller is unregistered; provider, retention, deletion, backup and custody activation gates remain held. + - Owner controller is registered only in explicit isolated receiving; production provider, retention, deletion, backup and custody activation gates remain held. - service: account-service route: POST /billing/hosting/subscriptions/{subscriptionId}/first-invoice/reauthenticate scope: account @@ -3243,7 +3263,7 @@ routes: mutation_contract: current_owner_and_actual_billing_purpose_primary_authentication implementation_status: known_drift: - - Prepared owner controller is unregistered; provider, retention, deletion, backup and custody activation gates remain held. + - Owner controller is registered only in explicit isolated receiving; production provider, retention, deletion, backup and custody activation gates remain held. - service: account-service route: POST /billing/hosting/subscriptions/{subscriptionId}/first-invoice/confirm scope: account @@ -3261,7 +3281,7 @@ routes: mutation_contract: current_owner_billing_purpose_reauthentication_explicit_exact_tuple_consent_single_dispatch implementation_status: known_drift: - - Prepared owner controller is unregistered; provider, retention, deletion, backup and custody activation gates remain held. + - Owner controller is registered only in explicit isolated receiving; production provider, retention, deletion, backup and custody activation gates remain held. - service: account-service route: POST /billing/hosting/subscriptions/{subscriptionId}/first-invoice/renew scope: account @@ -3279,7 +3299,7 @@ routes: mutation_contract: current_owner_fresh_billing_reauthentication_explicit_unchanged_consent_authorization_version_fence_no_command_replay implementation_status: known_drift: - - Prepared owner controller is unregistered; provider, retention, deletion, backup and custody activation gates remain held. + - Owner controller is registered only in explicit isolated receiving; production provider, retention, deletion, backup and custody activation gates remain held. - service: account-service route: GetSubscriptionTenantHighLevel scope: tenant diff --git a/design/architecture/system-architecture-gateway.md b/design/architecture/system-architecture-gateway.md index f479fef6a1..08361a8887 100644 --- a/design/architecture/system-architecture-gateway.md +++ b/design/architecture/system-architecture-gateway.md @@ -576,6 +576,12 @@ The following table summarizes the main network surfaces exposed or used by Spri --- +### Isolated Account Checkout Receiving + +The default-off `isolated-checkout-receiving` composition registers exact Gateway HTTPS handlers for Account login, the four [first-invoice owner operations](./microservices/account-service/api-contracts.md#hosting-first-invoice-checkout), and the separate raw signed-event intake. These are controller handlers rather than broadly proxied routes, so the general route retry filter never automatically redispatches a confirmation. Account receives actual verified HTTPS, not a synthesized forwarded secure scheme. Both outbound receiving transports disable automatic retries, including gRPC channel retries and HTTP connection-reset retries. The exact handlers retain the canonical client-IP rate limit before parsing credentials or calling Account; limiter refusal returns `429`, and unavailable limiter authority fails closed with `503`. + +Login uses the narrow Account RPC over file-backed mTLS. The existing server-peer call-credentials gate verifies Account's exact same-namespace URI SAN before sending primary credentials; the response fence independently rejects an incorrect server identity. Account authenticates the exact Gateway peer and produces registry-backed Account-only authority. Other Gateway control-plane forwarding responsibilities remain unchanged. Configuration and live-activation limits belong to [Account configuration](./microservices/account-service/configuration.md#isolated-first-invoice-receiving-configuration). + ## Related Documentation - [Deployment Environments](./infrastructure/deployment-environments.md) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index e8318e5c8d..640736d4b7 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -28,7 +28,7 @@ Account deletion remains held. Its conservative billing-owner precondition curre This receiver owns the [Stripe provisioner](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisioner.java), [provisioning composition](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java), their [adapter units](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisionerTest.java) and [composition units](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java), and the existing [dispatch physical suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java). Removing those four inherited source/unit files from #3389 preserves their bytes here alongside the canonical storage and dependent physical proof. This is an ownership transfer, not new payment support or qualification; both components remain manually composed and unregistered, with the authenticated create producer, provider worker and public billing route held. -The separate Account first-invoice successor now prepares provider-linked `AWAITING_PAYMENT` without authority, exact versioned commercial invoice/intent/instrument binding, distinct billing-purpose primary reauthentication, durable explicit consent, one existing-intent confirmation and narrowly protected HTTPS Stripe.js handoff. Exact signed payment success and a fresh invoice read precede atomic receipt, audit, billing and tenant-authority completion; delayed read-only reconciliation preserves the historical authorization without renewing a command or disclosing an expired secret. The web checkout component remains unmounted because the demo App has no genuine control-ui session producer. The same unregistered owner now prepares explicit fresh primary reauthentication and unchanged-consent renewal, append-only authorization-version fencing, and one durable command claim on the original payment operation. A crash before claim may resume only after a fresh explicit authorization; a claimed/ambiguous command is never resent. Renewal may resume the same intent's SCA handoff without changing any commercial/provider identity or extending invoice expiry. Focused renewal cases cover exact authorization/invoice expiry, replay, wrong operation/proof identity, changed consent, stale subscription/authorization fences, crash before claim, and ambiguous provider or claim outcomes. Canonical contracts remain [Account API](../../architecture/microservices/account-service/api-contracts.md#hosting-first-invoice-checkout) and [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md#first-invoice-confirmation-and-completion). The fresh post-renewal local graph executes 54 selected Account unit cases and all main/unit/integration compilation, schema generation, enabled main/unit/integration Checkstyle and SpotBugs, and Java formatting with zero unit failures, errors or skips. The unmounted client/component passes 32 cases, build, lint and formatting. Earlier 55-case Account and 29-case frontend results remain overlapping historical proof, not additional current coverage. Physical PostgreSQL/HTTPS migration and composition definitions compile but are unexecuted because Docker is unavailable. The final Markdown gate passed; link checking remains unrun after an existing external URL denial. No skipped case establishes physical qualification. The paid first-invoice finding and accepted route finding remain open. Registration, deletion, retention, backup/source custody and runtime activation remain held, with no live Stripe transaction or automatic provisioning charge. +The separate Account first-invoice successor now prepares provider-linked `AWAITING_PAYMENT` without authority, exact versioned commercial invoice/intent/instrument binding, distinct billing-purpose primary reauthentication, durable explicit consent, one existing-intent confirmation and narrowly protected HTTPS Stripe.js handoff. Exact signed payment success and a fresh invoice read precede atomic receipt, audit, billing and tenant-authority completion; delayed read-only reconciliation preserves the historical authorization without renewing a command or disclosing an expired secret. That preparation left checkout unmounted; the subsequent isolated receiving composition below adds its Account-session producer and App route. The same owner prepares explicit fresh primary reauthentication and unchanged-consent renewal, append-only authorization-version fencing, and one durable command claim on the original payment operation. A crash before claim may resume only after a fresh explicit authorization; a claimed/ambiguous command is never resent. Renewal may resume the same intent's SCA handoff without changing any commercial/provider identity or extending invoice expiry. Focused renewal cases cover exact authorization/invoice expiry, replay, wrong operation/proof identity, changed consent, stale subscription/authorization fences, crash before claim, and ambiguous provider or claim outcomes. Canonical contracts remain [Account API](../../architecture/microservices/account-service/api-contracts.md#hosting-first-invoice-checkout) and [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md#first-invoice-confirmation-and-completion). The fresh post-renewal local graph executes 54 selected Account unit cases and all main/unit/integration compilation, schema generation, enabled main/unit/integration Checkstyle and SpotBugs, and Java formatting with zero unit failures, errors or skips. The earlier unmounted client/component passes 32 cases, build, lint and formatting. Earlier 55-case Account and 29-case frontend results remain overlapping historical proof, not additional current coverage. Physical PostgreSQL/HTTPS migration and composition definitions compile but are unexecuted because Docker is unavailable. The final Markdown gate passed; link checking remains unrun after an existing external URL denial. No skipped case establishes physical qualification. The paid first-invoice finding and accepted route finding remain open. Production registration, deletion, retention, backup/source custody and runtime activation remain held, with no live Stripe transaction or automatic provisioning charge. The current billing-owner tuple deliberately rejects unaudited updates. Fixture reconciliation preserves that refusal and unchanged row/xmin, stale owner version/generation capture refusal, and genuine payment-instrument advancement concurrency. Positive queued-create fencing after a real audited owner-transfer commit remains an obligation of the unimplemented transfer owner; constructed stale comparison inputs do not prove that transfer. @@ -36,6 +36,12 @@ The same receiving boundary carries the distinct TENANT_OPERATION evidence, Acco The earlier published #3389 comparison deliberately left public facade and numeric runtime entitlement paths unavailable; its historical source-built340 run passed held-edge denial and LOGIN but failed PLAY with ENTITLEMENT_UNAVAILABLE. Authenticated teardown and independently empty resources passed. This remains incomplete runtime qualification for that historical comparison, not a passing smoke result or a description of the reconstructed #3389 foundation, which preserves the supported parent runtime. The complete public consumer receiving below restores its own supported canonical compositions; canonical runtime cutover and final functional restoration remain separate obligations. Ordinary UUID identity/profile/retention protections retain their focused proof. +### Isolated registered checkout receiving + +The next Account first-invoice extension composes actual registered Gateway HTTPS handlers, pre-disclosure verified Account mTLS login, the durable Account-only issuer/current actor, exact-method owner authentication and a bounded raw signed-event adapter. The Account-only source has no tenant/legal collaborator. Checkout imports the same pure protected JWKS source owner as other Account consumers and defines no competing API/client/trusted-source graph. The first-party App owns a memory-only session and subscription checkout route; expiry, local sign-out, replacement and navigation unmount it, with no automatic confirmation. + +Focused receiving proof passes 170 backend cases: two channel-factory, five codec, 27 Gateway and 136 Account cases, with zero failures, errors or skips. This includes three real loopback mTLS cases, including refusal of a CA-trusted wrong workload before any primary request or credential, and five verified HTTPS cases including no retry after an uncertain checkout POST. Affected production/unit/integration compilation and enabled Java formatting, Checkstyle and SpotBugs pass. The memory-only UI passes all 55 selected checkout cases, build, lint and scoped formatting; these overlap earlier component coverage rather than add to it. These sources use explicit isolated signer-platform, policy, custody, provider and PKI inputs. The qualified core signed-completion/guard repair from parent `77890399` is carried. Its separate physical HTTPS signed-completion, confirmed-guard and migration proof passed on that parent. The registered Gateway→Account→Redis/PostgreSQL receiving-chain definition compiles, but its physical proof and fresh-image/runtime qualification remain unrun. It starts from a controlled existing `AWAITING_PAYMENT` operation, not a newly supported subscription-create route. Fresh-image runtime proof, production registration/activation, approved finite category-specific retention/minimization/deletion/backup/provider treatment, genuine custody and live provider qualification remain held. Link validation remains unrun. + ### Canonical public Account facade receiving The receiving source now restores the complete canonical V2 public facade, actual Account JOIN intent/member/pair/role/event/audit owners, V1037 diagnostics and V1038 existing-membership terminal guard, plus the distinct PLAYER_ADMISSION codec/Account receiver/Game Session client and persisted Account→Entity CHARS purpose. It retains actual same-row actor UUID/name/level, successful empty discovery only for supported targets, truthful admission flags, default-unavailable composition and all original positive cases. Contracts belong to [Account API](../../architecture/microservices/account-service/api-contracts.md#public-bootstrap-worlds-discovery) and [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#account-bootstrap-persisted-actor-discovery). diff --git a/protos/account/v1/control_ui_authentication.proto b/protos/account/v1/control_ui_authentication.proto new file mode 100644 index 0000000000..8e1c789a8c --- /dev/null +++ b/protos/account/v1/control_ui_authentication.proto @@ -0,0 +1,43 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Workload-authenticated Control-UI login handoff from Gateway to Account. +service AccountControlUiAuthenticationService { + rpc AuthLogin(AuthLoginRequest) returns (AuthLoginResponse); +} + +enum AccountControlUiAuthLoginStatus { + ACCOUNT_CONTROL_UI_AUTH_LOGIN_STATUS_UNSPECIFIED = 0; + ACCOUNT_CONTROL_UI_AUTH_LOGIN_STATUS_SUCCESS = 1; + ACCOUNT_CONTROL_UI_AUTH_LOGIN_STATUS_DENIED = 2; +} + +// Repeated scalar members intentionally let the shared closed codec reject duplicate wire fields. +message AuthLoginRequest { + repeated uint32 schema_version = 1; + repeated string target_namespace = 2; + repeated string request_id = 3; + repeated string caller_context_id = 4; + repeated string email = 5; + // Transient primary credential. Never persist, log, echo, or include in an error. + repeated string secret = 6; +} + +// Account echoes stable request context, never the primary credential. +message AuthLoginResponse { + repeated uint32 schema_version = 1; + repeated string target_namespace = 2; + repeated string request_id = 3; + repeated string caller_context_id = 4; + repeated AccountControlUiAuthLoginStatus status = 5; + // Present exactly once only for SUCCESS. + repeated string account_id = 6; + // Compact Control-UI JWT. Present exactly once only for SUCCESS. + repeated string auth_token = 7; + // Whole UTC epoch seconds. Present exactly once only for SUCCESS. + repeated int64 expires_at_epoch_seconds = 8; +} diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index a561467fa3..b3c71e8f42 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -99,6 +99,10 @@ dependencies { integrationTestImplementation(entityBootstrapProof) integrationTestImplementation(testFixtures(project(":common-test-support"))) integrationTestImplementation(project(":social-groups-service")) + integrationTestImplementation(project(":spring-cloud-gateway")) + integrationTestImplementation(libs.spring.cloud.gateway) + integrationTestImplementation(libs.spring.boot.starter.webflux) + integrationTestImplementation(libs.spring.boot.starter.data.redis.reactive) integrationTestImplementation(testFixtures(project(":account-service"))) integrationTestImplementation(testFixtures(project(":logging-admin-service"))) } @@ -130,6 +134,22 @@ val socialIntegrationTestArtifacts = configurations } }.artifacts +// The registered checkout proof imports Gateway handlers, not its application or Flyway resources. +val gatewayIntegrationTestArtifacts = configurations + .getByName("integrationTestRuntimeClasspath") + .incoming.artifactView { + componentFilter { componentId -> + componentId is ProjectComponentIdentifier + && componentId.projectPath == ":spring-cloud-gateway" + } + }.artifacts + +val extractGatewayIntegrationTestClasses = tasks.register("extractGatewayIntegrationTestClasses") { + dependsOn(gatewayIntegrationTestArtifacts.artifactFiles) + archives.from(gatewayIntegrationTestArtifacts.artifactFiles) + destinationDirectory.set(layout.buildDirectory.dir("account-test-classpath/gateway-integration")) +} + val extractSocialIntegrationTestClasses = tasks.register("extractSocialIntegrationTestClasses") { dependsOn(socialIntegrationTestArtifacts.artifactFiles) archives.from(socialIntegrationTestArtifacts.artifactFiles) @@ -165,6 +185,9 @@ tasks.named("processIntegrationTestResources") { } tasks.named("integrationTest") { + // This JVM belongs to Account MVC. The checkout proof imports Gateway's explicit receiving + // configuration, not SCG's foreign application/route auto-configuration (which rejects MVC). + systemProperty("spring.cloud.gateway.server.webflux.enabled", "false") // Isolate fixture statics in separate JVMs; JUnit methods remain serial within each suite. // Keep other platforms' existing single-fork behavior and respect a one-worker invocation. if (System.getProperty("os.name").lowercase().startsWith("linux")) { @@ -183,6 +206,8 @@ tasks.named("integrationTest") { classpath = classpath.filter { it !in loggingArtifacts } + files(extractLoggingAdminIntegrationTestClasses) val socialArtifacts = socialIntegrationTestArtifacts.artifactFiles classpath = classpath.filter { it !in socialArtifacts } + files(extractSocialIntegrationTestClasses) + val gatewayArtifacts = gatewayIntegrationTestArtifacts.artifactFiles + classpath = classpath.filter { it !in gatewayArtifacts } + files(extractGatewayIntegrationTestClasses) } // Owner proof exports classes and required registry/projection resources without Account application or diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAccountAuthority.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAccountAuthority.java new file mode 100644 index 0000000000..ffbaff578d --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAccountAuthority.java @@ -0,0 +1,276 @@ +package net.firedevops.firemud.accountservice.authordraft; + +import static net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority.canonical; + +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority.ScopeKind; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority.Snapshot; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource.Category; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionMutationRequest.RestrictionState; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence; +import net.firedevops.firemud.accountservice.repository.AccountPlatformRestrictionOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import org.jooq.DSLContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Account-only source owner. No tenant, membership, creator or terms collaborator exists here. */ +public sealed class AccountControlUiAccountAuthority permits AccountControlUiAuthority { + private final AccountRepository accounts; + private final AccountAuthoritySourceEvidenceRepository upstream; + private final AccountPlatformRestrictionOperationRepository restrictions; + private final DSLContext dsl; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Account transaction collaborators are retained privately.") + public AccountControlUiAccountAuthority( + AccountRepository accounts, + AccountAuthoritySourceEvidenceRepository upstream, + AccountPlatformRestrictionOperationRepository restrictions, + DSLContext dsl) { + this.accounts = Objects.requireNonNull(accounts); + this.upstream = Objects.requireNonNull(upstream); + this.restrictions = Objects.requireNonNull(restrictions); + this.dsl = Objects.requireNonNull(dsl); + } + + /** + * Captures current Account-only owner sources in the caller's writable transaction. The supplied + * UUID selects a source; this observation authenticates no caller and is not later commit proof. + * Primary authentication and transaction-bound consumption belong to the issuance owner. + */ + public final Snapshot captureAccount(UUID authenticatedAccountId) { + requireOwnerTransaction(); + if (authenticatedAccountId == null || authenticatedAccountId.equals(new UUID(0L, 0L))) { + throw unavailable(); + } + Account account = + accounts + .findByAccountUuidForUpdate(authenticatedAccountId) + .orElseThrow(AccountControlUiAccountAuthority::unavailable); + if (account.getId() == null + || account.getId() <= 0L + || !authenticatedAccountId.equals(account.getAccountUuid()) + || !account.getId().equals(account.getAccountUuidSourceNumericId()) + || !AccountIdentityProvenance.isAccepted(account.getAccountUuidProvenance()) + || account.getLifecycleState() != AccountLifecycleState.ACTIVE) { + throw unavailable(); + } + var current = + upstream.readCurrentIssuerAccountSources("firemud-account-service", authenticatedAccountId); + var issuer = current.issuer(); + var source = current.account(); + var fence = current.issuanceFence(); + if (!AuthorityScope.issuer("firemud-account-service").equals(issuer.scope()) + || !AuthorityScope.account(authenticatedAccountId).equals(source.scope()) + || !fence.equals(source.issuanceFence()) + || !authenticatedAccountId.equals(fence.accountId()) + || !account.getId().equals(source.accountSourceNumericId()) + || !account.getAccountUuidProvenance().name().equals(source.accountUuidProvenance()) + || current.canonicalAccountProjection() == null + || current.canonicalIssuerProjection() == null) { + throw unavailable(); + } + var restrictionEvidence = new ArrayList>(); + for (Category category : + List.of(Category.ACCOUNT_SECURITY_LOCK, Category.PLATFORM_ACCESS_BAN)) { + var restriction = restrictions.readCurrent(authenticatedAccountId, category); + if (!authenticatedAccountId.equals(restriction.accountUuid()) + || restriction.category() != category + || restriction.state() != RestrictionState.NONRESTRICTED) { + throw unavailable(); + } + restrictionEvidence.add( + Map.of( + "category", category.name(), + "revision", restriction.revision(), + "enforcementEpoch", restriction.enforcementEpoch(), + "resultId", restriction.resultId().toString(), + "requestId", restriction.requestId().toString(), + "state", restriction.state().name())); + } + var roleRow = + dsl.fetchOne( + "SELECT account_uuid, account_uuid_source_numeric_id, account_uuid_provenance, " + + "global_roles, global_role_source_version FROM account_global_role_sources " + + "WHERE account_uuid = ? FOR SHARE", + authenticatedAccountId); + if (roleRow == null + || !authenticatedAccountId.equals(roleRow.get("account_uuid", UUID.class)) + || !account.getId().equals(roleRow.get("account_uuid_source_numeric_id", Long.class)) + || !account + .getAccountUuidProvenance() + .name() + .equals(roleRow.get("account_uuid_provenance", String.class))) { + throw unavailable(); + } + Long roleVersion = roleRow.get("global_role_source_version", Long.class); + String[] roleValues = roleRow.get("global_roles", String[].class); + if (roleVersion == null || roleVersion <= 0L || roleValues == null) { + throw unavailable(); + } + List roles = Arrays.asList(roleValues.clone()); + if (roles.stream() + .anyMatch( + value -> + value == null + || !java.util.Set.of("platformAdmin", "billingAdmin", "support") + .contains(value)) + || !roles.equals(roles.stream().distinct().sorted().toList())) { + throw unavailable(); + } + Map authority = new LinkedHashMap<>(); + authority.put("issuerAuthGeneration", issuer.generation()); + authority.put("accountAuthorityGeneration", source.generation()); + authority.put("tenantAuthorityGeneration", Map.of()); + authority.put("membershipAuthorityGeneration", Map.of()); + authority.put("privateRealmGrantVersions", List.of()); + source + .accountSecurityCutoff() + .ifPresent( + cutoff -> + authority.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", cutoff.accountAuthorityGeneration(), + "outboxStreamKey", cutoff.outboxStreamKey(), + "outboxSequence", cutoff.outboxSequence()))); + byte[] issuerBytes = + current.canonicalIssuerProjection().toJson().getBytes(StandardCharsets.UTF_8); + byte[] accountBytes = + current.canonicalAccountProjection().toJson().getBytes(StandardCharsets.UTF_8); + var vector = new ArrayList(); + vector.add(sourceEvidence(SourceKind.ISSUER, "firemud-account-service", issuer, issuerBytes)); + vector.add( + sourceEvidence( + SourceKind.ACCOUNT, + authenticatedAccountId.toString(), + source, + canonical( + Map.of( + "canonicalAccountProjection", + Base64.getEncoder().encodeToString(accountBytes), + "restrictions", + restrictionEvidence)))); + vector.add( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + authenticatedAccountId.toString(), + Long.toString(source.generation()), + Long.toString(roleVersion), + source.checkpoint().outboxStreamKey(), + Long.toString(source.checkpoint().sequence()), + canonical( + Map.of( + "accountId", + authenticatedAccountId.toString(), + "sourceNumericId", + account.getId(), + "provenance", + account.getAccountUuidProvenance().name(), + "globalRoleSourceVersion", + roleVersion, + "globalRoles", + roles)))); + vector.sort(java.util.Comparator.comparing(SourceEvidence::key)); + Map identity = + Map.of( + "sourceRowId", + account.getId(), + "provenance", + account.getAccountUuidProvenance().name(), + "sourceNumericId", + account.getId()); + byte[] evidence = + canonical( + Map.of( + "schemaVersion", + 1, + "scopeKind", + "ACCOUNT", + "accountId", + authenticatedAccountId.toString(), + "accountIdentitySource", + identity, + "issuanceFence", + fence.value(), + "issuanceFenceSourceVersion", + fence.sourceVersion(), + "sources", + vector.stream() + .map(value -> Base64.getEncoder().encodeToString(value.canonicalBytes())) + .toList())); + return new Snapshot( + authenticatedAccountId, + ScopeKind.ACCOUNT, + Optional.empty(), + Map.of(), + roles, + authority, + Map.of(), + fence.value(), + fence.sourceVersion(), + vector, + evidence, + List.of(checkpoint(issuer), checkpoint(source)), + identity); + } + + private static SourceEvidence sourceEvidence( + SourceKind kind, String scope, CurrentSourceEvidence source, byte[] evidence) { + return new SourceEvidence( + kind, + scope, + Long.toString(source.generation()), + Long.toString(source.sourceVersion()), + source.checkpoint().outboxStreamKey(), + Long.toString(source.checkpoint().sequence()), + evidence); + } + + private static Map checkpoint(CurrentSourceEvidence source) { + var checkpoint = source.checkpoint(); + Map result = new LinkedHashMap<>(); + result.put("outboxStreamKey", checkpoint.outboxStreamKey()); + result.put("outboxSequence", Long.toString(checkpoint.sequence())); + checkpoint.sourceEventId().ifPresent(value -> result.put("sourceEventId", value)); + checkpoint.sourceEventDigest().ifPresent(value -> result.put("sourceEventDigest", value)); + return Map.copyOf(result); + } + + private void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw unavailable(); + } + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw unavailable(); + } + }); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Current Account-only control-ui authority is unavailable"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthority.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthority.java index 33e5d8f330..e9f8f4c00f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthority.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthority.java @@ -1,9 +1,7 @@ package net.firedevops.firemud.accountservice.authordraft; import java.nio.charset.StandardCharsets; -import java.sql.Connection; import java.util.ArrayList; -import java.util.Arrays; import java.util.Base64; import java.util.LinkedHashMap; import java.util.List; @@ -11,16 +9,9 @@ import java.util.Objects; import java.util.Optional; import java.util.UUID; -import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource.Category; -import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionMutationRequest.RestrictionState; -import net.firedevops.firemud.accountservice.entity.Account; -import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; -import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; -import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; -import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence; import net.firedevops.firemud.accountservice.repository.AccountPlatformRestrictionOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.CreatorControlCaptureSources; @@ -28,11 +19,10 @@ import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import org.jooq.DSLContext; -import org.springframework.transaction.support.TransactionSynchronizationManager; import tools.jackson.databind.json.JsonMapper; /** Account-only and existing creator source capture in the caller's owner transaction. */ -public final class AccountControlUiAuthority { +public final class AccountControlUiAuthority extends AccountControlUiAccountAuthority { public enum ScopeKind { ACCOUNT, TENANT @@ -75,248 +65,15 @@ public static UUID decodeScopedTenant(ScopeKind scopeKind, UUID tenantId) { private static final JsonMapper JSON = JsonMapper.builder().build(); private final AccountDraftSourceCompositionService sources; - private final AccountRepository accounts; - private final AccountAuthoritySourceEvidenceRepository upstream; - private final AccountPlatformRestrictionOperationRepository restrictions; - private final DSLContext dsl; - - @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "Account transaction collaborators are retained privately.") + public AccountControlUiAuthority( AccountDraftSourceCompositionService sources, AccountRepository accounts, AccountAuthoritySourceEvidenceRepository upstream, AccountPlatformRestrictionOperationRepository restrictions, DSLContext dsl) { + super(accounts, upstream, restrictions, dsl); this.sources = Objects.requireNonNull(sources); - this.accounts = Objects.requireNonNull(accounts); - this.upstream = Objects.requireNonNull(upstream); - this.restrictions = Objects.requireNonNull(restrictions); - this.dsl = Objects.requireNonNull(dsl); - } - - /** - * Captures current Account-only owner sources in the caller's writable transaction. The supplied - * UUID selects a source; this observation authenticates no caller and is not later commit proof. - * Primary authentication and transaction-bound consumption belong to the issuance owner. - */ - public Snapshot captureAccount(UUID authenticatedAccountId) { - requireOwnerTransaction(); - if (authenticatedAccountId == null || authenticatedAccountId.equals(new UUID(0L, 0L))) { - throw unavailable(); - } - Account account = - accounts - .findByAccountUuidForUpdate(authenticatedAccountId) - .orElseThrow(AccountControlUiAuthority::unavailable); - if (account.getId() == null - || account.getId() <= 0L - || !authenticatedAccountId.equals(account.getAccountUuid()) - || !account.getId().equals(account.getAccountUuidSourceNumericId()) - || !AccountIdentityProvenance.isAccepted(account.getAccountUuidProvenance()) - || account.getLifecycleState() != AccountLifecycleState.ACTIVE) { - throw unavailable(); - } - var current = - upstream.readCurrentIssuerAccountSources("firemud-account-service", authenticatedAccountId); - var issuer = current.issuer(); - var source = current.account(); - var fence = current.issuanceFence(); - if (!AuthorityScope.issuer("firemud-account-service").equals(issuer.scope()) - || !AuthorityScope.account(authenticatedAccountId).equals(source.scope()) - || !fence.equals(source.issuanceFence()) - || !authenticatedAccountId.equals(fence.accountId()) - || !account.getId().equals(source.accountSourceNumericId()) - || !account.getAccountUuidProvenance().name().equals(source.accountUuidProvenance()) - || current.canonicalAccountProjection() == null - || current.canonicalIssuerProjection() == null) { - throw unavailable(); - } - var restrictionEvidence = new ArrayList>(); - for (Category category : - List.of(Category.ACCOUNT_SECURITY_LOCK, Category.PLATFORM_ACCESS_BAN)) { - var restriction = restrictions.readCurrent(authenticatedAccountId, category); - if (!authenticatedAccountId.equals(restriction.accountUuid()) - || restriction.category() != category - || restriction.state() != RestrictionState.NONRESTRICTED) { - throw unavailable(); - } - restrictionEvidence.add( - Map.of( - "category", category.name(), - "revision", restriction.revision(), - "enforcementEpoch", restriction.enforcementEpoch(), - "resultId", restriction.resultId().toString(), - "requestId", restriction.requestId().toString(), - "state", restriction.state().name())); - } - var roleRow = - dsl.fetchOne( - "SELECT account_uuid, account_uuid_source_numeric_id, account_uuid_provenance, " - + "global_roles, global_role_source_version FROM account_global_role_sources " - + "WHERE account_uuid = ? FOR SHARE", - authenticatedAccountId); - if (roleRow == null - || !authenticatedAccountId.equals(roleRow.get("account_uuid", UUID.class)) - || !account.getId().equals(roleRow.get("account_uuid_source_numeric_id", Long.class)) - || !account - .getAccountUuidProvenance() - .name() - .equals(roleRow.get("account_uuid_provenance", String.class))) { - throw unavailable(); - } - Long roleVersion = roleRow.get("global_role_source_version", Long.class); - String[] roleValues = roleRow.get("global_roles", String[].class); - if (roleVersion == null || roleVersion <= 0L || roleValues == null) { - throw unavailable(); - } - List roles = Arrays.asList(roleValues.clone()); - if (roles.stream() - .anyMatch( - value -> - value == null - || !java.util.Set.of("platformAdmin", "billingAdmin", "support") - .contains(value)) - || !roles.equals(roles.stream().distinct().sorted().toList())) { - throw unavailable(); - } - Map authority = new LinkedHashMap<>(); - authority.put("issuerAuthGeneration", issuer.generation()); - authority.put("accountAuthorityGeneration", source.generation()); - authority.put("tenantAuthorityGeneration", Map.of()); - authority.put("membershipAuthorityGeneration", Map.of()); - authority.put("privateRealmGrantVersions", List.of()); - source - .accountSecurityCutoff() - .ifPresent( - cutoff -> - authority.put( - "accountSecurityCutoff", - Map.of( - "accountAuthorityGeneration", cutoff.accountAuthorityGeneration(), - "outboxStreamKey", cutoff.outboxStreamKey(), - "outboxSequence", cutoff.outboxSequence()))); - byte[] issuerBytes = - current.canonicalIssuerProjection().toJson().getBytes(StandardCharsets.UTF_8); - byte[] accountBytes = - current.canonicalAccountProjection().toJson().getBytes(StandardCharsets.UTF_8); - var vector = new ArrayList(); - vector.add(sourceEvidence(SourceKind.ISSUER, "firemud-account-service", issuer, issuerBytes)); - vector.add( - sourceEvidence( - SourceKind.ACCOUNT, - authenticatedAccountId.toString(), - source, - canonical( - Map.of( - "canonicalAccountProjection", - Base64.getEncoder().encodeToString(accountBytes), - "restrictions", - restrictionEvidence)))); - vector.add( - new SourceEvidence( - SourceKind.GLOBAL_ROLES, - authenticatedAccountId.toString(), - Long.toString(source.generation()), - Long.toString(roleVersion), - source.checkpoint().outboxStreamKey(), - Long.toString(source.checkpoint().sequence()), - canonical( - Map.of( - "accountId", - authenticatedAccountId.toString(), - "sourceNumericId", - account.getId(), - "provenance", - account.getAccountUuidProvenance().name(), - "globalRoleSourceVersion", - roleVersion, - "globalRoles", - roles)))); - vector.sort(java.util.Comparator.comparing(SourceEvidence::key)); - Map identity = - Map.of( - "sourceRowId", - account.getId(), - "provenance", - account.getAccountUuidProvenance().name(), - "sourceNumericId", - account.getId()); - byte[] evidence = - canonical( - Map.of( - "schemaVersion", - 1, - "scopeKind", - "ACCOUNT", - "accountId", - authenticatedAccountId.toString(), - "accountIdentitySource", - identity, - "issuanceFence", - fence.value(), - "issuanceFenceSourceVersion", - fence.sourceVersion(), - "sources", - vector.stream() - .map(value -> Base64.getEncoder().encodeToString(value.canonicalBytes())) - .toList())); - return new Snapshot( - authenticatedAccountId, - ScopeKind.ACCOUNT, - Optional.empty(), - Map.of(), - roles, - authority, - Map.of(), - fence.value(), - fence.sourceVersion(), - vector, - evidence, - List.of(checkpoint(issuer), checkpoint(source)), - identity); - } - - private static SourceEvidence sourceEvidence( - SourceKind kind, String scope, CurrentSourceEvidence source, byte[] evidence) { - return new SourceEvidence( - kind, - scope, - Long.toString(source.generation()), - Long.toString(source.sourceVersion()), - source.checkpoint().outboxStreamKey(), - Long.toString(source.checkpoint().sequence()), - evidence); - } - - private static Map checkpoint(CurrentSourceEvidence source) { - var checkpoint = source.checkpoint(); - Map result = new LinkedHashMap<>(); - result.put("outboxStreamKey", checkpoint.outboxStreamKey()); - result.put("outboxSequence", Long.toString(checkpoint.sequence())); - checkpoint.sourceEventId().ifPresent(value -> result.put("sourceEventId", value)); - checkpoint.sourceEventDigest().ifPresent(value -> result.put("sourceEventDigest", value)); - return Map.copyOf(result); - } - - private void requireOwnerTransaction() { - if (!TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { - throw unavailable(); - } - dsl.connection( - connection -> { - if (connection.getAutoCommit() - || connection.isReadOnly() - || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { - throw unavailable(); - } - }); - } - - private static IllegalStateException unavailable() { - return new IllegalStateException("Current Account-only control-ui authority is unavailable"); } public Snapshot capture(UUID actor, UUID tenant, CapturedEnvironmentBoundary environment) { @@ -631,7 +388,7 @@ private Snapshot( identity); } - private Snapshot( + Snapshot( UUID actor, ScopeKind scopeKind, Optional tenant, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountCheckoutReceivingConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountCheckoutReceivingConfiguration.java new file mode 100644 index 0000000000..719511bcbf --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountCheckoutReceivingConfiguration.java @@ -0,0 +1,312 @@ +package net.firedevops.firemud.accountservice.config; + +import io.lettuce.core.RedisURI; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Duration; +import java.util.HashSet; +import java.util.List; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAccountAuthority; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.client.StripeHostingFirstInvoicePaymentClient; +import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.client.StripeHostingWebhookVerifier; +import net.firedevops.firemud.accountservice.controller.AccountHostingFirstInvoiceController; +import net.firedevops.firemud.accountservice.controller.AccountHostingFirstInvoiceWebhookController; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingFirstInvoicePaymentRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingPlanCatalog; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountPlatformRestrictionOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository; +import net.firedevops.firemud.accountservice.repository.StripeEventInboxRepository; +import net.firedevops.firemud.accountservice.security.AccountCheckoutHttpAuthInterceptor; +import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionLifecycleService; +import net.firedevops.firemud.accountservice.service.impl.AccountControlUiAuthenticationGrpcService; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiActorService; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiCoordination; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiIssuanceRepository; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiIssuanceService; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiKeyring; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiRegistryContract; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiResponseCryptography; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiSignerOwner; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider; +import net.firedevops.firemud.accountservice.service.session.AccountHostingFirstInvoicePaymentService; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksTrustedSource; +import net.firedevops.firemud.accountservice.service.session.AccountRecentReauthenticationPolicyRepository; +import net.firedevops.firemud.accountservice.service.session.AccountRecentReauthenticationRepository; +import net.firedevops.firemud.accountservice.service.session.AccountRecentReauthenticationService; +import net.firedevops.firemud.accountservice.service.session.LettuceAccountCoordinationPinnedConnectionProvider; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.GrpcAuthProperties; +import net.firedevops.firemud.common.security.HttpAuthProperties; +import net.firedevops.firemud.common.security.HttpJwtAuthInterceptor; +import net.firedevops.firemud.common.security.JwtUtil; +import org.jooq.DSLContext; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.context.annotation.Profile; +import org.springframework.core.env.Environment; +import org.springframework.core.env.Profiles; +import org.springframework.grpc.server.GlobalServerInterceptor; +import org.springframework.transaction.PlatformTransactionManager; + +/** + * Real registered receiving under explicitly isolated inputs only. No provider, policy, key, + * publication or credential is provisioned here; default production activation stays closed. + */ +@Configuration(proxyBeanMethods = false) +@Profile("isolated-checkout-receiving") +@ConditionalOnProperty( + prefix = "firemud.account.checkout-receiving", + name = "enabled", + havingValue = "true") +@Import({ + AccountProtectedJwksSourceConfiguration.class, + AccountHostingFirstInvoiceController.class, + AccountHostingFirstInvoiceWebhookController.class +}) +public class AccountCheckoutReceivingConfiguration { + public static final String COORDINATION_URI = "accountCheckoutIsolatedCoordinationUri"; + public static final String ACKNOWLEDGEMENTS = "accountCheckoutIsolatedAcknowledgements"; + public static final String STRIPE = "accountCheckoutIsolatedStripeClient"; + + @Bean + AccountCheckoutReceivingProperties accountCheckoutReceivingProperties(Environment environment) { + if (environment.acceptsProfiles(Profiles.of("prod", "production"))) { + throw new IllegalArgumentException("Checkout receiving is restricted to isolated inputs"); + } + return new AccountCheckoutReceivingProperties( + environment.getRequiredProperty("firemud.grpc.workload-namespace"), + Path.of( + environment.getRequiredProperty( + "firemud.account.checkout-receiving.private-signer-root")), + Path.of( + environment.getRequiredProperty( + "firemud.account.checkout-receiving.public-signer-root")), + Path.of( + environment.getRequiredProperty( + "firemud.account.checkout-receiving.control-ui-keyring-root")), + environment.getProperty("firemud.auth.session-safety-margin-ms", Long.class, 300_000L)); + } + + @Bean + AccountControlUiAccountAuthority accountCheckoutAuthority( + AccountRepository accounts, + AccountAuthoritySourceEvidenceRepository upstream, + AccountPlatformRestrictionOperationRepository restrictions, + DSLContext dsl) { + return new AccountControlUiAccountAuthority(accounts, upstream, restrictions, dsl); + } + + @Bean + DraftAuthorizationFenceRepository accountCheckoutProducerFences(DSLContext dsl) { + return new DraftAuthorizationFenceRepository(dsl); + } + + @Bean + AccountControlUiIssuanceRepository accountCheckoutIssuanceRepository(DSLContext dsl) { + return new AccountControlUiIssuanceRepository(dsl); + } + + @Bean + AccountControlUiSignerOwner accountCheckoutSigner( + AccountJwtSignerDesiredStateRepository signers, + AccountJwtSignerMaterializerTrustBinding trust, + AccountJwtJwksApiBinding api, + AccountCheckoutReceivingProperties properties) { + return new AccountControlUiSignerOwner( + signers, trust, api, properties.privateSignerRoot(), properties.publicSignerRoot()); + } + + @Bean + AccountControlUiResponseCryptography accountCheckoutCryptography( + AccountCheckoutReceivingProperties properties) { + return new AccountControlUiResponseCryptography( + new AccountControlUiKeyring(properties.controlUiKeyringRoot()), Clock.systemUTC()); + } + + @Bean(destroyMethod = "close") + LettuceAccountCoordinationPinnedConnectionProvider accountCheckoutCoordinationConnections( + @Qualifier(COORDINATION_URI) RedisURI deliveredIsolatedUri) { + return new LettuceAccountCoordinationPinnedConnectionProvider(deliveredIsolatedUri); + } + + @Bean + AccountControlUiCoordination accountCheckoutCoordination( + @Qualifier("accountCheckoutCoordinationConnections") + AccountCoordinationPinnedConnectionProvider connections, + @Qualifier(ACKNOWLEDGEMENTS) + AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements + acknowledgements) { + RedisScriptContribution contribution = + new RedisScriptContribution() { + @Override + public String ownerId() { + return AccountControlUiRegistryContract.descriptor().owner(); + } + + @Override + public java.util.Collection< + net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor> + descriptors() { + return List.of(AccountControlUiRegistryContract.descriptor()); + } + }; + return new AccountControlUiCoordination( + connections, acknowledgements, RedisScriptCatalog.fromContributions(List.of(contribution))); + } + + @Bean + AccountControlUiActorService accountCheckoutActors( + AccountControlUiIssuanceRepository operations, + AccountControlUiAccountAuthority authority, + AccountControlUiSignerOwner signers, + AccountControlUiCoordination coordination, + AccountJwtJwksTrustedSource publicSource, + DraftAuthorizationFenceRepository fences, + @Qualifier("transactionManager") PlatformTransactionManager transactions) { + return new AccountControlUiActorService( + operations, + authority, + signers, + coordination, + publicSource, + fences, + transactions, + Clock.systemUTC()); + } + + @Bean + AccountControlUiIssuanceService accountCheckoutIssuance( + AccountServiceImpl primary, + AccountControlUiIssuanceRepository operations, + AccountControlUiAccountAuthority authority, + DraftAuthorizationFenceRepository fences, + AccountControlUiSignerOwner signers, + AccountControlUiResponseCryptography cryptography, + AccountControlUiCoordination coordination, + AccountControlUiActorService actors, + @Qualifier("transactionManager") PlatformTransactionManager transactions, + AccountCheckoutReceivingProperties properties) { + return new AccountControlUiIssuanceService( + primary, + operations, + authority, + fences, + signers, + cryptography, + coordination, + actors, + transactions, + Clock.systemUTC(), + properties.sessionSafetyMarginMillis(), + properties.gatewayPeerUri()); + } + + @Bean + AccountRecentReauthenticationService accountCheckoutReauthentication( + AccountServiceImpl primary, + AccountRepository accounts, + AccountAuthorityGenerationRepository generations, + DSLContext dsl, + @Qualifier("transactionManager") PlatformTransactionManager transactions, + AccountControlUiResponseCryptography cryptography) { + return new AccountRecentReauthenticationService( + primary, + accounts, + generations, + new AccountRecentReauthenticationRepository(dsl), + new AccountRecentReauthenticationPolicyRepository(dsl), + transactions, + Clock.systemUTC(), + cryptography); + } + + @Bean + AccountSubscriptionIntentRepository accountCheckoutIntents( + DSLContext dsl, AccountHostingPlanCatalog plans) { + return new AccountSubscriptionIntentRepository(dsl, plans); + } + + @Bean + AccountHostingFirstInvoicePaymentRepository accountCheckoutPayments( + DSLContext dsl, AccountSubscriptionIntentRepository intents) { + return new AccountHostingFirstInvoicePaymentRepository(dsl, intents, Clock.systemUTC()); + } + + @Bean + AccountHostingSubscriptionLifecycleService accountCheckoutLifecycle( + DSLContext dsl, + AccountSubscriptionIntentRepository intents, + AccountHostingSubscriptionLifecycleRepository.ReconciliationLimits limits, + AccountHostingSubscriptionLifecyclePolicy policy, + AccountCheckoutReceivingProperties properties, + @Qualifier(STRIPE) com.stripe.StripeClient stripe, + @Qualifier("transactionManager") PlatformTransactionManager transactions) { + return new AccountHostingSubscriptionLifecycleService( + new AccountHostingSubscriptionLifecycleRepository( + dsl, intents, Clock.systemUTC(), limits, policy, properties.namespace(), false), + new StripeHostingSubscriptionObserver( + stripe, Clock.systemUTC(), Duration.ofSeconds(2), Duration.ofSeconds(5)), + transactions); + } + + @Bean + AccountHostingFirstInvoicePaymentService accountCheckoutPaymentService( + AccountControlUiActorService actors, + AccountRecentReauthenticationService reauthentication, + AccountHostingFirstInvoicePaymentRepository payments, + DSLContext dsl, + @Qualifier(STRIPE) com.stripe.StripeClient stripe, + PaymentProperties properties, + AccountHostingSubscriptionLifecycleService lifecycle, + @Qualifier("transactionManager") PlatformTransactionManager transactions) { + return new AccountHostingFirstInvoicePaymentService( + actors, + reauthentication, + payments, + new StripeEventInboxRepository(dsl), + new StripeHostingFirstInvoicePaymentClient( + stripe, Clock.systemUTC(), Duration.ofSeconds(2), Duration.ofSeconds(5)), + new StripeHostingWebhookVerifier(properties.getHostingWebhookSecret(), Clock.systemUTC()), + lifecycle, + transactions); + } + + @Bean + AccountControlUiAuthenticationGrpcService accountCheckoutAuthenticationGrpcService( + AccountControlUiIssuanceService issuance, + AccountControlUiActorService actors, + AccountCheckoutReceivingProperties properties) { + return new AccountControlUiAuthenticationGrpcService(issuance, actors, properties.namespace()); + } + + @Bean + HttpJwtAuthInterceptor accountCheckoutHttpAuthentication( + @Qualifier("jwtUtil") JwtUtil jwt, + HttpAuthProperties properties, + AccountControlUiActorService actors) { + return new AccountCheckoutHttpAuthInterceptor(jwt, properties, actors); + } + + @Bean + @GlobalServerInterceptor + AuthTokenInterceptor accountCheckoutGrpcAuthentication( + @Qualifier("jwtUtil") JwtUtil jwt, GrpcAuthProperties properties) { + var methods = new HashSet<>(properties.getPublicMethods()); + methods.add("account.v1.AccountControlUiAuthenticationService/AuthLogin"); + return new AuthTokenInterceptor(jwt, methods); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountCheckoutReceivingProperties.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountCheckoutReceivingProperties.java new file mode 100644 index 0000000000..294ba19c52 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountCheckoutReceivingProperties.java @@ -0,0 +1,37 @@ +package net.firedevops.firemud.accountservice.config; + +import java.nio.file.Path; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Explicit source selection for isolated receiving; never privacy or deployment qualification. */ +public record AccountCheckoutReceivingProperties( + String namespace, + Path privateSignerRoot, + Path publicSignerRoot, + Path controlUiKeyringRoot, + long sessionSafetyMarginMillis) { + public AccountCheckoutReceivingProperties { + if (!GrpcPeerIdentity.isValidNamespace(namespace) || sessionSafetyMarginMillis < 0L) + throw new IllegalArgumentException("Explicit Account checkout sources required"); + requirePath(privateSignerRoot); + requirePath(publicSignerRoot); + requirePath(controlUiKeyringRoot); + if (controlUiKeyringRoot.startsWith(privateSignerRoot) + || privateSignerRoot.startsWith(controlUiKeyringRoot) + || controlUiKeyringRoot.startsWith(publicSignerRoot) + || publicSignerRoot.startsWith(controlUiKeyringRoot)) { + throw new IllegalArgumentException("Dedicated control-ui custody must remain separate"); + } + } + + public String gatewayPeerUri() { + return "spiffe://firemud/ns/" + namespace + "/sa/spring-cloud-gateway"; + } + + private static void requirePath(Path path) { + if (path == null || !path.isAbsolute() || !path.equals(path.normalize())) { + throw new IllegalArgumentException( + "Explicit absolute protected Account source paths required"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountProtectedJwksSourceConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountProtectedJwksSourceConfiguration.java new file mode 100644 index 0000000000..938fc490d9 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountProtectedJwksSourceConfiguration.java @@ -0,0 +1,70 @@ +package net.firedevops.firemud.accountservice.config; + +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksTrustedSource; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.transaction.PlatformTransactionManager; + +/** + * Explicit-import owner of Account's single protected public-JWKS source graph. This lite bean + * owner is not component-scanned and selects no gameplay, public-read or other consumer. Each + * independently selected consumer imports this same owner; repeated imports share the graph. + */ +public class AccountProtectedJwksSourceConfiguration { + private static final String JWKS_API_BINDING_PATH = "/etc/firemud/account-jwt-api/binding.json"; + + @Bean + AccountJwtJwksApiBinding accountPublicJwksApiBinding( + AccountJwtSignerMaterializerTrustBinding materializerTrust, + @Value("${firemud.account.public-jwks.api-binding-path:}") String bindingPath, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + if (!JWKS_API_BINDING_PATH.equals(bindingPath) + || !GrpcPeerIdentity.isValidNamespace(namespace)) { + throw unavailable(); + } + try { + var api = new AccountJwtJwksApiBinding(true, bindingPath); + var materializer = materializerTrust.current().orElseThrow(); + var current = api.current(); + if (!namespace.equals(materializer.namespace()) + || !namespace.equals(current.namespace()) + || !materializer.environmentId().equals(current.environmentId()) + || !materializer.clusterId().equals(current.clusterId()) + || !materializer + .expectedClusterIncarnationUid() + .equals(current.expectedClusterIncarnationUid()) + || !materializer.expectedNamespaceUid().equals(current.expectedNamespaceUid())) { + throw unavailable(); + } + // current() pins the protected API identity. Existing owners reread and compare both trust + // sources on use; a later materializer namespace cannot replace this accepted API identity. + return api; + } catch (RuntimeException failure) { + throw unavailable(); + } + } + + @Bean + AccountJwtJwksConfigMapClient accountPublicJwksClient(AccountJwtJwksApiBinding api) { + return new AccountJwtJwksConfigMapClient(api); + } + + @Bean + AccountJwtJwksTrustedSource accountPublicTrustedJwks( + AccountJwtJwksConfigMapClient client, + AccountJwtSignerMaterializerTrustBinding trust, + AccountJwtSignerDesiredStateRepository signers, + AccountJwtJwksPublicationRepository publications, + @Qualifier("transactionManager") PlatformTransactionManager transactions) { + return new AccountJwtJwksTrustedSource(client, trust, signers, publications, transactions); + } + + private static IllegalArgumentException unavailable() { + return new IllegalArgumentException("Protected Account public JWKS configuration required"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceController.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceController.java index 0b810b1277..266b96f136 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceController.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceController.java @@ -19,7 +19,13 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.server.ResponseStatusException; -/** Deliberately NOT a registered controller. Retention/custody and route activation remain held. */ +/** Registered only by the isolated receiving composition; production activation remains held. */ +@org.springframework.web.bind.annotation.RestController +@org.springframework.context.annotation.Profile("isolated-checkout-receiving") +@org.springframework.boot.autoconfigure.condition.ConditionalOnProperty( + prefix = "firemud.account.checkout-receiving", + name = "enabled", + havingValue = "true") @RequestMapping("/billing/hosting/subscriptions/{subscriptionId}/first-invoice") public final class AccountHostingFirstInvoiceController { private final AccountHostingFirstInvoicePaymentService payments; @@ -106,6 +112,29 @@ public AccountHostingFirstInvoicePaymentService.Completion signedCompletion( return payments.completeSigned(payload, signature); } + @ExceptionHandler({ + net.firedevops.firemud.accountservice.service.session.AccountControlUiRegistryReader + .RegistryUnavailableException.class, + net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceUnavailableException.class, + net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier + .VerificationUnavailableException.class, + org.springframework.dao.DataAccessException.class + }) + public ResponseEntity authenticationUnavailable() { + return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE) + .cacheControl(CacheControl.noStore()) + .body(new ErrorResponse("AUTH_UNAVAILABLE")); + } + + @ExceptionHandler( + net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.VerificationException + .class) + public ResponseEntity authenticationRefused() { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED) + .cacheControl(CacheControl.noStore()) + .body(new ErrorResponse("AUTH_SESSION_REVOKED")); + } + @ExceptionHandler(StripeException.class) public ResponseEntity providerUncertain() { return ResponseEntity.status(HttpStatus.BAD_GATEWAY) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceWebhookController.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceWebhookController.java new file mode 100644 index 0000000000..aa6bd5d0b0 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceWebhookController.java @@ -0,0 +1,84 @@ +package net.firedevops.firemud.accountservice.controller; + +import com.stripe.exception.SignatureVerificationException; +import com.stripe.exception.StripeException; +import jakarta.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.accountservice.service.session.AccountHostingFirstInvoicePaymentService; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Profile; +import org.springframework.http.CacheControl; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.server.ResponseStatusException; + +/** Provider signature authentication over exact bounded bytes, independent of browser authority. */ +@RestController +@Profile("isolated-checkout-receiving") +@ConditionalOnProperty( + prefix = "firemud.account.checkout-receiving", + name = "enabled", + havingValue = "true") +public final class AccountHostingFirstInvoiceWebhookController { + public static final int MAX_BODY_BYTES = 256 * 1024; + private final AccountHostingFirstInvoicePaymentService payments; + + public AccountHostingFirstInvoiceWebhookController( + AccountHostingFirstInvoicePaymentService payments) { + this.payments = Objects.requireNonNull(payments); + } + + @PostMapping(value = "/billing/hosting/webhook", consumes = "application/json") + public ResponseEntity receive( + HttpServletRequest request) throws IOException { + if (!request.isSecure()) throw new ResponseStatusException(HttpStatus.UNAUTHORIZED); + var signatures = request.getHeaders("Stripe-Signature"); + if (signatures == null || !signatures.hasMoreElements()) + throw new ResponseStatusException(HttpStatus.BAD_REQUEST); + String signature = signatures.nextElement(); + if (signatures.hasMoreElements() || signature.isBlank() || signature.length() > 4096) + throw new ResponseStatusException(HttpStatus.BAD_REQUEST); + if (request.getContentLengthLong() > MAX_BODY_BYTES) + throw new ResponseStatusException(HttpStatus.PAYLOAD_TOO_LARGE); + byte[] bytes = request.getInputStream().readNBytes(MAX_BODY_BYTES + 1); + try { + if (bytes.length == 0 || bytes.length > MAX_BODY_BYTES) + throw new ResponseStatusException(HttpStatus.PAYLOAD_TOO_LARGE); + String raw = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + var completion = payments.completeSigned(raw, signature); + // Do not acknowledge a nonterminal owner outcome as processed. Provider redelivery may + // reconcile this same signed event, never issue another payment confirmation. + return ResponseEntity.status( + "COMMITTED".equals(completion.state()) + ? HttpStatus.OK + : HttpStatus.SERVICE_UNAVAILABLE) + .cacheControl(CacheControl.noStore()) + .header("Pragma", "no-cache") + .body(completion); + } catch (CharacterCodingException + | SignatureVerificationException + | IllegalArgumentException invalid) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST); + } catch (StripeException unavailable) { + throw new ResponseStatusException(HttpStatus.BAD_GATEWAY); + } catch (IllegalStateException refused) { + throw new ResponseStatusException(HttpStatus.CONFLICT); + } finally { + Arrays.fill(bytes, (byte) 0); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountCheckoutHttpAuthInterceptor.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountCheckoutHttpAuthInterceptor.java new file mode 100644 index 0000000000..43433e5c6b --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountCheckoutHttpAuthInterceptor.java @@ -0,0 +1,93 @@ +package net.firedevops.firemud.accountservice.security; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.util.Objects; +import java.util.Set; +import net.firedevops.firemud.accountservice.controller.AccountHostingFirstInvoiceController; +import net.firedevops.firemud.accountservice.controller.AccountHostingFirstInvoiceWebhookController; +import net.firedevops.firemud.accountservice.controller.AuthController; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiActorService; +import net.firedevops.firemud.common.security.HttpAuthProperties; +import net.firedevops.firemud.common.security.HttpJwtAuthInterceptor; +import net.firedevops.firemud.common.security.JwtUtil; +import org.springframework.web.method.HandlerMethod; + +/** + * Exact handler ownership, never a public billing path pattern or a global authentication bypass. + */ +public final class AccountCheckoutHttpAuthInterceptor extends HttpJwtAuthInterceptor { + private static final Set OWNER_METHODS = + Set.of("read", "reauthenticate", "confirm", "renew"); + private final AccountControlUiActorService actors; + + public AccountCheckoutHttpAuthInterceptor( + JwtUtil legacy, HttpAuthProperties properties, AccountControlUiActorService actors) { + super(legacy, properties); + this.actors = Objects.requireNonNull(actors); + } + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { + if (handler instanceof HandlerMethod method) { + if (method.getBeanType() == AuthController.class + && "login".equals(method.getMethod().getName())) { + // This isolated chain has one canonical login producer, reached through verified mTLS. + response.setStatus(404); + return false; + } + boolean owner = + method.getBeanType() == AccountHostingFirstInvoiceController.class + && OWNER_METHODS.contains(method.getMethod().getName()); + boolean webhook = + method.getBeanType() == AccountHostingFirstInvoiceWebhookController.class + && "receive".equals(method.getMethod().getName()); + if (owner || webhook) { + response.setHeader("Cache-Control", "no-store"); + response.setHeader("Pragma", "no-cache"); + if (!request.isSecure()) { + response.setStatus(401); + return false; + } + if (webhook) + return true; // The separate raw adapter requires the actual provider signature. + String authorization = request.getHeader("Authorization"); + if (authorization == null + || !authorization.startsWith("Bearer ") + || authorization.length() <= 7 + || authorization.length() > 16_391) { + response.setStatus(401); + return false; + } + try { + if (actors.authenticateAccount(authorization.substring(7)) == null) { + response.setStatus(503); + return false; + } + // Every owner mutation repeats currentness inside its actual owner transaction. + return true; + } catch (org.springframework.dao.DataAccessException + | io.lettuce.core.RedisException + | net.firedevops.firemud.accountservice.service.session.AccountControlUiRegistryReader + .RegistryUnavailableException + | net.firedevops.firemud.common.security.AccountPublicJwksCache + .SourceUnavailableException + | net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier + .VerificationUnavailableException + unavailable) { + response.setStatus(503); + return false; + } catch (IllegalArgumentException + | IllegalStateException + | net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier + .VerificationException + denied) { + response.setStatus(401); + return false; + } + } + } + return super.preHandle(request, response, handler); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcService.java new file mode 100644 index 0000000000..25e348f93f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcService.java @@ -0,0 +1,94 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountControlUiAuthenticationServiceGrpc; +import net.firedevops.firemud.account.v1.AuthLoginRequest; +import net.firedevops.firemud.account.v1.AuthLoginResponse; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiActorService; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiIssuanceService; +import net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Exact Gateway workload receiving. Primary authentication and issuance remain Account-owned. */ +public final class AccountControlUiAuthenticationGrpcService + extends AccountControlUiAuthenticationServiceGrpc + .AccountControlUiAuthenticationServiceImplBase { + private final AccountControlUiIssuanceService issuance; + private final AccountControlUiActorService actors; + private final String namespace; + private final String gatewayPeer; + + public AccountControlUiAuthenticationGrpcService( + AccountControlUiIssuanceService issuance, + AccountControlUiActorService actors, + String namespace) { + this.issuance = Objects.requireNonNull(issuance); + this.actors = Objects.requireNonNull(actors); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Exact Account namespace required"); + this.namespace = namespace; + this.gatewayPeer = "spiffe://firemud/ns/" + namespace + "/sa/spring-cloud-gateway"; + } + + @Override + public void authLogin(AuthLoginRequest wire, StreamObserver response) { + var peer = GrpcPeerIdentity.current(); + if (peer == null || !gatewayPeer.equals(peer.uri())) { + response.onError( + Status.PERMISSION_DENIED + .withDescription("Authenticated Gateway workload required") + .asRuntimeException()); + return; + } + AccountControlUiAuthenticationGrpcCodec.Request request; + try { + request = AccountControlUiAuthenticationGrpcCodec.parseRequest(wire); + if (!namespace.equals(request.callerNamespace())) throw new IllegalArgumentException(); + } catch (IllegalArgumentException invalid) { + response.onError( + Status.INVALID_ARGUMENT + .withDescription("Invalid Account login request") + .asRuntimeException()); + return; + } + try (var credential = + issuance.issueAccount( + new AccountControlUiIssuanceService.AccountSignInRequest( + request.requestId(), + request.email(), + request.secret(), + request.callerContextId()))) { + byte[] compact = credential.compactBytes(); + try { + String token = new String(compact, StandardCharsets.US_ASCII); + var actor = actors.authenticateAccount(token); + response.onNext( + AccountControlUiAuthenticationGrpcCodec.toResponse( + request, + new AccountControlUiAuthenticationGrpcCodec.Authenticated( + actor.accountId(), token, credential.expiresAt().getEpochSecond()))); + response.onCompleted(); + } finally { + Arrays.fill(compact, (byte) 0); + } + } catch (AuthenticationException denied) { + response.onNext(AccountControlUiAuthenticationGrpcCodec.toResponse(request, null)); + response.onCompleted(); + } catch (IllegalArgumentException conflict) { + response.onError( + Status.ALREADY_EXISTS + .withDescription("Account login request conflicts") + .asRuntimeException()); + } catch (RuntimeException unavailable) { + response.onError( + Status.UNAVAILABLE + .withDescription("Account login authority unavailable") + .asRuntimeException()); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java index 67278ace16..e74d9c4947 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java @@ -9,6 +9,7 @@ import java.util.Objects; import java.util.UUID; import java.util.function.Function; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAccountAuthority; import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; @@ -22,7 +23,11 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; -/** Genuine creator actor/currentness and same-transaction original Draft ordering; unregistered. */ +/** + * Genuine Account and creator currentness with same-transaction original Draft ordering. Only the + * Account actor is selected by isolated checkout receiving; default production activation stays + * closed. + */ public final class AccountControlUiActorService { private static final AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy POLICY = new AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy( @@ -38,7 +43,7 @@ public final class AccountControlUiActorService { 16384, claims -> ControlUiJwtProfileValidator.validateClaims(claims, 1)); private final AccountControlUiIssuanceRepository operations; - private final AccountControlUiAuthority authority; + private final AccountControlUiAccountAuthority authority; private final AccountControlUiSignerOwner signers; private final AccountControlUiCoordination registry; private final AccountJwtJwksTrustedSource publicSource; @@ -54,7 +59,7 @@ public final class AccountControlUiActorService { "Injected Draft fence repository is an internal Account owner transaction collaborator.") public AccountControlUiActorService( AccountControlUiIssuanceRepository operations, - AccountControlUiAuthority authority, + AccountControlUiAccountAuthority authority, AccountControlUiSignerOwner signers, AccountControlUiCoordination registry, AccountJwtJwksTrustedSource publicSource, @@ -78,6 +83,7 @@ public AccountControlUiActorService( public AuthenticatedActor authenticate( String compactJwt, UUID selectedTenant, CapturedEnvironmentBoundary environment) { + tenantAuthority(); return withCurrent( compactJwt, selectedTenant, @@ -203,6 +209,7 @@ private T withCurrentScope( CapturedEnvironmentBoundary environment, Function action) { outsideSql(); + if (scopeKind == AccountControlUiAuthority.ScopeKind.TENANT) tenantAuthority(); var signed = verifySigned(compactJwt); var acceptedKey = readAcceptedSignerKey(signed.claims.keyId()); String tokenHash = @@ -227,7 +234,8 @@ private T withCurrentScope( var current = switch (scopeKind) { case ACCOUNT -> authority.captureAccount(stored.accountId); - case TENANT -> authority.capture(stored.accountId, selectedTenant, environment); + case TENANT -> + tenantAuthority().capture(stored.accountId, selectedTenant, environment); }; if (current.scopeKind() != scopeKind) throw denied(); if (scopeKind == AccountControlUiAuthority.ScopeKind.ACCOUNT) { @@ -267,6 +275,7 @@ T withCurrentCommitted( Objects.requireNonNull(selectedTenant, "selected tenant is required"); Objects.requireNonNull(tokenJti, "control-ui token jti is required"); Objects.requireNonNull(environment, "captured Account environment is required"); + tenantAuthority(); Objects.requireNonNull(action, "current actor action is required"); var original = transaction.execute(ignored -> operations.findTokenJti(tokenJti)); if (original == null @@ -298,7 +307,7 @@ T withCurrentCommitted( } requireStoredActorIdentity(observed, actorAccountId, selectedTenant, tokenJti); signers.requireOriginal(observed.signerReceipt); - var current = authority.capture(actorAccountId, selectedTenant, environment); + var current = tenantAuthority().capture(actorAccountId, selectedTenant, environment); if (!Arrays.equals(current.evidence(), observed.sources) || !clock.instant().isBefore(observed.expiresAt)) { throw denied(); @@ -613,6 +622,11 @@ private static void outsideSql() { } } + private AccountControlUiAuthority tenantAuthority() { + if (authority instanceof AccountControlUiAuthority tenantAuthority) return tenantAuthority; + throw denied(); + } + private static IllegalStateException denied() { return new IllegalStateException("Exact current authenticated initial creator required"); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java index b97cd3d450..927c446529 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java @@ -7,6 +7,7 @@ import java.util.Map; import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAccountAuthority; import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; @@ -21,14 +22,15 @@ import org.springframework.transaction.support.TransactionTemplate; /** - * Minimum genuine backend creator issuance/recovery, deliberately unregistered and unmounted. - * Primary credentials, existing owner sources and actual Coordination are all required. An + * Genuine Account and creator issuance/recovery. Only Account issuance is selected by the isolated + * checkout receiving composition; creator receiving and default production activation remain + * closed. Primary credentials, existing owner sources and actual Coordination are all required. An * independently protected exact peer binding supplies transport identity, never creator authority. */ public final class AccountControlUiIssuanceService { private final AccountServiceImpl primaryAuthentication; private final AccountControlUiIssuanceRepository operations; - private final AccountControlUiAuthority authority; + private final AccountControlUiAccountAuthority authority; private final DraftAuthorizationFenceRepository fences; private final AccountControlUiSignerOwner signers; private final AccountControlUiResponseCryptography cryptography; @@ -46,7 +48,7 @@ public final class AccountControlUiIssuanceService { public AccountControlUiIssuanceService( AccountServiceImpl primaryAuthentication, AccountControlUiIssuanceRepository operations, - AccountControlUiAuthority authority, + AccountControlUiAccountAuthority authority, DraftAuthorizationFenceRepository fences, AccountControlUiSignerOwner signers, AccountControlUiResponseCryptography cryptography, @@ -80,6 +82,7 @@ public AccountControlUiIssuanceService( public IssuedCredential issue(Request request, CapturedEnvironmentBoundary environment) { Objects.requireNonNull(request); + tenantAuthority(); return issueInternal( new Invocation( request.requestId, @@ -143,8 +146,9 @@ private IssuedCredential issueInternal(Invocation request) { java.util.Optional tenantSource = request.scopeKind == AccountControlUiAuthority.ScopeKind.TENANT ? java.util.Optional.of( - authority.captureInitial( - request.tenantId.orElseThrow(), environment.orElseThrow())) + tenantAuthority() + .captureInitial( + request.tenantId.orElseThrow(), environment.orElseThrow())) : java.util.Optional.empty(); tenantSource.ifPresent(value -> fences.lockProducerSourcesNowait(value.sources())); AccountServiceImpl.ControlUiPrimaryIdentity authenticated; @@ -349,7 +353,8 @@ private Prepared current( var source = original.scopeKind() == AccountControlUiAuthority.ScopeKind.ACCOUNT ? authority.captureAccount(original.accountId) - : authority.capture(original.accountId, original.tenantId(), environment.orElseThrow()); + : tenantAuthority() + .capture(original.accountId, original.tenantId(), environment.orElseThrow()); fences.lockProducerSourcesNowait(source.sources()); if (!Arrays.equals(source.evidence(), original.sources)) { throw denied(); @@ -527,6 +532,11 @@ public String toString() { } } + private AccountControlUiAuthority tenantAuthority() { + if (authority instanceof AccountControlUiAuthority tenantAuthority) return tenantAuthority; + throw denied(); + } + private static IllegalStateException denied() { return new IllegalStateException("Control-ui original issuance/current recovery unavailable"); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReader.java index 917d03ba67..e520cd82d0 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReader.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReader.java @@ -104,8 +104,10 @@ public byte[] readActive(String tokenHash) { throw denied(); } return exact.clone(); + } catch (RegistryRefusedException refused) { + throw refused; } catch (RuntimeException unavailable) { - throw denied(); + throw new RegistryUnavailableException(); } } @@ -213,7 +215,19 @@ private static void outsideSql() { } private static IllegalStateException denied() { - return new IllegalStateException( - "Exact Account active control-ui registry evidence unavailable"); + return new RegistryRefusedException(); + } + + /** Dependency failure cannot certify revocation or make a cached token authoritative. */ + public static final class RegistryUnavailableException extends IllegalStateException { + private RegistryUnavailableException() { + super("Account control-ui registry transport unavailable"); + } + } + + private static final class RegistryRefusedException extends IllegalStateException { + private RegistryRefusedException() { + super("Exact Account active control-ui registry evidence unavailable"); + } } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationService.java index d399f6be09..4faa843e64 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationService.java @@ -31,8 +31,9 @@ import org.springframework.transaction.support.TransactionTemplate; /** - * Manually composed, unregistered Account source for recent ordinary reauthentication. It uses - * Account's existing real primary-authentication producer and creates no token, route or session. + * Account source for recent ordinary reauthentication, consumed by isolated checkout receiving. It + * uses Account's existing real primary-authentication producer and creates no token, route or + * session. */ public final class AccountRecentReauthenticationService { private final AccountServiceImpl primaryAuthentication; diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index fa308176c3..eb571b13e3 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -335,6 +335,31 @@ components: type: string required: [token] paths: + /billing/hosting/webhook: + post: + operationId: receiveHostingFirstInvoiceSignedEvent + x-runtime-status: isolated_only_default_off + summary: Receive an exact raw provider-signed first-invoice event + description: Actual HTTPS only. Single bounded signature and exact raw UTF-8 body; provider signature is independent of user authentication. Default production registration stays closed. + security: [] + parameters: + - name: Stripe-Signature + in: header + required: true + schema: {type: string, maxLength: 4096} + requestBody: + required: true + content: + application/json: + schema: {type: string, description: 'Exact raw signed JSON bytes, at most 262144 UTF-8 bytes'} + responses: + '200': {description: Original Account completion state; no-store} + '400': {description: Missing, ambiguous, malformed or invalid signed event} + '401': {description: Actual HTTPS required} + '409': {description: Exact retained event or billing evidence refused} + '413': {description: Event body exceeds the bound} + '502': {description: Provider outcome remains uncertain} + '503': {description: Retained completion is still reconciling; same signed event may be redelivered} /billing/hosting/subscriptions/{subscriptionId}/first-invoice: parameters: - name: subscriptionId @@ -344,7 +369,7 @@ paths: get: summary: Retrieve the exact retained first invoice for its current billing owner operationId: getHostingFirstInvoice - x-runtime-status: held_unregistered + x-runtime-status: isolated_only_default_off description: Current HTTPS control-ui billing owner only. No-store exact existing first invoice; never a client secret. responses: '200': @@ -378,7 +403,7 @@ paths: post: summary: Reauthenticate the current billing owner for first-invoice payment operationId: reauthenticateHostingFirstInvoice - x-runtime-status: held_unregistered + x-runtime-status: isolated_only_default_off description: Actual ordinary primary authentication for HOSTING_FIRST_INVOICE_PAYMENT. No gameplay or game-creation proof accepted. requestBody: required: true @@ -414,7 +439,7 @@ paths: post: summary: Confirm explicit consent for the retained first-invoice payment operationId: confirmHostingFirstInvoice - x-runtime-status: held_unregistered + x-runtime-status: isolated_only_default_off description: Exact explicit consent and one durable existing-intent command; repeat requests reconcile read-only and never create or confirm another payment. requestBody: required: true @@ -454,7 +479,7 @@ paths: post: summary: Renew authorization for the same first-invoice payment operation operationId: renewHostingFirstInvoiceAuthorization - x-runtime-status: held_unregistered + x-runtime-status: isolated_only_default_off description: Fresh primary reauthentication and explicit unchanged consent renew authorization on the original operation. A prior durable command claim is never resent. requestBody: required: true @@ -508,7 +533,8 @@ paths: description: Bad request /auth/login: post: - summary: Authenticate and return JWT + summary: Legacy Account HTTP login outside isolated checkout receiving + description: Isolated checkout receiving rejects this direct handler. Its canonical Gateway login uses verified mTLS Account issuance, with no HMAC checkout fallback. operationId: login security: [] requestBody: diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java index 70e6ede247..5eea739ea0 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java @@ -120,6 +120,11 @@ public static Fixture create(DataSource source, Account account) { } private static Fixture createInternal(DataSource source, Account existingAccount) { + return createInternal(source, existingAccount, "prod"); + } + + private static Fixture createInternal( + DataSource source, Account existingAccount, String namespace) { Objects.requireNonNull(source, "migrated Account datasource is required"); JdbcTemplate jdbc = new JdbcTemplate(source); DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); @@ -151,11 +156,11 @@ private static Fixture createInternal(DataSource source, Account existingAccount String tenantKey = "hosting-fixture-game-" + row; String tenantRequestDigest = GameTenantCreationDigest.requestDigest( - "prod", tenantCreateRequest, tenantKey, "Controlled hosting", "Storage only"); + namespace, tenantCreateRequest, tenantKey, "Controlled hosting", "Storage only"); var tenantSource = new FreshTenantCreationEvidence( 1, - "prod", + namespace, tenantCreateRequest, tenantCreateOperation, tenantRequestDigest, @@ -164,7 +169,7 @@ private static Fixture createInternal(DataSource source, Account existingAccount tenantKey, "NEW_GAME_ROW", GameTenantCreationDigest.evidenceDigest( - "prod", + namespace, tenantCreateRequest, tenantCreateOperation, tenantRequestDigest, @@ -175,7 +180,7 @@ private static Fixture createInternal(DataSource source, Account existingAccount in( transaction, () -> { - new FreshTenantIdentityAssociationRepository(dsl, "prod").importVerified(tenantSource); + new FreshTenantIdentityAssociationRepository(dsl, namespace).importVerified(tenantSource); return new AccountAuthorityGenerationRepository(dsl).initializeTenantIfAbsent(tenantId); }); @@ -263,7 +268,7 @@ private static Fixture createInternal(DataSource source, Account existingAccount new AccountHostingSubscriptionLifecyclePolicy( Duration.ofSeconds(15), new RecoveryTiming(Duration.ofSeconds(60), Duration.ofSeconds(120))), - "prod", + namespace, false); var observer = new StripeHostingSubscriptionObserver( @@ -304,6 +309,15 @@ public static Fixture createAwaitingPayment(DataSource source, Account account) return fixture; } + /** Same isolated receiving namespace, selected before immutable tenant-source creation. */ + public static Fixture createAwaitingPayment( + DataSource source, Account account, String namespace) { + var fixture = createInternal(source, Objects.requireNonNull(account), namespace); + fixture.awaitFirstInvoice(); + fixture.providerStatus("incomplete"); + return fixture; + } + /** Fresh Account insert through the real identity/authority owner, with a real test password. */ public static Account createBillingAccount(DSLContext dsl, TransactionTemplate transaction) { var generations = new AccountAuthorityGenerationRepository(dsl); @@ -881,6 +895,43 @@ public AccountHostingFirstInvoicePaymentRepository firstInvoiceRepository() { return awaitFirstInvoice().payments(); } + /** Actual SDK with only the existing bounded controlled transports, never Stripe network IO. */ + public com.stripe.StripeClient receivingClient() { + var checkoutTransport = awaitFirstInvoice().transport; + return new com.stripe.StripeClient( + new StripeResponseGetter() { + @Override + public T request( + BaseAddress address, + RequestMethod method, + String path, + Map params, + Type type, + RequestOptions options, + ApiMode mode) + throws StripeException { + StripeResponseGetter selected = + path.startsWith("/v1/subscriptions/") ? transport : checkoutTransport; + return selected.request(address, method, path, params, type, options, mode); + } + + @Override + public InputStream requestStream( + BaseAddress address, + RequestMethod method, + String path, + Map params, + RequestOptions options, + ApiMode mode) { + throw new AssertionError("No streaming provider calls in isolated receiving"); + } + }); + } + + public String receivingWebhookSecret() { + return WEBHOOK_SECRET; + } + public StripeHostingFirstInvoicePaymentClient firstInvoiceProvider() { return awaitFirstInvoice().provider(); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountCheckoutRegisteredReceivingPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountCheckoutRegisteredReceivingPostgresIntegrationTest.java new file mode 100644 index 0000000000..2697d5f88e --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountCheckoutRegisteredReceivingPostgresIntegrationTest.java @@ -0,0 +1,658 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.when; + +import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import java.net.InetSocketAddress; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLContext; +import net.firedevops.firemud.accountservice.config.AccountCheckoutReceivingConfiguration; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.PaymentProperties; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountHostingPlanCatalog; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecyclePolicy; +import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountPlatformRestrictionOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.impl.AccountControlUiAuthenticationGrpcService; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.common.config.CommonSecurityServletAutoConfiguration; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.GrpcAuthProperties; +import net.firedevops.firemud.common.security.HttpAuthProperties; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import net.firedevops.firemud.test.TestContainerImages; +import org.apache.catalina.startup.Tomcat; +import org.apache.coyote.http11.AbstractHttp11Protocol; +import org.apache.tomcat.util.net.SSLHostConfig; +import org.apache.tomcat.util.net.SSLHostConfigCertificate; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.AnnotationConfigUtils; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.MapPropertySource; +import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.web.context.support.GenericWebApplicationContext; +import org.springframework.web.reactive.config.EnableWebFlux; +import org.springframework.web.server.adapter.WebHttpHandlerBuilder; +import org.springframework.web.servlet.DispatcherServlet; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import reactor.netty.DisposableServer; +import reactor.netty.http.server.HttpServer; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Registered Gateway HTTPS -> actual mTLS login -> registered Account HTTPS/owners -> physical + * PostgreSQL/Coordination. Signer platform sources, custody, policy and SDK transport are + * explicitly controlled upstream inputs. This supplies no live payment, privacy, PKI or deployment + * qualification. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AccountCheckoutRegisteredReceivingPostgresIntegrationTest { + private static final String NAMESPACE = "firemud-prod"; + private static final String PASSWORD = "test-only-registered-checkout-password"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final Network NETWORK = Network.newNetwork(); + + @Container + static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .withNetworkAliases("checkout-receiving-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final GenericContainer replica = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .dependsOn(redis) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "checkout-receiving-primary", + "6379"); + + @TempDir Path temporary; + + @Test + void registeredChainAuthenticatesRealOwnerAndCommitsOnlyExactSignedProviderSuccess() + throws Exception { + try (var upstream = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary)) { + var account = upstream.prepareReceivingAccount(PASSWORD); + var otherAccount = upstream.prepareReceivingAccount(PASSWORD); + var source = upstream.receivingSources(); + var hosting = + CanonicalHostingSubscriptionTestFixture.createAwaitingPayment( + Objects.requireNonNull(source.manager.getDataSource()), account, NAMESPACE); + assertThat( + source + .dsl + .fetchSingle( + "SELECT count(*) FROM account_control_ui_issuance_operations WHERE account_uuid = ?", + account.getAccountUuid()) + .get(0, Long.class)) + .isZero(); + try (var receiving = new RegisteredChain(temporary, upstream, hosting)) { + var login = + Map.of( + "requestId", + UUID.randomUUID(), + "callerContextId", + UUID.randomUUID(), + "email", + account.getEmail(), + "secret", + PASSWORD); + var denied = new HashMap(login); + denied.put("requestId", UUID.randomUUID()); + denied.put("secret", "wrong-secret"); + assertThat(receiving.request("POST", "/api/account/auth/login", null, denied).statusCode()) + .isEqualTo(401); + var signedIn = receiving.request("POST", "/api/account/auth/login", null, login); + assertThat(signedIn.statusCode()).isEqualTo(200); + assertThat(signedIn.headers().firstValue("cache-control")).contains("no-store"); + var data = JSON.readTree(signedIn.body()).path("data"); + assertThat(data.path("accountId").asText()).isEqualTo(account.getAccountUuid().toString()); + String bearer = data.path("authToken").asText(); + assertThat( + JSON.readTree( + receiving.request("POST", "/api/account/auth/login", null, login).body()) + .path("data") + .path("authToken") + .asText()) + .isEqualTo(bearer); + assertThat( + source + .dsl + .fetchSingle( + "SELECT count(*) FROM account_tenant_membership WHERE account_id = ?", + account.getId()) + .get(0, Long.class)) + .isZero(); + String path = + "/api/account/billing/hosting/subscriptions/" + + hosting.creation().subscriptionId() + + "/first-invoice"; + assertThat(receiving.request("GET", path, null, null).statusCode()).isEqualTo(401); + assertThat(receiving.request("GET", path, "forged.hmac.token", null).statusCode()) + .isEqualTo(401); + var owner = receiving.request("GET", path, bearer, null); + assertThat(owner.statusCode()).isEqualTo(200); + JsonNode tuple = JSON.readTree(owner.body()); + assertThat(tuple.path("amount").asText()).isEqualTo("2400"); + var otherLogin = + receiving.request( + "POST", + "/api/account/auth/login", + null, + Map.of( + "requestId", + UUID.randomUUID(), + "callerContextId", + UUID.randomUUID(), + "email", + otherAccount.getEmail(), + "secret", + PASSWORD)); + assertThat(otherLogin.statusCode()).isEqualTo(200); + String otherBearer = + JSON.readTree(otherLogin.body()).path("data").path("authToken").asText(); + var wrongOwner = receiving.request("GET", path, otherBearer, null); + assertThat(wrongOwner.statusCode()).isEqualTo(409); + assertThat(wrongOwner.body()) + .doesNotContain(tuple.path("invoiceId").asText(), "clientSecret", PASSWORD); + assertThat(hosting.firstInvoiceConfirmations()).isZero(); + UUID confirmation = UUID.randomUUID(); + var proof = + receiving.request( + "POST", + path + "/reauthenticate", + bearer, + Map.of( + "requestId", + UUID.randomUUID(), + "confirmationRequestId", + confirmation, + "email", + account.getEmail(), + "secret", + PASSWORD)); + assertThat(proof.statusCode()).isEqualTo(200); + var consent = new HashMap(); + consent.put("requestId", confirmation); + consent.put("expectedRowVersion", tuple.path("expectedRowVersion").asLong()); + consent.put( + "reauthenticationEvidenceId", JSON.readTree(proof.body()).path("evidenceId").asText()); + consent.put("acceptedTupleDigest", tuple.path("tupleDigest").asText()); + consent.put("acceptCharge", false); + assertThat(receiving.request("POST", path + "/confirm", bearer, consent).statusCode()) + .isEqualTo(400); + assertThat(hosting.firstInvoiceConfirmations()).isZero(); + consent.put("acceptCharge", true); + hosting.firstInvoiceConfirmationStatus("requires_action"); + var handoff = receiving.request("POST", path + "/confirm", bearer, consent); + assertThat(handoff.statusCode()).isEqualTo(200); + assertThat(JSON.readTree(handoff.body()).path("status").asText()) + .isEqualTo("requires_action"); + assertThat(receiving.request("POST", path + "/confirm", bearer, consent).statusCode()) + .isEqualTo(200); + assertThat(hosting.firstInvoiceConfirmations()).isOne(); + assertThat( + JSON.readTree(receiving.request("GET", path, bearer, null).body()) + .path("state") + .asText()) + .isEqualTo("AWAITING_PAYMENT"); + hosting.firstInvoiceStatus("succeeded"); + hosting.providerStatus("active"); + assertThat( + JSON.readTree(receiving.request("GET", path, bearer, null).body()) + .path("state") + .asText()) + .isEqualTo("AWAITING_PAYMENT"); + assertThat(receiving.rawWebhook(hosting.signedSuccessPayload(), null).statusCode()) + .isEqualTo(400); + // Let the original controlled ten-second provider-dispatch lease expire without issuing + // repeated reconciliation commands or changing the real receiving clock. + Thread.sleep(Duration.ofSeconds(11)); + var completion = + receiving.rawWebhook(hosting.signedSuccessPayload(), hosting.signedSuccessHeader()); + assertThat(completion.statusCode()).isEqualTo(200); + assertThat(JSON.readTree(completion.body()).path("state").asText()).isEqualTo("COMMITTED"); + assertThat(hosting.firstInvoiceConfirmations()).isOne(); + assertThat( + JSON.readTree(receiving.request("GET", path, bearer, null).body()) + .path("state") + .asText()) + .isEqualTo("COMMITTED"); + assertThat( + receiving + .rawWebhook(hosting.signedSuccessPayload(), hosting.signedSuccessHeader()) + .statusCode()) + .isEqualTo(200); + assertThat( + source + .dsl + .fetchSingle( + "SELECT count(*) FROM subscription_first_invoice_completions WHERE subscription_id = ?", + hosting.creation().subscriptionId()) + .get(0, Long.class)) + .isOne(); + var admin = + io.lettuce.core.RedisClient.create( + io.lettuce.core.RedisURI.Builder.redis(redis.getHost(), redis.getMappedPort(6379)) + .build()); + try (var connection = admin.connect(io.lettuce.core.codec.ByteArrayCodec.INSTANCE)) { + String tokenHash = + AccountControlUiIssuanceRepository.hash( + bearer.getBytes(java.nio.charset.StandardCharsets.US_ASCII)); + connection + .sync() + .del( + ("session:auth:token:" + tokenHash) + .getBytes(java.nio.charset.StandardCharsets.US_ASCII)); + } finally { + admin.shutdown(); + } + assertThat(receiving.request("GET", path, bearer, null).statusCode()).isEqualTo(401); + assertThat(hosting.firstInvoiceConfirmations()).isOne(); + } + } + } + + private static final class RegisteredChain implements AutoCloseable { + private GenericWebApplicationContext account; + private Tomcat tomcat; + private Server grpc; + private AnnotationConfigApplicationContext gateway; + private DisposableServer gatewayHttps; + private HttpClient browser; + private URI origin; + + RegisteredChain( + Path directory, + AccountControlUiOriginalOrderFixture upstream, + CanonicalHostingSubscriptionTestFixture.Fixture hosting) + throws Exception { + var f = upstream.receivingSources(); + var signer = upstream.signerFixture; + try { + Path tls = Files.createDirectory(directory.resolve("registered-tls")); + var pki = + LoopbackMtlsTestPki.create( + tls, + "registered-checkout-ca", + new LoopbackMtlsTestPki.IdentitySpec( + "account", "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service", true), + new LoopbackMtlsTestPki.IdentitySpec( + "gateway-client", + "spiffe://firemud/ns/" + NAMESPACE + "/sa/spring-cloud-gateway", + false), + new LoopbackMtlsTestPki.IdentitySpec( + "gateway-https", + "spiffe://firemud/ns/" + NAMESPACE + "/sa/spring-cloud-gateway", + true)); + var accountTls = pki.clientProperties(tls, pki.identity("account")); + var gatewayTls = pki.clientProperties(tls, pki.identity("gateway-client")); + var gatewayHttpsTls = pki.clientProperties(tls, pki.identity("gateway-https")); + tomcat = new Tomcat(); + tomcat.setBaseDir(Files.createDirectory(directory.resolve("registered-tomcat")).toString()); + tomcat.setPort(0); + var connector = tomcat.getConnector(); + connector.setScheme("https"); + connector.setSecure(true); + connector.setProperty("address", "127.0.0.1"); + var protocol = (AbstractHttp11Protocol) connector.getProtocolHandler(); + protocol.setSSLEnabled(true); + var ssl = new SSLHostConfig(); + var certificate = new SSLHostConfigCertificate(ssl, SSLHostConfigCertificate.Type.RSA); + certificate.setCertificateFile(accountTls.getCertChain()); + certificate.setCertificateKeyFile(accountTls.getPrivateKey()); + certificate.setCertificateChainFile(accountTls.getCaCert()); + ssl.addCertificate(certificate); + protocol.addSslHostConfig(ssl); + var servlet = + tomcat.addContext( + "", Files.createDirectory(directory.resolve("registered-web")).toString()); + account = new GenericWebApplicationContext(); + account.setServletContext(servlet.getServletContext()); + account.getEnvironment().setActiveProfiles("isolated-checkout-receiving"); + account + .getEnvironment() + .getPropertySources() + .addFirst( + new MapPropertySource( + "explicit-isolated-inputs", + Map.of( + "firemud.account.checkout-receiving.enabled", + "true", + "firemud.grpc.workload-namespace", + NAMESPACE, + "firemud.account.public-jwks.api-binding-path", + "/etc/firemud/account-jwt-api/binding.json", + "firemud.account.checkout-receiving.private-signer-root", + signer.privateRoot.toString(), + "firemud.account.checkout-receiving.public-signer-root", + signer.publicRoot.toString(), + "firemud.account.checkout-receiving.control-ui-keyring-root", + directory.resolve("custody").toString(), + "firemud.auth.http.enabled", + "true"))); + AnnotationConfigUtils.registerAnnotationConfigProcessors(account); + account.registerBean(DSLContext.class, () -> f.dsl); + account.registerBean( + "transactionManager", PlatformTransactionManager.class, () -> f.manager); + account.registerBean(AccountRepository.class, () -> f.accounts); + var generations = new AccountAuthorityGenerationRepository(f.dsl); + account.registerBean(AccountAuthorityGenerationRepository.class, () -> generations); + account.registerBean( + AccountAuthoritySourceEvidenceRepository.class, + () -> + new AccountAuthoritySourceEvidenceRepository( + f.dsl, generations, new AccountAuthorityOutboxRepository(f.dsl))); + account.registerBean( + AccountPlatformRestrictionOperationRepository.class, () -> f.restrictionOperations); + account.registerBean(AccountServiceImpl.class, () -> f.primary); + account.registerBean(AccountJwtSignerDesiredStateRepository.class, () -> signer.desired); + account.registerBean(AccountJwtJwksPublicationRepository.class, () -> signer.publication); + account.registerBean(AccountJwtSignerMaterializerTrustBinding.class, () -> signer.trust); + account.registerBean( + AccountCheckoutReceivingConfiguration.COORDINATION_URI, + io.lettuce.core.RedisURI.class, + upstream::receivingCoordinationUri); + account.registerBean( + AccountCheckoutReceivingConfiguration.ACKNOWLEDGEMENTS, + AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements.class, + () -> + new AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements( + 1, 1, 5000)); + account.registerBean( + AccountCheckoutReceivingConfiguration.STRIPE, + com.stripe.StripeClient.class, + hosting::receivingClient); + account.registerBean( + AccountHostingPlanCatalog.class, () -> new AccountHostingPlanCatalog(List.of())); + account.registerBean( + AccountHostingSubscriptionLifecycleRepository.ReconciliationLimits.class, + () -> + new AccountHostingSubscriptionLifecycleRepository.ReconciliationLimits( + 4, 3, Duration.ofSeconds(10), Duration.ofSeconds(1), Duration.ofHours(1))); + account.registerBean( + AccountHostingSubscriptionLifecyclePolicy.class, + () -> + new AccountHostingSubscriptionLifecyclePolicy( + Duration.ofSeconds(15), + new AccountHostingSubscriptionLifecyclePolicy.RecoveryTiming( + Duration.ofSeconds(60), Duration.ofSeconds(120)))); + var paymentProperties = new PaymentProperties(); + paymentProperties.setHostingWebhookSecret(hosting.receivingWebhookSecret()); + account.registerBean(PaymentProperties.class, () -> paymentProperties); + account.registerBean( + "jwtUtil", + JwtUtil.class, + () -> new JwtUtil("test-only-legacy-secret-at-least-thirty-two-bytes", 300_000L)); + var http = new HttpAuthProperties(); + http.setEnabled(true); + account.registerBean(HttpAuthProperties.class, () -> http); + account.registerBean(GrpcAuthProperties.class, GrpcAuthProperties::new); + account.registerBean(ReceiverMvc.class); + account.registerBean(AccountCheckoutReceivingConfiguration.class); + // Only the external platform API/configmap inputs are controlled. Production source + // factories, + // trusted-source verification, signer receipts and all authentication/billing owners are + // real. + try (var api = + mockConstruction( + AccountJwtJwksApiBinding.class, + (mock, ignored) -> + when(mock.current()).thenAnswer(call -> signer.api.current())); + var client = + mockConstruction( + AccountJwtJwksConfigMapClient.class, + (mock, ignored) -> { + when(mock.identity()).thenAnswer(call -> signer.client.identity()); + when(mock.observe()).thenAnswer(call -> signer.client.observe()); + })) { + account.refresh(); + } + assertThat(account.getBeansOfType(AccountJwtJwksTrustedSource.class)).hasSize(1); + assertThat( + account.getBean( + net.firedevops.firemud.common.security.HttpJwtAuthInterceptor.class)) + .isInstanceOf( + net.firedevops.firemud.accountservice.security.AccountCheckoutHttpAuthInterceptor + .class); + assertThat( + account.getBean( + net.firedevops.firemud.accountservice.authordraft + .AccountControlUiAccountAuthority.class)) + .isNotInstanceOf( + net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority.class); + Tomcat.addServlet(servlet, "account", new DispatcherServlet(account)); + servlet.addServletMappingDecoded("/", "account"); + tomcat.start(); + var grpcTls = + GrpcSslContexts.forServer( + Path.of(accountTls.getCertChain()).toFile(), + Path.of(accountTls.getPrivateKey()).toFile()) + .trustManager(Path.of(accountTls.getCaCert()).toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build(); + grpc = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext(grpcTls) + .addService( + ServerInterceptors.intercept( + account.getBean(AccountControlUiAuthenticationGrpcService.class), + new GrpcPeerIdentityInterceptor(), + account.getBean(AuthTokenInterceptor.class))) + .build() + .start(); + gateway = new AnnotationConfigApplicationContext(); + gateway.getEnvironment().setActiveProfiles("isolated-checkout-receiving"); + gateway + .getEnvironment() + .getPropertySources() + .addFirst( + new MapPropertySource( + "isolated-gateway-inputs", + Map.of( + "firemud.account.checkout-receiving.enabled", + "true", + "firemud.account.checkout-receiving.workload-namespace", + NAMESPACE, + "firemud.account.checkout-receiving.account-https-base-url", + "https://localhost:" + connector.getLocalPort(), + "firemud.account.checkout-receiving.account-ca-cert-path", + accountTls.getCaCert()))); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + grpc.getPort()); + gateway.registerBean(ServiceEndpointsProperties.class, () -> endpoints); + gateway.registerBean(CommonGrpcClientProperties.class, () -> gatewayTls); + gateway.registerBean(GrpcChannelFactory.class, GrpcChannelFactory::new); + var gatewayProperties = new org.springframework.cloud.gateway.config.GatewayProperties(); + var rateFilter = new org.springframework.cloud.gateway.filter.FilterDefinition(); + rateFilter.setName("RequestRateLimiter"); + rateFilter.setArgs( + Map.of( + "redis-rate-limiter.replenishRate", + "20", + "redis-rate-limiter.burstCapacity", + "40")); + gatewayProperties.setDefaultFilters(List.of(rateFilter)); + gateway.registerBean( + org.springframework.cloud.gateway.config.GatewayProperties.class, + () -> gatewayProperties); + gateway.registerBean( + org.springframework.data.redis.core.ReactiveStringRedisTemplate.class, + () -> + org.mockito.Mockito.mock( + org.springframework.data.redis.core.ReactiveStringRedisTemplate.class)); + gateway.register( + GatewayWebFlux.class, + net.firedevops.firemud.springcloudgateway.config.AccountCheckoutReceivingConfiguration + .class); + // Gateway's external rate-limit decision is a stipulated upstream input in this composed + // proof; the same real selected factory and exact-path filter remain registered. + try (var rateLimiter = + mockConstruction( + org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter.class, + (mock, ignored) -> + when(mock.isAllowed( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString())) + .thenReturn( + reactor.core.publisher.Mono.just( + new org.springframework.cloud.gateway.filter.ratelimit.RateLimiter + .Response(true, Map.of()))))) { + gateway.refresh(); + } + var httpHandler = + new ReactorHttpHandlerAdapter( + WebHttpHandlerBuilder.applicationContext(gateway).build()); + var gatewayServerTls = + io.netty.handler.ssl.SslContextBuilder.forServer( + Path.of(gatewayHttpsTls.getCertChain()).toFile(), + Path.of(gatewayHttpsTls.getPrivateKey()).toFile()) + .build(); + gatewayHttps = + HttpServer.create() + .host("127.0.0.1") + .port(0) + .secure(spec -> spec.sslContext(gatewayServerTls)) + .handle(httpHandler) + .bindNow(Duration.ofSeconds(10)); + origin = URI.create("https://localhost:" + gatewayHttps.port()); + var trust = SSLContext.getInstance("TLS"); + trust.init(null, pki.trustManagerFactory().getTrustManagers(), null); + browser = + HttpClient.newBuilder().sslContext(trust).connectTimeout(Duration.ofSeconds(3)).build(); + } catch (Exception | Error failure) { + try { + close(); + } catch (Exception cleanup) { + failure.addSuppressed(cleanup); + } + throw failure; + } + } + + HttpResponse request(String method, String path, String bearer, Object body) + throws Exception { + var request = HttpRequest.newBuilder(origin.resolve(path)).timeout(Duration.ofSeconds(20)); + if (bearer != null) request.header("Authorization", "Bearer " + bearer); + if (body != null) request.header("Content-Type", "application/json"); + request.method( + method, + body == null + ? HttpRequest.BodyPublishers.noBody() + : HttpRequest.BodyPublishers.ofByteArray(JSON.writeValueAsBytes(body))); + return browser.send(request.build(), HttpResponse.BodyHandlers.ofString()); + } + + HttpResponse rawWebhook(String payload, String signature) throws Exception { + var request = + HttpRequest.newBuilder(origin.resolve("/api/account/billing/hosting/webhook")) + .timeout(Duration.ofSeconds(20)) + .header("Content-Type", "application/json"); + if (signature != null) request.header("Stripe-Signature", signature); + return browser.send( + request.POST(HttpRequest.BodyPublishers.ofString(payload)).build(), + HttpResponse.BodyHandlers.ofString()); + } + + @Override + public void close() throws Exception { + if (browser != null) browser.close(); + if (gatewayHttps != null) gatewayHttps.disposeNow(); + if (gateway != null) gateway.close(); + if (grpc != null) { + grpc.shutdownNow(); + grpc.awaitTermination(5, TimeUnit.SECONDS); + } + if (tomcat != null) { + tomcat.stop(); + tomcat.destroy(); + } + if (account != null) account.close(); + } + } + + @Configuration(proxyBeanMethods = false) + @EnableWebMvc + @org.springframework.boot.autoconfigure.ImportAutoConfiguration( + CommonSecurityServletAutoConfiguration.class) + static class ReceiverMvc {} + + @Configuration(proxyBeanMethods = false) + @EnableWebFlux + static class GatewayWebFlux {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAccountAuthorityTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAccountAuthorityTest.java new file mode 100644 index 0000000000..54e5b5325a --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAccountAuthorityTest.java @@ -0,0 +1,38 @@ +package net.firedevops.firemud.accountservice.authordraft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.verifyNoInteractions; + +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountControlUiAccountAuthorityTest { + @Test + void realAccountOnlySourceHasNoTenantCollaboratorAndPreservesExactCapture() throws Exception { + var f = new AccountControlUiAuthorityTest.AccountCaptureContext(); + var source = + new AccountControlUiAccountAuthority(f.accounts, f.upstream, f.restrictions, f.dsl); + byte[] existing = f.capture().evidence(); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + var actual = source.captureAccount(f.id); + assertThat(actual.evidence()).isEqualTo(existing); + assertThat(actual.optionalTenantId()).isEmpty(); + assertThat(actual.scopedRoles()).isEmpty(); + assertThat(source).isNotInstanceOf(AccountControlUiAuthority.class); + verifyNoInteractions(f.drafts); + } finally { + TransactionSynchronizationManager.clear(); + } + } + + @Test + void standaloneAccountSourcePreservesWritableTransactionRequirement() throws Exception { + var f = new AccountControlUiAuthorityTest.AccountCaptureContext(); + var source = + new AccountControlUiAccountAuthority(f.accounts, f.upstream, f.restrictions, f.dsl); + assertThatThrownBy(() -> source.captureAccount(f.id)).isInstanceOf(IllegalStateException.class); + verifyNoInteractions(f.accounts, f.upstream, f.restrictions); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthorityTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthorityTest.java index 785de480b1..e3e6aa278a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthorityTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthorityTest.java @@ -183,7 +183,7 @@ void accountCaptureRequiresWritableOwnerTransactionBeforeReadingAccount() throws } /** Controlled owner collaborators exercise composition only, not physical source authority. */ - private static final class AccountCaptureContext { + static final class AccountCaptureContext { final UUID id = UUID.randomUUID(); final UUID lockResult = UUID.randomUUID(); final Account account = new Account(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountCheckoutReceivingConfigurationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountCheckoutReceivingConfigurationTest.java new file mode 100644 index 0000000000..f341a42d89 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountCheckoutReceivingConfigurationTest.java @@ -0,0 +1,72 @@ +package net.firedevops.firemud.accountservice.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import net.firedevops.firemud.accountservice.controller.AccountHostingFirstInvoiceController; +import net.firedevops.firemud.accountservice.controller.AccountHostingFirstInvoiceWebhookController; +import net.firedevops.firemud.accountservice.service.impl.AccountControlUiAuthenticationGrpcService; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiActorService; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksTrustedSource; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.mock.env.MockEnvironment; + +class AccountCheckoutReceivingConfigurationTest { + @TempDir Path keys; + + private final ApplicationContextRunner context = + new ApplicationContextRunner() + .withUserConfiguration(AccountCheckoutReceivingConfiguration.class); + + @Test + void defaultAndUnqualifiedSelectionRegisterNoReceivingOrSourceGraph() { + context.run( + ctx -> { + assertThat(ctx).hasNotFailed(); + assertThat(ctx).doesNotHaveBean(AccountHostingFirstInvoiceController.class); + assertThat(ctx).doesNotHaveBean(AccountHostingFirstInvoiceWebhookController.class); + assertThat(ctx).doesNotHaveBean(AccountControlUiAuthenticationGrpcService.class); + assertThat(ctx).doesNotHaveBean(AccountJwtJwksTrustedSource.class); + assertThat(ctx).doesNotHaveBean(AccountControlUiActorService.class); + }); + context + .withPropertyValues("firemud.account.checkout-receiving.enabled=true") + .run( + ctx -> { + assertThat(ctx).hasNotFailed(); + assertThat(ctx).doesNotHaveBean(AccountControlUiAuthenticationGrpcService.class); + }); + } + + @Test + void isolatedModeWithoutDeliveredInputsRefusesStartup() { + context + .withPropertyValues( + "spring.profiles.active=isolated-checkout-receiving", + "firemud.account.checkout-receiving.enabled=true") + .run(ctx -> assertThat(ctx).hasFailed()); + } + + @Test + void productionCannotBeCombinedWithIsolatedReceivingAndCustodyIsSeparate() { + var environment = new MockEnvironment(); + environment.setActiveProfiles("prod", "isolated-checkout-receiving"); + assertThatThrownBy( + () -> + new AccountCheckoutReceivingConfiguration() + .accountCheckoutReceivingProperties(environment)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountCheckoutReceivingProperties( + "test", + keys.resolve("private"), + keys.resolve("public"), + keys.resolve("private/custody"), + 0)) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceControllerTest.java index 5a57b07689..bac16160a6 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceControllerTest.java @@ -13,6 +13,18 @@ import org.springframework.web.server.ResponseStatusException; class AccountHostingFirstInvoiceControllerTest { + @Test + void dependencyUnavailabilityIsNotReportedAsRevocationAndNeverDisclosesSecrets() { + var controller = + new AccountHostingFirstInvoiceController( + mock(AccountHostingFirstInvoicePaymentService.class)); + var unavailable = controller.authenticationUnavailable(); + assertThat(unavailable.getStatusCode().value()).isEqualTo(503); + assertThat(unavailable.getBody().code()).isEqualTo("AUTH_UNAVAILABLE"); + assertThat(unavailable.getHeaders().getCacheControl()).isEqualTo("no-store"); + assertThat(controller.authenticationRefused().getStatusCode().value()).isEqualTo(401); + } + @Test void insecureTransportAndMissingControlUiBearerCannotReadOrDiscloseCheckout() { var service = mock(AccountHostingFirstInvoicePaymentService.class); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceWebhookControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceWebhookControllerTest.java new file mode 100644 index 0000000000..6884e9ac5f --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceWebhookControllerTest.java @@ -0,0 +1,79 @@ +package net.firedevops.firemud.accountservice.controller; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.*; + +import java.nio.charset.StandardCharsets; +import java.util.UUID; +import net.firedevops.firemud.accountservice.service.session.AccountHostingFirstInvoicePaymentService; +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.web.server.ResponseStatusException; + +class AccountHostingFirstInvoiceWebhookControllerTest { + @Test + void exactRawBodyAndSignatureReachTheSignedCompletionOwner() throws Exception { + var payments = mock(AccountHostingFirstInvoicePaymentService.class); + var controller = new AccountHostingFirstInvoiceWebhookController(payments); + String raw = "{ \"id\": \"evt_controlled\",\n\"data\":{} }"; + var request = request(raw.getBytes(StandardCharsets.UTF_8)); + var result = + new AccountHostingFirstInvoicePaymentService.Completion("COMMITTED", UUID.randomUUID()); + when(payments.completeSigned(raw, "t=1,v1=controlled")).thenReturn(result); + var response = controller.receive(request); + assertThat(response.getBody()).isEqualTo(result); + assertThat(response.getHeaders().getCacheControl()).isEqualTo("no-store"); + verify(payments).completeSigned(raw, "t=1,v1=controlled"); + } + + @Test + void retainedButNonterminalCompletionIsNotAcknowledgedAsProcessed() throws Exception { + var payments = mock(AccountHostingFirstInvoicePaymentService.class); + when(payments.completeSigned("{}", "t=1,v1=controlled")) + .thenReturn( + new AccountHostingFirstInvoicePaymentService.Completion( + "RECONCILING", UUID.randomUUID())); + var result = + new AccountHostingFirstInvoiceWebhookController(payments) + .receive(request("{}".getBytes(StandardCharsets.UTF_8))); + assertThat(result.getStatusCode().value()).isEqualTo(503); + assertThat(result.getBody().state()).isEqualTo("RECONCILING"); + assertThat(result.getHeaders().getCacheControl()).isEqualTo("no-store"); + } + + @Test + void insecureUnsignedAmbiguousMalformedAndOversizeRequestsNeverReachOwner() { + var payments = mock(AccountHostingFirstInvoicePaymentService.class); + var controller = new AccountHostingFirstInvoiceWebhookController(payments); + var insecure = request(new byte[] {123, 125}); + insecure.setSecure(false); + assertThatThrownBy(() -> controller.receive(insecure)) + .isInstanceOf(ResponseStatusException.class); + var unsigned = request(new byte[] {123, 125}); + unsigned.removeHeader("Stripe-Signature"); + assertThatThrownBy(() -> controller.receive(unsigned)) + .isInstanceOf(ResponseStatusException.class); + var ambiguous = request(new byte[] {123, 125}); + ambiguous.addHeader("Stripe-Signature", "another"); + assertThatThrownBy(() -> controller.receive(ambiguous)) + .isInstanceOf(ResponseStatusException.class); + assertThatThrownBy(() -> controller.receive(request(new byte[] {(byte) 0xc3, 0x28}))) + .isInstanceOf(ResponseStatusException.class); + assertThatThrownBy( + () -> + controller.receive( + request( + new byte[AccountHostingFirstInvoiceWebhookController.MAX_BODY_BYTES + 1]))) + .isInstanceOf(ResponseStatusException.class); + verifyNoInteractions(payments); + } + + private static MockHttpServletRequest request(byte[] bytes) { + var request = new MockHttpServletRequest("POST", "/billing/hosting/webhook"); + request.setSecure(true); + request.setContent(bytes); + request.addHeader("Stripe-Signature", "t=1,v1=controlled"); + return request; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountCheckoutHttpAuthInterceptorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountCheckoutHttpAuthInterceptorTest.java new file mode 100644 index 0000000000..7213846e11 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountCheckoutHttpAuthInterceptorTest.java @@ -0,0 +1,135 @@ +package net.firedevops.firemud.accountservice.security; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.*; + +import java.util.UUID; +import net.firedevops.firemud.accountservice.controller.AccountHostingFirstInvoiceController; +import net.firedevops.firemud.accountservice.controller.AccountHostingFirstInvoiceWebhookController; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiActorService; +import net.firedevops.firemud.accountservice.service.session.AccountHostingFirstInvoicePaymentService; +import net.firedevops.firemud.common.security.HttpAuthProperties; +import net.firedevops.firemud.common.security.JwtUtil; +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.web.method.HandlerMethod; + +class AccountCheckoutHttpAuthInterceptorTest { + @Test + void exactOwnerUsesActualAccountActorAndDoesNotInvokeHmacMiddleware() throws Exception { + var legacy = mock(JwtUtil.class); + var actors = mock(AccountControlUiActorService.class); + var interceptor = + new AccountCheckoutHttpAuthInterceptor(legacy, new HttpAuthProperties(), actors); + var request = + new MockHttpServletRequest( + "GET", "/billing/hosting/subscriptions/" + UUID.randomUUID() + "/first-invoice"); + request.setSecure(true); + request.addHeader("Authorization", "Bearer asymmetric-control-ui"); + when(actors.authenticateAccount("asymmetric-control-ui")) + .thenReturn(mock(AccountControlUiActorService.AccountAuthenticatedActor.class)); + var controller = + new AccountHostingFirstInvoiceController( + mock(AccountHostingFirstInvoicePaymentService.class)); + var handler = + new HandlerMethod( + controller, + AccountHostingFirstInvoiceController.class.getMethod( + "read", jakarta.servlet.http.HttpServletRequest.class, String.class, UUID.class)); + assertThat(interceptor.preHandle(request, new MockHttpServletResponse(), handler)).isTrue(); + verify(actors).authenticateAccount("asymmetric-control-ui"); + verifyNoInteractions(legacy); + } + + @Test + void forgedForwardedSchemeAndMissingOrRejectedBearerNeverReachOwner() throws Exception { + var legacy = mock(JwtUtil.class); + var actors = mock(AccountControlUiActorService.class); + var interceptor = + new AccountCheckoutHttpAuthInterceptor(legacy, new HttpAuthProperties(), actors); + var request = + new MockHttpServletRequest("GET", "/billing/hosting/subscriptions/x/first-invoice"); + request.addHeader("X-Forwarded-Proto", "https"); + request.addHeader("Authorization", "Bearer rejected"); + var controller = + new AccountHostingFirstInvoiceController( + mock(AccountHostingFirstInvoicePaymentService.class)); + var handler = + new HandlerMethod( + controller, + AccountHostingFirstInvoiceController.class.getMethod( + "read", jakarta.servlet.http.HttpServletRequest.class, String.class, UUID.class)); + var response = new MockHttpServletResponse(); + assertThat(interceptor.preHandle(request, response, handler)).isFalse(); + assertThat(response.getStatus()).isEqualTo(401); + verifyNoInteractions(actors); + request.setSecure(true); + doThrow(new IllegalStateException("denied")).when(actors).authenticateAccount("rejected"); + assertThat(interceptor.preHandle(request, response, handler)).isFalse(); + assertThat(response.getStatus()).isEqualTo(401); + } + + @Test + void unavailableJwksDoesNotMisreportSessionRevocation() throws Exception { + var actors = mock(AccountControlUiActorService.class); + var interceptor = + new AccountCheckoutHttpAuthInterceptor( + mock(JwtUtil.class), new HttpAuthProperties(), actors); + var controller = + new AccountHostingFirstInvoiceController( + mock(AccountHostingFirstInvoicePaymentService.class)); + var handler = + new HandlerMethod( + controller, + AccountHostingFirstInvoiceController.class.getMethod( + "read", jakarta.servlet.http.HttpServletRequest.class, String.class, UUID.class)); + var request = + new MockHttpServletRequest("GET", "/billing/hosting/subscriptions/x/first-invoice"); + request.setSecure(true); + request.addHeader("Authorization", "Bearer controlled"); + doThrow( + new net.firedevops.firemud.common.security.AccountPublicJwksCache + .SourceUnavailableException()) + .when(actors) + .authenticateAccount("controlled"); + var response = new MockHttpServletResponse(); + assertThat(interceptor.preHandle(request, response, handler)).isFalse(); + assertThat(response.getStatus()).isEqualTo(503); + } + + @Test + void unrelatedBillingHandlerDoesNotInheritTheExactOwnerException() throws Exception { + var actors = mock(AccountControlUiActorService.class); + var interceptor = + new AccountCheckoutHttpAuthInterceptor( + mock(JwtUtil.class), new HttpAuthProperties(), actors); + var response = new MockHttpServletResponse(); + assertThat( + interceptor.preHandle( + new MockHttpServletRequest("POST", "/billing/arbitrary"), response, new Object())) + .isFalse(); + assertThat(response.getStatus()).isEqualTo(401); + verifyNoInteractions(actors); + } + + @Test + void webhookUsesItsOwnSignatureBoundaryWithoutAcceptingUserAuthority() throws Exception { + var actors = mock(AccountControlUiActorService.class); + var interceptor = + new AccountCheckoutHttpAuthInterceptor( + mock(JwtUtil.class), new HttpAuthProperties(), actors); + var controller = + new AccountHostingFirstInvoiceWebhookController( + mock(AccountHostingFirstInvoicePaymentService.class)); + var handler = + new HandlerMethod( + controller, + AccountHostingFirstInvoiceWebhookController.class.getMethod( + "receive", jakarta.servlet.http.HttpServletRequest.class)); + var request = new MockHttpServletRequest("POST", "/billing/hosting/webhook"); + request.setSecure(true); + assertThat(interceptor.preHandle(request, new MockHttpServletResponse(), handler)).isTrue(); + verifyNoInteractions(actors); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcServiceTest.java new file mode 100644 index 0000000000..33175dff87 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcServiceTest.java @@ -0,0 +1,128 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AuthLoginRequest; +import net.firedevops.firemud.account.v1.AuthLoginResponse; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiActorService; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiIssuanceService; +import net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.Test; + +class AccountControlUiAuthenticationGrpcServiceTest { + @Test + void missingAndWrongPeerAreDeniedBeforeDecodeOrPrimaryAuthentication() { + var issuer = mock(AccountControlUiIssuanceService.class); + var actors = mock(AccountControlUiActorService.class); + var receiver = new AccountControlUiAuthenticationGrpcService(issuer, actors, "test"); + var result = new Result(); + receiver.authLogin(AuthLoginRequest.getDefaultInstance(), result); + assertThat(result.failureCode).isEqualTo(Status.Code.PERMISSION_DENIED); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-session-service") + .orElseThrow()) + .run(() -> receiver.authLogin(AuthLoginRequest.getDefaultInstance(), result)); + verifyNoInteractions(issuer, actors); + } + + @Test + void exactGatewayUsesCommittedIssuerAndCurrentActorAndDoesNotEchoCredentials() { + var issuer = mock(AccountControlUiIssuanceService.class); + var actors = mock(AccountControlUiActorService.class); + var credential = mock(AccountControlUiIssuanceService.IssuedCredential.class); + byte[] returned = "controlled.compact.jwt".getBytes(StandardCharsets.US_ASCII); + when(credential.compactBytes()).thenReturn(returned); + when(credential.expiresAt()).thenReturn(Instant.ofEpochSecond(2_000_000_300L)); + when(issuer.issueAccount(any())).thenReturn(credential); + var actor = mock(AccountControlUiActorService.AccountAuthenticatedActor.class); + when(actor.accountId()).thenReturn(UUID.randomUUID()); + when(actors.authenticateAccount("controlled.compact.jwt")).thenReturn(actor); + var receiver = new AccountControlUiAuthenticationGrpcService(issuer, actors, "test"); + var request = request("test"); + var result = new Result(); + gateway() + .run( + () -> + receiver.authLogin( + AccountControlUiAuthenticationGrpcCodec.toRequest(request), result)); + assertThat(result.failureCode).isNull(); + assertThat(result.completed).isTrue(); + assertThat(result.value.toString()).doesNotContain(request.secret(), request.email()); + assertThat(returned).containsOnly((byte) 0); + verify(credential).close(); + verify(actors).authenticateAccount("controlled.compact.jwt"); + } + + @Test + void primaryDenialIsAClosedResultAndNamespaceConflictNeverAuthenticates() { + var issuer = mock(AccountControlUiIssuanceService.class); + var actors = mock(AccountControlUiActorService.class); + var receiver = new AccountControlUiAuthenticationGrpcService(issuer, actors, "test"); + var result = new Result(); + gateway() + .run( + () -> + receiver.authLogin( + AccountControlUiAuthenticationGrpcCodec.toRequest(request("other")), result)); + assertThat(result.failureCode).isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(issuer); + when(issuer.issueAccount(any())) + .thenThrow(new AuthenticationException("AUTH_INVALID_CREDENTIALS", "not disclosed")); + var denied = new Result(); + gateway() + .run( + () -> + receiver.authLogin( + AccountControlUiAuthenticationGrpcCodec.toRequest(request("test")), denied)); + assertThat(denied.failureCode).isNull(); + assertThat(denied.completed).isTrue(); + assertThat(denied.value.toString()).doesNotContain("not disclosed", "controlled-secret"); + verifyNoInteractions(actors); + } + + private static AccountControlUiAuthenticationGrpcCodec.Request request(String namespace) { + return new AccountControlUiAuthenticationGrpcCodec.Request( + UUID.randomUUID(), UUID.randomUUID(), namespace, "owner@example.test", "controlled-secret"); + } + + private static Context gateway() { + return Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/spring-cloud-gateway") + .orElseThrow()); + } + + private static final class Result implements StreamObserver { + AuthLoginResponse value; + Status.Code failureCode; + boolean completed; + + @Override + public void onNext(AuthLoginResponse value) { + this.value = value; + } + + @Override + public void onError(Throwable failure) { + failureCode = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java index aa7cb8600b..77653186f1 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java @@ -562,6 +562,47 @@ private static boolean sameOriginalRecord( && expected.recoveryExpiry.equals(actual.recoveryExpiry); } + @org.junit.jupiter.api.Test + void accountOnlyCompositionRefusesTenantIssuanceBeforePrimaryAuthentication() { + Fixture f = new Fixture(NOW.plusSeconds(600)); + var accountOnly = + new net.firedevops.firemud.accountservice.authordraft.AccountControlUiAccountAuthority( + mock(net.firedevops.firemud.accountservice.repository.AccountRepository.class), + mock( + net.firedevops.firemud.accountservice.repository + .AccountAuthoritySourceEvidenceRepository.class), + mock( + net.firedevops.firemud.accountservice.repository + .AccountPlatformRestrictionOperationRepository.class), + mock(org.jooq.DSLContext.class)); + var issuer = + new AccountControlUiIssuanceService( + f.primary, + f.operations, + accountOnly, + f.fences, + f.signers, + f.cryptography, + f.registry, + f.actors, + f.transactions, + Clock.fixed(NOW, ZoneOffset.UTC), + 300_000L, + ISSUER); + assertThatThrownBy( + () -> + issuer.issue( + new AccountControlUiIssuanceService.Request( + f.requestId, + "owner@example.test", + "controlled-secret", + f.tenant, + f.context), + f.environment)) + .isInstanceOf(IllegalStateException.class); + org.mockito.Mockito.verifyNoInteractions(f.primary, f.operations, f.signers, f.registry); + } + private static final class Fixture { final UUID requestId = UUID.randomUUID(); final UUID operationId = UUID.randomUUID(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReaderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReaderTest.java index bbc6417ef8..15cb761237 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReaderTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReaderTest.java @@ -23,6 +23,18 @@ class AccountControlUiRegistryReaderTest { private static final JsonMapper JSON = JsonMapper.builder().build(); private static final String TOKEN_HASH = "a".repeat(64); + @Test + void dependencyFailureIsUnavailableRatherThanEvidenceOfRevocation() { + var reader = + new AccountControlUiRegistryReader( + () -> { + throw new io.lettuce.core.RedisConnectionException("controlled transport failure"); + }); + assertThatThrownBy(() -> reader.readActive(TOKEN_HASH)) + .isInstanceOf(AccountControlUiRegistryReader.RegistryUnavailableException.class) + .hasNoCause(); + } + @Test void acceptsOnlyTheExactCanonicalActiveProfileRecord() throws Exception { byte[] bytes = canonicalRecord(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java index c25b99cd96..150705ceb2 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java @@ -575,6 +575,33 @@ void accountOriginalRecoveryRejectsChangedSourcesRegistrySignerAndProducerFence( } } + @Test + void accountOnlyActorHasNoTenantCaptureCapability() { + Fixture f = new Fixture(true); + var accountOnly = + new net.firedevops.firemud.accountservice.authordraft.AccountControlUiAccountAuthority( + mock(net.firedevops.firemud.accountservice.repository.AccountRepository.class), + mock( + net.firedevops.firemud.accountservice.repository + .AccountAuthoritySourceEvidenceRepository.class), + mock( + net.firedevops.firemud.accountservice.repository + .AccountPlatformRestrictionOperationRepository.class), + mock(org.jooq.DSLContext.class)); + var actor = + new AccountControlUiActorService( + f.operations, + accountOnly, + f.signers, + f.registry, + f.source, + f.fences, + f.transactions, + Clock.fixed(NOW, ZoneOffset.UTC)); + assertThatThrownBy(() -> actor.authenticate("not-a-token", f.tenant, f.environment)) + .isInstanceOf(IllegalStateException.class); + } + private static final class Fixture { final UUID actor = UUID.randomUUID(), tenant = UUID.randomUUID(), jti = UUID.randomUUID(); final UUID operationId = UUID.randomUUID(), requestId = UUID.randomUUID(); diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java index c08602aa0a..34de506332 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java @@ -43,6 +43,7 @@ public final class AccountControlUiOriginalOrderFixture implements AutoCloseable private final AccountControlUiIssuanceRepository operations; private final AccountControlUiCoordination coordination; private final RedisClient accountClient; + private final RedisURI receivingCoordinationUri; private final Path temporary; private IssuedCreator originalCreator; @@ -278,11 +279,11 @@ private AccountControlUiOriginalOrderFixture( custody("request-mac", "mac1", 29); String PASSWORD = UUID.randomUUID().toString(); var admin = RedisClient.create(RedisURI.Builder.redis(redisHost, redisPort).build()); - accountClient = - RedisClient.create( - RedisURI.Builder.redis(redisHost, redisPort) - .withAuthentication("account_coord_app", PASSWORD) - .build()); + receivingCoordinationUri = + RedisURI.Builder.redis(redisHost, redisPort) + .withAuthentication("account_coord_app", PASSWORD) + .build(); + accountClient = RedisClient.create(receivingCoordinationUri); allocatedClient = accountClient; accountClient.setOptions(ClientOptions.builder().autoReconnect(false).build()); try (var connection = admin.connect(ByteArrayCodec.INSTANCE)) { @@ -465,6 +466,19 @@ record IssuedCreator( AccountControlUiOwnerSourcesFixture sources) {} /** Same-package reuse of genuine certified ACCOUNT issuance, separate from tenant creation. */ + RedisURI receivingCoordinationUri() { + return receivingCoordinationUri; + } + + AccountControlUiOwnerSourcesFixture receivingSources() { + return f; + } + + /** The new HTTP/mTLS proof starts before login; no synthetic peer or token is supplied. */ + net.firedevops.firemud.accountservice.entity.Account prepareReceivingAccount(String password) { + return f.createCertifiedGlobalAccount(password); + } + IssuedAccount issueCertifiedAccount(String password) { var account = f.createCertifiedGlobalAccount(password); var request = diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcChannelFactory.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcChannelFactory.java index f6e31020e2..55a83f7429 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcChannelFactory.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcChannelFactory.java @@ -25,6 +25,24 @@ public ManagedChannel buildChannel( boolean keepAlive, ResolvedGrpcTlsMaterial tlsMaterial) throws SSLException { + return buildChannel(target, defaultPort, properties, keepAlive, tlsMaterial, false); + } + + /** Builds a channel with retry disabled for calls whose body must never be replayed. */ + public ManagedChannel buildNonRetryingChannel( + String target, int defaultPort, CommonGrpcClientProperties properties, boolean keepAlive) + throws SSLException { + return buildChannel(target, defaultPort, properties, keepAlive, null, true); + } + + private ManagedChannel buildChannel( + String target, + int defaultPort, + CommonGrpcClientProperties properties, + boolean keepAlive, + ResolvedGrpcTlsMaterial tlsMaterial, + boolean disableRetries) + throws SSLException { String resolved = target; if (resolved == null || resolved.isBlank()) { resolved = "localhost:" + defaultPort; @@ -32,6 +50,7 @@ public ManagedChannel buildChannel( if (properties.isPlaintext()) { ManagedChannelBuilder builder = createPlaintextBuilder(resolved, defaultPort); + if (disableRetries) builder.disableRetry(); configureKeepAlive(builder, keepAlive); return builder.build(); } @@ -61,11 +80,12 @@ public ManagedChannel buildChannel( } builder = builder.sslContext(sslBuilder.build()); } + if (disableRetries) builder.disableRetry(); configureKeepAlive(builder, keepAlive); return builder.build(); } - private ManagedChannelBuilder createPlaintextBuilder(String resolved, int defaultPort) { + protected ManagedChannelBuilder createPlaintextBuilder(String resolved, int defaultPort) { if (resolved.contains("://")) { return ManagedChannelBuilder.forTarget(resolved).usePlaintext(); } diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/grpc/GrpcChannelFactoryNoRetryTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/grpc/GrpcChannelFactoryNoRetryTest.java new file mode 100644 index 0000000000..e985b6f016 --- /dev/null +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/grpc/GrpcChannelFactoryNoRetryTest.java @@ -0,0 +1,62 @@ +package net.firedevops.firemud.common.grpc; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; +import javax.net.ssl.SSLException; +import org.junit.jupiter.api.Test; + +class GrpcChannelFactoryNoRetryTest { + @Test + void dedicatedChannelBuilderDisablesRetriesBeforeBuilding() throws SSLException { + ManagedChannel channel = mock(ManagedChannel.class); + ManagedChannelBuilder builder = mock(ManagedChannelBuilder.class); + when(builder.build()).thenReturn(channel); + GrpcChannelFactory factory = factoryReturning(builder); + CommonGrpcClientProperties properties = plaintextProperties(); + + ManagedChannel built = + factory.buildNonRetryingChannel("checkout-account:6565", 6565, properties, false); + + assertThat(built).isSameAs(channel); + var order = inOrder(builder); + order.verify(builder).disableRetry(); + order.verify(builder).build(); + } + + @Test + void existingChannelBuilderDoesNotChangeItsRetryBehavior() throws SSLException { + ManagedChannel channel = mock(ManagedChannel.class); + ManagedChannelBuilder builder = mock(ManagedChannelBuilder.class); + when(builder.build()).thenReturn(channel); + GrpcChannelFactory factory = factoryReturning(builder); + + ManagedChannel built = + factory.buildChannel("existing-service:6565", 6565, plaintextProperties(), false); + + assertThat(built).isSameAs(channel); + verify(builder, never()).disableRetry(); + verify(builder).build(); + } + + private static GrpcChannelFactory factoryReturning(ManagedChannelBuilder builder) { + return new GrpcChannelFactory() { + @Override + protected ManagedChannelBuilder createPlaintextBuilder(String resolved, int defaultPort) { + return builder; + } + }; + } + + private static CommonGrpcClientProperties plaintextProperties() { + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setPlaintext(true); + return properties; + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/auth/AccountControlUiAuthenticationGrpcCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/auth/AccountControlUiAuthenticationGrpcCodec.java new file mode 100644 index 0000000000..ccd8a3c73d --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/auth/AccountControlUiAuthenticationGrpcCodec.java @@ -0,0 +1,249 @@ +package net.firedevops.firemud.common.account.auth; + +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.account.v1.AccountControlUiAuthLoginStatus; +import net.firedevops.firemud.account.v1.AuthLoginRequest; +import net.firedevops.firemud.account.v1.AuthLoginResponse; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Closed bounded transport mapping for the Gateway-to-Account Control-UI login handoff. */ +public final class AccountControlUiAuthenticationGrpcCodec { + public static final int MAX_REQUEST_WIRE_BYTES = 8 * 1024; + public static final int MAX_RESPONSE_WIRE_BYTES = 20 * 1024; + public static final int MAX_EMAIL_UTF8_BYTES = 320; + public static final int MAX_SECRET_UTF8_BYTES = 4 * 1024; + public static final int MAX_COMPACT_AUTH_TOKEN_BYTES = 16 * 1024; + + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern COMPACT_JWT = + Pattern.compile("[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+"); + + private AccountControlUiAuthenticationGrpcCodec() {} + + /** + * The secret exists only in this transient request and is deliberately redacted in diagnostics. + */ + public record Request( + UUID requestId, UUID callerContextId, String callerNamespace, String email, String secret) { + public Request { + requireUuid(requestId); + requireUuid(callerContextId); + requireNamespace(callerNamespace); + requireEmail(email); + requireSecret(secret); + } + + @Override + public String toString() { + return "AccountControlUiLoginRequest[redacted]"; + } + } + + /** Successful Account-authenticated result. The token is never included in diagnostics. */ + public record Authenticated(UUID accountId, String authToken, long expiresAtEpochSeconds) { + public Authenticated { + requireUuid(accountId); + requireToken(authToken); + requireExpiry(expiresAtEpochSeconds); + } + + @Override + public String toString() { + return "AccountControlUiLoginResult[redacted]"; + } + } + + public enum Outcome { + SUCCESS, + DENIED + } + + /** A denial intentionally carries no account identity or token. */ + public record Result(Outcome outcome, Authenticated authenticated) { + public Result { + Objects.requireNonNull(outcome); + if ((outcome == Outcome.SUCCESS) != (authenticated != null)) throw invalid(); + } + + @Override + public String toString() { + return "AccountControlUiLoginResult[" + outcome + "]"; + } + } + + public static AuthLoginRequest toRequest(Request request) { + Objects.requireNonNull(request); + AuthLoginRequest wire = + AuthLoginRequest.newBuilder() + .addSchemaVersion(SCHEMA_VERSION) + .addTargetNamespace(request.callerNamespace()) + .addRequestId(request.requestId().toString()) + .addCallerContextId(request.callerContextId().toString()) + .addEmail(request.email()) + .addSecret(request.secret()) + .build(); + parseRequest(wire); + return wire; + } + + public static Request parseRequest(AuthLoginRequest wire) { + if (wire == null + || wire.getSerializedSize() > MAX_REQUEST_WIRE_BYTES + || !wire.getUnknownFields().asMap().isEmpty()) throw invalid(); + if (oneInt(wire.getSchemaVersionList()) != SCHEMA_VERSION) throw invalid(); + return new Request( + uuid(one(wire.getRequestIdList())), + uuid(one(wire.getCallerContextIdList())), + one(wire.getTargetNamespaceList()), + one(wire.getEmailList()), + one(wire.getSecretList())); + } + + /** Maps only stable request context into the response; the primary secret is never echoed. */ + public static AuthLoginResponse toResponse(Request request, Authenticated authenticated) { + Objects.requireNonNull(request); + AuthLoginResponse.Builder builder = + AuthLoginResponse.newBuilder() + .addSchemaVersion(SCHEMA_VERSION) + .addTargetNamespace(request.callerNamespace()) + .addRequestId(request.requestId().toString()) + .addCallerContextId(request.callerContextId().toString()) + .addStatus( + authenticated == null + ? AccountControlUiAuthLoginStatus.ACCOUNT_CONTROL_UI_AUTH_LOGIN_STATUS_DENIED + : AccountControlUiAuthLoginStatus.ACCOUNT_CONTROL_UI_AUTH_LOGIN_STATUS_SUCCESS); + if (authenticated != null) { + builder + .addAccountId(authenticated.accountId().toString()) + .addAuthToken(authenticated.authToken()) + .addExpiresAtEpochSeconds(authenticated.expiresAtEpochSeconds()); + } + AuthLoginResponse wire = builder.build(); + requireResponse(request, wire); + return wire; + } + + /** Validates the complete response against the exact request before exposing a token. */ + public static Result requireResponse(Request request, AuthLoginResponse wire) { + Objects.requireNonNull(request); + if (wire == null + || wire.getSerializedSize() > MAX_RESPONSE_WIRE_BYTES + || !wire.getUnknownFields().asMap().isEmpty() + || oneInt(wire.getSchemaVersionList()) != SCHEMA_VERSION + || !request.callerNamespace().equals(one(wire.getTargetNamespaceList())) + || !request.requestId().equals(uuid(one(wire.getRequestIdList()))) + || !request.callerContextId().equals(uuid(one(wire.getCallerContextIdList()))) + || wire.getStatusValueList().size() != 1) throw invalid(); + + int status = wire.getStatusValueList().getFirst(); + if (status + == AccountControlUiAuthLoginStatus.ACCOUNT_CONTROL_UI_AUTH_LOGIN_STATUS_DENIED_VALUE) { + if (!wire.getAccountIdList().isEmpty() + || !wire.getAuthTokenList().isEmpty() + || !wire.getExpiresAtEpochSecondsList().isEmpty()) throw invalid(); + return new Result(Outcome.DENIED, null); + } + if (status + != AccountControlUiAuthLoginStatus.ACCOUNT_CONTROL_UI_AUTH_LOGIN_STATUS_SUCCESS_VALUE) + throw invalid(); + Authenticated authenticated = + new Authenticated( + uuid(one(wire.getAccountIdList())), + one(wire.getAuthTokenList()), + oneLong(wire.getExpiresAtEpochSecondsList())); + return new Result(Outcome.SUCCESS, authenticated); + } + + private static String one(List values) { + if (values.size() != 1) throw invalid(); + return values.getFirst(); + } + + private static int oneInt(List values) { + if (values.size() != 1) throw invalid(); + return values.getFirst(); + } + + private static long oneLong(List values) { + if (values.size() != 1) throw invalid(); + return values.getFirst(); + } + + private static UUID uuid(String value) { + try { + UUID parsed = UUID.fromString(value); + if (parsed.equals(NIL_UUID) || !parsed.toString().equals(value)) throw invalid(); + return parsed; + } catch (IllegalArgumentException malformed) { + throw invalid(); + } + } + + private static void requireUuid(UUID value) { + if (value == null || value.equals(NIL_UUID)) throw invalid(); + } + + private static void requireNamespace(String value) { + if (!GrpcPeerIdentity.isValidNamespace(value)) throw invalid(); + } + + private static void requireEmail(String value) { + int length = utf8Length(value); + if (length < 3 || length > MAX_EMAIL_UTF8_BYTES || value.indexOf('@') <= 0) throw invalid(); + int at = value.indexOf('@'); + if (at != value.lastIndexOf('@') + || at == value.length() - 1 + || value.chars().anyMatch(Character::isWhitespace) + || value.chars().anyMatch(Character::isISOControl)) throw invalid(); + } + + private static void requireSecret(String value) { + int length = utf8Length(value); + if (length < 1 || length > MAX_SECRET_UTF8_BYTES || value.indexOf('\0') >= 0) throw invalid(); + } + + private static void requireToken(String value) { + int length = utf8Length(value); + if (length < 1 + || length > MAX_COMPACT_AUTH_TOKEN_BYTES + || !COMPACT_JWT.matcher(value).matches()) throw invalid(); + } + + private static void requireExpiry(long epochSeconds) { + if (epochSeconds <= 0L) throw invalid(); + try { + Instant.ofEpochSecond(epochSeconds); + } catch (RuntimeException malformed) { + throw invalid(); + } + } + + private static int utf8Length(String value) { + if (value == null) throw invalid(); + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + return encoded.remaining(); + } catch (CharacterCodingException malformed) { + throw invalid(); + } + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Exact bounded Control-UI authentication message required"); + } +} diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/account/auth/AccountControlUiAuthenticationGrpcCodecTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/account/auth/AccountControlUiAuthenticationGrpcCodecTest.java new file mode 100644 index 0000000000..6844ca0ff8 --- /dev/null +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/account/auth/AccountControlUiAuthenticationGrpcCodecTest.java @@ -0,0 +1,132 @@ +package net.firedevops.firemud.common.account.auth; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AccountControlUiAuthLoginStatus; +import net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec.Authenticated; +import net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec.Outcome; +import net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec.Request; +import org.junit.jupiter.api.Test; + +class AccountControlUiAuthenticationGrpcCodecTest { + private static final UUID REQUEST_ID = uuid("0e70cae4-13c7-4597-a3c0-630315312574"); + private static final UUID CALLER_CONTEXT_ID = uuid("bca4c5ab-4c36-4f18-9517-e99a34f93021"); + private static final UUID ACCOUNT_ID = uuid("8d3ce19e-8c28-4dba-9f11-dfa2e96ace3c"); + private static final String NAMESPACE = "checkout-test"; + private static final String EMAIL = "operator@example.test"; + private static final String SECRET = "synthetic-primary-secret"; + private static final String TOKEN = "eyJhbGciOiJub25lIn0.eyJzdWIiOiJ4In0.c2lnbmF0dXJl"; + + @Test + void mapsOneExactBoundedRequestWithoutExposingSecretInDiagnostics() { + Request request = request(); + + var wire = AccountControlUiAuthenticationGrpcCodec.toRequest(request); + var parsed = AccountControlUiAuthenticationGrpcCodec.parseRequest(wire); + + assertThat(parsed).isEqualTo(request); + assertThat(request.toString()).doesNotContain(SECRET); + assertThat(wire.getSecretList()).containsExactly(SECRET); + } + + @Test + void mapsSuccessAndDenialWhileNeverEchoingPrimarySecret() { + Request request = request(); + Authenticated authenticated = new Authenticated(ACCOUNT_ID, TOKEN, 1_900_000_000L); + + var success = + AccountControlUiAuthenticationGrpcCodec.requireResponse( + request, AccountControlUiAuthenticationGrpcCodec.toResponse(request, authenticated)); + var denied = + AccountControlUiAuthenticationGrpcCodec.requireResponse( + request, AccountControlUiAuthenticationGrpcCodec.toResponse(request, null)); + + assertThat(success.outcome()).isEqualTo(Outcome.SUCCESS); + assertThat(success.authenticated()).isEqualTo(authenticated); + assertThat(denied.outcome()).isEqualTo(Outcome.DENIED); + assertThat(denied.authenticated()).isNull(); + assertThat( + AccountControlUiAuthenticationGrpcCodec.toResponse(request, authenticated).toString()) + .doesNotContain(SECRET); + } + + @Test + void rejectsMissingDuplicateUnknownAndOversizedRequestMembers() { + var request = AccountControlUiAuthenticationGrpcCodec.toRequest(request()); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + + assertRejected(request.toBuilder().clearEmail().build()); + assertRejected(request.toBuilder().addSecret("duplicate").build()); + assertRejected(request.toBuilder().setUnknownFields(unknown).build()); + assertRejected(request.toBuilder().setSecret(0, "x".repeat(10_000)).build()); + assertRejected( + request.toBuilder().setRequestId(0, REQUEST_ID.toString().toUpperCase()).build()); + assertRejected(request.toBuilder().setTargetNamespace(0, "../namespace").build()); + assertRejected(request.toBuilder().setEmail(0, "not-an-email").build()); + assertRejected(request.toBuilder().setSecret(0, "").build()); + } + + @Test + void rejectsResponseSubstitutionUnknownDuplicateAndContradictoryOutcomes() { + Request request = request(); + var success = + AccountControlUiAuthenticationGrpcCodec.toResponse( + request, new Authenticated(ACCOUNT_ID, TOKEN, 1_900_000_000L)); + var denial = AccountControlUiAuthenticationGrpcCodec.toResponse(request, null); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + + assertResponseRejected( + success.toBuilder().setCallerContextId(0, ACCOUNT_ID.toString()).build()); + assertResponseRejected(success.toBuilder().addAuthToken(TOKEN).build()); + assertResponseRejected(success.toBuilder().setUnknownFields(unknown).build()); + assertResponseRejected(success.toBuilder().setAccountId(0, "not-a-uuid").build()); + assertResponseRejected(success.toBuilder().setAuthToken(0, "not-a-jwt").build()); + assertResponseRejected(success.toBuilder().setExpiresAtEpochSeconds(0, 0L).build()); + assertResponseRejected(denial.toBuilder().addAccountId(ACCOUNT_ID.toString()).build()); + assertResponseRejected( + denial.toBuilder() + .addStatus(AccountControlUiAuthLoginStatus.ACCOUNT_CONTROL_UI_AUTH_LOGIN_STATUS_DENIED) + .build()); + } + + @Test + void acceptsMaximumCompactTokenAndRejectsOneByteOverTheLimit() { + String maxToken = "a." + "b".repeat(16_380) + ".c"; + String oversizedToken = "a." + "b".repeat(16_381) + ".c"; + + assertThat(new Authenticated(ACCOUNT_ID, maxToken, 1_900_000_000L).authToken()) + .hasSize(AccountControlUiAuthenticationGrpcCodec.MAX_COMPACT_AUTH_TOKEN_BYTES); + assertThatThrownBy(() -> new Authenticated(ACCOUNT_ID, oversizedToken, 1_900_000_000L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Exact bounded Control-UI authentication message required"); + } + + private static Request request() { + return new Request(REQUEST_ID, CALLER_CONTEXT_ID, NAMESPACE, EMAIL, SECRET); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static void assertRejected(net.firedevops.firemud.account.v1.AuthLoginRequest request) { + assertThatThrownBy(() -> AccountControlUiAuthenticationGrpcCodec.parseRequest(request)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static void assertResponseRejected( + net.firedevops.firemud.account.v1.AuthLoginResponse response) { + assertThatThrownBy( + () -> AccountControlUiAuthenticationGrpcCodec.requireResponse(request(), response)) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/client/AccountCheckoutHttpClient.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/client/AccountCheckoutHttpClient.java new file mode 100644 index 0000000000..bc5e44403a --- /dev/null +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/client/AccountCheckoutHttpClient.java @@ -0,0 +1,255 @@ +package net.firedevops.firemud.springcloudgateway.client; + +import io.netty.channel.ChannelOption; +import io.netty.handler.ssl.SslContext; +import io.netty.handler.ssl.SslContextBuilder; +import java.io.File; +import java.net.URI; +import java.time.Duration; +import java.util.List; +import java.util.Objects; +import java.util.regex.Pattern; +import javax.net.ssl.SSLParameters; +import net.firedevops.firemud.springcloudgateway.config.AccountCheckoutReceivingProperties; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; +import org.springframework.http.MediaType; +import org.springframework.http.client.reactive.ReactorClientHttpConnector; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Mono; +import reactor.netty.http.client.HttpClient; + +/** Narrow no-retry HTTPS proxy for Account's first-invoice and Stripe webhook routes. */ +public final class AccountCheckoutHttpClient { + public static final int MAX_SUBSCRIPTION_REQUEST_BYTES = 128 * 1024; + public static final int MAX_WEBHOOK_REQUEST_BYTES = 256 * 1024; + public static final int MAX_RESPONSE_BYTES = 256 * 1024; + + private static final Pattern SUBSCRIPTION_PATH = + Pattern.compile( + "/billing/hosting/subscriptions/" + + "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}" + + "/first-invoice(?:/(?:reauthenticate|confirm|renew))?"); + private static final String WEBHOOK_PATH = "/billing/hosting/webhook"; + private static final Duration TOTAL_TIMEOUT_CEILING = Duration.ofSeconds(60); + + private final WebClient webClient; + private final URI accountBaseUri; + private final int connectTimeoutMs; + private final int responseTimeoutMs; + + private AccountCheckoutHttpClient( + WebClient webClient, URI accountBaseUri, int connectTimeoutMs, int responseTimeoutMs) { + this.webClient = Objects.requireNonNull(webClient); + this.accountBaseUri = Objects.requireNonNull(accountBaseUri); + this.connectTimeoutMs = connectTimeoutMs; + this.responseTimeoutMs = responseTimeoutMs; + } + + /** Builds a client that trusts only the explicitly configured Account HTTPS CA. */ + public static AccountCheckoutHttpClient create(AccountCheckoutReceivingProperties properties) { + Objects.requireNonNull(properties); + properties.validateEnabledConfiguration(); + try { + SslContext sslContext = + SslContextBuilder.forClient() + .trustManager(new File(properties.getAccountCaCertPath())) + .build(); + HttpClient httpClient = + HttpClient.newConnection() + .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, properties.getConnectTimeoutMs()) + .responseTimeout(Duration.ofMillis(properties.getResponseTimeoutMs())) + .disableRetry(true) + .followRedirect(false) + .secure( + ssl -> + ssl.sslContext(sslContext) + .handshakeTimeout(Duration.ofMillis(properties.getResponseTimeoutMs())) + .handlerConfigurator( + sslHandler -> { + SSLParameters parameters = sslHandler.engine().getSSLParameters(); + parameters.setEndpointIdentificationAlgorithm("HTTPS"); + sslHandler.engine().setSSLParameters(parameters); + })); + var strategies = + org.springframework.web.reactive.function.client.ExchangeStrategies.builder() + .codecs(codecs -> codecs.defaultCodecs().maxInMemorySize(MAX_RESPONSE_BYTES)) + .build(); + WebClient webClient = + WebClient.builder() + .clientConnector(new ReactorClientHttpConnector(httpClient)) + .exchangeStrategies(strategies) + .build(); + return new AccountCheckoutHttpClient( + webClient, + properties.accountHttpsBaseUri(), + properties.getConnectTimeoutMs(), + properties.getResponseTimeoutMs()); + } catch (Exception invalidTls) { + throw new IllegalStateException( + "Checkout receiving could not initialize verified Account HTTPS", invalidTls); + } + } + + /** + * Forwards one explicitly allowlisted method/path and only the caller headers required by that + * operation. Webhook bytes remain byte-for-byte unchanged. + */ + public Mono forward( + HttpMethod method, String accountPath, HttpHeaders inboundHeaders, byte[] body) { + Objects.requireNonNull(method); + Objects.requireNonNull(inboundHeaders); + Objects.requireNonNull(body); + boolean webhook = isWebhook(method, accountPath); + if (!webhook && !isSubscriptionRoute(method, accountPath)) { + return Mono.just(ForwardedResponse.gatewayError()); + } + int requestLimit = webhook ? MAX_WEBHOOK_REQUEST_BYTES : MAX_SUBSCRIPTION_REQUEST_BYTES; + if (body.length > requestLimit) return Mono.just(ForwardedResponse.payloadTooLarge()); + if ((HttpMethod.GET.equals(method) && body.length != 0) + || (HttpMethod.POST.equals(method) && body.length == 0)) + return Mono.just(ForwardedResponse.badRequest()); + + String contentType = oneHeader(inboundHeaders, HttpHeaders.CONTENT_TYPE); + if (contentType != null && !isJsonContentType(contentType)) { + return Mono.just(ForwardedResponse.badRequest()); + } + if (HttpMethod.POST.equals(method) && !isJsonContentType(contentType)) { + return Mono.just(ForwardedResponse.badRequest()); + } + String authorization = webhook ? null : oneHeader(inboundHeaders, HttpHeaders.AUTHORIZATION); + String stripeSignature = webhook ? oneHeader(inboundHeaders, "Stripe-Signature") : null; + if ((!webhook && !validAuthorization(authorization)) + || (webhook && !validStripeSignature(stripeSignature))) { + return Mono.just(ForwardedResponse.badRequest()); + } + + URI target = accountBaseUri.resolve(accountPath); + Duration totalTimeout = + Duration.ofMillis((long) connectTimeoutMs + responseTimeoutMs) + .compareTo(TOTAL_TIMEOUT_CEILING) + > 0 + ? TOTAL_TIMEOUT_CEILING + : Duration.ofMillis((long) connectTimeoutMs + responseTimeoutMs); + return webClient + .method(method) + .uri(target) + .headers( + outgoing -> { + if (contentType != null) outgoing.set(HttpHeaders.CONTENT_TYPE, contentType); + if (authorization != null) outgoing.set(HttpHeaders.AUTHORIZATION, authorization); + if (stripeSignature != null) outgoing.set("Stripe-Signature", stripeSignature); + }) + .bodyValue(body) + .exchangeToMono( + response -> + readResponse( + response.statusCode(), + response.headers().asHttpHeaders(), + response.bodyToMono(byte[].class))) + .timeout(totalTimeout) + .onErrorResume(ignored -> Mono.just(ForwardedResponse.gatewayError())); + } + + private Mono readResponse( + HttpStatusCode status, HttpHeaders headers, Mono responseBody) { + if (!status.is2xxSuccessful()) { + HttpStatusCode safeStatus = + status.is3xxRedirection() || status.is5xxServerError() ? HttpStatus.BAD_GATEWAY : status; + return responseBody + .onErrorResume(ignored -> Mono.empty()) + .thenReturn(new ForwardedResponse(safeStatus, null, new byte[0])); + } + String contentType = oneHeader(headers, HttpHeaders.CONTENT_TYPE); + if (status.value() == HttpStatus.NO_CONTENT.value() + || status.value() == HttpStatus.RESET_CONTENT.value()) { + return responseBody + .onErrorResume(ignored -> Mono.empty()) + .thenReturn(new ForwardedResponse(status, null, new byte[0])); + } + if (!isJsonContentType(contentType)) return Mono.just(ForwardedResponse.gatewayError()); + return responseBody + .defaultIfEmpty(new byte[0]) + .map(body -> new ForwardedResponse(status, contentType, body)); + } + + private static boolean isWebhook(HttpMethod method, String path) { + return HttpMethod.POST.equals(method) && WEBHOOK_PATH.equals(path); + } + + private static boolean isSubscriptionRoute(HttpMethod method, String path) { + if (path == null || !SUBSCRIPTION_PATH.matcher(path).matches()) return false; + boolean base = path.endsWith("/first-invoice"); + return (base && HttpMethod.GET.equals(method)) || (!base && HttpMethod.POST.equals(method)); + } + + private static boolean isJsonContentType(String contentType) { + if (contentType == null) return false; + try { + MediaType parsed = MediaType.parseMediaType(contentType); + return MediaType.APPLICATION_JSON.isCompatibleWith(parsed); + } catch (RuntimeException malformed) { + return false; + } + } + + private static String oneHeader(HttpHeaders headers, String name) { + List values = headers.get(name); + if (values == null || values.isEmpty()) return null; + if (values.size() != 1 || values.getFirst() == null || values.getFirst().isBlank()) { + return ""; + } + return values.getFirst(); + } + + private static boolean validAuthorization(String authorization) { + return authorization != null + && authorization.length() <= 16_400 + && authorization.startsWith("Bearer ") + && authorization.length() > "Bearer ".length() + && !authorization.contains("\r") + && !authorization.contains("\n"); + } + + private static boolean validStripeSignature(String signature) { + return signature != null + && signature.length() <= 4_096 + && !signature.contains("\r") + && !signature.contains("\n"); + } + + /** Raw successful response data is transient and deliberately hidden from diagnostics. */ + public record ForwardedResponse(HttpStatusCode status, String contentType, byte[] body) { + public ForwardedResponse { + Objects.requireNonNull(status); + body = body == null ? new byte[0] : body.clone(); + } + + @Override + public byte[] body() { + return body.clone(); + } + + @Override + public String toString() { + return "CheckoutUpstreamResponse[status=" + status.value() + ", body=redacted]"; + } + + private static ForwardedResponse badRequest() { + return new ForwardedResponse( + HttpStatus.BAD_REQUEST, MediaType.APPLICATION_JSON_VALUE, new byte[0]); + } + + private static ForwardedResponse gatewayError() { + return new ForwardedResponse( + HttpStatus.BAD_GATEWAY, MediaType.APPLICATION_JSON_VALUE, new byte[0]); + } + + private static ForwardedResponse payloadTooLarge() { + return new ForwardedResponse( + HttpStatus.PAYLOAD_TOO_LARGE, MediaType.APPLICATION_JSON_VALUE, new byte[0]); + } + } +} diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/client/AccountControlUiAuthenticationClient.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/client/AccountControlUiAuthenticationClient.java new file mode 100644 index 0000000000..539db9de72 --- /dev/null +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/client/AccountControlUiAuthenticationClient.java @@ -0,0 +1,151 @@ +package net.firedevops.firemud.springcloudgateway.client; + +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountControlUiAuthenticationServiceGrpc; +import net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec; +import net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec.Request; +import net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec.Result; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; + +/** File-backed Gateway mTLS client for Account's narrow Control-UI authentication RPC. */ +public final class AccountControlUiAuthenticationClient + extends AbstractReloadingBlockingGrpcClient< + AccountControlUiAuthenticationServiceGrpc + .AccountControlUiAuthenticationServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public AccountControlUiAuthenticationClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls( + tlsProperties, "Account Control-UI authentication requires file-backed workload mTLS"), + nonRetryingChannelFactory(channelFactory), + AccountControlUiAuthenticationClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when the isolated receiving profile explicitly enables this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) throw new IllegalStateException("Account authentication client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Account authentication stub is unavailable"); + } + initialized = true; + } + + /** Sends one exact authentication request without a retry or credential-bearing diagnostics. */ + public Result login(Request request) { + Objects.requireNonNull(request, "Control-UI authentication request is required"); + if (!workloadNamespace.equals(request.callerNamespace())) { + throw new IllegalArgumentException("Control-UI caller namespace does not match Gateway"); + } + var wireRequest = AccountControlUiAuthenticationGrpcCodec.toRequest(request); + try { + var wireResponse = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .authLogin(wireRequest); + return AccountControlUiAuthenticationGrpcCodec.requireResponse(request, wireResponse); + } catch (StatusRuntimeException unavailable) { + if (unavailable.getStatus().getCode() == Status.Code.ALREADY_EXISTS) { + throw new AuthenticationConflictException(); + } + throw new AuthenticationUnavailableException(); + } catch (IllegalArgumentException malformed) { + throw new IllegalStateException("Account authentication response was invalid"); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountControlUiAuthenticationServiceGrpc + .AccountControlUiAuthenticationServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return AccountControlUiAuthenticationServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(AccountControlUiAuthenticationGrpcCodec.MAX_RESPONSE_WIRE_BYTES) + .withMaxOutboundMessageSize(AccountControlUiAuthenticationGrpcCodec.MAX_REQUEST_WIRE_BYTES) + // CallCredentials runs before HTTP/2 releases request headers or the primary-secret body. + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)); + } + + @Override + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } + super.close(); + } + + private AccountControlUiAuthenticationServiceGrpc + .AccountControlUiAuthenticationServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new AuthenticationUnavailableException(); + } + return currentStub; + } + + private static GrpcChannelFactory nonRetryingChannelFactory(GrpcChannelFactory delegate) { + Objects.requireNonNull(delegate, "Account authentication requires a gRPC channel factory"); + return new GrpcChannelFactory() { + @Override + public ManagedChannel buildChannel( + String target, int defaultPort, CommonGrpcClientProperties properties, boolean keepAlive) + throws SSLException { + return delegate.buildNonRetryingChannel(target, defaultPort, properties, keepAlive); + } + }; + } + + /** Safe for public error handling; it deliberately has no credential-bearing cause. */ + public static final class AuthenticationUnavailableException extends RuntimeException { + private AuthenticationUnavailableException() { + super("Account authentication is unavailable"); + } + } + + /** Safe conflict signal for a changed input under a retained idempotency key. */ + public static final class AuthenticationConflictException extends RuntimeException { + public AuthenticationConflictException() { + super("Account authentication request conflicts"); + } + } +} diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfiguration.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfiguration.java new file mode 100644 index 0000000000..0864fd6ed5 --- /dev/null +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfiguration.java @@ -0,0 +1,195 @@ +package net.firedevops.firemud.springcloudgateway.config; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import java.util.regex.Pattern; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.springcloudgateway.client.AccountCheckoutHttpClient; +import net.firedevops.firemud.springcloudgateway.client.AccountControlUiAuthenticationClient; +import net.firedevops.firemud.springcloudgateway.controller.AccountCheckoutGatewayController; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.cloud.gateway.config.GatewayProperties; +import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver; +import org.springframework.cloud.gateway.filter.ratelimit.RateLimiter; +import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.core.Ordered; +import org.springframework.core.env.Environment; +import org.springframework.data.redis.core.ReactiveStringRedisTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.web.server.ServerWebExchange; +import org.springframework.web.server.WebFilter; +import org.springframework.web.server.WebFilterChain; +import reactor.core.publisher.Mono; + +/** Opt-in composition for the isolated checkout/login receiving endpoints. */ +@Configuration(proxyBeanMethods = false) +@EnableConfigurationProperties(AccountCheckoutReceivingProperties.class) +@Import({AccountCheckoutGatewayController.class, GatewayRateLimiterConfig.class}) +public final class AccountCheckoutReceivingConfiguration { + private static final String PROFILE = "isolated-checkout-receiving"; + + public AccountCheckoutReceivingConfiguration( + Environment environment, AccountCheckoutReceivingProperties properties) { + boolean isolatedProfile = Arrays.asList(environment.getActiveProfiles()).contains(PROFILE); + boolean productionProfile = + Arrays.stream(environment.getActiveProfiles()) + .anyMatch(profile -> "prod".equals(profile) || "production".equals(profile)); + if (isolatedProfile && productionProfile) { + throw new IllegalStateException( + "Isolated checkout receiving cannot be activated with a production profile"); + } + if (properties.isEnabled() && !isolatedProfile) { + throw new IllegalStateException( + "Checkout receiving requires the isolated-checkout-receiving profile"); + } + if (properties.isEnabled()) properties.validateEnabledConfiguration(); + } + + @Bean(destroyMethod = "close") + @ConditionalOnProperty( + prefix = "firemud.account.checkout-receiving", + name = "enabled", + havingValue = "true") + @org.springframework.context.annotation.Profile(PROFILE) + public AccountControlUiAuthenticationClient accountControlUiAuthenticationClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties grpcProperties, + GrpcChannelFactory channelFactory, + AccountCheckoutReceivingProperties properties) + throws SSLException, IOException { + var client = + new AccountControlUiAuthenticationClient( + endpoints, grpcProperties, channelFactory, properties.getWorkloadNamespace()); + client.init(); + return client; + } + + @Bean + @ConditionalOnProperty( + prefix = "firemud.account.checkout-receiving", + name = "enabled", + havingValue = "true") + @org.springframework.context.annotation.Profile(PROFILE) + public AccountCheckoutHttpClient accountCheckoutHttpClient( + AccountCheckoutReceivingProperties properties) { + return AccountCheckoutHttpClient.create(properties); + } + + /** Applies canonical rate limiting before the receiving controller reads credential/body data. */ + @Bean + @ConditionalOnProperty( + prefix = "firemud.account.checkout-receiving", + name = "enabled", + havingValue = "true") + @org.springframework.context.annotation.Profile(PROFILE) + public WebFilter accountCheckoutReceivingRateLimitWebFilter( + GatewayProperties gatewayProperties, + ReactiveStringRedisTemplate redisTemplate, + @Qualifier("gatewayClientIpKeyResolver") KeyResolver keyResolver, + ApplicationContext applicationContext) { + Objects.requireNonNull(redisTemplate, "Gateway Redis rate limiting must be available"); + GatewayRateLimiterConfig.DefaultRequestRateLimiterArguments arguments = + GatewayRateLimiterConfig.defaultRequestRateLimiterArguments(gatewayProperties); + RedisRateLimiter rateLimiter = + new RedisRateLimiter( + arguments.replenishRate(), arguments.burstCapacity(), arguments.requestedTokens()); + rateLimiter.setApplicationContext(applicationContext); + return receivingRateLimitWebFilter(rateLimiter, keyResolver); + } + + static WebFilter receivingRateLimitWebFilter( + RateLimiter rateLimiter, KeyResolver keyResolver) { + return new AccountCheckoutReceivingRateLimitWebFilter(rateLimiter, keyResolver); + } + + private static final class AccountCheckoutReceivingRateLimitWebFilter + implements WebFilter, Ordered { + private static final Pattern FIRST_INVOICE_PATH = + Pattern.compile( + "/api/account/billing/hosting/subscriptions/[^/]+/first-invoice(?:/(?:reauthenticate|confirm|renew))?"); + private static final String RATE_LIMITED_BODY = "{\"status\":\"ERROR\"}"; + + private final RateLimiter rateLimiter; + private final KeyResolver keyResolver; + + private AccountCheckoutReceivingRateLimitWebFilter( + RateLimiter rateLimiter, KeyResolver keyResolver) { + this.rateLimiter = Objects.requireNonNull(rateLimiter); + this.keyResolver = Objects.requireNonNull(keyResolver); + } + + @Override + public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { + if (!isReceivingRequest(exchange)) return chain.filter(exchange); + return Mono.defer( + () -> + keyResolver + .resolve(exchange) + .filter(key -> key != null && !key.isBlank()) + .switchIfEmpty( + Mono.error(new IllegalStateException("Rate-limit key unavailable"))) + .flatMap(key -> rateLimiter.isAllowed("account-checkout-receiving", key))) + .materialize() + .flatMap( + result -> { + var decision = result.isOnNext() ? result.get() : null; + if (decision == null) { + return reject(exchange, HttpStatus.SERVICE_UNAVAILABLE); + } + return decision.isAllowed() + ? chain.filter(exchange) + : reject(exchange, HttpStatus.TOO_MANY_REQUESTS); + }); + } + + private static boolean isReceivingRequest(ServerWebExchange exchange) { + String path = exchange.getRequest().getPath().pathWithinApplication().value(); + var method = exchange.getRequest().getMethod(); + if (org.springframework.http.HttpMethod.POST.equals(method)) { + return "/api/account/auth/login".equals(path) + || "/api/account/billing/hosting/webhook".equals(path) + || isFirstInvoiceAction(path); + } + return org.springframework.http.HttpMethod.GET.equals(method) + && path.endsWith("/first-invoice") + && FIRST_INVOICE_PATH.matcher(path).matches(); + } + + private static Mono reject(ServerWebExchange exchange, HttpStatus status) { + var response = exchange.getResponse(); + response.setStatusCode(status); + response.getHeaders().setCacheControl("no-store"); + response.getHeaders().setPragma("no-cache"); + response.getHeaders().setExpires(0); + response.getHeaders().setContentType(MediaType.APPLICATION_JSON); + return response.writeWith( + Mono.just( + response.bufferFactory().wrap(RATE_LIMITED_BODY.getBytes(StandardCharsets.UTF_8)))); + } + + private static boolean isFirstInvoiceAction(String path) { + return FIRST_INVOICE_PATH.matcher(path).matches() + && (path.endsWith("/first-invoice/reauthenticate") + || path.endsWith("/first-invoice/confirm") + || path.endsWith("/first-invoice/renew")); + } + + @Override + public int getOrder() { + // Run after HeaderTrustFilter (-4) so KeyResolver sees its canonical client-IP header. + return -3; + } + } +} diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingProperties.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingProperties.java new file mode 100644 index 0000000000..fb5b4e141d --- /dev/null +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingProperties.java @@ -0,0 +1,78 @@ +package net.firedevops.firemud.springcloudgateway.config; + +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Path; +import lombok.Data; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.boot.context.properties.ConfigurationProperties; + +/** Explicit opt-in configuration for the isolated Account checkout receiving surface. */ +@Data +@ConfigurationProperties(prefix = "firemud.account.checkout-receiving") +public class AccountCheckoutReceivingProperties { + private boolean enabled; + private String workloadNamespace; + private String accountHttpsBaseUrl; + private String accountCaCertPath; + private int connectTimeoutMs = 2_000; + private int responseTimeoutMs = 5_000; + + /** Rejects any enabled configuration that cannot establish a verified HTTPS upstream. */ + public void validateEnabledConfiguration() { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalStateException( + "Checkout receiving requires one canonical Gateway workload namespace"); + } + URI upstream; + try { + upstream = URI.create(accountHttpsBaseUrl); + } catch (RuntimeException malformed) { + throw new IllegalStateException("Checkout receiving requires an HTTPS Account upstream"); + } + if (!"https".equals(upstream.getScheme()) + || upstream.getHost() == null + || upstream.getHost().isBlank() + || upstream.getUserInfo() != null + || upstream.getQuery() != null + || upstream.getFragment() != null + || (upstream.getRawPath() != null + && !upstream.getRawPath().isEmpty() + && !"/".equals(upstream.getRawPath())) + || (upstream.getPort() != -1 && (upstream.getPort() < 1 || upstream.getPort() > 65_535))) { + throw new IllegalStateException( + "Checkout receiving requires an authority-only HTTPS Account upstream"); + } + if (accountCaCertPath == null || accountCaCertPath.isBlank()) { + throw new IllegalStateException("Checkout receiving requires an explicit Account HTTPS CA"); + } + Path caPath; + try { + if (accountCaCertPath.startsWith("classpath:")) { + throw new IllegalArgumentException("filesystem CA required"); + } + caPath = Path.of(accountCaCertPath); + } catch (RuntimeException malformed) { + throw new IllegalStateException( + "Checkout receiving requires readable file-backed Account HTTPS CA material"); + } + if (!Files.isRegularFile(caPath) || !Files.isReadable(caPath)) { + throw new IllegalStateException( + "Checkout receiving requires readable file-backed Account HTTPS CA material"); + } + if (connectTimeoutMs < 1 + || connectTimeoutMs > 30_000 + || responseTimeoutMs < 1 + || responseTimeoutMs > 30_000) { + throw new IllegalStateException("Checkout receiving requires bounded positive timeouts"); + } + } + + public URI accountHttpsBaseUri() { + return URI.create(accountHttpsBaseUrl); + } + + public Path accountCaCertPathAsPath() { + return Path.of(accountCaCertPath); + } +} diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfig.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfig.java index 9f787ce081..cbbeaac0e0 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfig.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfig.java @@ -1,6 +1,11 @@ package net.firedevops.firemud.springcloudgateway.config; import java.net.InetSocketAddress; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.springframework.cloud.gateway.config.GatewayProperties; +import org.springframework.cloud.gateway.filter.FilterDefinition; import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -13,12 +18,64 @@ public class GatewayRateLimiterConfig { private static final String X_FORWARDED_FOR = "X-Forwarded-For"; private static final String UNKNOWN_CLIENT_KEY = "unknown-client"; + private static final String RATE_LIMITER_FILTER = "RequestRateLimiter"; + private static final String REPLENISH_RATE = "redis-rate-limiter.replenishRate"; + private static final String BURST_CAPACITY = "redis-rate-limiter.burstCapacity"; + private static final String REQUESTED_TOKENS = "redis-rate-limiter.requestedTokens"; @Bean KeyResolver gatewayClientIpKeyResolver() { return exchange -> Mono.just(resolveClientKey(exchange)); } + static DefaultRequestRateLimiterArguments defaultRequestRateLimiterArguments( + GatewayProperties properties) { + if (properties == null) throw invalidRateLimiterConfiguration(); + List filters = properties.getDefaultFilters(); + if (filters == null) throw invalidRateLimiterConfiguration(); + List matches = + filters.stream() + .filter(filter -> RATE_LIMITER_FILTER.equalsIgnoreCase(filter.getName())) + .toList(); + if (matches.size() != 1) throw invalidRateLimiterConfiguration(); + Map args = matches.getFirst().getArgs(); + if (args == null + || !Set.of(REPLENISH_RATE, BURST_CAPACITY, REQUESTED_TOKENS).containsAll(args.keySet())) { + throw invalidRateLimiterConfiguration(); + } + return new DefaultRequestRateLimiterArguments( + parsePositiveInt(args.get(REPLENISH_RATE)), + parsePositiveLong(args.get(BURST_CAPACITY)), + parsePositiveInt(args.getOrDefault(REQUESTED_TOKENS, "1"))); + } + + private static int parsePositiveInt(String value) { + try { + int parsed = Integer.parseInt(value); + if (parsed <= 0) throw invalidRateLimiterConfiguration(); + return parsed; + } catch (NumberFormatException malformed) { + throw invalidRateLimiterConfiguration(); + } + } + + private static long parsePositiveLong(String value) { + try { + long parsed = Long.parseLong(value); + if (parsed <= 0L) throw invalidRateLimiterConfiguration(); + return parsed; + } catch (NumberFormatException malformed) { + throw invalidRateLimiterConfiguration(); + } + } + + private static IllegalStateException invalidRateLimiterConfiguration() { + return new IllegalStateException("Canonical Gateway rate-limit configuration is required"); + } + + record DefaultRequestRateLimiterArguments( + int replenishRate, long burstCapacity, int requestedTokens) {} + private String resolveClientKey(ServerWebExchange exchange) { String clientIp = exchange.getRequest().getHeaders().getFirst("X-Client-IP"); if (clientIp != null && !clientIp.isBlank()) { diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/controller/AccountCheckoutGatewayController.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/controller/AccountCheckoutGatewayController.java new file mode 100644 index 0000000000..8f30c79e76 --- /dev/null +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/controller/AccountCheckoutGatewayController.java @@ -0,0 +1,335 @@ +package net.firedevops.firemud.springcloudgateway.controller; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec; +import net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec.Authenticated; +import net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec.Request; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.springcloudgateway.client.AccountCheckoutHttpClient; +import net.firedevops.firemud.springcloudgateway.client.AccountCheckoutHttpClient.ForwardedResponse; +import net.firedevops.firemud.springcloudgateway.client.AccountControlUiAuthenticationClient; +import net.firedevops.firemud.springcloudgateway.config.AccountCheckoutReceivingProperties; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Profile; +import org.springframework.core.io.buffer.DataBuffer; +import org.springframework.core.io.buffer.DataBufferLimitException; +import org.springframework.core.io.buffer.DataBufferUtils; +import org.springframework.http.CacheControl; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; +import tools.jackson.core.JacksonException; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Exact checkout/login receiving allowlist; this controller does not define broad Gateway routes. + */ +@RestController +@RequestMapping("/api/account") +@Profile("isolated-checkout-receiving") +@ConditionalOnProperty( + prefix = "firemud.account.checkout-receiving", + name = "enabled", + havingValue = "true") +public final class AccountCheckoutGatewayController { + private static final int MAX_LOGIN_BODY_BYTES = 8 * 1024; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final AccountControlUiAuthenticationClient authenticationClient; + private final AccountCheckoutHttpClient checkoutHttpClient; + private final String workloadNamespace; + + public AccountCheckoutGatewayController( + AccountControlUiAuthenticationClient authenticationClient, + AccountCheckoutHttpClient checkoutHttpClient, + AccountCheckoutReceivingProperties properties) { + this.authenticationClient = Objects.requireNonNull(authenticationClient); + this.checkoutHttpClient = Objects.requireNonNull(checkoutHttpClient); + String configuredNamespace = Objects.requireNonNull(properties).getWorkloadNamespace(); + if (!GrpcPeerIdentity.isValidNamespace(configuredNamespace)) { + throw new IllegalArgumentException("Checkout Gateway namespace must be canonical"); + } + this.workloadNamespace = configuredNamespace; + } + + /** Public Control-UI login. The credential body is transient and errors never include it. */ + @PostMapping("/auth/login") + public Mono> login(ServerWebExchange exchange) { + if (!isSecureRequest(exchange) || hasQuery(exchange)) { + return Mono.just(jsonResponse(HttpStatus.BAD_REQUEST, errorJson("ERROR"))); + } + String contentType = oneHeader(exchange.getRequest().getHeaders(), HttpHeaders.CONTENT_TYPE); + if (!isJsonContentType(contentType)) { + return Mono.just(jsonResponse(HttpStatus.UNSUPPORTED_MEDIA_TYPE, errorJson("ERROR"))); + } + return boundedBody(exchange, MAX_LOGIN_BODY_BYTES) + .flatMap( + body -> { + final LoginBody input; + final Request request; + try { + input = JSON.readValue(body, LoginBody.class); + if (input == null) throw new IllegalArgumentException("Login object required"); + request = + new Request( + parseUuid(input.requestId()), + parseUuid(input.callerContextId()), + workloadNamespace, + input.email(), + input.secret()); + } catch (JacksonException | IllegalArgumentException malformed) { + return Mono.just(jsonResponse(HttpStatus.BAD_REQUEST, errorJson("ERROR"))); + } + return Mono.fromCallable(() -> authenticationClient.login(request)) + .subscribeOn(Schedulers.boundedElastic()) + .map( + result -> { + if (result.outcome() + == AccountControlUiAuthenticationGrpcCodec.Outcome.DENIED) { + return jsonResponse(HttpStatus.UNAUTHORIZED, errorJson("DENIED")); + } + Authenticated authenticated = result.authenticated(); + LoginSuccess success = + new LoginSuccess( + "SUCCESS", + new LoginData( + authenticated.accountId().toString(), + authenticated.authToken(), + Instant.ofEpochSecond(authenticated.expiresAtEpochSeconds()) + .toString())); + try { + return jsonResponse(HttpStatus.OK, JSON.writeValueAsBytes(success)); + } catch (JacksonException serializationFailure) { + return jsonResponse(HttpStatus.BAD_GATEWAY, errorJson("ERROR")); + } + }) + .onErrorResume( + AccountControlUiAuthenticationClient.AuthenticationConflictException.class, + conflict -> + Mono.just(jsonResponse(HttpStatus.CONFLICT, errorJson("CONFLICT")))) + .onErrorResume( + AccountControlUiAuthenticationClient.AuthenticationUnavailableException.class, + unavailable -> + Mono.just( + jsonResponse(HttpStatus.SERVICE_UNAVAILABLE, errorJson("ERROR")))) + .onErrorResume( + IllegalStateException.class, + invalid -> + Mono.just(jsonResponse(HttpStatus.BAD_GATEWAY, errorJson("ERROR")))); + }) + .onErrorResume( + DataBufferLimitException.class, + oversized -> Mono.just(jsonResponse(HttpStatus.PAYLOAD_TOO_LARGE, errorJson("ERROR")))); + } + + @GetMapping("/billing/hosting/subscriptions/{subscriptionId}/first-invoice") + public Mono> getFirstInvoice( + @PathVariable String subscriptionId, ServerWebExchange exchange) { + if (!isSecureRequest(exchange) || hasQuery(exchange) || !canonicalUuid(subscriptionId)) { + return Mono.just(jsonResponse(HttpStatus.BAD_REQUEST, errorJson("ERROR"))); + } + return forward(exchange, HttpMethod.GET, firstInvoicePath(subscriptionId)); + } + + @PostMapping("/billing/hosting/subscriptions/{subscriptionId}/first-invoice/reauthenticate") + public Mono> reauthenticateFirstInvoice( + @PathVariable String subscriptionId, ServerWebExchange exchange) { + return postSubscriptionAction(subscriptionId, exchange, "reauthenticate"); + } + + @PostMapping("/billing/hosting/subscriptions/{subscriptionId}/first-invoice/confirm") + public Mono> confirmFirstInvoice( + @PathVariable String subscriptionId, ServerWebExchange exchange) { + return postSubscriptionAction(subscriptionId, exchange, "confirm"); + } + + @PostMapping("/billing/hosting/subscriptions/{subscriptionId}/first-invoice/renew") + public Mono> renewFirstInvoice( + @PathVariable String subscriptionId, ServerWebExchange exchange) { + return postSubscriptionAction(subscriptionId, exchange, "renew"); + } + + @PostMapping("/billing/hosting/webhook") + public Mono> receiveStripeWebhook(ServerWebExchange exchange) { + if (!isSecureRequest(exchange) || hasQuery(exchange)) { + return Mono.just(jsonResponse(HttpStatus.BAD_REQUEST, errorJson("ERROR"))); + } + String contentType = oneHeader(exchange.getRequest().getHeaders(), HttpHeaders.CONTENT_TYPE); + String signature = oneHeader(exchange.getRequest().getHeaders(), "Stripe-Signature"); + if (!isJsonContentType(contentType) || signature == null || signature.isBlank()) { + return Mono.just(jsonResponse(HttpStatus.BAD_REQUEST, errorJson("ERROR"))); + } + return boundedBody(exchange, AccountCheckoutHttpClient.MAX_WEBHOOK_REQUEST_BYTES) + .flatMap(body -> forwardBytes(exchange, HttpMethod.POST, "/billing/hosting/webhook", body)) + .onErrorResume( + DataBufferLimitException.class, + oversized -> Mono.just(jsonResponse(HttpStatus.PAYLOAD_TOO_LARGE, errorJson("ERROR")))); + } + + private Mono> postSubscriptionAction( + String subscriptionId, ServerWebExchange exchange, String action) { + if (!isSecureRequest(exchange) || hasQuery(exchange) || !canonicalUuid(subscriptionId)) { + return Mono.just(jsonResponse(HttpStatus.BAD_REQUEST, errorJson("ERROR"))); + } + String contentType = oneHeader(exchange.getRequest().getHeaders(), HttpHeaders.CONTENT_TYPE); + if (!isJsonContentType(contentType)) { + return Mono.just(jsonResponse(HttpStatus.UNSUPPORTED_MEDIA_TYPE, errorJson("ERROR"))); + } + String path = firstInvoicePath(subscriptionId) + "/" + action; + return forward(exchange, HttpMethod.POST, path); + } + + private Mono> forward( + ServerWebExchange exchange, HttpMethod method, String path) { + String contentType = oneHeader(exchange.getRequest().getHeaders(), HttpHeaders.CONTENT_TYPE); + if (HttpMethod.POST.equals(method) && !isJsonContentType(contentType)) { + return Mono.just(jsonResponse(HttpStatus.UNSUPPORTED_MEDIA_TYPE, errorJson("ERROR"))); + } + return boundedBody(exchange, AccountCheckoutHttpClient.MAX_SUBSCRIPTION_REQUEST_BYTES) + .flatMap(body -> forwardBytes(exchange, method, path, body)) + .onErrorResume( + DataBufferLimitException.class, + oversized -> Mono.just(jsonResponse(HttpStatus.PAYLOAD_TOO_LARGE, errorJson("ERROR")))); + } + + private Mono> forwardBytes( + ServerWebExchange exchange, HttpMethod method, String path, byte[] body) { + return checkoutHttpClient + .forward(method, path, exchange.getRequest().getHeaders(), body) + .map(response -> response(response)); + } + + private static Mono boundedBody(ServerWebExchange exchange, int maximumBytes) { + long contentLength = exchange.getRequest().getHeaders().getContentLength(); + if (contentLength > maximumBytes) { + return Mono.error(new DataBufferLimitException("Request body exceeds the route limit")); + } + return DataBufferUtils.join(exchange.getRequest().getBody(), maximumBytes) + .map(AccountCheckoutGatewayController::readAndRelease) + .defaultIfEmpty(new byte[0]); + } + + private static byte[] readAndRelease(DataBuffer buffer) { + try { + byte[] bytes = new byte[buffer.readableByteCount()]; + buffer.read(bytes); + return bytes; + } finally { + DataBufferUtils.release(buffer); + } + } + + private static boolean isSecureRequest(ServerWebExchange exchange) { + return exchange.getRequest().getSslInfo() != null + && "https".equalsIgnoreCase(exchange.getRequest().getURI().getScheme()); + } + + private static boolean hasQuery(ServerWebExchange exchange) { + return exchange.getRequest().getURI().getRawQuery() != null; + } + + private static String oneHeader(HttpHeaders headers, String name) { + var values = headers.get(name); + if (values == null || values.isEmpty()) return null; + if (values.size() != 1 || values.getFirst() == null || values.getFirst().isBlank()) return ""; + return values.getFirst(); + } + + private static boolean isJsonContentType(String contentType) { + if (contentType == null || contentType.isBlank()) return false; + try { + return MediaType.APPLICATION_JSON.isCompatibleWith(MediaType.parseMediaType(contentType)); + } catch (RuntimeException malformed) { + return false; + } + } + + private static UUID parseUuid(String value) { + if (!canonicalUuid(value)) throw new IllegalArgumentException("Canonical UUID required"); + return UUID.fromString(value); + } + + private static boolean canonicalUuid(String value) { + if (value == null) return false; + try { + UUID parsed = UUID.fromString(value); + return !parsed.equals(new UUID(0L, 0L)) && parsed.toString().equals(value); + } catch (IllegalArgumentException malformed) { + return false; + } + } + + private static String firstInvoicePath(String subscriptionId) { + return "/billing/hosting/subscriptions/" + subscriptionId + "/first-invoice"; + } + + private static ResponseEntity response(ForwardedResponse upstream) { + HttpStatusCode status = upstream.status(); + byte[] body = upstream.body(); + String contentType = upstream.contentType(); + return ResponseEntity.status(status) + .cacheControl(CacheControl.noStore()) + .header(HttpHeaders.PRAGMA, "no-cache") + .header(HttpHeaders.EXPIRES, "0") + .contentType( + contentType == null + ? MediaType.APPLICATION_JSON + : MediaType.parseMediaType(contentType)) + .body(body); + } + + private static ResponseEntity jsonResponse(HttpStatus status, byte[] body) { + return ResponseEntity.status(status) + .cacheControl(CacheControl.noStore()) + .header(HttpHeaders.PRAGMA, "no-cache") + .header(HttpHeaders.EXPIRES, "0") + .contentType(MediaType.APPLICATION_JSON) + .body(body); + } + + private static byte[] errorJson(String status) { + return ("{\"status\":\"" + status + "\"}").getBytes(StandardCharsets.UTF_8); + } + + private record LoginBody(String requestId, String callerContextId, String email, String secret) { + @Override + public String toString() { + return "ControlUiLoginBody[redacted]"; + } + } + + private record LoginSuccess(String status, LoginData data) { + @Override + public String toString() { + return "ControlUiLoginSuccess[redacted]"; + } + } + + private record LoginData(String accountId, String authToken, String expiresAt) { + @Override + public String toString() { + return "ControlUiLoginData[redacted]"; + } + } +} diff --git a/services/spring-cloud-gateway/src/main/resources/openapi.yaml b/services/spring-cloud-gateway/src/main/resources/openapi.yaml index 916009491d..a5f9936f94 100644 --- a/services/spring-cloud-gateway/src/main/resources/openapi.yaml +++ b/services/spring-cloud-gateway/src/main/resources/openapi.yaml @@ -38,6 +38,126 @@ components: items: type: string paths: + /api/account/auth/login: + post: + operationId: authenticateAccountControlUi + x-runtime-status: isolated_only_default_off + summary: Authenticate an Account through the verified mTLS Account receiver + description: Explicit isolated HTTPS receiving only. No automatic retries. Exact request/context identities bind the durable Account issuance. + security: [] + requestBody: + required: true + content: + application/json: + schema: + type: object + additionalProperties: false + required: [requestId, callerContextId, email, secret] + properties: + requestId: {type: string, format: uuid} + callerContextId: {type: string, format: uuid} + email: {type: string, maxLength: 254} + secret: {type: string, maxLength: 1024, writeOnly: true} + responses: + '200': + description: No-store Account identity and memory-only control-ui credential + content: + application/json: + schema: + type: object + required: [status, data] + properties: + status: {type: string, enum: [SUCCESS]} + data: + type: object + required: [accountId, authToken, expiresAt] + properties: + accountId: {type: string, format: uuid} + authToken: {type: string, maxLength: 16384} + expiresAt: {type: string, format: date-time} + '400': {description: Invalid bounded request or actual HTTPS required} + '401': {description: Primary authentication denied} + '503': {description: Current Account authentication authority unavailable} + /api/account/billing/hosting/subscriptions/{subscriptionId}/first-invoice: + parameters: + - name: subscriptionId + in: path + required: true + schema: {type: string, format: uuid} + get: + operationId: getAccountHostingFirstInvoice + x-runtime-status: isolated_only_default_off + description: Exact HTTPS Account billing-owner operation. Passes only the necessary authenticated request over verified TLS without retry; Account owns the charge tuple, reauthentication, consent and result. + responses: + '200': {description: No-store Account owner result under the Account first-invoice API contract} + '400': {description: Malformed request} + '401': {description: Current control-ui owner authority required} + '409': {description: Exact retained evidence refused or outcome uncertain} + '502': {description: Upstream outcome uncertain; never automatically resend} + /api/account/billing/hosting/subscriptions/{subscriptionId}/first-invoice/reauthenticate: + parameters: + - name: subscriptionId + in: path + required: true + schema: {type: string, format: uuid} + post: + operationId: reauthenticateAccountHostingFirstInvoice + x-runtime-status: isolated_only_default_off + description: Exact HTTPS Account billing-owner operation. Passes only the necessary authenticated request over verified TLS without retry; Account owns the charge tuple, reauthentication, consent and result. + responses: + '200': {description: No-store Account owner result under the Account first-invoice API contract} + '400': {description: Malformed request} + '401': {description: Current control-ui owner authority required} + '409': {description: Exact retained evidence refused or outcome uncertain} + '502': {description: Upstream outcome uncertain; never automatically resend} + /api/account/billing/hosting/subscriptions/{subscriptionId}/first-invoice/confirm: + parameters: + - name: subscriptionId + in: path + required: true + schema: {type: string, format: uuid} + post: + operationId: confirmAccountHostingFirstInvoice + x-runtime-status: isolated_only_default_off + description: Exact HTTPS Account billing-owner operation. Passes only the necessary authenticated request over verified TLS without retry; Account owns the charge tuple, reauthentication, consent and result. + responses: + '200': {description: No-store Account owner result under the Account first-invoice API contract} + '400': {description: Malformed request} + '401': {description: Current control-ui owner authority required} + '409': {description: Exact retained evidence refused or outcome uncertain} + '502': {description: Upstream outcome uncertain; never automatically resend} + /api/account/billing/hosting/subscriptions/{subscriptionId}/first-invoice/renew: + parameters: + - name: subscriptionId + in: path + required: true + schema: {type: string, format: uuid} + post: + operationId: renewAccountHostingFirstInvoice + x-runtime-status: isolated_only_default_off + description: Exact HTTPS Account billing-owner operation. Passes only the necessary authenticated request over verified TLS without retry; Account owns the charge tuple, reauthentication, consent and result. + responses: + '200': {description: No-store Account owner result under the Account first-invoice API contract} + '400': {description: Malformed request} + '401': {description: Current control-ui owner authority required} + '409': {description: Exact retained evidence refused or outcome uncertain} + '502': {description: Upstream outcome uncertain; never automatically resend} + /api/account/billing/hosting/webhook: + post: + operationId: receiveAccountHostingFirstInvoiceSignedEvent + x-runtime-status: isolated_only_default_off + security: [] + description: Separately authenticated exact-byte provider signed event, at most 256 KiB. Forwards one signature header over verified HTTPS without retry or redirects. + parameters: + - name: Stripe-Signature + in: header + required: true + schema: {type: string, maxLength: 4096} + responses: + '200': {description: No-store Account completion state} + '400': {description: Invalid signed event} + '413': {description: Request exceeds the bound} + '502': {description: Upstream outcome remains uncertain} /ping: get: summary: Health check diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/client/AccountCheckoutHttpClientTlsTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/client/AccountCheckoutHttpClientTlsTest.java new file mode 100644 index 0000000000..d68bae82eb --- /dev/null +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/client/AccountCheckoutHttpClientTlsTest.java @@ -0,0 +1,348 @@ +package net.firedevops.firemud.springcloudgateway.client; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.netty.handler.ssl.SslContextBuilder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.Base64; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.springcloudgateway.config.AccountCheckoutReceivingProperties; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import reactor.core.publisher.Mono; +import reactor.netty.DisposableServer; +import reactor.netty.http.server.HttpServer; + +/** Real loopback HTTPS proofs with test-only PKI, not a live Account or Stripe endpoint. */ +class AccountCheckoutHttpClientTlsTest { + private static final String ACCOUNT_WORKLOAD = + "spiffe://firemud/ns/checkout-test/sa/account-service"; + private static final String SUBSCRIPTION_ID = "d0deddf3-d96d-456d-b85e-f025fa2e6ee3"; + private static final String SUBSCRIPTION_PATH = + "/billing/hosting/subscriptions/" + SUBSCRIPTION_ID + "/first-invoice"; + private static final String WEBHOOK_PATH = "/billing/hosting/webhook"; + private static final byte[] JSON_RESPONSE = + "{\"status\":\"OK\"}".getBytes(StandardCharsets.UTF_8); + + @TempDir static Path temporaryDirectory; + private static LoopbackMtlsTestPki.Pki pki; + private static LoopbackMtlsTestPki.Identity serverIdentity; + private DisposableServer server; + private AccountCheckoutHttpClient client; + + @BeforeAll + static void createPki() throws Exception { + pki = + LoopbackMtlsTestPki.create( + temporaryDirectory, + "Checkout HTTPS test CA", + new LoopbackMtlsTestPki.IdentitySpec("account-server", ACCOUNT_WORKLOAD, true)); + serverIdentity = pki.identity("account-server"); + } + + @AfterEach + void stopTransport() { + if (client != null) client = null; + if (server != null) { + server.disposeNow(Duration.ofSeconds(2)); + server = null; + } + } + + @Test + void forwardsOnlyNecessaryCheckoutHeadersAndUsesVerifiedHttps() throws Exception { + var captured = new AtomicReference(); + AtomicInteger requests = startServer(200, JSON_RESPONSE, captured); + client = newClient(pki.caCertificate(), server.port()); + HttpHeaders headers = new HttpHeaders(); + headers.set(HttpHeaders.AUTHORIZATION, "Bearer caller-jwt"); + headers.set("X-Forwarded-Proto", "https"); + headers.set("X-Firemud-Account-Id", "spoofed-account"); + headers.set("Cookie", "session=private"); + + var response = + client + .forward(HttpMethod.GET, SUBSCRIPTION_PATH, headers, new byte[0]) + .block(Duration.ofSeconds(8)); + + assertThat(response).isNotNull(); + assertThat(response.status()).isEqualTo(HttpStatus.OK); + assertThat(response.body()).isEqualTo(JSON_RESPONSE); + assertThat(requests).hasValue(1); + assertThat(captured.get().method()).isEqualTo("GET"); + assertThat(captured.get().path()).isEqualTo(SUBSCRIPTION_PATH); + assertThat(captured.get().authorization()).isEqualTo("Bearer caller-jwt"); + assertThat(captured.get().forwardedProto()).isNull(); + assertThat(captured.get().accountIdentity()).isNull(); + assertThat(captured.get().cookie()).isNull(); + } + + @Test + void preservesWebhookBytesAndForwardsOnlyContentTypeAndStripeSignature() throws Exception { + var captured = new AtomicReference(); + AtomicInteger requests = startServer(202, JSON_RESPONSE, captured); + client = newClient(pki.caCertificate(), server.port()); + byte[] rawPayload = "{\n \"id\": \"evt_123\"\n}\n".getBytes(StandardCharsets.UTF_8); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.set("Stripe-Signature", "t=123,v1=signature"); + headers.set(HttpHeaders.AUTHORIZATION, "Bearer must-not-pass"); + headers.set("X-Forwarded-For", "203.0.113.9"); + + var response = + client + .forward(HttpMethod.POST, WEBHOOK_PATH, headers, rawPayload) + .block(Duration.ofSeconds(8)); + + assertThat(response).isNotNull(); + assertThat(response.status()).isEqualTo(HttpStatus.ACCEPTED); + assertThat(requests).hasValue(1); + assertThat(captured.get().body()).isEqualTo(rawPayload); + assertThat(captured.get().contentType()).startsWith("application/json"); + assertThat(captured.get().stripeSignature()).isEqualTo("t=123,v1=signature"); + assertThat(captured.get().authorization()).isNull(); + assertThat(captured.get().forwardedFor()).isNull(); + } + + @Test + void rejectsUntrustedAccountCertificateBeforeSendingARequest() throws Exception { + var captured = new AtomicReference(); + AtomicInteger requests = startServer(200, JSON_RESPONSE, captured); + Path otherDirectory = Files.createDirectories(temporaryDirectory.resolve("other-ca")); + var otherPki = + LoopbackMtlsTestPki.create( + otherDirectory, + "Untrusted checkout HTTPS CA", + new LoopbackMtlsTestPki.IdentitySpec("untrusted-server", ACCOUNT_WORKLOAD, true)); + client = newClient(otherPki.caCertificate(), server.port()); + + var response = + client + .forward(HttpMethod.GET, SUBSCRIPTION_PATH, authorizationHeaders(), new byte[0]) + .block(Duration.ofSeconds(8)); + + assertThat(response).isNotNull(); + assertThat(response.status()).isEqualTo(HttpStatus.BAD_GATEWAY); + assertThat(requests).hasValue(0); + assertThat(captured.get()).isNull(); + } + + @Test + void refusesRedirectsAndOverLimitResponsesWithoutFollowingOrReturningTheirBody() + throws Exception { + var captured = new AtomicReference(); + AtomicInteger requests = startRedirectingServer(captured); + client = newClient(pki.caCertificate(), server.port()); + + var redirectResponse = + client + .forward(HttpMethod.GET, SUBSCRIPTION_PATH, authorizationHeaders(), new byte[0]) + .block(Duration.ofSeconds(8)); + + assertThat(redirectResponse).isNotNull(); + assertThat(redirectResponse.status()).isEqualTo(HttpStatus.BAD_GATEWAY); + assertThat(requests).hasValue(1); + assertThat(redirectResponse.body()).isEmpty(); + + client = null; + server.disposeNow(Duration.ofSeconds(2)); + server = null; + captured.set(null); + AtomicInteger oversizedRequests = + startServer(200, new byte[AccountCheckoutHttpClient.MAX_RESPONSE_BYTES + 1], captured); + client = newClient(pki.caCertificate(), server.port()); + var oversizedResponse = + client + .forward(HttpMethod.GET, SUBSCRIPTION_PATH, authorizationHeaders(), new byte[0]) + .block(Duration.ofSeconds(8)); + + assertThat(oversizedResponse).isNotNull(); + assertThat(oversizedResponse.status()).isEqualTo(HttpStatus.BAD_GATEWAY); + assertThat(oversizedResponse.body()).isEmpty(); + assertThat(oversizedRequests).hasValue(1); + } + + @Test + void doesNotRetryAnUncertainCheckoutPostAfterTheAccountConnectionResets() throws Exception { + AtomicInteger requests = startResettingServer(); + client = newClient(pki.caCertificate(), server.port()); + HttpHeaders headers = authorizationHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + byte[] body = "{\"confirm\":true}".getBytes(StandardCharsets.UTF_8); + + var response = + client + .forward(HttpMethod.POST, SUBSCRIPTION_PATH + "/confirm", headers, body) + .block(Duration.ofSeconds(8)); + + assertThat(response).isNotNull(); + assertThat(response.status()).isEqualTo(HttpStatus.BAD_GATEWAY); + assertThat(requests).hasValue(1); + } + + private AtomicInteger startServer( + int status, byte[] responseBody, AtomicReference captured) throws Exception { + Path cert = writeCertificate(temporaryDirectory.resolve("account-server.crt")); + Path key = writePrivateKey(temporaryDirectory.resolve("account-server.key")); + var sslContext = SslContextBuilder.forServer(cert.toFile(), key.toFile()).build(); + AtomicInteger requests = new AtomicInteger(); + server = + HttpServer.create() + .host("127.0.0.1") + .port(0) + .secure(spec -> spec.sslContext(sslContext)) + .handle( + (request, response) -> + request + .receive() + .aggregate() + .asByteArray() + .defaultIfEmpty(new byte[0]) + .flatMap( + body -> { + requests.incrementAndGet(); + captured.set(capture(request, body)); + return response + .status(status) + .header(HttpHeaders.CONTENT_TYPE, "application/json") + .sendByteArray(Mono.just(responseBody)) + .then(); + })) + .bindNow(Duration.ofSeconds(5)); + return requests; + } + + private AtomicInteger startRedirectingServer(AtomicReference captured) + throws Exception { + Path cert = writeCertificate(temporaryDirectory.resolve("account-server.crt")); + Path key = writePrivateKey(temporaryDirectory.resolve("account-server.key")); + var sslContext = SslContextBuilder.forServer(cert.toFile(), key.toFile()).build(); + AtomicInteger requests = new AtomicInteger(); + server = + HttpServer.create() + .host("127.0.0.1") + .port(0) + .secure(spec -> spec.sslContext(sslContext)) + .handle( + (request, response) -> + request + .receive() + .aggregate() + .asByteArray() + .defaultIfEmpty(new byte[0]) + .flatMap( + body -> { + requests.incrementAndGet(); + captured.set(capture(request, body)); + return response + .status(302) + .header(HttpHeaders.LOCATION, "/other-location") + .send() + .then(); + })) + .bindNow(Duration.ofSeconds(5)); + return requests; + } + + private AtomicInteger startResettingServer() throws Exception { + Path cert = writeCertificate(temporaryDirectory.resolve("account-server-reset.crt")); + Path key = writePrivateKey(temporaryDirectory.resolve("account-server-reset.key")); + var sslContext = SslContextBuilder.forServer(cert.toFile(), key.toFile()).build(); + AtomicInteger requests = new AtomicInteger(); + server = + HttpServer.create() + .host("127.0.0.1") + .port(0) + .secure(spec -> spec.sslContext(sslContext)) + .handle( + (request, response) -> + request + .receive() + .aggregate() + .asByteArray() + .defaultIfEmpty(new byte[0]) + .flatMap( + ignored -> { + requests.incrementAndGet(); + response.withConnection(connection -> connection.channel().close()); + return Mono.never(); + })) + .bindNow(Duration.ofSeconds(5)); + return requests; + } + + private AccountCheckoutHttpClient newClient( + java.security.cert.X509Certificate caCertificate, int port) throws Exception { + Path ca = + writeCertificate(temporaryDirectory.resolve("client-ca-" + port + ".crt"), caCertificate); + var properties = new AccountCheckoutReceivingProperties(); + properties.setEnabled(true); + properties.setWorkloadNamespace("checkout-test"); + properties.setAccountHttpsBaseUrl("https://127.0.0.1:" + port); + properties.setAccountCaCertPath(ca.toString()); + return AccountCheckoutHttpClient.create(properties); + } + + private static HttpHeaders authorizationHeaders() { + HttpHeaders headers = new HttpHeaders(); + headers.set(HttpHeaders.AUTHORIZATION, "Bearer caller-jwt"); + return headers; + } + + private static CapturedRequest capture( + reactor.netty.http.server.HttpServerRequest request, byte[] body) { + var headers = request.requestHeaders(); + return new CapturedRequest( + request.method().name(), + request.uri(), + headers.get(HttpHeaders.AUTHORIZATION), + headers.get(HttpHeaders.CONTENT_TYPE), + headers.get("Stripe-Signature"), + headers.get("X-Forwarded-Proto"), + headers.get("X-Forwarded-For"), + headers.get("X-Firemud-Account-Id"), + headers.get("Cookie"), + body.clone()); + } + + private Path writeCertificate(Path path) throws Exception { + return writeCertificate(path, serverIdentity.certificate()); + } + + private static Path writeCertificate(Path path, java.security.cert.X509Certificate certificate) + throws Exception { + return Files.writeString(path, pem("CERTIFICATE", certificate.getEncoded())); + } + + private Path writePrivateKey(Path path) throws Exception { + return Files.writeString(path, pem("PRIVATE KEY", serverIdentity.privateKey().getEncoded())); + } + + private static String pem(String label, byte[] value) { + String encoded = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(value); + return "-----BEGIN " + label + "-----\n" + encoded + "\n-----END " + label + "-----\n"; + } + + private record CapturedRequest( + String method, + String path, + String authorization, + String contentType, + String stripeSignature, + String forwardedProto, + String forwardedFor, + String accountIdentity, + String cookie, + byte[] body) {} +} diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/client/AccountControlUiAuthenticationClientMtlsTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/client/AccountControlUiAuthenticationClientMtlsTest.java new file mode 100644 index 0000000000..ee091eb01b --- /dev/null +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/client/AccountControlUiAuthenticationClientMtlsTest.java @@ -0,0 +1,216 @@ +package net.firedevops.firemud.springcloudgateway.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.net.InetSocketAddress; +import java.nio.file.Path; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.AccountControlUiAuthenticationServiceGrpc; +import net.firedevops.firemud.account.v1.AuthLoginRequest; +import net.firedevops.firemud.account.v1.AuthLoginResponse; +import net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec; +import net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec.Authenticated; +import net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec.Outcome; +import net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec.Request; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.api.parallel.ResourceLock; +import org.junit.jupiter.api.parallel.Resources; + +/** Socket mTLS proof: a trusted but wrong server workload receives no authentication request. */ +@ResourceLock(Resources.SYSTEM_PROPERTIES) +class AccountControlUiAuthenticationClientMtlsTest { + private static final String NAMESPACE = "checkout-test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/checkout-test/sa/account-service"; + private static final String GATEWAY_URI = + "spiffe://firemud/ns/checkout-test/sa/spring-cloud-gateway"; + private static final UUID REQUEST_ID = UUID.fromString("2a1a9840-a249-4e19-90be-774d6afc937a"); + private static final UUID CALLER_CONTEXT_ID = + UUID.fromString("540923e1-bb03-4cf2-98e7-25344c4a6ae8"); + private static final UUID ACCOUNT_ID = UUID.fromString("d0deddf3-d96d-456d-b85e-f025fa2e6ee3"); + private static final String SECRET = "ephemeral-test-primary-secret"; + private static final String TOKEN = "header.payload.signature"; + + @TempDir static Path temporaryDirectory; + private static LoopbackMtlsTestPki.Pki pki; + private Server server; + private AccountControlUiAuthenticationClient client; + private GrpcChannelFactory channelFactory; + + @BeforeAll + static void createPki() throws Exception { + pki = + LoopbackMtlsTestPki.create( + temporaryDirectory, + "Checkout Gateway test CA", + new LoopbackMtlsTestPki.IdentitySpec("account-server", ACCOUNT_URI, true), + new LoopbackMtlsTestPki.IdentitySpec( + "wrong-server", "spiffe://firemud/ns/checkout-test/sa/game-session-service", true), + new LoopbackMtlsTestPki.IdentitySpec("gateway-client", GATEWAY_URI, false)); + } + + @AfterEach + void stopTransport() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void authenticatesAccountPeerAndReturnsOnlyAnExactBoundResponse() throws Exception { + var observed = new AtomicReference(); + var peer = new AtomicReference(); + AtomicInteger handlers = startServer("account-server", observed, peer); + client = newClient(server.getPort()); + client.init(); + + var result = client.login(request()); + + assertThat(result.outcome()).isEqualTo(Outcome.SUCCESS); + assertThat(result.authenticated()) + .isEqualTo(new Authenticated(ACCOUNT_ID, TOKEN, 1_900_000_000L)); + assertThat(observed.get()).isEqualTo(request()); + assertThat(observed.get().toString()).doesNotContain(SECRET); + assertThat(peer.get().uri()).isEqualTo(GATEWAY_URI); + assertThat(handlers).hasValue(1); + org.mockito.Mockito.verify(channelFactory) + .buildNonRetryingChannel( + eq("localhost:" + server.getPort()), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true)); + } + + @Test + void caTrustedWrongServerWorkloadReceivesNoPrimaryRequestOrSecret() throws Exception { + var observed = new AtomicReference(); + var peer = new AtomicReference(); + AtomicInteger handlers = startServer("wrong-server", observed, peer); + client = newClient(server.getPort()); + client.init(); + + assertThatThrownBy(() -> client.login(request())) + .isInstanceOf(AccountControlUiAuthenticationClient.AuthenticationUnavailableException.class) + .hasMessage("Account authentication is unavailable"); + + assertThat(handlers).hasValue(0); + assertThat(observed.get()).isNull(); + assertThat(peer.get()).isNull(); + } + + @Test + void mapsRetainedRequestInputConflictWithoutForwardingGrpcErrorDetails() throws Exception { + var observed = new AtomicReference(); + var peer = new AtomicReference(); + AtomicInteger handlers = startServer("account-server", observed, peer, true); + client = newClient(server.getPort()); + client.init(); + + assertThatThrownBy(() -> client.login(request())) + .isInstanceOf(AccountControlUiAuthenticationClient.AuthenticationConflictException.class) + .hasMessage("Account authentication request conflicts") + .hasNoCause(); + + assertThat(handlers).hasValue(1); + assertThat(observed.get()).isEqualTo(request()); + } + + private AtomicInteger startServer( + String serverIdentityAlias, + AtomicReference observed, + AtomicReference peer) + throws Exception { + return startServer(serverIdentityAlias, observed, peer, false); + } + + private AtomicInteger startServer( + String serverIdentityAlias, + AtomicReference observed, + AtomicReference peer, + boolean conflict) + throws Exception { + var serverIdentity = pki.identity(serverIdentityAlias); + AtomicInteger handlers = new AtomicInteger(); + AccountControlUiAuthenticationServiceGrpc.AccountControlUiAuthenticationServiceImplBase + service = + new AccountControlUiAuthenticationServiceGrpc + .AccountControlUiAuthenticationServiceImplBase() { + @Override + public void authLogin( + AuthLoginRequest wireRequest, + StreamObserver responseObserver) { + handlers.incrementAndGet(); + peer.set(GrpcPeerIdentity.current()); + Request request = AccountControlUiAuthenticationGrpcCodec.parseRequest(wireRequest); + observed.set(request); + if (conflict) { + responseObserver.onError( + Status.ALREADY_EXISTS + .withDescription("retained request input changed") + .asRuntimeException()); + return; + } + responseObserver.onNext( + AccountControlUiAuthenticationGrpcCodec.toResponse( + request, new Authenticated(ACCOUNT_ID, TOKEN, 1_900_000_000L))); + responseObserver.onCompleted(); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverIdentity.privateKey(), serverIdentity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + return handlers; + } + + private AccountControlUiAuthenticationClient newClient(int port) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + port); + channelFactory = org.mockito.Mockito.spy(new GrpcChannelFactory()); + return new AccountControlUiAuthenticationClient( + endpoints, + pki.clientProperties(temporaryDirectory, pki.identity("gateway-client")), + channelFactory, + NAMESPACE); + } + + private static Request request() { + return new Request(REQUEST_ID, CALLER_CONTEXT_ID, NAMESPACE, "operator@example.test", SECRET); + } +} diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfigurationTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfigurationTest.java new file mode 100644 index 0000000000..1633c0d066 --- /dev/null +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfigurationTest.java @@ -0,0 +1,238 @@ +package net.firedevops.firemud.springcloudgateway.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Collections; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.springcloudgateway.client.AccountCheckoutHttpClient; +import net.firedevops.firemud.springcloudgateway.client.AccountControlUiAuthenticationClient; +import net.firedevops.firemud.springcloudgateway.controller.AccountCheckoutGatewayController; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.cloud.gateway.filter.ratelimit.RateLimiter; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.core.env.MapPropertySource; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.mock.http.server.reactive.MockServerHttpRequest; +import org.springframework.mock.web.server.MockServerWebExchange; +import org.springframework.web.server.WebFilter; +import reactor.core.publisher.Mono; + +class AccountCheckoutReceivingConfigurationTest { + @TempDir Path temporaryDirectory; + + @Test + void defaultAbsentConfigurationCreatesNoHandlerOrReceivingClients() { + try (var context = new AnnotationConfigApplicationContext()) { + context.register(AccountCheckoutReceivingConfiguration.class); + context.refresh(); + + assertThat(context.getBean(AccountCheckoutReceivingProperties.class).isEnabled()).isFalse(); + assertThat(context.getBeansOfType(AccountCheckoutGatewayController.class)).isEmpty(); + assertThat(context.getBeansOfType(AccountCheckoutHttpClient.class)).isEmpty(); + assertThat(context.getBeansOfType(AccountControlUiAuthenticationClient.class)).isEmpty(); + assertThat( + context.getBeansOfType(org.springframework.cloud.gateway.route.RouteDefinition.class)) + .isEmpty(); + } + } + + @Test + void enabledPropertyWithoutTheIsolatedProfileFailsClosed() { + try (var context = new AnnotationConfigApplicationContext()) { + addProperties( + context, + Map.of( + "firemud.account.checkout-receiving.enabled", "true", + "firemud.account.checkout-receiving.workload-namespace", "checkout-test")); + context.register(AccountCheckoutReceivingConfiguration.class); + + Throwable failure = catchThrowable(context::refresh); + + assertThat(failure).isNotNull(); + assertThat(messageChain(failure)) + .contains("requires the isolated-checkout-receiving profile"); + } + } + + @Test + void isolatedReceivingProfileCannotRunWithProductionProfile() { + try (var context = new AnnotationConfigApplicationContext()) { + context.getEnvironment().setActiveProfiles("isolated-checkout-receiving", "prod"); + context.register(AccountCheckoutReceivingConfiguration.class); + + Throwable failure = catchThrowable(context::refresh); + + assertThat(failure).isNotNull(); + assertThat(messageChain(failure)).contains("cannot be activated with a production profile"); + } + } + + @Test + void enabledReceivingRequiresHttpsAccountAuthorityAndReadableCaFile() throws Exception { + Path ca = Files.writeString(temporaryDirectory.resolve("account-ca.pem"), "test CA"); + var properties = new AccountCheckoutReceivingProperties(); + properties.setEnabled(true); + properties.setWorkloadNamespace("checkout-test"); + properties.setAccountHttpsBaseUrl("https://account-service:8443"); + properties.setAccountCaCertPath(ca.toString()); + + properties.validateEnabledConfiguration(); + + properties.setAccountHttpsBaseUrl("http://account-service:8080"); + Throwable httpFailure = catchThrowable(properties::validateEnabledConfiguration); + assertThat(httpFailure).isInstanceOf(IllegalStateException.class); + assertThat(httpFailure.getMessage()).contains("authority-only HTTPS Account upstream"); + + properties.setAccountHttpsBaseUrl("https://user:secret@account-service:8443"); + Throwable credentialFailure = catchThrowable(properties::validateEnabledConfiguration); + assertThat(credentialFailure).isInstanceOf(IllegalStateException.class); + assertThat(credentialFailure.getMessage()).contains("authority-only HTTPS Account upstream"); + } + + @Test + void receivingRateLimitRunsOnlyOnSelectedHandlersAndFailsClosedWhenDenied() { + AtomicReference resolvedKey = new AtomicReference<>(); + AtomicReference routeId = new AtomicReference<>(); + AtomicBoolean handlerCalled = new AtomicBoolean(); + WebFilter filter = + AccountCheckoutReceivingConfiguration.receivingRateLimitWebFilter( + limiter( + false, + (route, key) -> { + routeId.set(route); + resolvedKey.set(key); + }), + new GatewayRateLimiterConfig().gatewayClientIpKeyResolver()); + var exchange = + receivingExchange( + HttpMethod.POST, + "/api/account/billing/hosting/subscriptions/927fb6a8-3975-4cba-8145-c2a8f4a9b0d1/first-invoice/confirm"); + + filter + .filter( + exchange, + ignored -> { + handlerCalled.set(true); + return Mono.empty(); + }) + .block(); + + assertThat(handlerCalled).isFalse(); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.TOO_MANY_REQUESTS); + assertThat(exchange.getResponse().getHeaders().getCacheControl()).contains("no-store"); + assertThat(routeId).hasValue("account-checkout-receiving"); + assertThat(resolvedKey).hasValue("192.0.2.123"); + } + + @Test + void receivingRateLimitUnavailableReturnsServiceUnavailableAndIgnoresOtherPaths() { + AtomicBoolean handlerCalled = new AtomicBoolean(); + WebFilter filter = + AccountCheckoutReceivingConfiguration.receivingRateLimitWebFilter( + failingLimiter(), new GatewayRateLimiterConfig().gatewayClientIpKeyResolver()); + var unrelated = receivingExchange(HttpMethod.POST, "/api/account/auth/logout"); + + filter + .filter( + unrelated, + ignored -> { + handlerCalled.set(true); + return Mono.empty(); + }) + .block(); + + assertThat(handlerCalled).isTrue(); + assertThat(unrelated.getResponse().getStatusCode()).isNull(); + + var login = receivingExchange(HttpMethod.POST, "/api/account/auth/login"); + filter.filter(login, ignored -> Mono.empty()).block(); + + assertThat(login.getResponse().getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); + assertThat(login.getResponse().getHeaders().getCacheControl()).contains("no-store"); + } + + private static void addProperties( + AnnotationConfigApplicationContext context, Map properties) { + context + .getEnvironment() + .getPropertySources() + .addFirst(new MapPropertySource("checkout-test", properties)); + } + + private static String messageChain(Throwable failure) { + StringBuilder messages = new StringBuilder(); + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + messages.append(cause.getMessage()).append('\n'); + } + return messages.toString(); + } + + private static MockServerWebExchange receivingExchange(HttpMethod method, String path) { + return MockServerWebExchange.from( + MockServerHttpRequest.method(method, URI.create("https://localhost" + path)) + .header("X-Client-IP", "192.0.2.123") + .build()); + } + + private static RateLimiter limiter(boolean allowed, RateLimitObservation observation) { + return new RateLimiter<>() { + @Override + public Mono isAllowed(String routeId, String id) { + observation.record(routeId, id); + return Mono.just(new Response(allowed, Collections.emptyMap())); + } + + @Override + public Map getConfig() { + return Collections.emptyMap(); + } + + @Override + public Class getConfigClass() { + return Object.class; + } + + @Override + public Object newConfig() { + return new Object(); + } + }; + } + + private static RateLimiter failingLimiter() { + return new RateLimiter<>() { + @Override + public Mono isAllowed(String routeId, String id) { + return Mono.error(new IllegalStateException("controlled test failure")); + } + + @Override + public Map getConfig() { + return Collections.emptyMap(); + } + + @Override + public Class getConfigClass() { + return Object.class; + } + + @Override + public Object newConfig() { + return new Object(); + } + }; + } + + @FunctionalInterface + private interface RateLimitObservation { + void record(String routeId, String key); + } +} diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfigTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfigTest.java index 775ef74caf..0f77b5684a 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfigTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfigTest.java @@ -1,8 +1,13 @@ package net.firedevops.firemud.springcloudgateway.config; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.util.List; +import java.util.Map; import org.junit.jupiter.api.Test; +import org.springframework.cloud.gateway.config.GatewayProperties; +import org.springframework.cloud.gateway.filter.FilterDefinition; import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; @@ -38,4 +43,70 @@ void fallsBackToForwardedForWhenGatewayOwnedHeaderMissing() { assertThat(key).isEqualTo("203.0.113.77"); } + + @Test + void readsOnlyTheCanonicalBoundedRequestRateLimiterDefaults() { + GatewayProperties properties = new GatewayProperties(); + FilterDefinition limiter = new FilterDefinition("RequestRateLimiter"); + limiter.setArgs( + Map.of( + "redis-rate-limiter.replenishRate", "20", + "redis-rate-limiter.burstCapacity", "40")); + properties.setDefaultFilters(List.of(limiter)); + + var arguments = GatewayRateLimiterConfig.defaultRequestRateLimiterArguments(properties); + + assertThat(arguments.replenishRate()).isEqualTo(20); + assertThat(arguments.burstCapacity()).isEqualTo(40L); + assertThat(arguments.requestedTokens()).isEqualTo(1); + } + + @Test + void preservesConfiguredRequestedTokensWhenPresent() { + GatewayProperties properties = new GatewayProperties(); + FilterDefinition limiter = limiter("20", "40"); + limiter.getArgs().put("redis-rate-limiter.requestedTokens", "2"); + properties.setDefaultFilters(List.of(limiter)); + + var arguments = GatewayRateLimiterConfig.defaultRequestRateLimiterArguments(properties); + + assertThat(arguments.requestedTokens()).isEqualTo(2); + } + + @Test + void rejectsMissingDuplicateOrNonpositiveDefaultRateLimiterConfiguration() { + GatewayProperties missing = new GatewayProperties(); + missing.setDefaultFilters(List.of()); + + GatewayProperties duplicate = new GatewayProperties(); + duplicate.setDefaultFilters(List.of(limiter("20", "40"), limiter("10", "20"))); + + GatewayProperties malformed = new GatewayProperties(); + malformed.setDefaultFilters(List.of(limiter("0", "40"))); + + GatewayProperties unsupported = new GatewayProperties(); + FilterDefinition unsupportedLimiter = limiter("20", "40"); + unsupportedLimiter.getArgs().put("key-resolver", "customKeyResolver"); + unsupported.setDefaultFilters(List.of(unsupportedLimiter)); + + assertThatThrownBy(() -> GatewayRateLimiterConfig.defaultRequestRateLimiterArguments(missing)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> GatewayRateLimiterConfig.defaultRequestRateLimiterArguments(duplicate)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> GatewayRateLimiterConfig.defaultRequestRateLimiterArguments(malformed)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> GatewayRateLimiterConfig.defaultRequestRateLimiterArguments(unsupported)) + .isInstanceOf(IllegalStateException.class); + } + + private static FilterDefinition limiter(String replenishRate, String burstCapacity) { + FilterDefinition limiter = new FilterDefinition("RequestRateLimiter"); + limiter.setArgs( + new java.util.HashMap<>( + Map.of( + "redis-rate-limiter.replenishRate", replenishRate, + "redis-rate-limiter.burstCapacity", burstCapacity))); + return limiter; + } } diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/controller/AccountCheckoutGatewayControllerTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/controller/AccountCheckoutGatewayControllerTest.java new file mode 100644 index 0000000000..fab70437a5 --- /dev/null +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/controller/AccountCheckoutGatewayControllerTest.java @@ -0,0 +1,295 @@ +package net.firedevops.firemud.springcloudgateway.controller; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.UUID; +import net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec; +import net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec.Authenticated; +import net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec.Request; +import net.firedevops.firemud.springcloudgateway.client.AccountCheckoutHttpClient; +import net.firedevops.firemud.springcloudgateway.client.AccountControlUiAuthenticationClient; +import net.firedevops.firemud.springcloudgateway.config.AccountCheckoutReceivingProperties; +import org.junit.jupiter.api.Test; +import org.springframework.core.io.buffer.DefaultDataBufferFactory; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.server.reactive.SslInfo; +import org.springframework.mock.http.server.reactive.MockServerHttpRequest; +import org.springframework.mock.web.server.MockServerWebExchange; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import reactor.core.publisher.Mono; + +class AccountCheckoutGatewayControllerTest { + private static final UUID REQUEST_ID = UUID.fromString("1ca7f2e5-1362-4ac8-9312-38bbf73bc33f"); + private static final UUID CALLER_CONTEXT_ID = + UUID.fromString("af64ad5f-e9ee-48a1-9b5d-6fb28845ff71"); + private static final UUID ACCOUNT_ID = UUID.fromString("56f945f8-b85e-45e1-8254-69569203fc67"); + private static final UUID SUBSCRIPTION_ID = + UUID.fromString("927fb6a8-3975-4cba-8145-c2a8f4a9b0d1"); + private static final String SECRET = "do-not-reflect-primary-secret"; + private static final String TOKEN = "header.payload.signature"; + + @Test + void loginRequiresActualTlsAndReturnsNoStoreSuccessWithoutEchoingSecret() { + var authClient = mock(AccountControlUiAuthenticationClient.class); + var checkoutClient = mock(AccountCheckoutHttpClient.class); + var properties = properties(); + var controller = new AccountCheckoutGatewayController(authClient, checkoutClient, properties); + properties.setWorkloadNamespace("changed-after-controller-construction"); + when(authClient.login(any())) + .thenReturn( + new AccountControlUiAuthenticationGrpcCodec.Result( + AccountControlUiAuthenticationGrpcCodec.Outcome.SUCCESS, + new Authenticated(ACCOUNT_ID, TOKEN, 1_900_000_000L))); + String body = loginJson(); + + var response = controller.login(secureExchange("/api/account/auth/login", body)).block(); + + assertThat(response).isNotNull(); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(response.getHeaders().getCacheControl()).contains("no-store"); + assertThat(response.getHeaders().getFirst(HttpHeaders.PRAGMA)).isEqualTo("no-cache"); + assertThat(new String(response.getBody(), StandardCharsets.UTF_8)) + .contains("\"status\":\"SUCCESS\"") + .contains("\"accountId\":\"" + ACCOUNT_ID + "\"") + .contains("\"authToken\":\"" + TOKEN + "\"") + .contains("\"expiresAt\":\"2030-03-17T17:46:40Z\"") + .doesNotContain(SECRET); + var requestCaptor = org.mockito.ArgumentCaptor.forClass(Request.class); + verify(authClient).login(requestCaptor.capture()); + assertThat(requestCaptor.getValue().requestId()).isEqualTo(REQUEST_ID); + assertThat(requestCaptor.getValue().callerContextId()).isEqualTo(CALLER_CONTEXT_ID); + assertThat(requestCaptor.getValue().callerNamespace()).isEqualTo("checkout-test"); + assertThat(requestCaptor.getValue().secret()).isEqualTo(SECRET); + assertThat(requestCaptor.getValue().toString()).doesNotContain(SECRET); + verifyNoCheckoutCalls(checkoutClient); + } + + @Test + void rejectsForwardedProtoAsSubstituteForARealTlsSession() { + var authClient = mock(AccountControlUiAuthenticationClient.class); + var checkoutClient = mock(AccountCheckoutHttpClient.class); + var controller = new AccountCheckoutGatewayController(authClient, checkoutClient, properties()); + var request = + MockServerHttpRequest.post("/api/account/auth/login") + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .header("X-Forwarded-Proto", "https") + .body(loginJson()); + + var response = controller.login(MockServerWebExchange.from(request)).block(); + + assertThat(response).isNotNull(); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); + assertThat(response.getHeaders().getCacheControl()).contains("no-store"); + verify(authClient, never()).login(any()); + verifyNoCheckoutCalls(checkoutClient); + } + + @Test + void mapsRetainedRequestInputConflictsToSafeHttpConflict() { + var authClient = mock(AccountControlUiAuthenticationClient.class); + var checkoutClient = mock(AccountCheckoutHttpClient.class); + var controller = new AccountCheckoutGatewayController(authClient, checkoutClient, properties()); + when(authClient.login(any())) + .thenThrow(new AccountControlUiAuthenticationClient.AuthenticationConflictException()); + + var response = controller.login(secureExchange("/api/account/auth/login", loginJson())).block(); + + assertThat(response).isNotNull(); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CONFLICT); + assertThat(response.getHeaders().getCacheControl()).contains("no-store"); + assertThat(new String(response.getBody(), StandardCharsets.UTF_8)) + .contains("\"status\":\"CONFLICT\"") + .doesNotContain(SECRET); + verifyNoCheckoutCalls(checkoutClient); + } + + @Test + void redactsCredentialAndTokenFromTransientLoginRecordDiagnostics() throws Exception { + Class dataType = + Class.forName(AccountCheckoutGatewayController.class.getName() + "$LoginData"); + var dataConstructor = dataType.getDeclaredConstructor(String.class, String.class, String.class); + dataConstructor.setAccessible(true); + Object data = dataConstructor.newInstance(ACCOUNT_ID.toString(), TOKEN, "2030-03-17T17:46:40Z"); + + Class successType = + Class.forName(AccountCheckoutGatewayController.class.getName() + "$LoginSuccess"); + var successConstructor = successType.getDeclaredConstructor(String.class, dataType); + successConstructor.setAccessible(true); + Object success = successConstructor.newInstance("SUCCESS", data); + + assertThat(data.toString()).doesNotContain(TOKEN); + assertThat(success.toString()).doesNotContain(TOKEN).doesNotContain(SECRET); + } + + @Test + void rejectsDuplicateUnknownAndOversizedLoginJsonWithoutCallingAccount() { + var authClient = mock(AccountControlUiAuthenticationClient.class); + var checkoutClient = mock(AccountCheckoutHttpClient.class); + var controller = new AccountCheckoutGatewayController(authClient, checkoutClient, properties()); + for (String body : + new String[] { + loginJson() + .replace("\"secret\":", "\"secret\":\"first\",\"secret\":") + .replace("\"do-not-reflect-primary-secret\"", "\"second\""), + loginJson().replace("\"secret\":", "\"unexpected\":true,\"secret\":") + }) { + var response = controller.login(secureExchange("/api/account/auth/login", body)).block(); + assertThat(response).isNotNull(); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); + assertThat(new String(response.getBody(), StandardCharsets.UTF_8)).doesNotContain(SECRET); + } + + var oversized = + controller + .login(secureExchange("/api/account/auth/login", "x".repeat(8 * 1024 + 1))) + .block(); + + assertThat(oversized).isNotNull(); + assertThat(oversized.getStatusCode()).isEqualTo(HttpStatus.PAYLOAD_TOO_LARGE); + verify(authClient, never()).login(any()); + verifyNoCheckoutCalls(checkoutClient); + } + + @Test + void forwardsOnlyExactCheckoutRoutesAndSetsNoStoreOnProxyResponses() { + var authClient = mock(AccountControlUiAuthenticationClient.class); + var checkoutClient = mock(AccountCheckoutHttpClient.class); + var controller = new AccountCheckoutGatewayController(authClient, checkoutClient, properties()); + byte[] payload = "{\"acceptCharge\":true}".getBytes(StandardCharsets.UTF_8); + when(checkoutClient.forward( + eq(HttpMethod.POST), + eq("/billing/hosting/subscriptions/" + SUBSCRIPTION_ID + "/first-invoice/confirm"), + any(), + any())) + .thenReturn( + Mono.just( + new AccountCheckoutHttpClient.ForwardedResponse( + HttpStatus.OK, MediaType.APPLICATION_JSON_VALUE, payload))); + var request = + MockServerHttpRequest.method( + HttpMethod.POST, + URI.create( + "https://localhost/api/account/billing/hosting/subscriptions/" + + SUBSCRIPTION_ID + + "/first-invoice/confirm")) + .sslInfo(mock(SslInfo.class)) + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .header(HttpHeaders.AUTHORIZATION, "Bearer caller-token") + .body(new String(payload, StandardCharsets.UTF_8)); + + var response = + controller + .confirmFirstInvoice(SUBSCRIPTION_ID.toString(), MockServerWebExchange.from(request)) + .block(); + + assertThat(response).isNotNull(); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(response.getHeaders().getCacheControl()).contains("no-store"); + assertThat(response.getBody()).isEqualTo(payload); + verify(checkoutClient) + .forward( + eq(HttpMethod.POST), + eq("/billing/hosting/subscriptions/" + SUBSCRIPTION_ID + "/first-invoice/confirm"), + any(), + any()); + verify(authClient, never()).login(any()); + } + + @Test + void webhookForwardsRawBytesAndOnlyMapsItsDedicatedPostRoute() { + var authClient = mock(AccountControlUiAuthenticationClient.class); + var checkoutClient = mock(AccountCheckoutHttpClient.class); + var controller = new AccountCheckoutGatewayController(authClient, checkoutClient, properties()); + byte[] payload = "{\n\"id\":\"evt_raw\"\n}".getBytes(StandardCharsets.UTF_8); + when(checkoutClient.forward(eq(HttpMethod.POST), eq("/billing/hosting/webhook"), any(), any())) + .thenReturn( + Mono.just( + new AccountCheckoutHttpClient.ForwardedResponse( + HttpStatus.ACCEPTED, MediaType.APPLICATION_JSON_VALUE, new byte[0]))); + var request = + MockServerHttpRequest.method( + HttpMethod.POST, + URI.create("https://localhost/api/account/billing/hosting/webhook")) + .sslInfo(mock(SslInfo.class)) + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .header("Stripe-Signature", "t=123,v1=signature") + .body(Mono.just(new DefaultDataBufferFactory().wrap(payload))); + + var response = controller.receiveStripeWebhook(MockServerWebExchange.from(request)).block(); + + assertThat(response).isNotNull(); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.ACCEPTED); + assertThat(response.getHeaders().getCacheControl()).contains("no-store"); + verify(checkoutClient) + .forward(eq(HttpMethod.POST), eq("/billing/hosting/webhook"), any(), any()); + verify(authClient, never()).login(any()); + } + + @Test + void exposesOnlyTheExplicitMethodAndPathAnnotations() throws Exception { + assertThat( + AccountCheckoutGatewayController.class + .getMethod("login", org.springframework.web.server.ServerWebExchange.class) + .getAnnotation(PostMapping.class) + .value()) + .containsExactly("/auth/login"); + assertThat( + AccountCheckoutGatewayController.class + .getMethod( + "getFirstInvoice", + String.class, + org.springframework.web.server.ServerWebExchange.class) + .getAnnotation(GetMapping.class) + .value()) + .containsExactly("/billing/hosting/subscriptions/{subscriptionId}/first-invoice"); + assertThat( + AccountCheckoutGatewayController.class + .getMethod( + "receiveStripeWebhook", org.springframework.web.server.ServerWebExchange.class) + .getAnnotation(PostMapping.class) + .value()) + .containsExactly("/billing/hosting/webhook"); + } + + private static AccountCheckoutReceivingProperties properties() { + var properties = new AccountCheckoutReceivingProperties(); + properties.setEnabled(true); + properties.setWorkloadNamespace("checkout-test"); + return properties; + } + + private static String loginJson() { + return "{\"requestId\":\"" + + REQUEST_ID + + "\",\"callerContextId\":\"" + + CALLER_CONTEXT_ID + + "\",\"email\":\"operator@example.test\",\"secret\":\"" + + SECRET + + "\"}"; + } + + private static MockServerWebExchange secureExchange(String path, String body) { + var request = + MockServerHttpRequest.method(HttpMethod.POST, URI.create("https://localhost" + path)) + .sslInfo(mock(SslInfo.class)) + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .body(body); + return MockServerWebExchange.from(request); + } + + private static void verifyNoCheckoutCalls(AccountCheckoutHttpClient checkoutClient) { + verify(checkoutClient, never()).forward(any(), any(), any(), any()); + } +} diff --git a/web-client/package.json b/web-client/package.json index 74f6032ace..ef4bc038f7 100644 --- a/web-client/package.json +++ b/web-client/package.json @@ -11,7 +11,7 @@ "format": "prettier --check \"src/**/*.{ts,tsx}\"", "format:fix": "prettier --write \"src/**/*.{ts,tsx}\"", "accessibility": "npm run build && npx serve dist -l 5000 & npx wait-on http://localhost:5000/index.html && npx axe http://localhost:5000/index.html --chrome-options=\"--no-sandbox\" --exit", - "test:checkout": "vitest run src/billing/HostingFirstInvoiceCheckout.test.tsx src/api/hostingFirstInvoice.test.ts" + "test:checkout": "vitest run src/billing/HostingFirstInvoiceCheckout.test.tsx src/api/hostingFirstInvoice.test.ts src/api/accountControlUi.test.ts src/account/controlUiSession.test.ts src/account/AccountCheckoutRoute.test.tsx" }, "dependencies": { "@emotion/react": "^11.14.0", diff --git a/web-client/src/App.tsx b/web-client/src/App.tsx index 1941b252ea..9a5dbef7ab 100644 --- a/web-client/src/App.tsx +++ b/web-client/src/App.tsx @@ -1,15 +1,38 @@ -import { useState } from 'react'; +import { useEffect, useState } from 'react'; import Button from '@mui/material/Button'; import GameEditor from './GameEditor'; import ScriptEditor from './ScriptEditor'; +import AccountCheckoutRoute, { + type AccountCheckoutRouteProps, +} from './account/AccountCheckoutRoute'; import reactLogo from './assets/react.svg'; import viteLogo from '/vite.svg'; import './App.css'; -function App() { +export interface AppProps { + accountCheckoutRouteProps?: Omit; +} + +function App({ accountCheckoutRouteProps }: AppProps = {}) { + const [pathname, setPathname] = useState(() => window.location.pathname); const [count, setCount] = useState(0); const [mode, setMode] = useState<'demo' | 'game' | 'script'>('demo'); + useEffect(() => { + const updatePathname = () => setPathname(window.location.pathname); + window.addEventListener('popstate', updatePathname); + return () => window.removeEventListener('popstate', updatePathname); + }, []); + + if (pathname.startsWith('/account/')) { + return ( + + ); + } + return ( <>
diff --git a/web-client/src/account/AccountCheckoutRoute.test.tsx b/web-client/src/account/AccountCheckoutRoute.test.tsx new file mode 100644 index 0000000000..0e985a06f0 --- /dev/null +++ b/web-client/src/account/AccountCheckoutRoute.test.tsx @@ -0,0 +1,329 @@ +// @vitest-environment jsdom +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { + act, + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/react'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import App from '../App'; +import type { AccountControlUiApi } from '../api/accountControlUi'; +import type { HostingStripe } from '../billing/hostingStripe'; +import { + createControlUiSessionStore, + type ControlUiSessionStore, +} from './controlUiSession'; + +const origin = 'https://gateway.example.test'; +const subscriptionId = '11111111-1111-4111-8111-111111111111'; +const accountId = '22222222-2222-4222-8222-222222222222'; +const checkoutPath = `/account/subscriptions/${subscriptionId}/checkout`; +const stores = new Set(); + +const firstInvoice = { + subscriptionId, + invoiceId: 'in_existing', + paymentIntentId: 'pi_existing', + paymentInstrumentId: '33333333-3333-4333-8333-333333333333', + amount: '1299', + currency: 'usd', + tupleDigest: `sha256:${'a'.repeat(64)}`, + expectedRowVersion: 3, + state: 'AWAITING_PAYMENT', + expiresAt: '2099-01-01T00:00:00Z', + confirmationRequestId: null, + authorizationVersion: 0, +}; + +function makeIds() { + const ids = [ + '44444444-4444-4444-8444-444444444444', + '55555555-5555-4555-8555-555555555555', + '66666666-6666-4666-8666-666666666666', + '77777777-7777-4777-8777-777777777777', + '88888888-8888-4888-8888-888888888888', + ]; + let index = 0; + return () => ids[index++] ?? '99999999-9999-4999-8999-999999999999'; +} + +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +function setupApp( + options: { + key?: string; + invoiceStatus?: number; + loadStripeClient?: (publishableKey: string) => Promise; + } = {} +) { + const queries = new QueryClient({ + defaultOptions: { + queries: { retry: false }, + mutations: { retry: false }, + }, + }); + const clearQueryCache = vi.fn(() => queries.clear()); + const fetchImpl = vi + .fn() + .mockImplementation(async (input, init) => { + const url = input instanceof URL ? input : new URL(String(input)); + if ( + url.pathname === + `/api/account/billing/hosting/subscriptions/${subscriptionId}/first-invoice` && + (init?.method ?? 'GET') === 'GET' + ) { + if (options.invoiceStatus && options.invoiceStatus !== 200) { + return new Response('private owner response', { + status: options.invoiceStatus, + }); + } + return new Response(JSON.stringify(firstInvoice), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }); + } + return new Response('private owner response', { status: 404 }); + }); + const sessionStore = createControlUiSessionStore({ + origin: () => origin, + fetchImpl, + idFactory: makeIds(), + clearQueryCache, + }); + stores.add(sessionStore); + const api: AccountControlUiApi = { + login: vi.fn().mockResolvedValue({ + accountId, + authToken: 'header.payload.signature', + expiresAt: new Date(Date.now() + 60 * 60 * 1000).toISOString(), + }), + }; + const stripe: HostingStripe = { + handleNextAction: vi.fn().mockResolvedValue({}), + }; + const loadStripeClient = + options.loadStripeClient ?? vi.fn().mockResolvedValue(stripe); + window.history.replaceState({}, '', checkoutPath); + const view = render( + + + + ); + return { + ...view, + api, + queries, + clearQueryCache, + fetchImpl, + sessionStore, + loadStripeClient, + }; +} + +async function signIn() { + fireEvent.change(screen.getByLabelText('Account email'), { + target: { value: 'owner@example.com' }, + }); + fireEvent.change(screen.getByLabelText('Primary authentication secret'), { + target: { value: 'primary-secret' }, + }); + fireEvent.click(screen.getByRole('button', { name: 'Sign in' })); + await screen.findByText('in_existing'); +} + +afterEach(() => { + cleanup(); + for (const store of stores) store.signOut(); + stores.clear(); + window.history.replaceState({}, '', '/'); + vi.restoreAllMocks(); +}); + +describe('App-owned first-invoice route', () => { + it('renders the login form, loads only the existing owner invoice, and signs out locally', async () => { + const { api, fetchImpl, clearQueryCache } = setupApp(); + expect( + screen.getByRole('heading', { name: 'Sign in to Account' }) + ).toBeTruthy(); + await signIn(); + + expect(api.login).toHaveBeenCalledOnce(); + expect(fetchImpl).toHaveBeenCalledOnce(); + expect(fetchImpl.mock.calls[0][0]).toEqual( + new URL( + `/api/account/billing/hosting/subscriptions/${subscriptionId}/first-invoice`, + origin + ) + ); + expect( + new Headers(fetchImpl.mock.calls[0][1]?.headers).get('authorization') + ).toBe('Bearer header.payload.signature'); + expect( + fetchImpl.mock.calls.some(([input]) => + String(input).includes('/first-invoice/confirm') + ) + ).toBe(false); + + fireEvent.click(screen.getByRole('button', { name: 'Sign out' })); + await screen.findByRole('heading', { name: 'Sign in to Account' }); + expect( + screen.getByText(/Account token revocation is not available here/) + ).toBeTruthy(); + expect(clearQueryCache).toHaveBeenCalled(); + expect( + fetchImpl.mock.calls.some(([input]) => + String(input).includes('/auth/logout') + ) + ).toBe(false); + }); + + it('fails closed before network or Stripe loading when the Vite key is missing', () => { + const queries = new QueryClient(); + const fetchImpl = vi.fn(); + const api: AccountControlUiApi = { login: vi.fn() }; + const loadStripeClient = vi.fn(); + const sessionStore = createControlUiSessionStore({ + origin: () => origin, + fetchImpl, + idFactory: makeIds(), + clearQueryCache: () => queries.clear(), + }); + stores.add(sessionStore); + window.history.replaceState({}, '', checkoutPath); + render( + + + + ); + expect(screen.getByText(/No checkout request was sent/)).toBeTruthy(); + expect(fetchImpl).not.toHaveBeenCalled(); + expect(api.login).not.toHaveBeenCalled(); + expect(loadStripeClient).not.toHaveBeenCalled(); + }); + + it('handles browser Back and Forward by remounting read-only checkout without confirming', async () => { + const { fetchImpl } = setupApp(); + await signIn(); + expect(fetchImpl).toHaveBeenCalledOnce(); + + window.history.pushState({}, '', '/'); + window.dispatchEvent(new PopStateEvent('popstate')); + expect( + await screen.findByRole('heading', { name: 'Vite + React' }) + ).toBeTruthy(); + + window.history.pushState({}, '', checkoutPath); + window.dispatchEvent(new PopStateEvent('popstate')); + await screen.findByText('in_existing'); + await waitFor(() => expect(fetchImpl).toHaveBeenCalledTimes(2)); + expect( + fetchImpl.mock.calls.some(([input]) => + String(input).includes('/first-invoice/confirm') + ) + ).toBe(false); + }); + + it('hides replaced Stripe context and ignores a stale loader result without confirming', async () => { + const stripeA: HostingStripe = { handleNextAction: vi.fn() }; + const stripeB: HostingStripe = { handleNextAction: vi.fn() }; + const stripeC: HostingStripe = { handleNextAction: vi.fn() }; + const loadA = vi.fn().mockResolvedValue(stripeA); + const { api, fetchImpl, queries, rerender, sessionStore } = setupApp({ + loadStripeClient: loadA, + }); + await signIn(); + expect(screen.getByText('Hosting first invoice')).toBeTruthy(); + + const loadBDeferred = deferred(); + const loadB = vi.fn().mockReturnValue(loadBDeferred.promise); + const renderWith = ( + key: string, + loadStripeClient: (publishableKey: string) => Promise + ) => + rerender( + + + + ); + + renderWith('pk_test_replaced', loadB); + expect(screen.queryByText('Hosting first invoice')).toBeNull(); + expect( + screen.getByText('Loading secure payment authentication.') + ).toBeTruthy(); + await waitFor(() => expect(loadB).toHaveBeenCalledWith('pk_test_replaced')); + + const loadCDeferred = deferred(); + const loadC = vi.fn().mockReturnValue(loadCDeferred.promise); + renderWith('pk_test_replacedagain', loadC); + await waitFor(() => + expect(loadC).toHaveBeenCalledWith('pk_test_replacedagain') + ); + + await act(async () => { + loadBDeferred.resolve(stripeB); + await loadBDeferred.promise; + }); + expect(screen.queryByText('Hosting first invoice')).toBeNull(); + expect( + screen.getByText('Loading secure payment authentication.') + ).toBeTruthy(); + + await act(async () => { + loadCDeferred.resolve(stripeC); + await loadCDeferred.promise; + }); + await screen.findByText('in_existing'); + expect( + fetchImpl.mock.calls.some(([input]) => String(input).includes('/confirm')) + ).toBe(false); + expect(stripeA.handleNextAction).not.toHaveBeenCalled(); + expect(stripeB.handleNextAction).not.toHaveBeenCalled(); + expect(stripeC.handleNextAction).not.toHaveBeenCalled(); + }); + + it('unmounts the checkout and returns to login when Account rejects the current bearer', async () => { + const { sessionStore, fetchImpl } = setupApp({ invoiceStatus: 403 }); + fireEvent.change(screen.getByLabelText('Account email'), { + target: { value: 'owner@example.com' }, + }); + fireEvent.change(screen.getByLabelText('Primary authentication secret'), { + target: { value: 'primary-secret' }, + }); + fireEvent.click(screen.getByRole('button', { name: 'Sign in' })); + await waitFor(() => expect(fetchImpl).toHaveBeenCalledOnce()); + await waitFor(() => expect(sessionStore.getSession()).toBeNull()); + await screen.findByRole('heading', { name: 'Sign in to Account' }); + expect(screen.queryByText('Hosting first invoice')).toBeNull(); + }); +}); diff --git a/web-client/src/account/AccountCheckoutRoute.tsx b/web-client/src/account/AccountCheckoutRoute.tsx new file mode 100644 index 0000000000..0df8beb570 --- /dev/null +++ b/web-client/src/account/AccountCheckoutRoute.tsx @@ -0,0 +1,403 @@ +import { + useEffect, + useLayoutEffect, + useMemo, + useRef, + useState, + useSyncExternalStore, + type FormEvent, +} from 'react'; +import Alert from '@mui/material/Alert'; +import Box from '@mui/material/Box'; +import Button from '@mui/material/Button'; +import CircularProgress from '@mui/material/CircularProgress'; +import Stack from '@mui/material/Stack'; +import TextField from '@mui/material/TextField'; +import Typography from '@mui/material/Typography'; +import { useQueryClient } from '@tanstack/react-query'; +import { + AccountControlUiApiError, + createAccountControlUiApi, + type AccountControlUiApi, +} from '../api/accountControlUi'; +import { createFirstInvoiceClient } from '../api/hostingFirstInvoice'; +import HostingFirstInvoiceCheckout from '../billing/HostingFirstInvoiceCheckout'; +import { + loadHostingStripe, + type HostingStripe, +} from '../billing/hostingStripe'; +import { queryClient } from '../api/queryClient'; +import { + ControlUiSessionError, + createControlUiSessionStore, + type ControlUiCredentials, + type ControlUiSessionStore, +} from './controlUiSession'; + +const subscriptionRoute = + /^\/account\/subscriptions\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/checkout\/?$/i; +const publishableKeyPattern = /^pk_(test|live)_[A-Za-z0-9]+$/; + +export interface AccountCheckoutRouteProps { + pathname: string; + sessionStore?: ControlUiSessionStore; + api?: AccountControlUiApi; + stripePublishableKey?: string; + loadStripeClient?: (publishableKey: string) => Promise; +} + +const defaultSessionStore = createControlUiSessionStore({ + origin: () => window.location.origin, + fetchImpl: (input, init) => fetch(input, init), + clearQueryCache: () => queryClient.clear(), +}); +const defaultLoginApi = createAccountControlUiApi( + () => window.location.origin, + (input, init) => fetch(input, init) +); + +function parseSubscriptionId(pathname: string): string | null { + const match = subscriptionRoute.exec(pathname); + return match?.[1].toLowerCase() ?? null; +} + +export default function AccountCheckoutRoute({ + pathname, + sessionStore = defaultSessionStore, + api = defaultLoginApi, + stripePublishableKey = import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY, + loadStripeClient = loadHostingStripe, +}: AccountCheckoutRouteProps) { + const subscriptionId = parseSubscriptionId(pathname); + const publishableKey = stripePublishableKey ?? ''; + + if (!subscriptionId) { + return ( + + This account checkout route is invalid. + + ); + } + + if (!publishableKeyPattern.test(publishableKey)) { + return ( + + + Hosting checkout + + + Checkout is unavailable because the Stripe publishable key is not + configured. No checkout request was sent. + + + ); + } + + return ( + + ); +} + +interface ActiveRouteProps { + subscriptionId: string; + sessionStore: ControlUiSessionStore; + api: AccountControlUiApi; + stripePublishableKey: string; + loadStripeClient: (publishableKey: string) => Promise; +} + +function ActiveAccountCheckoutRoute({ + subscriptionId, + sessionStore, + api, + stripePublishableKey, + loadStripeClient, +}: ActiveRouteProps) { + const queryClient = useQueryClient(); + const session = useSyncExternalStore( + sessionStore.subscribe, + sessionStore.getSession, + () => null + ); + const previousIdentity = useRef(session?.identity ?? null); + const [signoutNotice, setSignoutNotice] = useState(''); + + useLayoutEffect(() => { + const nextIdentity = session?.identity ?? null; + if (previousIdentity.current !== nextIdentity) { + // A cache belongs to one memory-only authority identity. Clear it before + // the next route's passive query effects can run. + queryClient.clear(); + previousIdentity.current = nextIdentity; + } + }, [queryClient, session?.identity]); + + if (!session) { + return ( + + ); + } + + return ( + + + + + + Hosting checkout + + + Signed in to Account {session.accountId} + + + + + + Sign out clears this browser's in-memory session. It does not + revoke the Account token or cancel a confirmation already sent. + + + + + ); +} + +interface CheckoutProps { + subscriptionId: string; + sessionStore: ControlUiSessionStore; + sessionIdentity: string; + stripePublishableKey: string; + loadStripeClient: (publishableKey: string) => Promise; +} + +type StripeLoadResult = + | { + sessionIdentity: string; + publishableKey: string; + loader: CheckoutProps['loadStripeClient']; + status: 'ready'; + stripe: HostingStripe; + } + | { + sessionIdentity: string; + publishableKey: string; + loader: CheckoutProps['loadStripeClient']; + status: 'unavailable'; + }; + +function CheckoutForSession({ + subscriptionId, + sessionStore, + sessionIdentity, + stripePublishableKey, + loadStripeClient, +}: CheckoutProps) { + const [stripeLoadResult, setStripeLoadResult] = + useState(null); + const client = useMemo( + () => + createFirstInvoiceClient( + sessionStore.getGatewayOrigin(), + sessionStore.authenticatedRequest + ), + [sessionStore] + ); + + useEffect(() => { + let current = true; + void Promise.resolve() + .then(() => loadStripeClient(stripePublishableKey)) + .then( + (loaded) => { + if (current) { + setStripeLoadResult({ + sessionIdentity, + publishableKey: stripePublishableKey, + loader: loadStripeClient, + status: 'ready', + stripe: loaded, + }); + } + }, + () => { + if (current) { + setStripeLoadResult({ + sessionIdentity, + publishableKey: stripePublishableKey, + loader: loadStripeClient, + status: 'unavailable', + }); + } + } + ); + return () => { + current = false; + }; + }, [loadStripeClient, sessionIdentity, stripePublishableKey]); + + const matchingResult = + stripeLoadResult?.sessionIdentity === sessionIdentity && + stripeLoadResult.publishableKey === stripePublishableKey && + stripeLoadResult.loader === loadStripeClient + ? stripeLoadResult + : null; + + if (matchingResult?.status === 'unavailable') { + return ( + + Stripe authentication is unavailable. Account payment status remains + unchanged. + + ); + } + if (matchingResult?.status !== 'ready') { + return ( + + + Loading secure payment authentication. + + ); + } + return ( + + ); +} + +interface LoginFormProps { + api: AccountControlUiApi; + sessionStore: ControlUiSessionStore; + notice: string; +} + +function AccountLoginForm({ api, sessionStore, notice }: LoginFormProps) { + const [email, setEmail] = useState(''); + const [secret, setSecret] = useState(''); + const [busy, setBusy] = useState(false); + const [message, setMessage] = useState(''); + const locked = useRef(false); + + async function submit(event: FormEvent) { + event.preventDefault(); + if (locked.current || busy) return; + locked.current = true; + setBusy(true); + setMessage(''); + const credentials: ControlUiCredentials = { + email: email.trim(), + secret, + }; + setSecret(''); + try { + await sessionStore.signIn(api, credentials); + } catch (error) { + if (error instanceof AccountControlUiApiError && error.status === 503) { + setMessage('Account sign-in is temporarily unavailable. Try again.'); + } else if ( + error instanceof ControlUiSessionError && + error.code === 'SESSION_REPLACED' + ) { + setMessage('This sign-in attempt was replaced. Sign in again.'); + } else { + setMessage( + 'Sign-in could not be completed. Check your email and primary authentication secret.' + ); + } + } finally { + credentials.secret = ''; + locked.current = false; + setBusy(false); + } + } + + return ( + + void submit(event)} + > + + Sign in to Account + + + Sign in to review the existing hosting invoice. Sign-in does not + authorize a payment. + + {notice && {notice}} + setEmail(event.target.value)} + slotProps={{ htmlInput: { maxLength: 254 } }} + /> + setSecret(event.target.value)} + slotProps={{ htmlInput: { maxLength: 1024 } }} + /> + + {message && ( + + {message} + + )} + + Sign out clears this browser's in-memory session. It does not + confirm server-side token revocation. + + + + ); +} diff --git a/web-client/src/account/controlUiSession.test.ts b/web-client/src/account/controlUiSession.test.ts new file mode 100644 index 0000000000..ec463e10ef --- /dev/null +++ b/web-client/src/account/controlUiSession.test.ts @@ -0,0 +1,335 @@ +// @vitest-environment jsdom +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type { + AccountControlUiApi, + AccountControlUiLoginRequest, +} from '../api/accountControlUi'; +import { + ControlUiSessionError, + createControlUiSessionStore, +} from './controlUiSession'; + +const origin = 'https://gateway.example.test'; +const accountId = '11111111-1111-4111-8111-111111111111'; +const subscriptionId = '22222222-2222-4222-8222-222222222222'; +const authToken = 'header.payload.signature'; +const stores = new Set>(); + +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +function ids() { + const values = [ + '33333333-3333-4333-8333-333333333333', + '44444444-4444-4444-8444-444444444444', + '55555555-5555-4555-8555-555555555555', + '66666666-6666-4666-8666-666666666666', + '77777777-7777-4777-8777-777777777777', + '88888888-8888-4888-8888-888888888888', + '99999999-9999-4999-8999-999999999999', + ]; + let index = 0; + return () => values[index++] ?? 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'; +} + +function successfulLogin( + expiresAt = new Date(Date.now() + 60_000).toISOString() +) { + return { + accountId, + authToken, + expiresAt, + }; +} + +function makeStore( + options: { + fetchImpl?: typeof fetch; + now?: () => number; + clearQueryCache?: () => void; + } = {} +) { + const store = createControlUiSessionStore({ + origin: () => origin, + fetchImpl: options.fetchImpl ?? vi.fn(), + now: options.now, + idFactory: ids(), + clearQueryCache: options.clearQueryCache, + }); + stores.add(store); + return store; +} + +function loginApi(result = successfulLogin()): AccountControlUiApi { + return { + login: vi.fn().mockResolvedValue(result), + }; +} + +function getRequest( + url = new URL( + `/api/account/billing/hosting/subscriptions/${subscriptionId}/first-invoice`, + origin + ) +) { + return { + url, + init: { method: 'GET', headers: { Accept: 'application/json' } }, + }; +} + +afterEach(() => { + for (const store of stores) store.signOut(); + stores.clear(); + vi.useRealTimers(); + vi.restoreAllMocks(); +}); + +describe('memory-only control-ui session owner', () => { + it('uses one login attempt with stable IDs and attaches the current bearer only to the exact owner read', async () => { + const fetchImpl = vi.fn().mockResolvedValue( + new Response(JSON.stringify({ state: 'AWAITING_PAYMENT' }), { + status: 200, + }) + ); + const store = makeStore({ fetchImpl }); + const sentLoginRequests: AccountControlUiLoginRequest[] = []; + const login = vi + .fn() + .mockImplementation(async (request) => { + sentLoginRequests.push({ ...request }); + return successfulLogin(); + }); + const api: AccountControlUiApi = { login }; + + const session = await store.signIn(api, { + email: 'owner@example.com', + secret: 'primary-secret', + }); + const [loginRequest] = sentLoginRequests; + expect(login).toHaveBeenCalledOnce(); + expect(loginRequest).toMatchObject({ + requestId: expect.stringMatching(/^[0-9a-f-]{36}$/i), + callerContextId: expect.stringMatching(/^[0-9a-f-]{36}$/i), + email: 'owner@example.com', + secret: 'primary-secret', + }); + expect(login.mock.calls[0][0].secret).toBe(''); + expect(session).not.toHaveProperty('authToken'); + + const { url, init } = getRequest(); + const response = await store.authenticatedRequest(url, init); + expect(await response.json()).toEqual({ state: 'AWAITING_PAYMENT' }); + expect(fetchImpl).toHaveBeenCalledOnce(); + const [sentUrl, sentInit] = fetchImpl.mock.calls[0]; + expect(sentUrl).toEqual(url); + expect(new Headers(sentInit?.headers).get('authorization')).toBe( + `Bearer ${authToken}` + ); + expect(sentInit).toMatchObject({ + method: 'GET', + credentials: 'omit', + cache: 'no-store', + redirect: 'error', + referrerPolicy: 'no-referrer', + mode: 'same-origin', + }); + expect(window.localStorage.length).toBe(0); + expect(window.sessionStorage.length).toBe(0); + }); + + it('rejects cross-origin, non-HTTPS, wrong-route, and caller-supplied bearer requests before dispatch', async () => { + const fetchImpl = vi.fn(); + const store = makeStore({ fetchImpl }); + await store.signIn(loginApi(), { + email: 'owner@example.com', + secret: 'primary-secret', + }); + + const cases = [ + getRequest( + new URL( + `/api/account/billing/hosting/subscriptions/${subscriptionId}/first-invoice`, + 'https://attacker.example.test' + ) + ), + getRequest( + new URL( + `/api/account/billing/hosting/subscriptions/${subscriptionId}/first-invoice`, + 'http://gateway.example.test' + ) + ), + getRequest(new URL('/api/account/auth/logout', origin)), + { + ...getRequest(), + init: { + method: 'GET', + headers: { + Accept: 'application/json', + Authorization: 'Bearer caller-supplied', + }, + }, + }, + ]; + + for (const { url, init } of cases) { + await expect( + store.authenticatedRequest(url, init) + ).rejects.toBeInstanceOf(ControlUiSessionError); + } + expect(fetchImpl).not.toHaveBeenCalled(); + }); + + it('clears local auth and query state on expiry and sign-out', async () => { + vi.useFakeTimers(); + const clearQueryCache = vi.fn(); + const store = makeStore({ clearQueryCache }); + await store.signIn(loginApi(), { + email: 'owner@example.com', + secret: 'primary-secret', + }); + expect(store.getSession()).not.toBeNull(); + + vi.advanceTimersByTime(60_001); + expect(store.getSession()).toBeNull(); + expect(clearQueryCache).toHaveBeenCalled(); + + const secondStore = makeStore({ clearQueryCache }); + await secondStore.signIn(loginApi(), { + email: 'owner@example.com', + secret: 'primary-secret', + }); + const countBeforeSignOut = clearQueryCache.mock.calls.length; + secondStore.signOut(); + expect(secondStore.getSession()).toBeNull(); + expect(clearQueryCache.mock.calls.length).toBe(countBeforeSignOut + 1); + }); + + it('keeps an ordinary 503 session but clears it after an authentication rejection', async () => { + const fetchImpl = vi + .fn() + .mockResolvedValue( + new Response('private error details', { status: 503 }) + ); + const store = makeStore({ fetchImpl }); + await store.signIn(loginApi(), { + email: 'owner@example.com', + secret: 'primary-secret', + }); + const { url, init } = getRequest(); + const unavailable = await store.authenticatedRequest(url, init); + expect(unavailable.status).toBe(503); + expect(store.getSession()).not.toBeNull(); + + fetchImpl.mockResolvedValue( + new Response('private error details', { status: 401 }) + ); + await expect(store.authenticatedRequest(url, init)).rejects.toMatchObject({ + code: 'AUTH_REJECTED', + }); + expect(store.getSession()).toBeNull(); + }); + + it('denies a stale owner response after sign-out even if fetch ignores abort', async () => { + const pending = deferred(); + const fetchImpl = vi.fn().mockReturnValue(pending.promise); + const store = makeStore({ fetchImpl }); + await store.signIn(loginApi(), { + email: 'owner@example.com', + secret: 'primary-secret', + }); + const { url, init } = getRequest(); + const request = store.authenticatedRequest(url, init); + await Promise.resolve(); + expect(fetchImpl).toHaveBeenCalledOnce(); + + store.signOut(); + pending.resolve( + new Response(JSON.stringify({ state: 'COMMITTED' }), { status: 200 }) + ); + await expect(request).rejects.toMatchObject({ code: 'SESSION_REPLACED' }); + expect(store.getSession()).toBeNull(); + }); + + it('aborts and denies old owner work when a signed-in identity is replaced', async () => { + const pending = deferred(); + const fetchImpl = vi.fn().mockReturnValue(pending.promise); + const clearQueryCache = vi.fn(); + const store = makeStore({ fetchImpl, clearQueryCache }); + await store.signIn(loginApi(), { + email: 'first@example.com', + secret: 'first-secret', + }); + const oldSession = store.getSession(); + const { url, init } = getRequest(); + const request = store.authenticatedRequest(url, init); + expect(fetchImpl).toHaveBeenCalledOnce(); + + const nextSession = await store.signIn( + loginApi({ + accountId, + authToken: 'next.header.signature', + expiresAt: new Date(Date.now() + 60_000).toISOString(), + }), + { email: 'second@example.com', secret: 'second-secret' } + ); + pending.resolve( + new Response(JSON.stringify({ state: 'COMMITTED' }), { status: 200 }) + ); + + await expect(request).rejects.toMatchObject({ code: 'SESSION_REPLACED' }); + expect(oldSession?.identity).not.toBe(nextSession.identity); + expect(store.getSession()?.identity).toBe(nextSession.identity); + expect(clearQueryCache.mock.calls.length).toBeGreaterThanOrEqual(3); + }); + + it('denies a stale login response when a newer attempt replaces it', async () => { + const earlier = deferred>(); + const login = vi + .fn() + .mockReturnValueOnce(earlier.promise) + .mockResolvedValueOnce(successfulLogin()); + const store = makeStore(); + const api: AccountControlUiApi = { login }; + + const first = store + .signIn(api, { email: 'first@example.com', secret: 'first-secret' }) + .catch((error: unknown) => error); + const second = await store.signIn(api, { + email: 'second@example.com', + secret: 'second-secret', + }); + earlier.resolve(successfulLogin()); + + expect(await first).toMatchObject({ code: 'SESSION_REPLACED' }); + expect(store.getSession()?.identity).toBe(second.identity); + expect(login).toHaveBeenCalledTimes(2); + expect(login.mock.calls[0][0].requestId).not.toBe( + login.mock.calls[1][0].requestId + ); + }); + + it('rejects a buffered success body if the session changes before JSON is consumed', async () => { + const fetchImpl = vi.fn().mockResolvedValue( + new Response(JSON.stringify({ state: 'AWAITING_PAYMENT' }), { + status: 200, + }) + ); + const store = makeStore({ fetchImpl }); + await store.signIn(loginApi(), { + email: 'owner@example.com', + secret: 'primary-secret', + }); + const { url, init } = getRequest(); + const response = await store.authenticatedRequest(url, init); + store.signOut(); + await expect(response.json()).rejects.toMatchObject({ + code: 'SESSION_REPLACED', + }); + }); +}); diff --git a/web-client/src/account/controlUiSession.ts b/web-client/src/account/controlUiSession.ts new file mode 100644 index 0000000000..8571c3cb10 --- /dev/null +++ b/web-client/src/account/controlUiSession.ts @@ -0,0 +1,529 @@ +import { + maxControlUiSessionLifetimeMs, + type AccountControlUiApi, + type AccountControlUiLoginRequest, + type AccountControlUiLoginResult, +} from '../api/accountControlUi'; + +export interface ControlUiSessionView { + readonly identity: string; + readonly accountId: string; + readonly expiresAt: string; +} + +export interface ControlUiCredentials { + email: string; + secret: string; +} + +export type ControlUiSessionErrorCode = + | 'SESSION_REQUIRED' + | 'SESSION_EXPIRED' + | 'SESSION_REPLACED' + | 'AUTH_REJECTED' + | 'REQUEST_CANCELLED' + | 'REQUEST_FAILED' + | 'INVALID_RESPONSE'; + +export class ControlUiSessionError extends Error { + readonly code: ControlUiSessionErrorCode; + + constructor(code: ControlUiSessionErrorCode) { + super('The account session is unavailable.'); + this.name = 'ControlUiSessionError'; + this.code = code; + } +} + +export interface ControlUiSessionOptions { + origin: () => string; + fetchImpl?: typeof fetch; + now?: () => number; + idFactory?: () => string; + clearQueryCache?: () => void; +} + +const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const jwt = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/; +const ownerPath = + /^\/api\/account\/billing\/hosting\/subscriptions\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/first-invoice(?:\/(reauthenticate|confirm|renew))?$/i; +const maxOwnerRequestBytes = 16 * 1024; +const maxOwnerResponseBytes = 64 * 1024; + +function secureOrigin(value: string): URL { + let parsed: URL; + try { + parsed = new URL(value); + } catch { + throw new ControlUiSessionError('REQUEST_FAILED'); + } + if ( + parsed.protocol !== 'https:' || + parsed.username || + parsed.password || + parsed.pathname !== '/' || + parsed.search || + parsed.hash + ) { + throw new ControlUiSessionError('REQUEST_FAILED'); + } + return parsed; +} + +function checkedLoginResult( + result: AccountControlUiLoginResult, + now: number +): number { + if ( + typeof result.accountId !== 'string' || + !uuid.test(result.accountId) || + typeof result.authToken !== 'string' || + result.authToken.length > 16_384 || + !jwt.test(result.authToken) || + typeof result.expiresAt !== 'string' + ) { + throw new ControlUiSessionError('INVALID_RESPONSE'); + } + const expiry = Date.parse(result.expiresAt); + if ( + !Number.isFinite(expiry) || + expiry <= now || + expiry - now > maxControlUiSessionLifetimeMs + ) { + throw new ControlUiSessionError('INVALID_RESPONSE'); + } + return expiry; +} + +function makeUuid(): string { + if (!globalThis.crypto?.randomUUID) { + throw new ControlUiSessionError('REQUEST_FAILED'); + } + return globalThis.crypto.randomUUID(); +} + +async function readBoundedBytes( + response: Response, + signal: AbortSignal +): Promise { + if (!response.body) return new Uint8Array(); + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let size = 0; + try { + for (;;) { + if (signal.aborted) throw new ControlUiSessionError('REQUEST_CANCELLED'); + const { done, value } = await reader.read(); + if (done) break; + size += value.byteLength; + if (size > maxOwnerResponseBytes) { + await reader.cancel(); + throw new ControlUiSessionError('REQUEST_FAILED'); + } + chunks.push(value); + } + } catch { + try { + await reader.cancel(); + } catch { + // The response body is private Account data and is never surfaced here. + } + throw new ControlUiSessionError('REQUEST_FAILED'); + } + const bytes = new Uint8Array(size); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } + return bytes; +} + +function validateOwnerRequest( + url: URL, + init: RequestInit, + origin: URL +): string { + if ( + url.protocol !== 'https:' || + url.origin !== origin.origin || + url.username || + url.password || + url.search || + url.hash + ) { + throw new ControlUiSessionError('REQUEST_FAILED'); + } + const match = ownerPath.exec(url.pathname); + if (!match) throw new ControlUiSessionError('REQUEST_FAILED'); + const expectedMethod = match[2] ? 'POST' : 'GET'; + const method = (init.method ?? 'GET').toUpperCase(); + if (method !== expectedMethod) + throw new ControlUiSessionError('REQUEST_FAILED'); + if (method === 'GET' && init.body != null) { + throw new ControlUiSessionError('REQUEST_FAILED'); + } + if ( + method === 'POST' && + (typeof init.body !== 'string' || init.body.length > maxOwnerRequestBytes) + ) { + throw new ControlUiSessionError('REQUEST_FAILED'); + } + + let headers: Headers; + try { + headers = new Headers(init.headers); + } catch { + throw new ControlUiSessionError('REQUEST_FAILED'); + } + if (headers.has('authorization')) { + throw new ControlUiSessionError('REQUEST_FAILED'); + } + for (const [name, value] of headers.entries()) { + if ( + name.toLowerCase() !== 'accept' && + name.toLowerCase() !== 'content-type' + ) { + throw new ControlUiSessionError('REQUEST_FAILED'); + } + if ( + name.toLowerCase() === 'content-type' && + value.toLowerCase() !== 'application/json' + ) { + throw new ControlUiSessionError('REQUEST_FAILED'); + } + } + if (method === 'POST' && headers.get('content-type') !== 'application/json') { + throw new ControlUiSessionError('REQUEST_FAILED'); + } + return method; +} + +function guardedJsonResponse( + status: number, + bytes: Uint8Array, + assertCurrent: () => void, + contentType: string +): Response { + const body = new ArrayBuffer(bytes.byteLength); + new Uint8Array(body).set(bytes); + const response = new Response(body, { + status, + headers: { + 'Content-Type': contentType, + 'Cache-Control': 'no-store', + }, + }); + const json = response.json.bind(response); + Object.defineProperty(response, 'json', { + configurable: false, + value: async () => { + assertCurrent(); + const value = await json(); + assertCurrent(); + return value; + }, + }); + return response; +} + +/** + * Memory-only owner for the current Account control-ui token. It is intentionally + * narrower than a general API client: only the exact first-invoice owner paths + * can receive the bearer, and local sign-out makes no server revocation claim. + */ +export class ControlUiSessionStore { + private readonly listeners = new Set<() => void>(); + private readonly requests = new Set(); + private readonly origin: () => string; + private readonly fetchImpl: typeof fetch; + private readonly now: () => number; + private readonly idFactory: () => string; + private readonly clearQueryCache?: () => void; + private snapshot: ControlUiSessionView | null = null; + private bearer: string | null = null; + private revision = 0; + private loginController: AbortController | null = null; + private expiryTimer: ReturnType | null = null; + + constructor(options: ControlUiSessionOptions) { + this.origin = options.origin; + this.fetchImpl = options.fetchImpl ?? fetch; + this.now = options.now ?? Date.now; + this.idFactory = options.idFactory ?? makeUuid; + this.clearQueryCache = options.clearQueryCache; + } + + readonly getSession = (): ControlUiSessionView | null => { + if (this.snapshot && this.now() >= Date.parse(this.snapshot.expiresAt)) { + return null; + } + return this.snapshot; + }; + + readonly getGatewayOrigin = (): string => secureOrigin(this.origin()).origin; + + readonly subscribe = (listener: () => void): (() => void) => { + this.listeners.add(listener); + return () => this.listeners.delete(listener); + }; + + readonly authenticatedRequest = async ( + input: URL, + init: RequestInit + ): Promise => { + let target: URL; + let origin: URL; + let method: string; + try { + origin = secureOrigin(this.origin()); + target = new URL(input.href); + method = validateOwnerRequest(target, init, origin); + } catch (error) { + if (error instanceof ControlUiSessionError) throw error; + throw new ControlUiSessionError('REQUEST_FAILED'); + } + + const session = this.requireCurrentSession(); + const revision = this.revision; + const bearer = this.bearer; + if (!bearer) throw new ControlUiSessionError('SESSION_REQUIRED'); + + const controller = new AbortController(); + const externalSignal = init.signal; + const cancelFromCaller = () => controller.abort(); + if (externalSignal?.aborted) controller.abort(); + else + externalSignal?.addEventListener('abort', cancelFromCaller, { + once: true, + }); + this.requests.add(controller); + + const isCurrent = () => + this.revision === revision && + this.snapshot?.identity === session.identity && + this.bearer === bearer && + this.now() < Date.parse(session.expiresAt); + const assertCurrent = () => { + if ( + this.revision === revision && + this.snapshot?.identity === session.identity && + this.bearer === bearer && + this.now() >= Date.parse(session.expiresAt) + ) { + this.clearIfCurrent(session.identity, revision); + throw new ControlUiSessionError('SESSION_EXPIRED'); + } + if (!isCurrent()) throw new ControlUiSessionError('SESSION_REPLACED'); + }; + + try { + assertCurrent(); + + const headers = new Headers(init.headers); + headers.set('Authorization', `Bearer ${bearer}`); + let response: Response; + try { + response = await this.fetchImpl(target, { + method, + headers, + ...(init.body !== undefined ? { body: init.body } : {}), + cache: 'no-store', + credentials: 'omit', + redirect: 'error', + referrerPolicy: 'no-referrer', + mode: 'same-origin', + signal: controller.signal, + }); + } catch { + assertCurrent(); + throw new ControlUiSessionError( + controller.signal.aborted ? 'REQUEST_CANCELLED' : 'REQUEST_FAILED' + ); + } + + assertCurrent(); + if (response.status === 401 || response.status === 403) { + this.clearIfCurrent(session.identity, revision); + throw new ControlUiSessionError('AUTH_REJECTED'); + } + if (!response.ok) { + try { + await response.body?.cancel(); + } catch { + // Error bodies may contain sensitive provider or Account details. + } + assertCurrent(); + return new Response(null, { + status: response.status, + headers: { 'Cache-Control': 'no-store' }, + }); + } + if (response.status !== 200) { + try { + await response.body?.cancel(); + } catch { + // A success response outside the owner contract is discarded. + } + assertCurrent(); + throw new ControlUiSessionError('REQUEST_FAILED'); + } + + const bytes = await readBoundedBytes(response, controller.signal); + assertCurrent(); + return guardedJsonResponse( + response.status, + bytes, + assertCurrent, + response.headers.get('content-type') ?? 'application/json' + ); + } finally { + externalSignal?.removeEventListener('abort', cancelFromCaller); + this.requests.delete(controller); + } + }; + + async signIn( + api: AccountControlUiApi, + credentials: ControlUiCredentials + ): Promise { + const hadSession = this.snapshot !== null || this.bearer !== null; + const revision = this.beginReplacement(); + if (hadSession) this.emitSessionChange(); + const controller = new AbortController(); + this.loginController = controller; + const request: AccountControlUiLoginRequest = { + requestId: this.idFactory(), + callerContextId: this.idFactory(), + email: credentials.email, + secret: credentials.secret, + }; + + try { + const result = await api.login(request, controller.signal); + if ( + controller.signal.aborted || + this.revision !== revision || + this.loginController !== controller + ) { + throw new ControlUiSessionError('SESSION_REPLACED'); + } + + const expiry = checkedLoginResult(result, this.now()); + const identity = this.idFactory(); + if (!uuid.test(identity)) + throw new ControlUiSessionError('INVALID_RESPONSE'); + const next: ControlUiSessionView = Object.freeze({ + identity, + accountId: result.accountId, + expiresAt: result.expiresAt, + }); + this.snapshot = next; + this.bearer = result.authToken; + this.scheduleExpiry(next.identity, revision, expiry); + this.loginController = null; + this.emitSessionChange(); + return next; + } catch (error) { + if ( + controller.signal.aborted || + this.revision !== revision || + this.loginController !== controller + ) { + throw new ControlUiSessionError('SESSION_REPLACED'); + } + this.loginController = null; + throw error; + } finally { + request.secret = ''; + } + } + + /** Clear only this browser's in-memory credentials; no remote logout is sent. */ + signOut(): void { + const hadSession = this.snapshot !== null || this.bearer !== null; + this.beginReplacement(); + if (hadSession) this.emitSessionChange(); + } + + private requireCurrentSession(): ControlUiSessionView { + if (this.snapshot && this.now() >= Date.parse(this.snapshot.expiresAt)) { + const { identity } = this.snapshot; + this.clearIfCurrent(identity, this.revision); + throw new ControlUiSessionError('SESSION_EXPIRED'); + } + if (!this.snapshot || !this.bearer) { + throw new ControlUiSessionError('SESSION_REQUIRED'); + } + return this.snapshot; + } + + private beginReplacement(): number { + this.revision += 1; + this.loginController?.abort(); + this.loginController = null; + this.abortRequests(); + this.clearExpiryTimer(); + this.snapshot = null; + this.bearer = null; + return this.revision; + } + + private expireIfCurrent(identity: string, revision: number): void { + if ( + this.revision === revision && + this.snapshot?.identity === identity && + this.now() >= Date.parse(this.snapshot.expiresAt) + ) { + this.clearIfCurrent(identity, revision); + } + } + + private clearIfCurrent(identity: string, revision: number): void { + if (this.revision !== revision || this.snapshot?.identity !== identity) { + return; + } + this.beginReplacement(); + this.emitSessionChange(); + } + + private scheduleExpiry( + identity: string, + revision: number, + expiry: number + ): void { + this.clearExpiryTimer(); + this.expiryTimer = setTimeout( + () => { + this.expiryTimer = null; + this.expireIfCurrent(identity, revision); + }, + Math.max(0, expiry - this.now()) + ); + } + + private clearExpiryTimer(): void { + if (this.expiryTimer !== null) clearTimeout(this.expiryTimer); + this.expiryTimer = null; + } + + private abortRequests(): void { + for (const controller of this.requests) controller.abort(); + this.requests.clear(); + } + + private emitSessionChange(): void { + try { + this.clearQueryCache?.(); + } catch { + // Cache clearing must not restore or retain the invalidated token. + } + for (const listener of this.listeners) listener(); + } +} + +export function createControlUiSessionStore( + options: ControlUiSessionOptions +): ControlUiSessionStore { + return new ControlUiSessionStore(options); +} diff --git a/web-client/src/api/accountControlUi.test.ts b/web-client/src/api/accountControlUi.test.ts new file mode 100644 index 0000000000..928aa72486 --- /dev/null +++ b/web-client/src/api/accountControlUi.test.ts @@ -0,0 +1,197 @@ +import { describe, expect, it, vi } from 'vitest'; +import { + AccountControlUiApiError, + createAccountControlUiApi, + maxControlUiSessionLifetimeMs, + type AccountControlUiLoginRequest, +} from './accountControlUi'; + +const origin = 'https://gateway.example.test'; +const accountId = '11111111-1111-4111-8111-111111111111'; +const requestId = '22222222-2222-4222-8222-222222222222'; +const callerContextId = '33333333-3333-4333-8333-333333333333'; +const now = Date.parse('2026-11-07T12:00:00.000Z'); +const authToken = 'header.payload.signature'; + +function successfulLogin(expiresAt = new Date(now + 60_000).toISOString()) { + return new Response( + JSON.stringify({ + status: 'SUCCESS', + data: { accountId, authToken, expiresAt }, + }), + { status: 200, headers: { 'Content-Type': 'application/json' } } + ); +} + +const loginRequest: AccountControlUiLoginRequest = { + requestId, + callerContextId, + email: 'owner@example.com', + secret: 'primary-secret', +}; + +const invalidResponses: Array<[string, () => unknown]> = [ + [ + 'extra response field', + () => ({ + status: 'SUCCESS', + data: { + accountId, + authToken, + expiresAt: new Date(now + 60_000).toISOString(), + }, + debug: 'unexpected', + }), + ], + [ + 'wrong status', + () => ({ + status: 'FAILED', + data: { + accountId, + authToken, + expiresAt: new Date(now + 60_000).toISOString(), + }, + }), + ], + [ + 'non-JWT bearer', + () => ({ + status: 'SUCCESS', + data: { + accountId, + authToken: 'not-a-jwt', + expiresAt: new Date(now + 60_000).toISOString(), + }, + }), + ], + [ + 'expired session', + () => ({ + status: 'SUCCESS', + data: { + accountId, + authToken, + expiresAt: new Date(now - 1).toISOString(), + }, + }), + ], + [ + 'unbounded session lifetime', + () => ({ + status: 'SUCCESS', + data: { + accountId, + authToken, + expiresAt: new Date( + now + maxControlUiSessionLifetimeMs + 1 + ).toISOString(), + }, + }), + ], +]; + +describe('account control-ui login transport', () => { + it('posts one stable request to the same-origin HTTPS Account route without cookies', async () => { + const fetchImpl = vi + .fn() + .mockResolvedValue(successfulLogin()); + const api = createAccountControlUiApi(origin, fetchImpl, () => now); + + await expect(api.login(loginRequest)).resolves.toEqual({ + accountId, + authToken, + expiresAt: new Date(now + 60_000).toISOString(), + }); + + expect(fetchImpl).toHaveBeenCalledOnce(); + const [input, init] = fetchImpl.mock.calls[0]; + expect(input).toEqual(new URL('/api/account/auth/login', origin)); + expect(init).toMatchObject({ + method: 'POST', + cache: 'no-store', + credentials: 'omit', + redirect: 'error', + referrerPolicy: 'no-referrer', + mode: 'same-origin', + }); + expect(JSON.parse(String(init?.body))).toEqual(loginRequest); + expect(init?.headers).toEqual({ + 'Content-Type': 'application/json', + Accept: 'application/json', + }); + }); + + it('does not retry a transport failure or expose secret or server text', async () => { + const fetchImpl = vi + .fn() + .mockRejectedValue(new Error('primary-secret leaked by transport')); + const api = createAccountControlUiApi(origin, fetchImpl, () => now); + + let error: unknown; + try { + await api.login(loginRequest); + } catch (caught) { + error = caught; + } + expect(fetchImpl).toHaveBeenCalledOnce(); + expect(error).toBeInstanceOf(AccountControlUiApiError); + expect((error as Error).message).not.toContain('primary-secret'); + }); + + it('discards non-success response bodies and preserves only the status', async () => { + const fetchImpl = vi + .fn() + .mockResolvedValue( + new Response('sensitive internal response', { status: 503 }) + ); + const api = createAccountControlUiApi(origin, fetchImpl, () => now); + + await expect(api.login(loginRequest)).rejects.toMatchObject({ + name: 'AccountControlUiApiError', + status: 503, + message: 'Account sign-in could not be completed.', + }); + expect(fetchImpl).toHaveBeenCalledOnce(); + }); + + it.each(invalidResponses)( + 'rejects %s response data', + async (_name, makeBody) => { + const fetchImpl = vi + .fn() + .mockResolvedValue( + new Response(JSON.stringify(makeBody()), { status: 200 }) + ); + const api = createAccountControlUiApi(origin, fetchImpl, () => now); + await expect(api.login(loginRequest)).rejects.toBeInstanceOf( + AccountControlUiApiError + ); + } + ); + + it('rejects insecure origins before dispatch', async () => { + const fetchImpl = vi.fn(); + expect(() => + createAccountControlUiApi('http://gateway.example.test', fetchImpl) + ).toThrow('same-origin HTTPS'); + const api = createAccountControlUiApi( + () => 'http://gateway.example.test', + fetchImpl + ); + await expect(api.login(loginRequest)).rejects.toBeInstanceOf(Error); + expect(fetchImpl).not.toHaveBeenCalled(); + }); + + it('rejects oversized response bodies', async () => { + const oversized = 'x'.repeat(40 * 1024); + const fetchImpl = vi + .fn() + .mockResolvedValue(new Response(oversized, { status: 200 })); + const api = createAccountControlUiApi(origin, fetchImpl, () => now); + + await expect(api.login(loginRequest)).rejects.toBeInstanceOf( + AccountControlUiApiError + ); + }); +}); diff --git a/web-client/src/api/accountControlUi.ts b/web-client/src/api/accountControlUi.ts new file mode 100644 index 0000000000..30f8e6cbc9 --- /dev/null +++ b/web-client/src/api/accountControlUi.ts @@ -0,0 +1,220 @@ +export interface AccountControlUiLoginRequest { + requestId: string; + callerContextId: string; + email: string; + secret: string; +} + +export interface AccountControlUiLoginResult { + accountId: string; + authToken: string; + expiresAt: string; +} + +export interface AccountControlUiApi { + login( + request: AccountControlUiLoginRequest, + signal?: AbortSignal + ): Promise; +} + +export class AccountControlUiApiError extends Error { + readonly status: number; + + constructor(status: number) { + super('Account sign-in could not be completed.'); + this.name = 'AccountControlUiApiError'; + this.status = status; + } +} + +const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const jwt = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/; +const timestamp = + /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/; +const maxLoginResponseBytes = 32 * 1024; +export const maxControlUiSessionLifetimeMs = 24 * 60 * 60 * 1000; + +function requireSecureOrigin(value: string): URL { + let origin: URL; + try { + origin = new URL(value); + } catch { + throw new Error('A same-origin HTTPS Gateway URL is required.'); + } + if ( + origin.protocol !== 'https:' || + origin.username || + origin.password || + origin.pathname !== '/' || + origin.search || + origin.hash + ) { + throw new Error('A same-origin HTTPS Gateway URL is required.'); + } + return origin; +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function hasExactKeys(value: Record, keys: string[]): boolean { + const actual = Object.keys(value).sort(); + const expected = [...keys].sort(); + return ( + actual.length === expected.length && + actual.every((key, index) => key === expected[index]) + ); +} + +async function readBoundedJson( + response: Response, + signal?: AbortSignal +): Promise { + if (!response.body) throw new AccountControlUiApiError(0); + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let size = 0; + try { + for (;;) { + if (signal?.aborted) throw new AccountControlUiApiError(0); + const { done, value } = await reader.read(); + if (done) break; + size += value.byteLength; + if (size > maxLoginResponseBytes) { + await reader.cancel(); + throw new AccountControlUiApiError(0); + } + chunks.push(value); + } + } catch { + try { + await reader.cancel(); + } catch { + // Do not expose a stream or transport error that could contain response data. + } + throw new AccountControlUiApiError(0); + } + + const bytes = new Uint8Array(size); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } + + try { + const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes); + return JSON.parse(text) as unknown; + } catch { + throw new AccountControlUiApiError(0); + } +} + +function parseLoginResult( + value: unknown, + now: number +): AccountControlUiLoginResult { + if ( + !isRecord(value) || + !hasExactKeys(value, ['status', 'data']) || + value.status !== 'SUCCESS' || + !isRecord(value.data) || + !hasExactKeys(value.data, ['accountId', 'authToken', 'expiresAt']) + ) { + throw new AccountControlUiApiError(0); + } + + const { accountId, authToken, expiresAt } = value.data; + if ( + typeof accountId !== 'string' || + !uuid.test(accountId) || + typeof authToken !== 'string' || + authToken.length > 16_384 || + !jwt.test(authToken) || + typeof expiresAt !== 'string' || + !timestamp.test(expiresAt) + ) { + throw new AccountControlUiApiError(0); + } + + const expiry = Date.parse(expiresAt); + if ( + !Number.isFinite(expiry) || + expiry <= now || + expiry - now > maxControlUiSessionLifetimeMs + ) { + throw new AccountControlUiApiError(0); + } + + return { accountId, authToken, expiresAt }; +} + +/** + * Builds the only login transport used by the account checkout route. The + * caller supplies the browser's current origin, never an API URL from a form. + */ +export function createAccountControlUiApi( + origin: string | (() => string), + fetchImpl: typeof fetch = fetch, + now: () => number = Date.now +): AccountControlUiApi { + if (typeof origin === 'string') requireSecureOrigin(origin); + + function currentOrigin(): URL { + return requireSecureOrigin( + typeof origin === 'function' ? origin() : origin + ); + } + + return { + async login(request, signal) { + const url = new URL('/api/account/auth/login', currentOrigin()); + if ( + !uuid.test(request.requestId) || + !uuid.test(request.callerContextId) || + typeof request.email !== 'string' || + request.email.length < 3 || + request.email.length > 254 || + request.email.trim() !== request.email || + typeof request.secret !== 'string' || + request.secret.length < 1 || + request.secret.length > 1024 + ) { + throw new AccountControlUiApiError(0); + } + + let response: Response; + try { + response = await fetchImpl(url, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Accept: 'application/json', + }, + body: JSON.stringify(request), + cache: 'no-store', + credentials: 'omit', + redirect: 'error', + referrerPolicy: 'no-referrer', + mode: 'same-origin', + signal, + }); + } catch { + throw new AccountControlUiApiError(0); + } + + if (response.status !== 200) { + try { + await response.body?.cancel(); + } catch { + // The body is deliberately discarded; server text is never surfaced. + } + throw new AccountControlUiApiError(response.status); + } + + return parseLoginResult(await readBoundedJson(response, signal), now()); + }, + }; +} diff --git a/web-client/src/billing/HostingFirstInvoiceCheckout.tsx b/web-client/src/billing/HostingFirstInvoiceCheckout.tsx index be4e4da750..da3cb4cf4e 100644 --- a/web-client/src/billing/HostingFirstInvoiceCheckout.tsx +++ b/web-client/src/billing/HostingFirstInvoiceCheckout.tsx @@ -33,9 +33,10 @@ interface Attempt { } /** - * Mount under QueryClientProvider only inside a genuine control-ui session. - * The demo App has no such session producer and intentionally does not mount it. - * Changing subscription/session must unmount this component (use a React key). + * Mount under QueryClientProvider only from the App-owned account checkout + * route, after its memory-only control-ui session is active. The route keys + * this component by session identity and subscription so either change unmounts + * it; mounting, remounting, or browser navigation never authorizes a payment. */ export default function HostingFirstInvoiceCheckout({ subscriptionId, From f824341da02ec94469d6138af18dd7e7328b56db Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 8 Nov 2026 19:47:46 +1300 Subject: [PATCH 02/29] Fix checkout receiving OpenAPI lint errors --- services/account-service/src/main/resources/openapi.yaml | 2 +- .../spring-cloud-gateway/src/main/resources/openapi.yaml | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index eb571b13e3..54acbb08c8 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -354,7 +354,7 @@ paths: schema: {type: string, description: 'Exact raw signed JSON bytes, at most 262144 UTF-8 bytes'} responses: '200': {description: Original Account completion state; no-store} - '400': {description: Missing, ambiguous, malformed or invalid signed event} + '400': {description: 'Missing, ambiguous, malformed or invalid signed event'} '401': {description: Actual HTTPS required} '409': {description: Exact retained event or billing evidence refused} '413': {description: Event body exceeds the bound} diff --git a/services/spring-cloud-gateway/src/main/resources/openapi.yaml b/services/spring-cloud-gateway/src/main/resources/openapi.yaml index a5f9936f94..acd11e771f 100644 --- a/services/spring-cloud-gateway/src/main/resources/openapi.yaml +++ b/services/spring-cloud-gateway/src/main/resources/openapi.yaml @@ -86,6 +86,7 @@ paths: schema: {type: string, format: uuid} get: operationId: getAccountHostingFirstInvoice + summary: Read the exact first-invoice checkout state x-runtime-status: isolated_only_default_off description: Exact HTTPS Account billing-owner operation. Passes only the necessary authenticated request over verified TLS without retry; Account owns the charge tuple, reauthentication, consent and result. responses: @@ -102,6 +103,7 @@ paths: schema: {type: string, format: uuid} post: operationId: reauthenticateAccountHostingFirstInvoice + summary: Reauthenticate the first-invoice billing owner x-runtime-status: isolated_only_default_off description: Exact HTTPS Account billing-owner operation. Passes only the necessary authenticated request over verified TLS without retry; Account owns the charge tuple, reauthentication, consent and result. responses: @@ -118,6 +120,7 @@ paths: schema: {type: string, format: uuid} post: operationId: confirmAccountHostingFirstInvoice + summary: Confirm the original first-invoice payment x-runtime-status: isolated_only_default_off description: Exact HTTPS Account billing-owner operation. Passes only the necessary authenticated request over verified TLS without retry; Account owns the charge tuple, reauthentication, consent and result. responses: @@ -134,6 +137,7 @@ paths: schema: {type: string, format: uuid} post: operationId: renewAccountHostingFirstInvoice + summary: Renew authorization for the original first-invoice checkout x-runtime-status: isolated_only_default_off description: Exact HTTPS Account billing-owner operation. Passes only the necessary authenticated request over verified TLS without retry; Account owns the charge tuple, reauthentication, consent and result. responses: @@ -145,6 +149,7 @@ paths: /api/account/billing/hosting/webhook: post: operationId: receiveAccountHostingFirstInvoiceSignedEvent + summary: Forward an exact raw provider-signed first-invoice event x-runtime-status: isolated_only_default_off security: [] description: Separately authenticated exact-byte provider signed event, at most 256 KiB. Forwards one signature header over verified HTTPS without retry or redirects. From a06441f1a610aca9b8884d1088c164c44cf4f7ce Mon Sep 17 00:00:00 2001 From: Codex Date: Tue, 10 Nov 2026 14:39:03 +1300 Subject: [PATCH 03/29] Carry complete V1039 migration history assertion --- .../AccountCanonicalJoinScopePersistenceIntegrationTest.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java index 48f6ffd468..6739e60bb1 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java @@ -366,19 +366,20 @@ void firstInvoiceAndCapacityUpgradeFromParent1036Through1040PreservesCanonicalRo .isEqualTo(MigrationVersion.fromVersion("1041")); List> upgradedHistory = flywayHistory(setupDsl); - assertThat(upgradedHistory).hasSize(parentHistory.size() + 4); + assertThat(upgradedHistory).hasSize(parentHistory.size() + 5); assertThat(upgradedHistory.subList(0, parentHistory.size())) .containsExactlyElementsOf(parentHistory); List> addedHistory = upgradedHistory.subList(parentHistory.size(), upgradedHistory.size()); assertThat(addedHistory) .extracting(row -> row.get("version")) - .containsExactly("1037", "1038", "1040", "1041"); + .containsExactly("1037", "1038", "1039", "1040", "1041"); assertThat(addedHistory) .extracting(row -> row.get("script")) .containsExactly( "V1037__canonical_join_failure_and_attempt_diagnostics.sql", "V1038__canonical_join_existing_membership_terminal.sql", + "V1039__hosting_unclaimed_wallet_settlement.sql", "V1040__account_tenant_capacity_owner.sql", "V1041__hosting_first_invoice_completion.sql"); assertThat(addedHistory) From 79974f5be42510c22c46fa2494350bbf0543cf32 Mon Sep 17 00:00:00 2001 From: benhook1013 Date: Tue, 10 Nov 2026 16:28:38 +1300 Subject: [PATCH 04/29] Return unauthorized for invalid checkout owner bearer credentials --- .../client/AccountCheckoutHttpClient.java | 11 ++- .../AccountCheckoutHttpClientTlsTest.java | 73 +++++++++++++++++++ 2 files changed, 82 insertions(+), 2 deletions(-) diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/client/AccountCheckoutHttpClient.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/client/AccountCheckoutHttpClient.java index bc5e44403a..998618cd1d 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/client/AccountCheckoutHttpClient.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/client/AccountCheckoutHttpClient.java @@ -121,8 +121,10 @@ public Mono forward( } String authorization = webhook ? null : oneHeader(inboundHeaders, HttpHeaders.AUTHORIZATION); String stripeSignature = webhook ? oneHeader(inboundHeaders, "Stripe-Signature") : null; - if ((!webhook && !validAuthorization(authorization)) - || (webhook && !validStripeSignature(stripeSignature))) { + if (!webhook && !validAuthorization(authorization)) { + return Mono.just(ForwardedResponse.unauthorized()); + } + if (webhook && !validStripeSignature(stripeSignature)) { return Mono.just(ForwardedResponse.badRequest()); } @@ -237,6 +239,11 @@ public String toString() { return "CheckoutUpstreamResponse[status=" + status.value() + ", body=redacted]"; } + private static ForwardedResponse unauthorized() { + return new ForwardedResponse( + HttpStatus.UNAUTHORIZED, MediaType.APPLICATION_JSON_VALUE, new byte[0]); + } + private static ForwardedResponse badRequest() { return new ForwardedResponse( HttpStatus.BAD_REQUEST, MediaType.APPLICATION_JSON_VALUE, new byte[0]); diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/client/AccountCheckoutHttpClientTlsTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/client/AccountCheckoutHttpClientTlsTest.java index d68bae82eb..36a9c9e884 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/client/AccountCheckoutHttpClientTlsTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/client/AccountCheckoutHttpClientTlsTest.java @@ -88,6 +88,79 @@ void forwardsOnlyNecessaryCheckoutHeadersAndUsesVerifiedHttps() throws Exception assertThat(captured.get().cookie()).isNull(); } + @Test + void refusesMissingOrInvalidOwnerBearerAsUnauthorizedWithoutContactingAccount() throws Exception { + var captured = new AtomicReference(); + AtomicInteger requests = startServer(200, JSON_RESPONSE, captured); + client = newClient(pki.caCertificate(), server.port()); + for (String authorization : + new String[] { + null, + "", + "Basic caller", + "Bearer ", + "Bearer " + "x".repeat(16_400), + "Bearer caller\r\ninjected" + }) { + HttpHeaders headers = new HttpHeaders(); + if (authorization != null) headers.set(HttpHeaders.AUTHORIZATION, authorization); + var response = + client + .forward(HttpMethod.GET, SUBSCRIPTION_PATH, headers, new byte[0]) + .block(Duration.ofSeconds(8)); + assertThat(response).isNotNull(); + assertThat(response.status()).isEqualTo(HttpStatus.UNAUTHORIZED); + assertThat(response.body()).isEmpty(); + } + HttpHeaders duplicateAuthorization = authorizationHeaders(); + duplicateAuthorization.add(HttpHeaders.AUTHORIZATION, "Bearer second-caller"); + var duplicateResponse = + client + .forward(HttpMethod.GET, SUBSCRIPTION_PATH, duplicateAuthorization, new byte[0]) + .block(Duration.ofSeconds(8)); + assertThat(duplicateResponse).isNotNull(); + assertThat(duplicateResponse.status()).isEqualTo(HttpStatus.UNAUTHORIZED); + assertThat(duplicateResponse.body()).isEmpty(); + assertThat(requests).hasValue(0); + assertThat(captured.get()).isNull(); + } + + @Test + void keepsMalformedBodyAndWebhookSignatureAsBadRequestWithoutContactingAccount() + throws Exception { + var captured = new AtomicReference(); + AtomicInteger requests = startServer(200, JSON_RESPONSE, captured); + client = newClient(pki.caCertificate(), server.port()); + var bodyResponse = + client + .forward(HttpMethod.GET, SUBSCRIPTION_PATH, authorizationHeaders(), new byte[] {1}) + .block(Duration.ofSeconds(8)); + assertThat(bodyResponse).isNotNull(); + assertThat(bodyResponse.status()).isEqualTo(HttpStatus.BAD_REQUEST); + assertThat(bodyResponse.body()).isEmpty(); + + HttpHeaders webhookHeaders = new HttpHeaders(); + webhookHeaders.setContentType(MediaType.APPLICATION_JSON); + byte[] payload = "{}".getBytes(StandardCharsets.UTF_8); + var missingSignature = + client + .forward(HttpMethod.POST, WEBHOOK_PATH, webhookHeaders, payload) + .block(Duration.ofSeconds(8)); + assertThat(missingSignature).isNotNull(); + assertThat(missingSignature.status()).isEqualTo(HttpStatus.BAD_REQUEST); + assertThat(missingSignature.body()).isEmpty(); + webhookHeaders.set("Stripe-Signature", "signature\r\ninjected"); + var malformedSignature = + client + .forward(HttpMethod.POST, WEBHOOK_PATH, webhookHeaders, payload) + .block(Duration.ofSeconds(8)); + assertThat(malformedSignature).isNotNull(); + assertThat(malformedSignature.status()).isEqualTo(HttpStatus.BAD_REQUEST); + assertThat(malformedSignature.body()).isEmpty(); + assertThat(requests).hasValue(0); + assertThat(captured.get()).isNull(); + } + @Test void preservesWebhookBytesAndForwardsOnlyContentTypeAndStripeSignature() throws Exception { var captured = new AtomicReference(); From e69bae8e164e930b218d9f3f04ed2d9fed478c2c Mon Sep 17 00:00:00 2001 From: benhook1013 Date: Tue, 10 Nov 2026 16:35:29 +1300 Subject: [PATCH 05/29] Order controlled provider success after real checkout consent --- ...teredReceivingPostgresIntegrationTest.java | 23 ++++++++++++++----- 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountCheckoutRegisteredReceivingPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountCheckoutRegisteredReceivingPostgresIntegrationTest.java index 2697d5f88e..76a8e86f00 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountCheckoutRegisteredReceivingPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountCheckoutRegisteredReceivingPostgresIntegrationTest.java @@ -18,6 +18,8 @@ import java.nio.file.Files; import java.nio.file.Path; import java.time.Duration; +import java.time.Instant; +import java.time.OffsetDateTime; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -283,8 +285,20 @@ void registeredChainAuthenticatesRealOwnerAndCommitsOnlyExactSignedProviderSucce // Let the original controlled ten-second provider-dispatch lease expire without issuing // repeated reconciliation commands or changing the real receiving clock. Thread.sleep(Duration.ofSeconds(11)); - var completion = - receiving.rawWebhook(hosting.signedSuccessPayload(), hosting.signedSuccessHeader()); + // The controlled provider event follows real owner consent. Advance only the provider + // fixture clock; receiving keeps its genuine clock and unchanged consent/lease guards. + hosting.clock().advance(Duration.between(hosting.clock().instant(), Instant.now())); + var success = hosting.signedSuccess(); + var consentedAt = + source + .dsl + .fetchSingle( + "SELECT consented_at FROM subscription_first_invoice_confirmations WHERE request_id = ?", + confirmation) + .get(0, OffsetDateTime.class); + assertThat(JSON.readTree(success.payload()).path("created").asLong()) + .isGreaterThanOrEqualTo(consentedAt.toEpochSecond()); + var completion = receiving.rawWebhook(success.payload(), success.signature()); assertThat(completion.statusCode()).isEqualTo(200); assertThat(JSON.readTree(completion.body()).path("state").asText()).isEqualTo("COMMITTED"); assertThat(hosting.firstInvoiceConfirmations()).isOne(); @@ -293,10 +307,7 @@ void registeredChainAuthenticatesRealOwnerAndCommitsOnlyExactSignedProviderSucce .path("state") .asText()) .isEqualTo("COMMITTED"); - assertThat( - receiving - .rawWebhook(hosting.signedSuccessPayload(), hosting.signedSuccessHeader()) - .statusCode()) + assertThat(receiving.rawWebhook(success.payload(), success.signature()).statusCode()) .isEqualTo(200); assertThat( source From b8bcfc6dc6c6163e90d034bd99b7a39c13692a1e Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Tue, 10 Nov 2026 19:28:38 +1300 Subject: [PATCH 06/29] Order shared Redis composition before Boot Redis defaults --- .../config/DatabaseAutoConfiguration.java | 2 + .../config/DatabaseAutoConfigurationTest.java | 90 +++++++++++++++++++ 2 files changed, 92 insertions(+) diff --git a/services/common-data-runtime/src/main/java/net/firedevops/firemud/common/config/DatabaseAutoConfiguration.java b/services/common-data-runtime/src/main/java/net/firedevops/firemud/common/config/DatabaseAutoConfiguration.java index 9c0e29157c..d32766a26e 100644 --- a/services/common-data-runtime/src/main/java/net/firedevops/firemud/common/config/DatabaseAutoConfiguration.java +++ b/services/common-data-runtime/src/main/java/net/firedevops/firemud/common/config/DatabaseAutoConfiguration.java @@ -30,6 +30,8 @@ @AutoConfigureBefore( name = { "org.springframework.boot.jdbc.autoconfigure.DataSourceAutoConfiguration", + "org.springframework.boot.data.redis.autoconfigure.DataRedisAutoConfiguration", + "org.springframework.boot.data.redis.autoconfigure.DataRedisReactiveAutoConfiguration", "org.springframework.boot.flyway.autoconfigure.FlywayAutoConfiguration", "org.springframework.boot.sql.autoconfigure.flyway.FlywayAutoConfiguration" }) diff --git a/services/common-data-runtime/src/test/java/net/firedevops/firemud/common/config/DatabaseAutoConfigurationTest.java b/services/common-data-runtime/src/test/java/net/firedevops/firemud/common/config/DatabaseAutoConfigurationTest.java index 697d6369f9..d12276eef3 100644 --- a/services/common-data-runtime/src/test/java/net/firedevops/firemud/common/config/DatabaseAutoConfigurationTest.java +++ b/services/common-data-runtime/src/test/java/net/firedevops/firemud/common/config/DatabaseAutoConfigurationTest.java @@ -2,17 +2,107 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import io.lettuce.core.SslVerifyMode; import io.lettuce.core.resource.ClientResources; +import io.micrometer.core.instrument.MeterRegistry; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.data.redis.autoconfigure.DataRedisAutoConfiguration; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.ResolvableType; +import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.RedisStandaloneConfiguration; import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.serializer.StringRedisSerializer; class DatabaseAutoConfigurationTest { + private final ApplicationContextRunner contextRunner = + new ApplicationContextRunner() + .withConfiguration( + AutoConfigurations.of( + DatabaseAutoConfiguration.class, DataRedisAutoConfiguration.class)) + .withBean(MeterRegistry.class, SimpleMeterRegistry::new) + .withPropertyValues("firemud.database.enabled=false"); + + @Test + void bootRedisAutoConfigurationPreservesTypedObjectAndStringTemplates() { + contextRunner + .withBean(RedisConnectionFactory.class, () -> mock(RedisConnectionFactory.class)) + .run( + context -> { + Object typed = + context + .getBeanProvider( + ResolvableType.forClassWithGenerics( + RedisTemplate.class, String.class, Object.class)) + .getIfUnique(); + assertNotNull(typed, "Session consumers require RedisTemplate"); + assertSame(context.getBean("redisTemplate"), typed); + assertSame( + context.getBean(RedisConnectionFactory.class), + context.getBean(StringRedisTemplate.class).getConnectionFactory()); + }); + } + + @Test + void bootRedisAutoConfigurationCannotReplaceTheFiremudEndpoint() { + contextRunner + .withPropertyValues( + "firemud.redis.host=firemud-redis.internal", + "firemud.redis.port=6380", + "firemud.redis.database=3", + "spring.data.redis.host=unrelated-boot-default.internal") + .run( + context -> { + var factory = context.getBean(LettuceConnectionFactory.class); + assertEquals( + "firemud-redis.internal", factory.getStandaloneConfiguration().getHostName()); + assertEquals(6380, factory.getStandaloneConfiguration().getPort()); + assertEquals(3, factory.getStandaloneConfiguration().getDatabase()); + }); + } + + @Test + void explicitTypedTemplateOverrideStillWinsAlongsideBootAutoConfiguration() { + contextRunner + .withBean(RedisConnectionFactory.class, () -> mock(RedisConnectionFactory.class)) + .withUserConfiguration(ExplicitRedisTemplate.class) + .run( + context -> { + var template = context.getBean("redisTemplate", RedisTemplate.class); + assertSame( + template, + context + .getBeanProvider( + ResolvableType.forClassWithGenerics( + RedisTemplate.class, String.class, Object.class)) + .getObject()); + assertEquals(StringRedisSerializer.class, template.getKeySerializer().getClass()); + }); + } + + @Configuration(proxyBeanMethods = false) + static class ExplicitRedisTemplate { + @Bean + RedisTemplate redisTemplate(RedisConnectionFactory factory) { + RedisTemplate template = new RedisTemplate<>(); + template.setConnectionFactory(factory); + template.setKeySerializer(new StringRedisSerializer()); + return template; + } + } + @Test void mapsRedisStandaloneCredentialsAndDatabaseIndex() { PostgresProperties postgres = new PostgresProperties(); From be992acdf5829a96ebfa473358c735f0758f01e8 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Tue, 10 Nov 2026 20:55:17 +1300 Subject: [PATCH 07/29] Preserve invalid input and contracted checkout error outcomes --- ...ystem-architecture-authz-route-matrix.yaml | 4 + ...untControlUiAuthenticationGrpcService.java | 12 +-- ...ontrolUiAuthenticationGrpcServiceTest.java | 41 ++++++++ ...countControlUiAuthenticationGrpcCodec.java | 16 +++- ...tControlUiAuthenticationGrpcCodecTest.java | 21 ++++ .../client/AccountCheckoutHttpClient.java | 70 +++++++++++++- .../AccountControlUiAuthenticationClient.java | 10 ++ .../AccountCheckoutGatewayController.java | 5 + .../AccountCheckoutHttpClientTlsTest.java | 95 +++++++++++++++++++ ...ControlUiAuthenticationClientMtlsTest.java | 38 +++++++- ...untCheckoutReceivingConfigurationTest.java | 49 ++++++++++ .../src/account/AccountCheckoutRoute.test.tsx | 35 ++++++- .../src/account/AccountCheckoutRoute.tsx | 9 +- web-client/src/api/accountControlUi.test.ts | 3 +- 14 files changed, 385 insertions(+), 23 deletions(-) diff --git a/design/architecture/system-architecture-authz-route-matrix.yaml b/design/architecture/system-architecture-authz-route-matrix.yaml index 5947361c2f..2a6fe1e0af 100644 --- a/design/architecture/system-architecture-authz-route-matrix.yaml +++ b/design/architecture/system-architecture-authz-route-matrix.yaml @@ -1771,10 +1771,14 @@ routes: scope: account classification: internal_workload route_status: target_not_currently_routable + auth_path: exact_mtls_workload + issued_token_state: none accepted_token_profiles: [] token_type: none token_issuer: none token_audience: none + issued_token_profile: control-ui + issued_token_audience: control-ui method_policy: exact_declared_route allowed_callers: any_of: [spring-cloud-gateway] diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcService.java index 25e348f93f..103c0cbc23 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcService.java @@ -46,9 +46,13 @@ public void authLogin(AuthLoginRequest wire, StreamObserver r return; } AccountControlUiAuthenticationGrpcCodec.Request request; + AccountControlUiIssuanceService.AccountSignInRequest signInRequest; try { request = AccountControlUiAuthenticationGrpcCodec.parseRequest(wire); if (!namespace.equals(request.callerNamespace())) throw new IllegalArgumentException(); + signInRequest = + new AccountControlUiIssuanceService.AccountSignInRequest( + request.requestId(), request.email(), request.secret(), request.callerContextId()); } catch (IllegalArgumentException invalid) { response.onError( Status.INVALID_ARGUMENT @@ -56,13 +60,7 @@ public void authLogin(AuthLoginRequest wire, StreamObserver r .asRuntimeException()); return; } - try (var credential = - issuance.issueAccount( - new AccountControlUiIssuanceService.AccountSignInRequest( - request.requestId(), - request.email(), - request.secret(), - request.callerContextId()))) { + try (var credential = issuance.issueAccount(signInRequest)) { byte[] compact = credential.compactBytes(); try { String token = new String(compact, StandardCharsets.US_ASCII); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcServiceTest.java index 33175dff87..f68ff9e43e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcServiceTest.java @@ -92,6 +92,47 @@ void primaryDenialIsAClosedResultAndNamespaceConflictNeverAuthenticates() { verifyNoInteractions(actors); } + @Test + void overlongSecretIsInvalidArgumentBeforeIssuance() { + var issuer = mock(AccountControlUiIssuanceService.class); + var actors = mock(AccountControlUiActorService.class); + var receiver = new AccountControlUiAuthenticationGrpcService(issuer, actors, "test"); + var wire = + AuthLoginRequest.newBuilder() + .addSchemaVersion(1) + .addTargetNamespace("test") + .addRequestId(UUID.randomUUID().toString()) + .addCallerContextId(UUID.randomUUID().toString()) + .addEmail("owner@example.test") + .addSecret("s".repeat(1025)) + .build(); + var result = new Result(); + + gateway().run(() -> receiver.authLogin(wire, result)); + + assertThat(result.failureCode).isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(issuer, actors); + } + + @Test + void issuanceConflictRemainsAlreadyExists() { + var issuer = mock(AccountControlUiIssuanceService.class); + var actors = mock(AccountControlUiActorService.class); + when(issuer.issueAccount(any())) + .thenThrow(new IllegalArgumentException("retained input differs")); + var receiver = new AccountControlUiAuthenticationGrpcService(issuer, actors, "test"); + var result = new Result(); + + gateway() + .run( + () -> + receiver.authLogin( + AccountControlUiAuthenticationGrpcCodec.toRequest(request("test")), result)); + + assertThat(result.failureCode).isEqualTo(Status.Code.ALREADY_EXISTS); + verifyNoInteractions(actors); + } + private static AccountControlUiAuthenticationGrpcCodec.Request request(String namespace) { return new AccountControlUiAuthenticationGrpcCodec.Request( UUID.randomUUID(), UUID.randomUUID(), namespace, "owner@example.test", "controlled-secret"); diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/auth/AccountControlUiAuthenticationGrpcCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/auth/AccountControlUiAuthenticationGrpcCodec.java index ccd8a3c73d..40943e973c 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/account/auth/AccountControlUiAuthenticationGrpcCodec.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/auth/AccountControlUiAuthenticationGrpcCodec.java @@ -21,6 +21,8 @@ public final class AccountControlUiAuthenticationGrpcCodec { public static final int MAX_RESPONSE_WIRE_BYTES = 20 * 1024; public static final int MAX_EMAIL_UTF8_BYTES = 320; public static final int MAX_SECRET_UTF8_BYTES = 4 * 1024; + public static final int MAX_EMAIL_CHARS = 254; + public static final int MAX_SECRET_CHARS = 1024; public static final int MAX_COMPACT_AUTH_TOKEN_BYTES = 16 * 1024; private static final int SCHEMA_VERSION = 1; @@ -198,8 +200,11 @@ private static void requireNamespace(String value) { } private static void requireEmail(String value) { - int length = utf8Length(value); - if (length < 3 || length > MAX_EMAIL_UTF8_BYTES || value.indexOf('@') <= 0) throw invalid(); + int bytes = utf8Length(value); + if (bytes < 3 + || bytes > MAX_EMAIL_UTF8_BYTES + || value.length() > MAX_EMAIL_CHARS + || value.indexOf('@') <= 0) throw invalid(); int at = value.indexOf('@'); if (at != value.lastIndexOf('@') || at == value.length() - 1 @@ -208,8 +213,11 @@ private static void requireEmail(String value) { } private static void requireSecret(String value) { - int length = utf8Length(value); - if (length < 1 || length > MAX_SECRET_UTF8_BYTES || value.indexOf('\0') >= 0) throw invalid(); + int bytes = utf8Length(value); + if (bytes < 1 + || bytes > MAX_SECRET_UTF8_BYTES + || value.length() > MAX_SECRET_CHARS + || value.indexOf('\0') >= 0) throw invalid(); } private static void requireToken(String value) { diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/account/auth/AccountControlUiAuthenticationGrpcCodecTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/account/auth/AccountControlUiAuthenticationGrpcCodecTest.java index 6844ca0ff8..eca9b75aa7 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/account/auth/AccountControlUiAuthenticationGrpcCodecTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/account/auth/AccountControlUiAuthenticationGrpcCodecTest.java @@ -32,6 +32,27 @@ void mapsOneExactBoundedRequestWithoutExposingSecretInDiagnostics() { assertThat(wire.getSecretList()).containsExactly(SECRET); } + @Test + void enforcesAccountUtf16CharacterLimitsAndAcceptsBoundedUnicode() { + String unicodeBoundaryEmail = "\u00e9".repeat(66) + "a".repeat(186) + "@x"; + String unicodeBoundarySecret = new String(Character.toChars(0x1F510)).repeat(512); + assertThat(unicodeBoundaryEmail).hasSize(254); + assertThat(unicodeBoundarySecret).hasSize(1024); + Request boundary = + new Request( + REQUEST_ID, CALLER_CONTEXT_ID, NAMESPACE, unicodeBoundaryEmail, unicodeBoundarySecret); + + assertThat( + AccountControlUiAuthenticationGrpcCodec.parseRequest( + AccountControlUiAuthenticationGrpcCodec.toRequest(boundary))) + .isEqualTo(boundary); + + var wire = AccountControlUiAuthenticationGrpcCodec.toRequest(request()); + assertRejected(wire.toBuilder().setEmail(0, "a".repeat(253) + "@x").build()); + assertRejected(wire.toBuilder().setEmail(0, "\u00e9".repeat(252) + "@x").build()); + assertRejected(wire.toBuilder().setSecret(0, "s".repeat(1025)).build()); + } + @Test void mapsSuccessAndDenialWhileNeverEchoingPrimarySecret() { Request request = request(); diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/client/AccountCheckoutHttpClient.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/client/AccountCheckoutHttpClient.java index 998618cd1d..2b7fb3b7dd 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/client/AccountCheckoutHttpClient.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/client/AccountCheckoutHttpClient.java @@ -20,6 +20,10 @@ import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; import reactor.netty.http.client.HttpClient; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; /** Narrow no-retry HTTPS proxy for Account's first-invoice and Stripe webhook routes. */ public final class AccountCheckoutHttpClient { @@ -32,6 +36,12 @@ public final class AccountCheckoutHttpClient { "/billing/hosting/subscriptions/" + "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}" + "/first-invoice(?:/(?:reauthenticate|confirm|renew))?"); + private static final int MAX_ERROR_RESPONSE_BYTES = 1024; + private static final JsonMapper ERROR_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); private static final String WEBHOOK_PATH = "/billing/hosting/webhook"; private static final Duration TOTAL_TIMEOUT_CEILING = Duration.ofSeconds(60); @@ -148,6 +158,8 @@ public Mono forward( .exchangeToMono( response -> readResponse( + method, + accountPath, response.statusCode(), response.headers().asHttpHeaders(), response.bodyToMono(byte[].class))) @@ -156,13 +168,23 @@ public Mono forward( } private Mono readResponse( - HttpStatusCode status, HttpHeaders headers, Mono responseBody) { + HttpMethod method, + String path, + HttpStatusCode status, + HttpHeaders headers, + Mono responseBody) { if (!status.is2xxSuccessful()) { HttpStatusCode safeStatus = - status.is3xxRedirection() || status.is5xxServerError() ? HttpStatus.BAD_GATEWAY : status; + status.value() == HttpStatus.SERVICE_UNAVAILABLE.value() + ? status + : status.is3xxRedirection() || status.is5xxServerError() + ? HttpStatus.BAD_GATEWAY + : status; + var empty = new ForwardedResponse(safeStatus, null, new byte[0]); return responseBody - .onErrorResume(ignored -> Mono.empty()) - .thenReturn(new ForwardedResponse(safeStatus, null, new byte[0])); + .map(body -> closedErrorResponse(method, path, status, safeStatus, headers, body)) + .onErrorReturn(empty) + .defaultIfEmpty(empty); } String contentType = oneHeader(headers, HttpHeaders.CONTENT_TYPE); if (status.value() == HttpStatus.NO_CONTENT.value() @@ -177,6 +199,46 @@ private Mono readResponse( .map(body -> new ForwardedResponse(status, contentType, body)); } + private static ForwardedResponse closedErrorResponse( + HttpMethod method, + String path, + HttpStatusCode upstreamStatus, + HttpStatusCode safeStatus, + HttpHeaders headers, + byte[] body) { + var empty = new ForwardedResponse(safeStatus, null, new byte[0]); + if (!isSubscriptionRoute(method, path) + || body.length == 0 + || body.length > MAX_ERROR_RESPONSE_BYTES + || !isJsonContentType(oneHeader(headers, HttpHeaders.CONTENT_TYPE))) return empty; + boolean confirmation = + HttpMethod.POST.equals(method) && (path.endsWith("/confirm") || path.endsWith("/renew")); + String expected = + switch (upstreamStatus.value()) { + case 400 -> "FIRST_INVOICE_INVALID_REQUEST"; + case 401 -> "AUTH_SESSION_REVOKED"; + case 409 -> "FIRST_INVOICE_EVIDENCE_REFUSED"; + case 502 -> confirmation ? "FIRST_INVOICE_PROVIDER_UNCERTAIN" : null; + case 503 -> "AUTH_UNAVAILABLE"; + default -> null; + }; + if (expected == null) return empty; + try { + JsonNode root = ERROR_JSON.readTree(body); + if (root == null + || !root.isObject() + || root.size() != 1 + || !root.has("code") + || !root.get("code").isTextual() + || !expected.equals(root.get("code").textValue())) return empty; + byte[] safeBody = + ("{\"code\":\"" + expected + "\"}").getBytes(java.nio.charset.StandardCharsets.US_ASCII); + return new ForwardedResponse(safeStatus, MediaType.APPLICATION_JSON_VALUE, safeBody); + } catch (RuntimeException invalid) { + return empty; + } + } + private static boolean isWebhook(HttpMethod method, String path) { return HttpMethod.POST.equals(method) && WEBHOOK_PATH.equals(path); } diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/client/AccountControlUiAuthenticationClient.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/client/AccountControlUiAuthenticationClient.java index 539db9de72..1af223a273 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/client/AccountControlUiAuthenticationClient.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/client/AccountControlUiAuthenticationClient.java @@ -75,6 +75,9 @@ public Result login(Request request) { if (unavailable.getStatus().getCode() == Status.Code.ALREADY_EXISTS) { throw new AuthenticationConflictException(); } + if (unavailable.getStatus().getCode() == Status.Code.INVALID_ARGUMENT) { + throw new AuthenticationInvalidRequestException(); + } throw new AuthenticationUnavailableException(); } catch (IllegalArgumentException malformed) { throw new IllegalStateException("Account authentication response was invalid"); @@ -148,4 +151,11 @@ public AuthenticationConflictException() { super("Account authentication request conflicts"); } } + + /** Safe invalid-request signal that carries no upstream gRPC details or cause. */ + public static final class AuthenticationInvalidRequestException extends RuntimeException { + public AuthenticationInvalidRequestException() { + super("Account authentication request is invalid"); + } + } } diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/controller/AccountCheckoutGatewayController.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/controller/AccountCheckoutGatewayController.java index 8f30c79e76..0350d3ba38 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/controller/AccountCheckoutGatewayController.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/controller/AccountCheckoutGatewayController.java @@ -124,6 +124,11 @@ public Mono> login(ServerWebExchange exchange) { return jsonResponse(HttpStatus.BAD_GATEWAY, errorJson("ERROR")); } }) + .onErrorResume( + AccountControlUiAuthenticationClient.AuthenticationInvalidRequestException + .class, + invalid -> + Mono.just(jsonResponse(HttpStatus.BAD_REQUEST, errorJson("ERROR")))) .onErrorResume( AccountControlUiAuthenticationClient.AuthenticationConflictException.class, conflict -> diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/client/AccountCheckoutHttpClientTlsTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/client/AccountCheckoutHttpClientTlsTest.java index 36a9c9e884..c69eb259a9 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/client/AccountCheckoutHttpClientTlsTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/client/AccountCheckoutHttpClientTlsTest.java @@ -10,12 +10,16 @@ import java.util.Base64; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.Stream; import net.firedevops.firemud.springcloudgateway.config.AccountCheckoutReceivingProperties; import net.firedevops.firemud.test.LoopbackMtlsTestPki; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; @@ -264,6 +268,97 @@ void doesNotRetryAnUncertainCheckoutPostAfterTheAccountConnectionResets() throws assertThat(requests).hasValue(1); } + @ParameterizedTest + @MethodSource("contractedErrors") + void preservesOnlyContractedOwnerErrorCodesWithoutRetry( + HttpMethod method, String suffix, int status, String code) throws Exception { + var captured = new AtomicReference(); + String body = "{ \"code\": \"" + code + "\" }"; + AtomicInteger requests = startServer(status, body.getBytes(StandardCharsets.UTF_8), captured); + client = newClient(pki.caCertificate(), server.port()); + HttpHeaders headers = authorizationHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + var result = + client + .forward( + method, + SUBSCRIPTION_PATH + suffix, + headers, + HttpMethod.GET.equals(method) ? new byte[0] : "{}".getBytes(StandardCharsets.UTF_8)) + .block(Duration.ofSeconds(8)); + assertThat(result).isNotNull(); + assertThat(result.status().value()).isEqualTo(status); + assertThat(result.contentType()).isEqualTo(MediaType.APPLICATION_JSON_VALUE); + assertThat(new String(result.body(), StandardCharsets.UTF_8)) + .isEqualTo("{\"code\":\"" + code + "\"}"); + assertThat(requests).hasValue(1); + } + + private static Stream contractedErrors() { + return Stream.of( + Arguments.of(HttpMethod.POST, "/reauthenticate", 400, "FIRST_INVOICE_INVALID_REQUEST"), + Arguments.of(HttpMethod.GET, "", 401, "AUTH_SESSION_REVOKED"), + Arguments.of(HttpMethod.POST, "/confirm", 409, "FIRST_INVOICE_EVIDENCE_REFUSED"), + Arguments.of(HttpMethod.POST, "/confirm", 502, "FIRST_INVOICE_PROVIDER_UNCERTAIN"), + Arguments.of(HttpMethod.POST, "/renew", 502, "FIRST_INVOICE_PROVIDER_UNCERTAIN"), + Arguments.of(HttpMethod.GET, "", 503, "AUTH_UNAVAILABLE")); + } + + @Test + void preservesReconcilingWebhook503WithoutForwardingPrivateOutcomeOrRetrying() throws Exception { + var captured = new AtomicReference(); + AtomicInteger requests = + startServer( + 503, + "{\"state\":\"RECONCILING\",\"private\":\"never-forward\"}" + .getBytes(StandardCharsets.UTF_8), + captured); + client = newClient(pki.caCertificate(), server.port()); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.set("Stripe-Signature", "t=123,v1=signature"); + var result = + client + .forward(HttpMethod.POST, WEBHOOK_PATH, headers, "{}".getBytes(StandardCharsets.UTF_8)) + .block(Duration.ofSeconds(8)); + assertThat(result).isNotNull(); + assertThat(result.status()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); + assertThat(result.body()).isEmpty(); + assertThat(requests).hasValue(1); + } + + @ParameterizedTest + @MethodSource("untrustedErrors") + void stripsUncontractedOrMalformedErrorBodies(int upstreamStatus, String body, int publicStatus) + throws Exception { + var captured = new AtomicReference(); + AtomicInteger requests = + startServer(upstreamStatus, body.getBytes(StandardCharsets.UTF_8), captured); + client = newClient(pki.caCertificate(), server.port()); + var result = + client + .forward(HttpMethod.GET, SUBSCRIPTION_PATH, authorizationHeaders(), new byte[0]) + .block(Duration.ofSeconds(8)); + assertThat(result).isNotNull(); + assertThat(result.status().value()).isEqualTo(publicStatus); + assertThat(result.body()).isEmpty(); + assertThat(requests).hasValue(1); + } + + private static Stream untrustedErrors() { + return Stream.of( + Arguments.of(503, "{broken", 503), + Arguments.of(503, "{\"code\":\"AUTH_UNAVAILABLE\",\"secret\":\"private\"}", 503), + Arguments.of(503, "{\"code\":\"arbitrary-data\"}", 503), + Arguments.of(409, "{\"code\":\"AUTH_UNAVAILABLE\"}", 409), + Arguments.of(503, "{\"code\":\"AUTH_UNAVAILABLE\",\"code\":\"AUTH_UNAVAILABLE\"}", 503), + Arguments.of(503, "{\"code\":\"AUTH_UNAVAILABLE\"} {}", 503), + Arguments.of(503, "{\"code\":42}", 503), + Arguments.of(503, "{\"code\":\"AUTH_UNAVAILABLE\"}" + " ".repeat(2048), 503), + Arguments.of(502, "{\"code\":\"FIRST_INVOICE_PROVIDER_UNCERTAIN\"}", 502), + Arguments.of(500, "{\"code\":\"AUTH_UNAVAILABLE\"}", 502)); + } + private AtomicInteger startServer( int status, byte[] responseBody, AtomicReference captured) throws Exception { Path cert = writeCertificate(temporaryDirectory.resolve("account-server.crt")); diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/client/AccountControlUiAuthenticationClientMtlsTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/client/AccountControlUiAuthenticationClientMtlsTest.java index ee091eb01b..e42687c6cf 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/client/AccountControlUiAuthenticationClientMtlsTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/client/AccountControlUiAuthenticationClientMtlsTest.java @@ -126,6 +126,26 @@ void caTrustedWrongServerWorkloadReceivesNoPrimaryRequestOrSecret() throws Excep assertThat(peer.get()).isNull(); } + @Test + void mapsAuthenticatedInvalidArgumentWithoutForwardingGrpcErrorDetails() throws Exception { + var observed = new AtomicReference(); + var peer = new AtomicReference(); + AtomicInteger handlers = + startServer("account-server", observed, peer, Status.Code.INVALID_ARGUMENT); + client = newClient(server.getPort()); + client.init(); + + assertThatThrownBy(() -> client.login(request())) + .isInstanceOf( + AccountControlUiAuthenticationClient.AuthenticationInvalidRequestException.class) + .hasMessage("Account authentication request is invalid") + .hasNoCause(); + + assertThat(handlers).hasValue(1); + assertThat(observed.get()).isEqualTo(request()); + assertThat(peer.get().uri()).isEqualTo(GATEWAY_URI); + } + @Test void mapsRetainedRequestInputConflictWithoutForwardingGrpcErrorDetails() throws Exception { var observed = new AtomicReference(); @@ -148,7 +168,7 @@ private AtomicInteger startServer( AtomicReference observed, AtomicReference peer) throws Exception { - return startServer(serverIdentityAlias, observed, peer, false); + return startServer(serverIdentityAlias, observed, peer, (Status.Code) null); } private AtomicInteger startServer( @@ -157,6 +177,16 @@ private AtomicInteger startServer( AtomicReference peer, boolean conflict) throws Exception { + return startServer( + serverIdentityAlias, observed, peer, conflict ? Status.Code.ALREADY_EXISTS : null); + } + + private AtomicInteger startServer( + String serverIdentityAlias, + AtomicReference observed, + AtomicReference peer, + Status.Code failureCode) + throws Exception { var serverIdentity = pki.identity(serverIdentityAlias); AtomicInteger handlers = new AtomicInteger(); AccountControlUiAuthenticationServiceGrpc.AccountControlUiAuthenticationServiceImplBase @@ -171,10 +201,10 @@ public void authLogin( peer.set(GrpcPeerIdentity.current()); Request request = AccountControlUiAuthenticationGrpcCodec.parseRequest(wireRequest); observed.set(request); - if (conflict) { + if (failureCode != null) { responseObserver.onError( - Status.ALREADY_EXISTS - .withDescription("retained request input changed") + Status.fromCode(failureCode) + .withDescription("controlled upstream detail") .asRuntimeException()); return; } diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfigurationTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfigurationTest.java index 1633c0d066..4ba852a46c 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfigurationTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfigurationTest.java @@ -2,8 +2,13 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import java.net.URI; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; @@ -18,8 +23,11 @@ import org.springframework.cloud.gateway.filter.ratelimit.RateLimiter; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.core.env.MapPropertySource; +import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.server.reactive.SslInfo; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.server.WebFilter; @@ -97,6 +105,40 @@ void enabledReceivingRequiresHttpsAccountAuthorityAndReadableCaFile() throws Exc assertThat(credentialFailure.getMessage()).contains("authority-only HTTPS Account upstream"); } + @Test + void authenticatedAccountInvalidArgumentMapsToSafeBadRequest() { + var authenticationClient = mock(AccountControlUiAuthenticationClient.class); + var checkoutClient = mock(AccountCheckoutHttpClient.class); + var controller = + new AccountCheckoutGatewayController( + authenticationClient, checkoutClient, receivingProperties()); + when(authenticationClient.login(any())) + .thenThrow( + new AccountControlUiAuthenticationClient.AuthenticationInvalidRequestException()); + String secret = "controlled-primary-secret"; + String body = + "{\"requestId\":\"927fb6a8-3975-4cba-8145-c2a8f4a9b0d1\"," + + "\"callerContextId\":\"af64ad5f-e9ee-48a1-9b5d-6fb28845ff71\"," + + "\"email\":\"owner@example.test\",\"secret\":\"" + + secret + + "\"}"; + var request = + MockServerHttpRequest.post(URI.create("https://localhost/api/account/auth/login")) + .sslInfo(mock(SslInfo.class)) + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .body(body); + + var response = controller.login(MockServerWebExchange.from(request)).block(); + + assertThat(response).isNotNull(); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); + assertThat(response.getHeaders().getCacheControl()).contains("no-store"); + assertThat(new String(response.getBody(), StandardCharsets.UTF_8)) + .contains("\"status\":\"ERROR\"") + .doesNotContain(secret); + verify(authenticationClient).login(any()); + } + @Test void receivingRateLimitRunsOnlyOnSelectedHandlersAndFailsClosedWhenDenied() { AtomicReference resolvedKey = new AtomicReference<>(); @@ -159,6 +201,13 @@ void receivingRateLimitUnavailableReturnsServiceUnavailableAndIgnoresOtherPaths( assertThat(login.getResponse().getHeaders().getCacheControl()).contains("no-store"); } + private static AccountCheckoutReceivingProperties receivingProperties() { + var properties = new AccountCheckoutReceivingProperties(); + properties.setEnabled(true); + properties.setWorkloadNamespace("checkout-test"); + return properties; + } + private static void addProperties( AnnotationConfigApplicationContext context, Map properties) { context diff --git a/web-client/src/account/AccountCheckoutRoute.test.tsx b/web-client/src/account/AccountCheckoutRoute.test.tsx index 0e985a06f0..d439b357c0 100644 --- a/web-client/src/account/AccountCheckoutRoute.test.tsx +++ b/web-client/src/account/AccountCheckoutRoute.test.tsx @@ -10,7 +10,10 @@ import { } from '@testing-library/react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import App from '../App'; -import type { AccountControlUiApi } from '../api/accountControlUi'; +import { + AccountControlUiApiError, + type AccountControlUiApi, +} from '../api/accountControlUi'; import type { HostingStripe } from '../billing/hostingStripe'; import { createControlUiSessionStore, @@ -224,6 +227,36 @@ describe('App-owned first-invoice route', () => { expect(loadStripeClient).not.toHaveBeenCalled(); }); + it.each([429, 0])( + 'shows safe temporary feedback for sign-in status %i without retrying', + async (status) => { + const { api } = setupApp(); + vi.mocked(api.login).mockRejectedValue( + new AccountControlUiApiError(status) + ); + fireEvent.change(screen.getByLabelText('Account email'), { + target: { value: 'owner@example.com' }, + }); + fireEvent.change(screen.getByLabelText('Primary authentication secret'), { + target: { value: 'primary-secret' }, + }); + fireEvent.click(screen.getByRole('button', { name: 'Sign in' })); + + await screen.findByText( + 'Account sign-in is temporarily unavailable. Try again later.' + ); + expect(api.login).toHaveBeenCalledOnce(); + expect(vi.mocked(api.login).mock.calls[0][0].secret).toBe(''); + expect( + ( + screen.getByLabelText( + 'Primary authentication secret' + ) as HTMLInputElement + ).value + ).toBe(''); + } + ); + it('handles browser Back and Forward by remounting read-only checkout without confirming', async () => { const { fetchImpl } = setupApp(); await signIn(); diff --git a/web-client/src/account/AccountCheckoutRoute.tsx b/web-client/src/account/AccountCheckoutRoute.tsx index 0df8beb570..b04da168b1 100644 --- a/web-client/src/account/AccountCheckoutRoute.tsx +++ b/web-client/src/account/AccountCheckoutRoute.tsx @@ -329,8 +329,13 @@ function AccountLoginForm({ api, sessionStore, notice }: LoginFormProps) { try { await sessionStore.signIn(api, credentials); } catch (error) { - if (error instanceof AccountControlUiApiError && error.status === 503) { - setMessage('Account sign-in is temporarily unavailable. Try again.'); + if ( + error instanceof AccountControlUiApiError && + [0, 429, 503].includes(error.status) + ) { + setMessage( + 'Account sign-in is temporarily unavailable. Try again later.' + ); } else if ( error instanceof ControlUiSessionError && error.code === 'SESSION_REPLACED' diff --git a/web-client/src/api/accountControlUi.test.ts b/web-client/src/api/accountControlUi.test.ts index 928aa72486..089fbe810c 100644 --- a/web-client/src/api/accountControlUi.test.ts +++ b/web-client/src/api/accountControlUi.test.ts @@ -136,6 +136,7 @@ describe('account control-ui login transport', () => { } expect(fetchImpl).toHaveBeenCalledOnce(); expect(error).toBeInstanceOf(AccountControlUiApiError); + expect(error).toMatchObject({ status: 0 }); expect((error as Error).message).not.toContain('primary-secret'); }); @@ -184,7 +185,7 @@ describe('account control-ui login transport', () => { }); it('rejects oversized response bodies', async () => { - const oversized = 'x'.repeat(40 * 1024); + const oversized = (await successfulLogin().text()) + ' '.repeat(40 * 1024); const fetchImpl = vi .fn() .mockResolvedValue(new Response(oversized, { status: 200 })); From 5026019573dadc4f5a51e9aae30b5426439d003c Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Tue, 10 Nov 2026 21:16:20 +1300 Subject: [PATCH 08/29] Use the supported mock HTTP request builder in checkout proof --- .../config/AccountCheckoutReceivingConfigurationTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfigurationTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfigurationTest.java index 4ba852a46c..ee0e52eaba 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfigurationTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfigurationTest.java @@ -123,7 +123,7 @@ void authenticatedAccountInvalidArgumentMapsToSafeBadRequest() { + secret + "\"}"; var request = - MockServerHttpRequest.post(URI.create("https://localhost/api/account/auth/login")) + MockServerHttpRequest.post("https://localhost/api/account/auth/login") .sslInfo(mock(SslInfo.class)) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .body(body); From 94c0b573cf48dddba6604c16e5cebeb53771cd39 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 11 Nov 2026 01:04:09 +1300 Subject: [PATCH 09/29] Separate checkout conflict from signer outages and qualify isolated HTTPS contracts --- .../account-service/stripe-integration.md | 2 +- .../system-architecture-gateway.md | 3 +- ...untControlUiAuthenticationGrpcService.java | 2 +- .../AccountControlUiIssuanceService.java | 8 ++- ...ontrolUiAuthenticationGrpcServiceTest.java | 31 +++++++++- .../AccountControlUiIssuanceWorkflowTest.java | 2 +- .../common/grpc/GrpcChannelFactory.java | 2 +- .../grpc/GrpcChannelFactoryNoRetryTest.java | 61 +++++++++++++++++++ .../src/main/resources/openapi.yaml | 38 +++++++++--- 9 files changed, 134 insertions(+), 15 deletions(-) diff --git a/design/architecture/microservices/account-service/stripe-integration.md b/design/architecture/microservices/account-service/stripe-integration.md index 50fd57641a..76a74e1c21 100644 --- a/design/architecture/microservices/account-service/stripe-integration.md +++ b/design/architecture/microservices/account-service/stripe-integration.md @@ -56,7 +56,7 @@ Only a verified signed `payment_intent.succeeded` event, matched to the exact re The Account lifecycle transaction atomically commits the exact completion, hosting receipt, audit/observation evidence, billing sequence/outbox and tenant authority-generation/outbox. Independent receipt/current-source and completion-journal reads follow commit. A lost provider response or local commit failure remains on the same operation. An exact owner retry is read-only and cannot send another confirmation; if the intent still requires confirmation, it reports `AUTHORIZED_NOT_CONFIRMED`. Recovery of that held outcome or expired client-secret disclosure requires a separately explicit fresh primary reauthentication and unchanged charge consent. Its distinct authorization request is append-only and compare-and-set against the current authorization version on the original payment operation. It preserves the original invoice, PaymentIntent, subscription, instrument, quote, amount/currency, provider idempotency key, lifecycle and audit identities. The new attempt supersedes older disclosure/command permissions without rewriting the original consent. It may recover a crash before any durable command claim, but it cannot repeat an already claimed command, even if the provider still reports `requires_confirmation`. A crash or ambiguous commit after that claim remains nonterminal and read-only until exact provider evidence or audited remediation resolves it. The same fresh authorization may redisclose the existing intent's `requires_action` secret; it does not create or confirm another intent. Authorization expiry never extends the original incomplete-subscription expiry. Read-only reconciliation and authorization expiry follow [ADR 0045's authorization-linearization contract](../../decisions/adr-0045-ordinary-login-factors-and-https-sensitive-action-step-up.md#handoff-authorization-linearization); neither a delayed event nor an expired handoff permits a new charge or changed tuple. A paid-but-unfulfilled result remains non-authorizing until that exact atomic fulfillment succeeds or audited remediation resolves it. -Registration remains held by the category-specific retention/minimization, deletion, backup, source-custody and provider qualification prerequisites above. Controlled SDK or SQL tests do not establish live Stripe/SCA support or deployment activation. +Production registration remains held by the category-specific retention/minimization, deletion, backup, source-custody and provider qualification prerequisites above. This production hold is distinct from registration of the default-off isolated receiving handlers, which does not enable production billing or hosted activation. Controlled SDK or SQL tests do not establish live Stripe/SCA support or deployment activation. ## Domain Model diff --git a/design/architecture/system-architecture-gateway.md b/design/architecture/system-architecture-gateway.md index 3a65478ea8..e2856c5b12 100644 --- a/design/architecture/system-architecture-gateway.md +++ b/design/architecture/system-architecture-gateway.md @@ -570,7 +570,8 @@ The following table summarizes the main network surfaces exposed or used by Spri | Surface | Direction | Protocol(s) | Typical Port(s) | Auth / TLS Expectations | | --- | --- | --- | --- | --- | -| Public player/admin ingress → Spring Cloud Gateway | Inbound | `HTTP(S)`, `WS(S)` | Load balancer ports (for example, `80`/`443`) | TLS terminates at the Internet-facing load balancer; gateway receives `http://` / `ws://` as described in [TLS Termination for Gateway](./system-architecture-security.md#tls-termination-for-gateway). | +| Public player/admin ingress → Spring Cloud Gateway | Inbound | `HTTP(S)`, `WS(S)` | Load balancer ports (for example, `80`/`443`) | Ordinary public traffic uses TLS termination at the Internet-facing load balancer, which forwards `http://` / `ws://` to Gateway as described in [TLS Termination for Gateway](./system-architecture-security.md#tls-termination-for-gateway). The isolated Account checkout HTTPS listener below is an explicit exception. | +| Isolated Account checkout client → Spring Cloud Gateway HTTPS listener | Inbound (isolated composition only) | `HTTPS` | Deployment-configured Gateway TLS port | The exact checkout/login handlers require TLS on the hop delivered to Gateway: the controller checks Gateway-side SSL information and an `https` scheme, so plain HTTP after load-balancer termination is refused. This requires a Gateway TLS listener; forwarded scheme headers alone do not satisfy it. The default-off `isolated-checkout-receiving` profile cannot be combined with `prod` or `production`, and [production registration remains held](./microservices/account-service/stripe-integration.md). | | TCP Proxy Service → Spring Cloud Gateway gameplay route (certificate-bound profiles) | Inbound (internal only) | `WS(S)` | Gateway internal mTLS port (for example, `8443`) | The internal-only listener applies the selected exclusive certificate-bound trust profile after certificate chain/client-auth checks: exact URI SAN, exact DNS SAN, or one leaf SHA-256 fingerprint. The gateway promotes `X-Proxy-*` inputs only after that profile succeeds. The host in `GATEWAY_WS_URL` must match the gateway certificate’s SANs. | | TCP Proxy Service → Spring Cloud Gateway gameplay route (`development_cidr` only) | Inbound (development/test only) | `WSS` | Gateway internal TLS port (for example, `8443`) | The development-only listener uses TLS without client authentication and applies only the exact configured source-CIDR predicate; it does not claim certificate identity, is prohibited in player-facing environments, and never authorizes a plain-transport bridge. The host in `GATEWAY_WS_URL` must match the gateway certificate’s SANs. | | Spring Cloud Gateway → backend services | Outbound | `HTTP`, `WS` | `8080` (typical) | In-cluster hop; protected by NetworkPolicies and namespace boundaries. Backend services handle JWT validation/authorization as applicable; gameplay traffic remains on the `/ws/game/**` WebSocket route to the Game Session Service. | diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcService.java index 103c0cbc23..c1c393e789 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcService.java @@ -77,7 +77,7 @@ public void authLogin(AuthLoginRequest wire, StreamObserver r } catch (AuthenticationException denied) { response.onNext(AccountControlUiAuthenticationGrpcCodec.toResponse(request, null)); response.onCompleted(); - } catch (IllegalArgumentException conflict) { + } catch (AccountControlUiIssuanceService.IdempotencyConflictException conflict) { response.onError( Status.ALREADY_EXISTS .withDescription("Account login request conflicts") diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java index 927c446529..1b46f14bf0 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java @@ -336,7 +336,13 @@ private void requireRequest( || !stored.callerContextId.equals(request.callerContextId) || !stored.requestDigest.equals( cryptography.requestDigest(stored.requestMacKeyId, exactRequest))) { - throw new IllegalArgumentException("Control-ui issuance idempotency conflict"); + throw new IdempotencyConflictException(); + } + } + + public static final class IdempotencyConflictException extends IllegalArgumentException { + public IdempotencyConflictException() { + super("Control-ui issuance idempotency conflict"); } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcServiceTest.java index f68ff9e43e..21837aca55 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcServiceTest.java @@ -119,7 +119,7 @@ void issuanceConflictRemainsAlreadyExists() { var issuer = mock(AccountControlUiIssuanceService.class); var actors = mock(AccountControlUiActorService.class); when(issuer.issueAccount(any())) - .thenThrow(new IllegalArgumentException("retained input differs")); + .thenThrow(new AccountControlUiIssuanceService.IdempotencyConflictException()); var receiver = new AccountControlUiAuthenticationGrpcService(issuer, actors, "test"); var result = new Result(); @@ -130,6 +130,30 @@ void issuanceConflictRemainsAlreadyExists() { AccountControlUiAuthenticationGrpcCodec.toRequest(request("test")), result)); assertThat(result.failureCode).isEqualTo(Status.Code.ALREADY_EXISTS); + assertThat(result.failureDescription).isEqualTo("Account login request conflicts"); + verifyNoInteractions(actors); + } + + @Test + void signerStyleIllegalArgumentIsUnavailableAndSanitized() { + var issuer = mock(AccountControlUiIssuanceService.class); + var actors = mock(AccountControlUiActorService.class); + when(issuer.issueAccount(any())) + .thenThrow(new IllegalArgumentException("mounted signer rejected configured key material")); + var receiver = new AccountControlUiAuthenticationGrpcService(issuer, actors, "test"); + var request = request("test"); + var result = new Result(); + + gateway() + .run( + () -> + receiver.authLogin( + AccountControlUiAuthenticationGrpcCodec.toRequest(request), result)); + + assertThat(result.failureCode).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(result.failureDescription).isEqualTo("Account login authority unavailable"); + assertThat(result.failureDescription) + .doesNotContain("mounted signer rejected", request.email(), request.secret()); verifyNoInteractions(actors); } @@ -149,6 +173,7 @@ private static Context gateway() { private static final class Result implements StreamObserver { AuthLoginResponse value; Status.Code failureCode; + String failureDescription; boolean completed; @Override @@ -158,7 +183,9 @@ public void onNext(AuthLoginResponse value) { @Override public void onError(Throwable failure) { - failureCode = Status.fromThrowable(failure).getCode(); + Status status = Status.fromThrowable(failure); + failureCode = status.getCode(); + failureDescription = status.getDescription(); } @Override diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java index 77653186f1..c5b60d0f4d 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java @@ -403,7 +403,7 @@ void accountGlobalReplayReturnsOriginalCredentialAndCrossScopeRetriesConflict() .isInstanceOf(IllegalArgumentException.class); } else { assertThatThrownBy(() -> conflict.service().issueAccount(conflict.accountRequest())) - .isInstanceOf(IllegalArgumentException.class); + .isInstanceOf(AccountControlUiIssuanceService.IdempotencyConflictException.class); } } verify(conflict.operations, never()).beginRecoveryFailure(any()); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcChannelFactory.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcChannelFactory.java index 55a83f7429..f1827d0f35 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcChannelFactory.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcChannelFactory.java @@ -95,7 +95,7 @@ protected ManagedChannelBuilder createPlaintextBuilder(String resolved, int d return ManagedChannelBuilder.forAddress(host, port).usePlaintext(); } - private NettyChannelBuilder createTlsBuilder(String resolved, int defaultPort) { + protected NettyChannelBuilder createTlsBuilder(String resolved, int defaultPort) { if (resolved.contains("://")) { return NettyChannelBuilder.forTarget(resolved); } diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/grpc/GrpcChannelFactoryNoRetryTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/grpc/GrpcChannelFactoryNoRetryTest.java index e985b6f016..9ca3432fb3 100644 --- a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/grpc/GrpcChannelFactoryNoRetryTest.java +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/grpc/GrpcChannelFactoryNoRetryTest.java @@ -4,15 +4,76 @@ import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import java.nio.file.Path; +import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; class GrpcChannelFactoryNoRetryTest { + @TempDir static Path temporaryDirectory; + private static LoopbackMtlsTestPki.Pki pki; + + @BeforeAll + static void createPki() throws Exception { + pki = + LoopbackMtlsTestPki.create( + temporaryDirectory, + "No-retry channel test CA", + new LoopbackMtlsTestPki.IdentitySpec( + "gateway-client", "spiffe://firemud/ns/retry-test/sa/spring-cloud-gateway", false)); + } + + @Test + void dedicatedTlsBuilderDisablesRetriesBeforeBuilding() throws Exception { + NettyChannelBuilder builder = spy(NettyChannelBuilder.forAddress("localhost", 6565)); + GrpcChannelFactory factory = tlsFactoryReturning(builder); + var properties = pki.clientProperties(temporaryDirectory, pki.identity("gateway-client")); + ManagedChannel channel = + factory.buildNonRetryingChannel("localhost:6565", 6565, properties, true); + try { + var order = inOrder(builder); + order.verify(builder).disableRetry(); + order.verify(builder).build(); + } finally { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } + + @Test + void existingTlsBuilderDoesNotChangeItsRetryBehavior() throws Exception { + NettyChannelBuilder builder = spy(NettyChannelBuilder.forAddress("localhost", 6565)); + GrpcChannelFactory factory = tlsFactoryReturning(builder); + var properties = pki.clientProperties(temporaryDirectory, pki.identity("gateway-client")); + ManagedChannel channel = factory.buildChannel("localhost:6565", 6565, properties, false); + try { + verify(builder, never()).disableRetry(); + verify(builder).build(); + } finally { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } + + private static GrpcChannelFactory tlsFactoryReturning(NettyChannelBuilder builder) { + return new GrpcChannelFactory() { + @Override + protected NettyChannelBuilder createTlsBuilder(String resolved, int defaultPort) { + return builder; + } + }; + } + @Test void dedicatedChannelBuilderDisablesRetriesBeforeBuilding() throws SSLException { ManagedChannel channel = mock(ManagedChannel.class); diff --git a/services/spring-cloud-gateway/src/main/resources/openapi.yaml b/services/spring-cloud-gateway/src/main/resources/openapi.yaml index acd11e771f..cd21120af2 100644 --- a/services/spring-cloud-gateway/src/main/resources/openapi.yaml +++ b/services/spring-cloud-gateway/src/main/resources/openapi.yaml @@ -77,7 +77,12 @@ paths: expiresAt: {type: string, format: date-time} '400': {description: Invalid bounded request or actual HTTPS required} '401': {description: Primary authentication denied} - '503': {description: Current Account authentication authority unavailable} + '409': {description: Account login request conflicts with retained idempotency evidence} + '413': {description: Login request exceeds the Gateway body limit} + '415': {description: Login requires an application/json request} + '429': {description: Receiving rate limit exceeded} + '502': {description: Gateway could not safely complete the Account authentication call} + '503': {description: Account authentication or receiving rate-limit authority unavailable} /api/account/billing/hosting/subscriptions/{subscriptionId}/first-invoice: parameters: - name: subscriptionId @@ -94,7 +99,10 @@ paths: '400': {description: Malformed request} '401': {description: Current control-ui owner authority required} '409': {description: Exact retained evidence refused or outcome uncertain} - '502': {description: Upstream outcome uncertain; never automatically resend} + '413': {description: Request exceeds the subscription-operation body limit} + '429': {description: Receiving rate limit exceeded} + '502': {description: Gateway transport or upstream outcome uncertain; never automatically resend} + '503': {description: Account authentication/reconciliation or Gateway rate-limit authority unavailable; no automatic retry} /api/account/billing/hosting/subscriptions/{subscriptionId}/first-invoice/reauthenticate: parameters: - name: subscriptionId @@ -111,7 +119,11 @@ paths: '400': {description: Malformed request} '401': {description: Current control-ui owner authority required} '409': {description: Exact retained evidence refused or outcome uncertain} - '502': {description: Upstream outcome uncertain; never automatically resend} + '413': {description: Request exceeds the subscription-operation body limit} + '415': {description: Action requires an application/json request} + '429': {description: Receiving rate limit exceeded} + '502': {description: Gateway transport or upstream outcome uncertain; never automatically resend} + '503': {description: Account authentication/reconciliation or Gateway rate-limit authority unavailable; no automatic retry} /api/account/billing/hosting/subscriptions/{subscriptionId}/first-invoice/confirm: parameters: - name: subscriptionId @@ -128,7 +140,11 @@ paths: '400': {description: Malformed request} '401': {description: Current control-ui owner authority required} '409': {description: Exact retained evidence refused or outcome uncertain} - '502': {description: Upstream outcome uncertain; never automatically resend} + '413': {description: Request exceeds the subscription-operation body limit} + '415': {description: Action requires an application/json request} + '429': {description: Receiving rate limit exceeded} + '502': {description: Gateway transport or upstream outcome uncertain; never automatically resend} + '503': {description: Account authentication/reconciliation or Gateway rate-limit authority unavailable; no automatic retry} /api/account/billing/hosting/subscriptions/{subscriptionId}/first-invoice/renew: parameters: - name: subscriptionId @@ -145,7 +161,11 @@ paths: '400': {description: Malformed request} '401': {description: Current control-ui owner authority required} '409': {description: Exact retained evidence refused or outcome uncertain} - '502': {description: Upstream outcome uncertain; never automatically resend} + '413': {description: Request exceeds the subscription-operation body limit} + '415': {description: Action requires an application/json request} + '429': {description: Receiving rate limit exceeded} + '502': {description: Gateway transport or upstream outcome uncertain; never automatically resend} + '503': {description: Account authentication/reconciliation or Gateway rate-limit authority unavailable; no automatic retry} /api/account/billing/hosting/webhook: post: operationId: receiveAccountHostingFirstInvoiceSignedEvent @@ -161,8 +181,12 @@ paths: responses: '200': {description: No-store Account completion state} '400': {description: Invalid signed event} - '413': {description: Request exceeds the bound} - '502': {description: Upstream outcome remains uncertain} + '401': {description: Account rejected provider-event authentication} + '409': {description: Account could not accept this event against retained state} + '413': {description: Request exceeds the webhook body limit} + '429': {description: Receiving rate limit exceeded} + '502': {description: Gateway transport or upstream outcome remains uncertain} + '503': {description: Account reconciliation or Gateway rate-limit authority unavailable; provider delivery may be retried} /ping: get: summary: Health check From b5d0320fe85de5badb990afeffb240149c5c0228 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 11 Nov 2026 02:55:33 +1300 Subject: [PATCH 10/29] Fail closed on checkout Redis rate-limit errors and strengthen receiving proof --- .../player-access-and-session.md | 2 +- ...ontrolUiAuthenticationGrpcServiceTest.java | 14 +- .../AccountControlUiIssuanceWorkflowTest.java | 28 +-- .../AccountControlUiRegistryReaderTest.java | 25 ++- .../AccountControlUiOriginalOrderFixture.java | 3 +- ...AccountCheckoutReceivingConfiguration.java | 10 +- .../AccountCheckoutReceivingRateLimiter.java | 78 +++++++ ...countCheckoutReceivingRateLimiterTest.java | 198 ++++++++++++++++++ .../src/account/AccountCheckoutRoute.test.tsx | 2 +- .../src/account/AccountCheckoutRoute.tsx | 2 +- 10 files changed, 336 insertions(+), 26 deletions(-) create mode 100644 services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingRateLimiter.java create mode 100644 services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingRateLimiterTest.java diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index c291ae912f..f1784543a9 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -82,7 +82,7 @@ The earlier published #3389 comparison deliberately left public facade and numer The next Account first-invoice extension composes actual registered Gateway HTTPS handlers, pre-disclosure verified Account mTLS login, the durable Account-only issuer/current actor, exact-method owner authentication and a bounded raw signed-event adapter. The Account-only source has no tenant/legal collaborator. Checkout imports the same pure protected JWKS source owner as other Account consumers and defines no competing API/client/trusted-source graph. The first-party App owns a memory-only session and subscription checkout route; expiry, local sign-out, replacement and navigation unmount it, with no automatic confirmation. -Focused receiving proof passes 170 backend cases: two channel-factory, five codec, 27 Gateway and 136 Account cases, with zero failures, errors or skips. This includes three real loopback mTLS cases, including refusal of a CA-trusted wrong workload before any primary request or credential, and five verified HTTPS cases including no retry after an uncertain checkout POST. Affected production/unit/integration compilation and enabled Java formatting, Checkstyle and SpotBugs pass. The memory-only UI passes all 55 selected checkout cases, build, lint and scoped formatting; these overlap earlier component coverage rather than add to it. These sources use explicit isolated signer-platform, policy, custody, provider and PKI inputs. The qualified core signed-completion/guard repair from parent `77890399` is carried. Its separate physical HTTPS signed-completion, confirmed-guard and migration proof passed on that parent. The registered Gateway→Account→Redis/PostgreSQL receiving-chain definition compiles, but its physical proof and fresh-image/runtime qualification remain unrun. It starts from a controlled existing `AWAITING_PAYMENT` operation, not a newly supported subscription-create route. Fresh-image runtime proof, production registration/activation, approved finite category-specific retention/minimization/deletion/backup/provider treatment, genuine custody and live provider qualification remain held. Link validation remains unrun. +Historical receiving proof passed 170 backend cases on its earlier source: two channel-factory, five codec, 27 Gateway and 136 Account cases, with zero failures, errors or skips. That run included three real loopback mTLS cases, including refusal of a CA-trusted wrong workload before any primary request or credential, and five verified HTTPS cases including no retry after an uncertain checkout POST. These historical counts exclude later channel-factory TLS-builder, HTTPS error-body and isolated rate-limiter coverage; they do not describe the current suites or prove the later changes. Affected production/unit/integration compilation and enabled Java formatting, Checkstyle and SpotBugs pass. The memory-only UI passes all 55 selected checkout cases, build, lint and scoped formatting; these overlap earlier component coverage rather than add to it. These sources use explicit isolated signer-platform, policy, custody, provider and PKI inputs. The qualified core signed-completion/guard repair from parent `77890399` is carried. Its separate physical HTTPS signed-completion, confirmed-guard and migration proof passed on that parent. The registered Gateway→Account→Redis/PostgreSQL receiving-chain definition compiles, but its physical proof and fresh-image/runtime qualification remain unrun. It starts from a controlled existing `AWAITING_PAYMENT` operation, not a newly supported subscription-create route. Fresh-image runtime proof, production registration/activation, approved finite category-specific retention/minimization/deletion/backup/provider treatment, genuine custody and live provider qualification remain held. Link validation was unrun for that historical receiving proof; later scoped documentation runs retain their own attribution. ### Canonical public Account facade receiving diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcServiceTest.java index 21837aca55..cc3cb70472 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcServiceTest.java @@ -10,6 +10,7 @@ import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.UUID; +import net.firedevops.firemud.account.v1.AccountControlUiAuthLoginStatus; import net.firedevops.firemud.account.v1.AuthLoginRequest; import net.firedevops.firemud.account.v1.AuthLoginResponse; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; @@ -28,12 +29,14 @@ void missingAndWrongPeerAreDeniedBeforeDecodeOrPrimaryAuthentication() { var result = new Result(); receiver.authLogin(AuthLoginRequest.getDefaultInstance(), result); assertThat(result.failureCode).isEqualTo(Status.Code.PERMISSION_DENIED); + var wrongPeer = new Result(); Context.current() .withValue( GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-session-service") .orElseThrow()) - .run(() -> receiver.authLogin(AuthLoginRequest.getDefaultInstance(), result)); + .run(() -> receiver.authLogin(AuthLoginRequest.getDefaultInstance(), wrongPeer)); + assertThat(wrongPeer.failureCode).isEqualTo(Status.Code.PERMISSION_DENIED); verifyNoInteractions(issuer, actors); } @@ -47,7 +50,8 @@ void exactGatewayUsesCommittedIssuerAndCurrentActorAndDoesNotEchoCredentials() { when(credential.expiresAt()).thenReturn(Instant.ofEpochSecond(2_000_000_300L)); when(issuer.issueAccount(any())).thenReturn(credential); var actor = mock(AccountControlUiActorService.AccountAuthenticatedActor.class); - when(actor.accountId()).thenReturn(UUID.randomUUID()); + UUID accountId = UUID.randomUUID(); + when(actor.accountId()).thenReturn(accountId); when(actors.authenticateAccount("controlled.compact.jwt")).thenReturn(actor); var receiver = new AccountControlUiAuthenticationGrpcService(issuer, actors, "test"); var request = request("test"); @@ -60,6 +64,9 @@ void exactGatewayUsesCommittedIssuerAndCurrentActorAndDoesNotEchoCredentials() { assertThat(result.failureCode).isNull(); assertThat(result.completed).isTrue(); assertThat(result.value.toString()).doesNotContain(request.secret(), request.email()); + assertThat(result.value.getAccountIdList()).containsExactly(accountId.toString()); + assertThat(result.value.getAuthTokenList()).containsExactly("controlled.compact.jwt"); + assertThat(result.value.getExpiresAtEpochSecondsList()).containsExactly(2_000_000_300L); assertThat(returned).containsOnly((byte) 0); verify(credential).close(); verify(actors).authenticateAccount("controlled.compact.jwt"); @@ -88,6 +95,9 @@ void primaryDenialIsAClosedResultAndNamespaceConflictNeverAuthenticates() { AccountControlUiAuthenticationGrpcCodec.toRequest(request("test")), denied)); assertThat(denied.failureCode).isNull(); assertThat(denied.completed).isTrue(); + assertThat(denied.value.getStatusList()) + .containsExactly( + AccountControlUiAuthLoginStatus.ACCOUNT_CONTROL_UI_AUTH_LOGIN_STATUS_DENIED); assertThat(denied.value.toString()).doesNotContain("not disclosed", "controlled-secret"); verifyNoInteractions(actors); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java index c5b60d0f4d..24e81ed826 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java @@ -144,7 +144,7 @@ void changedDigestTenantOrCallerContextConflictsWithoutTerminalizingOriginal() { } try (var ignored = fixture.withPeer(ISSUER)) { assertThatThrownBy(() -> fixture.service().issue(request, fixture.environment)) - .isInstanceOf(IllegalArgumentException.class); + .isInstanceOf(AccountControlUiIssuanceService.IdempotencyConflictException.class); } verify(fixture.operations, never()).beginRecoveryFailure(any()); verifyNoInteractions(fixture.registry, fixture.primary, fixture.signers); @@ -400,7 +400,7 @@ void accountGlobalReplayReturnsOriginalCredentialAndCrossScopeRetriesConflict() conflict.request( conflict.tenant, conflict.context, "test-only-secret"), conflict.environment)) - .isInstanceOf(IllegalArgumentException.class); + .isInstanceOf(AccountControlUiIssuanceService.IdempotencyConflictException.class); } else { assertThatThrownBy(() -> conflict.service().issueAccount(conflict.accountRequest())) .isInstanceOf(AccountControlUiIssuanceService.IdempotencyConflictException.class); @@ -589,17 +589,19 @@ void accountOnlyCompositionRefusesTenantIssuanceBeforePrimaryAuthentication() { Clock.fixed(NOW, ZoneOffset.UTC), 300_000L, ISSUER); - assertThatThrownBy( - () -> - issuer.issue( - new AccountControlUiIssuanceService.Request( - f.requestId, - "owner@example.test", - "controlled-secret", - f.tenant, - f.context), - f.environment)) - .isInstanceOf(IllegalStateException.class); + try (var ignored = f.withPeer(ISSUER)) { + assertThatThrownBy( + () -> + issuer.issue( + new AccountControlUiIssuanceService.Request( + f.requestId, + "owner@example.test", + "controlled-secret", + f.tenant, + f.context), + f.environment)) + .isInstanceOf(IllegalStateException.class); + } org.mockito.Mockito.verifyNoInteractions(f.primary, f.operations, f.signers, f.registry); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReaderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReaderTest.java index 15cb761237..6b9e2c94fb 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReaderTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReaderTest.java @@ -110,7 +110,30 @@ void deniesWhenPhysicalExpiryDiffersFromExactCleanupDeadline() throws Exception AccountControlUiRegistryReader reader = new AccountControlUiRegistryReader(() -> connection); assertThatThrownBy(() -> reader.readActive(TOKEN_HASH)) - .isInstanceOf(IllegalStateException.class); + .isInstanceOf(IllegalStateException.class) + .isNotInstanceOf(AccountControlUiRegistryReader.RegistryUnavailableException.class); + } + + @Test + void refusesMissingKeyWithoutReportingRegistryUnavailable() { + StatefulRedisConnection connection = mock(StatefulRedisConnection.class); + ClientOptions options = mock(ClientOptions.class); + @SuppressWarnings("unchecked") + RedisCommands commands = mock(RedisCommands.class); + when(connection.isOpen()).thenReturn(true); + when(connection.getOptions()).thenReturn(options); + when(options.isAutoReconnect()).thenReturn(false); + when(connection.sync()).thenReturn(commands); + when(commands.aclWhoami()).thenReturn(AccountControlUiRegistryReader.REQUIRED_ACL_IDENTITY); + when(commands.get(any(byte[].class))).thenReturn(null); + + AccountControlUiRegistryReader reader = new AccountControlUiRegistryReader(() -> connection); + + assertThatThrownBy(() -> reader.readActive(TOKEN_HASH)) + .isInstanceOf(IllegalStateException.class) + .isNotInstanceOf(AccountControlUiRegistryReader.RegistryUnavailableException.class); + verify(commands).aclWhoami(); + verify(commands).get(any(byte[].class)); } @Test diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java index 34de506332..b92b4e76f6 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java @@ -465,7 +465,7 @@ record IssuedCreator( CapturedEnvironmentBoundary environment, AccountControlUiOwnerSourcesFixture sources) {} - /** Same-package reuse of genuine certified ACCOUNT issuance, separate from tenant creation. */ + /** Returns the fixture's authenticated Account Coordination Redis URI. */ RedisURI receivingCoordinationUri() { return receivingCoordinationUri; } @@ -479,6 +479,7 @@ net.firedevops.firemud.accountservice.entity.Account prepareReceivingAccount(Str return f.createCertifiedGlobalAccount(password); } + /** Same-package reuse of genuine certified ACCOUNT issuance, separate from tenant creation. */ IssuedAccount issueCertifiedAccount(String password) { var account = f.createCertifiedGlobalAccount(password); var request = diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfiguration.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfiguration.java index 0864fd6ed5..e82fe4e703 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfiguration.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfiguration.java @@ -3,6 +3,7 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Arrays; +import java.util.List; import java.util.Objects; import java.util.regex.Pattern; import javax.net.ssl.SSLException; @@ -19,13 +20,13 @@ import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver; import org.springframework.cloud.gateway.filter.ratelimit.RateLimiter; import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter; -import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.core.Ordered; import org.springframework.core.env.Environment; import org.springframework.data.redis.core.ReactiveStringRedisTemplate; +import org.springframework.data.redis.core.script.RedisScript; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.server.ServerWebExchange; @@ -98,14 +99,11 @@ public WebFilter accountCheckoutReceivingRateLimitWebFilter( GatewayProperties gatewayProperties, ReactiveStringRedisTemplate redisTemplate, @Qualifier("gatewayClientIpKeyResolver") KeyResolver keyResolver, - ApplicationContext applicationContext) { + @Qualifier(RedisRateLimiter.REDIS_SCRIPT_NAME) RedisScript> script) { Objects.requireNonNull(redisTemplate, "Gateway Redis rate limiting must be available"); GatewayRateLimiterConfig.DefaultRequestRateLimiterArguments arguments = GatewayRateLimiterConfig.defaultRequestRateLimiterArguments(gatewayProperties); - RedisRateLimiter rateLimiter = - new RedisRateLimiter( - arguments.replenishRate(), arguments.burstCapacity(), arguments.requestedTokens()); - rateLimiter.setApplicationContext(applicationContext); + var rateLimiter = new AccountCheckoutReceivingRateLimiter(redisTemplate, script, arguments); return receivingRateLimitWebFilter(rateLimiter, keyResolver); } diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingRateLimiter.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingRateLimiter.java new file mode 100644 index 0000000000..2162705f52 --- /dev/null +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingRateLimiter.java @@ -0,0 +1,78 @@ +package net.firedevops.firemud.springcloudgateway.config; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import org.springframework.cloud.gateway.filter.ratelimit.RateLimiter; +import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter; +import org.springframework.data.redis.core.ReactiveStringRedisTemplate; +import org.springframework.data.redis.core.script.RedisScript; +import reactor.core.publisher.Mono; + +/** Fixed isolated-handler adapter for the Gateway token bucket, without its fail-open fallback. */ +final class AccountCheckoutReceivingRateLimiter + implements RateLimiter { + private final ReactiveStringRedisTemplate redisTemplate; + private final RedisScript> script; + private final GatewayRateLimiterConfig.DefaultRequestRateLimiterArguments configuration; + private final List arguments; + + AccountCheckoutReceivingRateLimiter( + ReactiveStringRedisTemplate redisTemplate, + RedisScript> script, + GatewayRateLimiterConfig.DefaultRequestRateLimiterArguments configuration) { + this.redisTemplate = Objects.requireNonNull(redisTemplate); + this.script = Objects.requireNonNull(script); + this.configuration = Objects.requireNonNull(configuration); + // Retain the installed Gateway's token-bucket configuration constraints as well as its script. + new RedisRateLimiter.Config() + .setReplenishRate(configuration.replenishRate()) + .setBurstCapacity(configuration.burstCapacity()) + .setRequestedTokens(configuration.requestedTokens()); + this.arguments = + List.of( + Integer.toString(configuration.replenishRate()), + Long.toString(configuration.burstCapacity()), + "", + Integer.toString(configuration.requestedTokens())); + } + + @Override + public Mono isAllowed(String routeId, String id) { + // Match Gateway's cluster hash tag and let the existing Lua script obtain Redis server time. + String prefix = "request_rate_limiter.{" + routeId + "." + id + "}."; + var keys = List.of(prefix + "tokens", prefix + "timestamp"); + return Mono.defer(() -> redisTemplate.execute(script, keys, arguments).single()) + .map(this::decision); + } + + private Response decision(List result) { + if (result.size() != 2 + || !(result.get(0) instanceof Long allowed) + || (allowed != 0L && allowed != 1L) + || !(result.get(1) instanceof Long remaining) + || remaining < 0L + || remaining > configuration.burstCapacity() + || (allowed == 1L + && remaining > configuration.burstCapacity() - configuration.requestedTokens()) + || (allowed == 0L && remaining >= configuration.requestedTokens())) { + throw new IllegalStateException("Gateway rate-limit result unavailable"); + } + return new Response(allowed == 1L, Map.of()); + } + + @Override + public Map getConfig() { + return Map.of(); + } + + @Override + public Class getConfigClass() { + return GatewayRateLimiterConfig.DefaultRequestRateLimiterArguments.class; + } + + @Override + public GatewayRateLimiterConfig.DefaultRequestRateLimiterArguments newConfig() { + return configuration; + } +} diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingRateLimiterTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingRateLimiterTest.java new file mode 100644 index 0000000000..f051cef1c0 --- /dev/null +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingRateLimiterTest.java @@ -0,0 +1,198 @@ +package net.firedevops.firemud.springcloudgateway.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.cloud.gateway.config.GatewayProperties; +import org.springframework.cloud.gateway.filter.FilterDefinition; +import org.springframework.core.io.ClassPathResource; +import org.springframework.data.redis.core.ReactiveStringRedisTemplate; +import org.springframework.data.redis.core.script.DefaultRedisScript; +import org.springframework.data.redis.core.script.RedisScript; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.mock.env.MockEnvironment; +import org.springframework.mock.http.server.reactive.MockServerHttpRequest; +import org.springframework.mock.web.server.MockServerWebExchange; +import org.springframework.web.server.WebFilter; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +class AccountCheckoutReceivingRateLimiterTest { + @ParameterizedTest + @MethodSource("redisFailures") + void configuredFilterRefusesReactiveAndSynchronousRedisErrorsWithoutForwarding( + boolean synchronous, HttpMethod method, String path) { + var redis = mock(ReactiveStringRedisTemplate.class); + var script = tokenBucketScript(); + if (synchronous) { + when(redis.execute(eq(script), anyList(), anyList())) + .thenThrow(new IllegalStateException("controlled Redis failure")); + } else { + when(redis.execute(eq(script), anyList(), anyList())) + .thenReturn(Flux.error(new IllegalStateException("controlled Redis failure"))); + } + + assertDecision( + configuredFilter(redis, script), HttpStatus.SERVICE_UNAVAILABLE, false, method, path); + + verify(redis).execute(eq(script), anyList(), anyList()); + } + + static Stream redisFailures() { + String firstInvoice = + "/api/account/billing/hosting/subscriptions/927fb6a8-3975-4cba-8145-c2a8f4a9b0d1/first-invoice"; + return Stream.of(false, true) + .flatMap( + synchronous -> + Stream.of( + Arguments.of(synchronous, HttpMethod.POST, "/api/account/auth/login"), + Arguments.of( + synchronous, HttpMethod.POST, "/api/account/billing/hosting/webhook"), + Arguments.of(synchronous, HttpMethod.GET, firstInvoice), + Arguments.of(synchronous, HttpMethod.POST, firstInvoice + "/reauthenticate"), + Arguments.of(synchronous, HttpMethod.POST, firstInvoice + "/confirm"), + Arguments.of(synchronous, HttpMethod.POST, firstInvoice + "/renew"))); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("malformedResults") + @SuppressWarnings({"unchecked", "rawtypes"}) + void configuredFilterRefusesMalformedOrMissingScriptResultsWithoutForwarding( + String description, Flux> result) { + var redis = mock(ReactiveStringRedisTemplate.class); + var script = tokenBucketScript(); + when(redis.execute(eq(script), anyList(), anyList())).thenReturn((Flux) result); + + assertDecision(configuredFilter(redis, script), HttpStatus.SERVICE_UNAVAILABLE, false); + + verify(redis).execute(eq(script), anyList(), anyList()); + } + + static Stream malformedResults() { + return Stream.of( + Arguments.of("empty publisher", Flux.empty()), + Arguments.of("empty tuple", Flux.just(List.of())), + Arguments.of("short tuple", Flux.just(List.of(1L))), + Arguments.of("extra value", Flux.just(List.of(1L, 10L, 9L))), + Arguments.of("unknown decision", Flux.just(List.of(2L, 10L))), + Arguments.of("negative remainder", Flux.just(List.of(1L, -1L))), + Arguments.of("remainder above capacity", Flux.just(List.of(1L, 41L))), + Arguments.of("unspent allowed tokens", Flux.just(List.of(1L, 40L))), + Arguments.of("unexhausted denial", Flux.just(List.of(0L, 20L))), + Arguments.of("wrong numeric type", Flux.just(List.of(1, 10))), + Arguments.of("null decision", Flux.just(Arrays.asList(null, 10L))), + Arguments.of("null remainder", Flux.just(Arrays.asList(1L, null))), + Arguments.of("multiple replies", Flux.just(List.of(1L, 10L), List.of(0L, 0L)))); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void configuredFilterPreservesTokenBucketArgumentsAndNormalAllowOr429(boolean allowed) { + var redis = mock(ReactiveStringRedisTemplate.class); + var script = tokenBucketScript(); + when(redis.execute(eq(script), anyList(), anyList())) + .thenReturn(Flux.just(List.of(allowed ? 1L : 0L, allowed ? 38L : 0L))); + + assertDecision( + configuredFilter(redis, script), allowed ? null : HttpStatus.TOO_MANY_REQUESTS, allowed); + + verify(redis) + .execute( + script, + List.of( + "request_rate_limiter.{account-checkout-receiving.192.0.2.123}.tokens", + "request_rate_limiter.{account-checkout-receiving.192.0.2.123}.timestamp"), + List.of("20", "40", "", "2")); + } + + @Test + void configuredFilterLeavesOrdinaryPathsOutsideTheIsolatedLimiter() { + var redis = mock(ReactiveStringRedisTemplate.class); + var exchange = + MockServerWebExchange.from(MockServerHttpRequest.post("https://localhost/api/ordinary")); + var forwarded = new AtomicBoolean(); + + configuredFilter(redis, tokenBucketScript()) + .filter( + exchange, + ignored -> { + forwarded.set(true); + return Mono.empty(); + }) + .block(); + + assertThat(forwarded).isTrue(); + assertThat(exchange.getResponse().getStatusCode()).isNull(); + org.mockito.Mockito.verifyNoInteractions(redis); + } + + private static WebFilter configuredFilter( + ReactiveStringRedisTemplate redis, RedisScript> script) { + var gateway = new GatewayProperties(); + var rateLimit = new FilterDefinition(); + rateLimit.setName("RequestRateLimiter"); + rateLimit.setArgs( + Map.of( + "redis-rate-limiter.replenishRate", "20", + "redis-rate-limiter.burstCapacity", "40", + "redis-rate-limiter.requestedTokens", "2")); + gateway.setDefaultFilters(List.of(rateLimit)); + return new AccountCheckoutReceivingConfiguration( + new MockEnvironment(), new AccountCheckoutReceivingProperties()) + .accountCheckoutReceivingRateLimitWebFilter( + gateway, redis, new GatewayRateLimiterConfig().gatewayClientIpKeyResolver(), script); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private static RedisScript> tokenBucketScript() { + var script = new DefaultRedisScript>(); + script.setLocation(new ClassPathResource("META-INF/scripts/request_rate_limiter.lua")); + script.setResultType((Class) List.class); + return script; + } + + private static void assertDecision(WebFilter filter, HttpStatus expected, boolean allowed) { + assertDecision(filter, expected, allowed, HttpMethod.POST, "/api/account/auth/login"); + } + + private static void assertDecision( + WebFilter filter, HttpStatus expected, boolean allowed, HttpMethod method, String path) { + var exchange = + MockServerWebExchange.from( + MockServerHttpRequest.method(method, "https://localhost" + path) + .header("X-Client-IP", "192.0.2.123")); + var forwarded = new AtomicBoolean(); + + filter + .filter( + exchange, + ignored -> { + forwarded.set(true); + return Mono.empty(); + }) + .block(); + + assertThat(forwarded.get()).isEqualTo(allowed); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(expected); + if (!allowed) { + assertThat(exchange.getResponse().getHeaders().getCacheControl()).contains("no-store"); + assertThat(exchange.getResponse().getBodyAsString().block()) + .isEqualTo("{\"status\":\"ERROR\"}"); + } + } +} diff --git a/web-client/src/account/AccountCheckoutRoute.test.tsx b/web-client/src/account/AccountCheckoutRoute.test.tsx index d439b357c0..28632a49d1 100644 --- a/web-client/src/account/AccountCheckoutRoute.test.tsx +++ b/web-client/src/account/AccountCheckoutRoute.test.tsx @@ -227,7 +227,7 @@ describe('App-owned first-invoice route', () => { expect(loadStripeClient).not.toHaveBeenCalled(); }); - it.each([429, 0])( + it.each([0, 429, 502, 503])( 'shows safe temporary feedback for sign-in status %i without retrying', async (status) => { const { api } = setupApp(); diff --git a/web-client/src/account/AccountCheckoutRoute.tsx b/web-client/src/account/AccountCheckoutRoute.tsx index b04da168b1..62b884c83e 100644 --- a/web-client/src/account/AccountCheckoutRoute.tsx +++ b/web-client/src/account/AccountCheckoutRoute.tsx @@ -331,7 +331,7 @@ function AccountLoginForm({ api, sessionStore, notice }: LoginFormProps) { } catch (error) { if ( error instanceof AccountControlUiApiError && - [0, 429, 503].includes(error.status) + [0, 429, 502, 503].includes(error.status) ) { setMessage( 'Account sign-in is temporarily unavailable. Try again later.' From d69384df0f1d4e047d6fab5a27c9edb9b37c4066 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 11 Nov 2026 04:02:54 +1300 Subject: [PATCH 11/29] Compose the canonical rate script in registered checkout proof --- .../player-access-and-session.md | 2 +- ...teredReceivingPostgresIntegrationTest.java | 55 ++++++++++++------- 2 files changed, 37 insertions(+), 20 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 8c2754b61b..6d873205b8 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -84,7 +84,7 @@ The earlier published #3389 comparison deliberately left public facade and numer The next Account first-invoice extension composes actual registered Gateway HTTPS handlers, pre-disclosure verified Account mTLS login, the durable Account-only issuer/current actor, exact-method owner authentication and a bounded raw signed-event adapter. The Account-only source has no tenant/legal collaborator. Checkout imports the same pure protected JWKS source owner as other Account consumers and defines no competing API/client/trusted-source graph. The first-party App owns a memory-only session and subscription checkout route; expiry, local sign-out, replacement and navigation unmount it, with no automatic confirmation. -Historical receiving proof passed 170 backend cases on its earlier source: two channel-factory, five codec, 27 Gateway and 136 Account cases, with zero failures, errors or skips. That run included three real loopback mTLS cases, including refusal of a CA-trusted wrong workload before any primary request or credential, and five verified HTTPS cases including no retry after an uncertain checkout POST. These historical counts exclude later channel-factory TLS-builder, HTTPS error-body and isolated rate-limiter coverage; they do not describe the current suites or prove the later changes. Affected production/unit/integration compilation and enabled Java formatting, Checkstyle and SpotBugs pass. The memory-only UI passes all 55 selected checkout cases, build, lint and scoped formatting; these overlap earlier component coverage rather than add to it. These sources use explicit isolated signer-platform, policy, custody, provider and PKI inputs. The qualified core signed-completion/guard repair from parent `77890399` is carried. Its separate physical HTTPS signed-completion, confirmed-guard and migration proof passed on that parent. The registered Gateway→Account→Redis/PostgreSQL receiving-chain definition compiles, but its physical proof and fresh-image/runtime qualification remain unrun. It starts from a controlled existing `AWAITING_PAYMENT` operation, not a newly supported subscription-create route. Fresh-image runtime proof, production registration/activation, approved finite category-specific retention/minimization/deletion/backup/provider treatment, genuine custody and live provider qualification remain held. Link validation was unrun for that historical receiving proof; later scoped documentation runs retain their own attribution. +Historical receiving proof passed 170 backend cases on its earlier source: two channel-factory, five codec, 27 Gateway and 136 Account cases, with zero failures, errors or skips. That run included three real loopback mTLS cases, including refusal of a CA-trusted wrong workload before any primary request or credential, and five verified HTTPS cases including no retry after an uncertain checkout POST. These historical counts exclude later channel-factory TLS-builder, HTTPS error-body and isolated rate-limiter coverage; they do not describe the current suites or prove the later changes. Affected production/unit/integration compilation and enabled Java formatting, Checkstyle and SpotBugs pass. The memory-only UI passes all 55 selected checkout cases, build, lint and scoped formatting; these overlap earlier component coverage rather than add to it. These sources use explicit isolated signer-platform, policy, custody, provider and PKI inputs. The qualified core signed-completion/guard repair from parent `77890399` is carried. Its separate physical HTTPS signed-completion, confirmed-guard and migration proof passed on that parent. The registered Gateway→Account→Redis/PostgreSQL receiving-chain test now passes its actual HTTPS/mTLS and physical PostgreSQL/Coordination composition, including exact signed-provider-success completion and token-revocation refusal. Its non-Boot Gateway context supplies the same named token-bucket script resource as normal Gateway auto-configuration; Redis rate execution is a deterministic admitted upstream input, while the actual configured adapter and filter run. The same scoped invocation passes 40 Gateway configuration/limiter cases, including error/malformed-result refusal without forwarding. These 41 fresh cases are component proof with controlled signer-platform, policy, custody, provider and PKI inputs; they do not establish live Redis rate execution or fresh-image/runtime qualification. It starts from a controlled existing `AWAITING_PAYMENT` operation, not a newly supported subscription-create route. Fresh-image runtime proof, production registration/activation, approved finite category-specific retention/minimization/deletion/backup/provider treatment, genuine custody and live provider qualification remain held. Link validation was unrun for that historical receiving proof; later scoped documentation runs retain their own attribution. ### Canonical public Account facade receiving diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountCheckoutRegisteredReceivingPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountCheckoutRegisteredReceivingPostgresIntegrationTest.java index 76a8e86f00..5070e44f74 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountCheckoutRegisteredReceivingPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountCheckoutRegisteredReceivingPostgresIntegrationTest.java @@ -61,10 +61,15 @@ import org.jooq.DSLContext; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.AnnotationConfigUtils; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.MapPropertySource; +import org.springframework.core.io.ClassPathResource; +import org.springframework.data.redis.core.ReactiveStringRedisTemplate; +import org.springframework.data.redis.core.script.DefaultRedisScript; +import org.springframework.data.redis.core.script.RedisScript; import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.web.context.support.GenericWebApplicationContext; @@ -77,6 +82,7 @@ import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; +import reactor.core.publisher.Flux; import reactor.netty.DisposableServer; import reactor.netty.http.server.HttpServer; import tools.jackson.databind.JsonNode; @@ -335,6 +341,11 @@ void registeredChainAuthenticatesRealOwnerAndCommitsOnlyExactSignedProviderSucce } assertThat(receiving.request("GET", path, bearer, null).statusCode()).isEqualTo(401); assertThat(hosting.firstInvoiceConfirmations()).isOne(); + org.mockito.Mockito.verify(receiving.rateLimitRedis, org.mockito.Mockito.atLeastOnce()) + .execute( + org.mockito.ArgumentMatchers.same(receiving.rateLimitScript), + org.mockito.ArgumentMatchers.anyList(), + org.mockito.ArgumentMatchers.eq(List.of("20", "40", "", "1"))); } } } @@ -347,6 +358,8 @@ private static final class RegisteredChain implements AutoCloseable { private DisposableServer gatewayHttps; private HttpClient browser; private URI origin; + private ReactiveStringRedisTemplate rateLimitRedis; + private RedisScript> rateLimitScript; RegisteredChain( Path directory, @@ -562,30 +575,26 @@ private static final class RegisteredChain implements AutoCloseable { gateway.registerBean( org.springframework.cloud.gateway.config.GatewayProperties.class, () -> gatewayProperties); + rateLimitScript = canonicalRateLimitScript(); + rateLimitRedis = org.mockito.Mockito.mock(ReactiveStringRedisTemplate.class); + when(rateLimitRedis.execute( + org.mockito.ArgumentMatchers.same(rateLimitScript), + org.mockito.ArgumentMatchers.anyList(), + org.mockito.ArgumentMatchers.eq(List.of("20", "40", "", "1")))) + .thenReturn(Flux.just(List.of(1L, 39L))); + gateway.registerBean(ReactiveStringRedisTemplate.class, () -> rateLimitRedis); gateway.registerBean( - org.springframework.data.redis.core.ReactiveStringRedisTemplate.class, - () -> - org.mockito.Mockito.mock( - org.springframework.data.redis.core.ReactiveStringRedisTemplate.class)); + RedisRateLimiter.REDIS_SCRIPT_NAME, RedisScript.class, () -> rateLimitScript); gateway.register( GatewayWebFlux.class, net.firedevops.firemud.springcloudgateway.config.AccountCheckoutReceivingConfiguration .class); - // Gateway's external rate-limit decision is a stipulated upstream input in this composed - // proof; the same real selected factory and exact-path filter remain registered. - try (var rateLimiter = - mockConstruction( - org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter.class, - (mock, ignored) -> - when(mock.isAllowed( - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.anyString())) - .thenReturn( - reactor.core.publisher.Mono.just( - new org.springframework.cloud.gateway.filter.ratelimit.RateLimiter - .Response(true, Map.of()))))) { - gateway.refresh(); - } + // This non-Boot fixture supplies the same script resource/name as + // GatewayRedisAutoConfiguration. + // Only Redis execution is stipulated; the real configured adapter and exact-path filter + // run. + gateway.refresh(); + assertThat(gateway.getBean(RedisRateLimiter.REDIS_SCRIPT_NAME)).isSameAs(rateLimitScript); var httpHandler = new ReactorHttpHandlerAdapter( WebHttpHandlerBuilder.applicationContext(gateway).build()); @@ -616,6 +625,14 @@ private static final class RegisteredChain implements AutoCloseable { } } + @SuppressWarnings({"unchecked", "rawtypes"}) + private static RedisScript> canonicalRateLimitScript() { + var script = new DefaultRedisScript>(); + script.setLocation(new ClassPathResource("META-INF/scripts/request_rate_limiter.lua")); + script.setResultType((Class) List.class); + return script; + } + HttpResponse request(String method, String path, String bearer, Object body) throws Exception { var request = HttpRequest.newBuilder(origin.resolve(path)).timeout(Duration.ofSeconds(20)); From f73c7b304d1572adf84fcf6da14ab7212d4a0b8f Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 11 Nov 2026 14:52:37 +1300 Subject: [PATCH 12/29] Format checkout receiving controller test --- .../controller/AccountHostingFirstInvoiceControllerTest.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceControllerTest.java index 524a93a383..af0fe27146 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceControllerTest.java @@ -75,9 +75,7 @@ void exactControllerExceptionMappingPreservesStatusAndNoStore( static Stream ownerFailures() { return Stream.of( Arguments.of( - new AccountAsymmetricJwtVerifier.VerificationException(), - 401, - "AUTH_SESSION_REVOKED"), + new AccountAsymmetricJwtVerifier.VerificationException(), 401, "AUTH_SESSION_REVOKED"), Arguments.of( new IllegalArgumentException("private request detail"), 400, From 830ed70adcb0c7476a418ed5a20ed1f6f6063594 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 11 Nov 2026 16:41:37 +1300 Subject: [PATCH 13/29] Prove exact bound checkout through registered receiving --- ...teredReceivingPostgresIntegrationTest.java | 69 +++++++++++++++---- .../src/main/resources/openapi.yaml | 2 +- 2 files changed, 56 insertions(+), 15 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountCheckoutRegisteredReceivingPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountCheckoutRegisteredReceivingPostgresIntegrationTest.java index 5070e44f74..c02185b96f 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountCheckoutRegisteredReceivingPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountCheckoutRegisteredReceivingPostgresIntegrationTest.java @@ -59,8 +59,9 @@ import org.apache.tomcat.util.net.SSLHostConfig; import org.apache.tomcat.util.net.SSLHostConfigCertificate; import org.jooq.DSLContext; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.AnnotationConfigUtils; @@ -144,8 +145,10 @@ class AccountCheckoutRegisteredReceivingPostgresIntegrationTest { @TempDir Path temporary; - @Test - void registeredChainAuthenticatesRealOwnerAndCommitsOnlyExactSignedProviderSuccess() + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void registeredChainAuthenticatesRealOwnerAndCommitsOnlyExactSignedProviderSuccess( + boolean preRowRenewal) throws Exception { try (var upstream = new AccountControlUiOriginalOrderFixture( @@ -245,15 +248,8 @@ void registeredChainAuthenticatesRealOwnerAndCommitsOnlyExactSignedProviderSucce "POST", path + "/reauthenticate", bearer, - Map.of( - "requestId", - UUID.randomUUID(), - "confirmationRequestId", - confirmation, - "email", - account.getEmail(), - "secret", - PASSWORD)); + billingReauthentication( + tuple, confirmation, confirmation, "INITIAL_CONFIRMATION", account.getEmail())); assertThat(proof.statusCode()).isEqualTo(200); var consent = new HashMap(); consent.put("requestId", confirmation); @@ -266,13 +262,42 @@ void registeredChainAuthenticatesRealOwnerAndCommitsOnlyExactSignedProviderSucce .isEqualTo(400); assertThat(hosting.firstInvoiceConfirmations()).isZero(); consent.put("acceptCharge", true); + String authorizationPath = path + "/confirm"; + Map authorization = consent; + if (preRowRenewal) { + assertThat( + JSON.readTree(receiving.request("GET", path, bearer, null).body()) + .path("confirmationRequestId") + .isNull()) + .isTrue(); + UUID renewal = UUID.randomUUID(); + var renewalProof = + receiving.request( + "POST", + path + "/reauthenticate", + bearer, + billingReauthentication( + tuple, confirmation, renewal, "PRE_ROW_RENEWAL", account.getEmail())); + assertThat(renewalProof.statusCode()).isEqualTo(200); + authorizationPath = path + "/renew"; + authorization = new HashMap<>(consent); + authorization.put("authorizationRequestId", renewal); + authorization.put("expectedAuthorizationVersion", 0L); + authorization.put( + "reauthenticationEvidenceId", + JSON.readTree(renewalProof.body()).path("evidenceId").asText()); + } hosting.firstInvoiceConfirmationStatus("requires_action"); - var handoff = receiving.request("POST", path + "/confirm", bearer, consent); + var handoff = receiving.request("POST", authorizationPath, bearer, authorization); assertThat(handoff.statusCode()).isEqualTo(200); assertThat(JSON.readTree(handoff.body()).path("status").asText()) .isEqualTo("requires_action"); - assertThat(receiving.request("POST", path + "/confirm", bearer, consent).statusCode()) + assertThat(receiving.request("POST", authorizationPath, bearer, authorization).statusCode()) .isEqualTo(200); + if (preRowRenewal) { + assertThat(receiving.request("POST", path + "/confirm", bearer, consent).statusCode()) + .isEqualTo(409); + } assertThat(hosting.firstInvoiceConfirmations()).isOne(); assertThat( JSON.readTree(receiving.request("GET", path, bearer, null).body()) @@ -350,6 +375,22 @@ void registeredChainAuthenticatesRealOwnerAndCommitsOnlyExactSignedProviderSucce } } + private static Map billingReauthentication( + JsonNode tuple, UUID original, UUID authorization, String purpose, String email) { + return Map.of( + "requestId", UUID.randomUUID(), + "confirmationRequestId", authorization, + "billingBinding", Map.of( + "originalRequestId", original, + "expectedRowVersion", tuple.path("expectedRowVersion").asLong(), + "expectedAuthorizationVersion", tuple.path("authorizationVersion").asLong(), + "acceptedTupleDigest", tuple.path("tupleDigest").asText(), + "invoiceExpiresAt", tuple.path("expiresAt").asText(), + "authorizationPurpose", purpose), + "email", email, + "secret", PASSWORD); + } + private static final class RegisteredChain implements AutoCloseable { private GenericWebApplicationContext account; private Tomcat tomcat; diff --git a/services/spring-cloud-gateway/src/main/resources/openapi.yaml b/services/spring-cloud-gateway/src/main/resources/openapi.yaml index cd21120af2..fa20f31d10 100644 --- a/services/spring-cloud-gateway/src/main/resources/openapi.yaml +++ b/services/spring-cloud-gateway/src/main/resources/openapi.yaml @@ -113,7 +113,7 @@ paths: operationId: reauthenticateAccountHostingFirstInvoice summary: Reauthenticate the first-invoice billing owner x-runtime-status: isolated_only_default_off - description: Exact HTTPS Account billing-owner operation. Passes only the necessary authenticated request over verified TLS without retry; Account owns the charge tuple, reauthentication, consent and result. + description: Exact HTTPS Account billing-owner operation. Passes only the necessary authenticated request over verified TLS without retry; Account owns the charge tuple, reauthentication, consent and result. Account validates the typed billingBinding against the retained invoice and authorization attempt. responses: '200': {description: No-store Account owner result under the Account first-invoice API contract} '400': {description: Malformed request} From 8ce1debf5e7fbf6cce707a2ec29b1d885caaaa6b Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 11 Nov 2026 16:47:27 +1300 Subject: [PATCH 14/29] Format registered checkout proof --- ...steredReceivingPostgresIntegrationTest.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountCheckoutRegisteredReceivingPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountCheckoutRegisteredReceivingPostgresIntegrationTest.java index c02185b96f..2a4f1f272b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountCheckoutRegisteredReceivingPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountCheckoutRegisteredReceivingPostgresIntegrationTest.java @@ -148,8 +148,7 @@ class AccountCheckoutRegisteredReceivingPostgresIntegrationTest { @ParameterizedTest @ValueSource(booleans = {false, true}) void registeredChainAuthenticatesRealOwnerAndCommitsOnlyExactSignedProviderSuccess( - boolean preRowRenewal) - throws Exception { + boolean preRowRenewal) throws Exception { try (var upstream = new AccountControlUiOriginalOrderFixture( postgres.getJdbcUrl(), @@ -380,13 +379,14 @@ private static Map billingReauthentication( return Map.of( "requestId", UUID.randomUUID(), "confirmationRequestId", authorization, - "billingBinding", Map.of( - "originalRequestId", original, - "expectedRowVersion", tuple.path("expectedRowVersion").asLong(), - "expectedAuthorizationVersion", tuple.path("authorizationVersion").asLong(), - "acceptedTupleDigest", tuple.path("tupleDigest").asText(), - "invoiceExpiresAt", tuple.path("expiresAt").asText(), - "authorizationPurpose", purpose), + "billingBinding", + Map.of( + "originalRequestId", original, + "expectedRowVersion", tuple.path("expectedRowVersion").asLong(), + "expectedAuthorizationVersion", tuple.path("authorizationVersion").asLong(), + "acceptedTupleDigest", tuple.path("tupleDigest").asText(), + "invoiceExpiresAt", tuple.path("expiresAt").asText(), + "authorizationPurpose", purpose), "email", email, "secret", PASSWORD); } From 99a6f8aa53eacb84cbc4b2debd96f16e6784f28b Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 11 Nov 2026 20:04:23 +1300 Subject: [PATCH 15/29] Map checkout owner transaction failures to unavailable --- .../AccountHostingFirstInvoiceController.java | 3 +- .../AccountCheckoutHttpAuthInterceptor.java | 1 + ...ountHostingFirstInvoiceControllerTest.java | 15 +++++++++ ...ccountCheckoutHttpAuthInterceptorTest.java | 31 ++++++++++++++----- 4 files changed, 42 insertions(+), 8 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceController.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceController.java index d6907a834c..f55a6178d0 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceController.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceController.java @@ -139,7 +139,8 @@ public AccountHostingFirstInvoicePaymentService.Completion signedCompletion( net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceUnavailableException.class, net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier .VerificationUnavailableException.class, - org.springframework.dao.DataAccessException.class + org.springframework.dao.DataAccessException.class, + org.springframework.transaction.TransactionException.class }) public ResponseEntity authenticationUnavailable() { return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountCheckoutHttpAuthInterceptor.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountCheckoutHttpAuthInterceptor.java index 43433e5c6b..5cc3d0b282 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountCheckoutHttpAuthInterceptor.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountCheckoutHttpAuthInterceptor.java @@ -68,6 +68,7 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons // Every owner mutation repeats currentness inside its actual owner transaction. return true; } catch (org.springframework.dao.DataAccessException + | org.springframework.transaction.TransactionException | io.lettuce.core.RedisException | net.firedevops.firemud.accountservice.service.session.AccountControlUiRegistryReader .RegistryUnavailableException diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceControllerTest.java index af0fe27146..560ae5e6d7 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceControllerTest.java @@ -74,6 +74,21 @@ void exactControllerExceptionMappingPreservesStatusAndNoStore( static Stream ownerFailures() { return Stream.of( + Arguments.of( + new org.springframework.transaction.CannotCreateTransactionException( + "private database connection detail"), + 503, + "AUTH_UNAVAILABLE"), + Arguments.of( + new org.springframework.transaction.TransactionSystemException( + "private transaction detail"), + 503, + "AUTH_UNAVAILABLE"), + Arguments.of( + new org.springframework.transaction.UnexpectedRollbackException( + "private rollback detail"), + 503, + "AUTH_UNAVAILABLE"), Arguments.of( new AccountAsymmetricJwtVerifier.VerificationException(), 401, "AUTH_SESSION_REVOKED"), Arguments.of( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountCheckoutHttpAuthInterceptorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountCheckoutHttpAuthInterceptorTest.java index 7213846e11..d9262878ab 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountCheckoutHttpAuthInterceptorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountCheckoutHttpAuthInterceptorTest.java @@ -4,6 +4,7 @@ import static org.mockito.Mockito.*; import java.util.UUID; +import java.util.stream.Stream; import net.firedevops.firemud.accountservice.controller.AccountHostingFirstInvoiceController; import net.firedevops.firemud.accountservice.controller.AccountHostingFirstInvoiceWebhookController; import net.firedevops.firemud.accountservice.service.session.AccountControlUiActorService; @@ -11,6 +12,8 @@ import net.firedevops.firemud.common.security.HttpAuthProperties; import net.firedevops.firemud.common.security.JwtUtil; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.web.method.HandlerMethod; @@ -70,8 +73,10 @@ void forgedForwardedSchemeAndMissingOrRejectedBearerNeverReachOwner() throws Exc assertThat(response.getStatus()).isEqualTo(401); } - @Test - void unavailableJwksDoesNotMisreportSessionRevocation() throws Exception { + @ParameterizedTest + @MethodSource("unavailableAuthorities") + void unavailableAuthorityDoesNotMisreportSessionRevocation(RuntimeException failure) + throws Exception { var actors = mock(AccountControlUiActorService.class); var interceptor = new AccountCheckoutHttpAuthInterceptor( @@ -88,14 +93,26 @@ void unavailableJwksDoesNotMisreportSessionRevocation() throws Exception { new MockHttpServletRequest("GET", "/billing/hosting/subscriptions/x/first-invoice"); request.setSecure(true); request.addHeader("Authorization", "Bearer controlled"); - doThrow( - new net.firedevops.firemud.common.security.AccountPublicJwksCache - .SourceUnavailableException()) - .when(actors) - .authenticateAccount("controlled"); + doThrow(failure).when(actors).authenticateAccount("controlled"); var response = new MockHttpServletResponse(); assertThat(interceptor.preHandle(request, response, handler)).isFalse(); assertThat(response.getStatus()).isEqualTo(503); + assertThat(response.getHeader("Cache-Control")).isEqualTo("no-store"); + assertThat(response.getHeader("Pragma")).isEqualTo("no-cache"); + assertThat(response.getContentAsString()).isEmpty(); + verify(actors).authenticateAccount("controlled"); + verifyNoMoreInteractions(actors); + } + + static Stream unavailableAuthorities() { + return Stream.of( + new net.firedevops.firemud.common.security.AccountPublicJwksCache + .SourceUnavailableException(), + new org.springframework.transaction.CannotCreateTransactionException( + "private database connection detail"), + new org.springframework.transaction.TransactionSystemException( + "private transaction detail"), + new org.springframework.transaction.UnexpectedRollbackException("private rollback detail")); } @Test From dad692ed3ad57ac914d73415f18e0b9d723e3930 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 12 Nov 2026 01:18:10 +1300 Subject: [PATCH 16/29] Use the first Stripe handle from the original loading context --- .../src/account/AccountCheckoutRoute.test.tsx | 132 ++++++++++++++++++ .../src/account/AccountCheckoutRoute.tsx | 9 ++ .../HostingFirstInvoiceCheckout.test.tsx | 72 +++++++++- .../billing/HostingFirstInvoiceCheckout.tsx | 24 +++- 4 files changed, 229 insertions(+), 8 deletions(-) diff --git a/web-client/src/account/AccountCheckoutRoute.test.tsx b/web-client/src/account/AccountCheckoutRoute.test.tsx index 3aa5c41ea8..44068d5be4 100644 --- a/web-client/src/account/AccountCheckoutRoute.test.tsx +++ b/web-client/src/account/AccountCheckoutRoute.test.tsx @@ -250,6 +250,138 @@ describe('App-owned first-invoice route', () => { ).toBe(true); }); + it.each(['unchanged', 'replaced key', 'replaced loader'])( + 'binds an in-flight confirmation to its %s Stripe loading context', + async (contextChange) => { + const loading = deferred(); + const replacementLoading = deferred(); + const confirmation = deferred(); + const stripe: HostingStripe = { + handleNextAction: vi.fn().mockResolvedValue({}), + }; + const replacement: HostingStripe = { + handleNextAction: vi.fn().mockResolvedValue({}), + }; + const loader = vi + .fn() + .mockReturnValueOnce(loading.promise) + .mockReturnValue(replacementLoading.promise); + const replacementLoader = vi + .fn() + .mockReturnValue(replacementLoading.promise); + const { api, fetchImpl, queries, rerender, sessionStore } = setupApp({ + loadStripeClient: loader, + }); + const read = fetchImpl.getMockImplementation()!; + fetchImpl.mockImplementation(async (input, init) => { + if (String(input).endsWith('/reauthenticate')) { + return new Response( + JSON.stringify({ + evidenceId: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', + }), + { status: 200 } + ); + } + if (String(input).endsWith('/confirm')) return confirmation.promise; + return read(input, init); + }); + await signIn(); + fireEvent.change(screen.getByLabelText('Account email'), { + target: { value: 'owner@example.com' }, + }); + fireEvent.change(screen.getByLabelText('Primary authentication secret'), { + target: { value: 'primary-secret' }, + }); + fireEvent.click(screen.getByRole('checkbox')); + fireEvent.click( + screen.getByRole('button', { name: 'Authorize first-invoice charge' }) + ); + await waitFor(() => + expect( + fetchImpl.mock.calls.filter(([input]) => + String(input).endsWith('/confirm') + ) + ).toHaveLength(1) + ); + + if (contextChange !== 'unchanged') { + rerender( + + + + ); + } + await act(async () => { + loading.resolve(stripe); + await loading.promise; + }); + if (contextChange !== 'unchanged') { + expect( + screen.getByText('Loading secure payment authentication.') + ).toBeTruthy(); + await act(async () => { + replacementLoading.resolve(replacement); + await replacementLoading.promise; + }); + } + await waitFor(() => + expect( + screen.queryByText('Loading secure payment authentication.') + ).toBeNull() + ); + await act(async () => { + confirmation.resolve( + new Response( + JSON.stringify({ + status: 'requires_action', + clientSecret: 'pi_existing_secret_ephemeral', + }), + { status: 200 } + ) + ); + await confirmation.promise; + }); + if (contextChange === 'unchanged') { + await waitFor(() => + expect(stripe.handleNextAction).toHaveBeenCalledExactlyOnceWith({ + clientSecret: 'pi_existing_secret_ephemeral', + }) + ); + } else { + await screen.findByText( + /Stripe authentication is unavailable. Check Account status/ + ); + expect(stripe.handleNextAction).not.toHaveBeenCalled(); + } + expect(replacement.handleNextAction).not.toHaveBeenCalled(); + expect( + fetchImpl.mock.calls.filter(([input]) => + String(input).endsWith('/confirm') + ) + ).toHaveLength(1); + expect( + fetchImpl.mock.calls.some(([input]) => String(input).endsWith('/renew')) + ).toBe(false); + expect(screen.queryByText(/Account confirmed and committed/)).toBeNull(); + expect(document.body.textContent).not.toContain( + 'pi_existing_secret_ephemeral' + ); + } + ); + it.each([0, 429, 502, 503])( 'shows safe temporary feedback for sign-in status %i without retrying', async (status) => { diff --git a/web-client/src/account/AccountCheckoutRoute.tsx b/web-client/src/account/AccountCheckoutRoute.tsx index 92431a396d..5210dbfe6d 100644 --- a/web-client/src/account/AccountCheckoutRoute.tsx +++ b/web-client/src/account/AccountCheckoutRoute.tsx @@ -210,6 +210,14 @@ function CheckoutForSession({ }: CheckoutProps) { const [stripeLoadResult, setStripeLoadResult] = useState(null); + const stripeContext = useMemo( + () => ({ + sessionIdentity, + publishableKey: stripePublishableKey, + loader: loadStripeClient, + }), + [sessionIdentity, stripePublishableKey, loadStripeClient] + ); const client = useMemo( () => createFirstInvoiceClient( @@ -285,6 +293,7 @@ function CheckoutForSession({ () { function setup(value: FirstInvoice = initial, stripeAvailable = true) { let current = value; + let stripeContext = {}; const client = { read: vi .fn() @@ -79,6 +80,7 @@ function setup(value: FirstInvoice = initial, stripeAvailable = true) { @@ -86,16 +88,19 @@ function setup(value: FirstInvoice = initial, stripeAvailable = true) { return { client, stripe, - replaceStripe: (next: HostingStripe | null) => + replaceStripe: (next: HostingStripe | null, context = stripeContext) => { + stripeContext = context; view.rerender( - ), + ); + }, setCurrent: (next: FirstInvoice) => { current = next; }, @@ -149,7 +154,68 @@ describe('owner first-invoice checkout', () => { ); }); - it('preserves the original confirmation but refuses a replaced Stripe context', async () => { + it('uses the first Stripe handle loaded while the original confirmation is in flight', async () => { + const { client, stripe, replaceStripe } = setup(initial, false); + const confirmation = deferred<{ status: string; clientSecret: string }>(); + client.confirm.mockReturnValue(confirmation.promise); + fireEvent.click(await consent()); + await waitFor(() => expect(client.confirm).toHaveBeenCalledTimes(1)); + replaceStripe(stripe); + await act(async () => + confirmation.resolve({ + status: 'requires_action', + clientSecret: 'pi_existing_secret_ephemeral', + }) + ); + await waitFor(() => + expect(stripe.handleNextAction).toHaveBeenCalledExactlyOnceWith({ + clientSecret: 'pi_existing_secret_ephemeral', + }) + ); + expect(client.confirm).toHaveBeenCalledTimes(1); + expect(client.reauthenticate).toHaveBeenCalledTimes(1); + expect(client.renew).not.toHaveBeenCalled(); + expect(screen.queryByText(/Account confirmed and committed/)).toBeNull(); + expect(document.body.textContent).not.toContain( + 'pi_existing_secret_ephemeral' + ); + }); + + it.each(['handle', 'context'])( + 'refuses a replaced Stripe %s after its first handle loads in flight', + async (replacementKind) => { + const { client, stripe, replaceStripe } = setup(initial, false); + const confirmation = deferred<{ status: string; clientSecret: string }>(); + client.confirm.mockReturnValue(confirmation.promise); + fireEvent.click(await consent()); + await waitFor(() => expect(client.confirm).toHaveBeenCalledTimes(1)); + replaceStripe(stripe); + const replacement = { + handleNextAction: vi.fn(), + }; + if (replacementKind === 'handle') { + replaceStripe(replacement); + replaceStripe(stripe); + } else { + replaceStripe(stripe, {}); + } + await act(async () => + confirmation.resolve({ + status: 'requires_action', + clientSecret: 'pi_existing_secret_ephemeral', + }) + ); + await screen.findByText( + /Stripe authentication is unavailable. Check Account status/ + ); + expect(stripe.handleNextAction).not.toHaveBeenCalled(); + expect(replacement.handleNextAction).not.toHaveBeenCalled(); + expect(client.confirm).toHaveBeenCalledTimes(1); + expect(client.renew).not.toHaveBeenCalled(); + } + ); + + it('preserves the original confirmation but refuses a replaced Stripe handle', async () => { const { client, stripe, replaceStripe } = setup(); const confirmation = deferred<{ status: string; clientSecret: string }>(); client.confirm.mockReturnValue(confirmation.promise); diff --git a/web-client/src/billing/HostingFirstInvoiceCheckout.tsx b/web-client/src/billing/HostingFirstInvoiceCheckout.tsx index 8d992101ee..a731b6d4ea 100644 --- a/web-client/src/billing/HostingFirstInvoiceCheckout.tsx +++ b/web-client/src/billing/HostingFirstInvoiceCheckout.tsx @@ -20,6 +20,7 @@ import type { HostingStripe } from './hostingStripe'; interface Props { subscriptionId: string; client: FirstInvoiceClient; + stripeContext: object; stripe: HostingStripe | null; } @@ -41,6 +42,7 @@ interface Attempt { export default function HostingFirstInvoiceCheckout({ subscriptionId, client, + stripeContext, stripe, }: Props) { const queryId = useId(); @@ -62,11 +64,21 @@ export default function HostingFirstInvoiceCheckout({ const attempt = useRef(null); const locked = useRef(false); const operation = useRef(0); - const currentStripe = useRef(stripe); + const currentStripe = useRef({ context: stripeContext, stripe }); useLayoutEffect(() => { - currentStripe.current = stripe; - }, [stripe]); + const current = currentStripe.current; + if ( + current.context !== stripeContext || + (current.stripe !== null && current.stripe !== stripe) + ) { + currentStripe.current = { context: stripeContext, stripe }; + } else { + // A first load may finish in flight; replacing its context or handle + // invalidates the old binding even if that context or handle returns. + current.stripe = stripe; + } + }, [stripeContext, stripe]); useEffect(() => { const tick = window.setInterval(() => setNow(Date.now()), 1000); @@ -159,6 +171,7 @@ export default function HostingFirstInvoiceCheckout({ setBusy(true); const currentOperation = ++operation.current; const active = () => operation.current === currentOperation; + const submittedStripe = currentStripe.current; const credentials = { email, secret }; setSecret(''); setMessage('Checking the current Account invoice before confirmation.'); @@ -285,7 +298,8 @@ export default function HostingFirstInvoiceCheckout({ 'Account retained the authorization, but provider confirmation is unresolved. Only status recovery is available. No replacement charge was requested.' ); } else if (handoff.status === 'requires_action' && handoff.clientSecret) { - if (!stripe || currentStripe.current !== stripe) { + const loadedStripe = submittedStripe.stripe; + if (!loadedStripe || currentStripe.current !== submittedStripe) { setMessage( 'Stripe authentication is unavailable. Check Account status or explicitly resume this same confirmation when authentication is available.' ); @@ -296,7 +310,7 @@ export default function HostingFirstInvoiceCheckout({ 'Complete the Stripe authentication prompt for this invoice.' ); // The server already confirmed this exact intent. Never confirm/create another. - const result = await stripe.handleNextAction({ + const result = await loadedStripe.handleNextAction({ clientSecret: handoff.clientSecret, }); if (!active()) return; From e61301f73ebdae9f41a2e6d36aea54da6a36ceb1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 13 Nov 2026 02:36:36 +1300 Subject: [PATCH 17/29] Bound Account sign-in and preserve exact uncertain retry --- .../account-service/api-contracts.md | 6 +- .../account-service/stripe-integration.md | 4 +- .../src/main/resources/openapi.yaml | 10 +- .../config/GatewayRateLimiterConfig.java | 9 +- .../config/GatewayRateLimiterConfigTest.java | 34 +++++++ .../AccountCheckoutGatewayControllerTest.java | 14 ++- .../src/account/AccountCheckoutRoute.test.tsx | 58 +++++++++++- .../src/account/AccountCheckoutRoute.tsx | 28 ++++-- .../src/account/controlUiSession.test.ts | 67 ++++++++++++- web-client/src/account/controlUiSession.ts | 56 ++++++++++- web-client/src/api/accountControlUi.test.ts | 68 +++++++++++++- web-client/src/api/accountControlUi.ts | 93 +++++++++++++------ 12 files changed, 390 insertions(+), 57 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 3aa31493d7..d5fce6143b 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -547,12 +547,12 @@ The private self-service game-creation reauthentication owner binds exact origin The isolated receiving login is public `POST /api/account/auth/login` at Gateway. Its bounded JSON body is `{requestId, callerContextId, email, secret}`, with non-nil request/context UUIDs and one enabled ordinary primary secret. Gateway authenticates Account's exact same-namespace URI SAN before releasing credentials over the narrow mTLS `AccountControlUiAuthenticationService/AuthLogin` RPC. Account permits only the exact same-namespace Gateway workload and delegates to its durable Account-only issuer and current-actor owners. Gateway's existing header-trust WebFilter supplies a process-private canonical source proof; the controller does not interpret public source headers as proof. The closed RPC requires one canonical literal client address and the fixed HTTP transport class, and Account carries that transient source into the sign-in owner. Missing Gateway proof returns no-store HTTP 503 before credential forwarding; absent, duplicate, malformed or unsupported wire source fields are rejected before issuance. Source metadata does not change the retained v1 credential-request MAC or reset its replay budget. Success is `{status: SUCCESS, data: {accountId, authToken, expiresAt}}`, with no-store headers. Exact retries retain the same issuance; changed input conflicts. Credential-bearing replay uses a constant-time MAC comparison and an Account-owned, serialized five-failure budget bound to the immutable original issuance operation and request. Failed comparisons commit independent immutable attempt records before returning the conflict; after five failures, that request is denied before credential-MAC access. Exact retries below the budget recover the original credential without primary reauthentication or another OTP consumption, and never reset the budget. Scope, caller or context conflicts and unavailable custody are not counted as credential failures. This short recovery-request budget changes neither Account security state nor other requests and does not replace the broader credential-abuse policy in [ADR 0034](../../decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md). The direct legacy Account HTTP login is rejected in this isolated mode and cannot provide a checkout fallback. Production legacy-login drift elsewhere remains unchanged. -The first-party `/account/subscriptions/{subscriptionId}/checkout` route obtains its bearer only from that login, holds it in memory, restricts authenticated requests to the exact owner endpoints, and unmounts checkout on expiry, local sign-out, session replacement or route departure. Local sign-out clears this UI's credentials; it does not claim server-side token revocation. Navigation, Back/Forward, reload and remount never authorize a provider command. +The first-party `/account/subscriptions/{subscriptionId}/checkout` route obtains its bearer only from that login, holds it in memory, restricts authenticated requests to the exact owner endpoints, and unmounts checkout on expiry, local sign-out, session replacement or route departure. The browser bounds login dispatch and response-body consumption to ten seconds. An uncertain response lets the user re-enter the original secret and retry with the same request IDs for up to one minute from first submission. Only the original IDs, email and deadline remain in browser memory for that retry. Local sign-out clears this UI's credentials; it does not claim server-side token revocation. Navigation, Back/Forward, reload and remount never authorize a provider command. -The Account-owned HTTPS owner surface is `/billing/hosting/subscriptions/{subscriptionId}/first-invoice`, externally prefixed by `/api/account`. It is an account-scoped billing-owner operation, not tenant-role authority: the exact current `control-ui` Account subject must own the subscription and selected instrument. Billing suspension does not remove this recovery surface. The controller is registered only by the explicitly isolated, default-off receiving composition; the [Stripe owner contract](./stripe-integration.md#first-invoice-confirmation-and-completion) and existing retention, deletion, backup, custody and registration gates remain binding. +The Account-owned HTTPS owner surface is `/billing/hosting/subscriptions/{subscriptionId}/first-invoice`, externally prefixed by `/api/account`. It is an account-scoped billing-owner operation, not tenant-role authority: the exact current `control-ui` Account subject must own the subscription and selected instrument. Billing suspension does not remove this recovery surface. The handlers register only in the explicitly isolated, default-off controlled-fixture composition; this does not enable actual provider or customer-data intake. Live provider/customer qualification and the applicable retention, deletion, backup, custody and deployment prerequisites remain necessary before production intake, as defined by the [Stripe owner contract](./stripe-integration.md#first-invoice-confirmation-and-completion). - `GET` returns the exact existing invoice, PaymentIntent, selected instrument, amount, currency, immutable `tupleDigest`, expected current subscription row version, expiry, nullable retained `confirmationRequestId`, nullable server-verified `preRowOriginalRequestId`, current `authorizationVersion` (zero before first consent) and `AWAITING_PAYMENT` or `COMMITTED` state. `amount` is a positive decimal integer string in Stripe minor units, not a floating-point or major-unit amount. No client secret appears in status, URLs, logs or audit. A null `confirmationRequestId` means only that no confirmation row is currently committed; it does not prove that an original operation has stopped. That absence does not authorize a replacement request or charge. Before a confirmation row exists, `preRowOriginalRequestId` exposes only the original operation identity from an exact owner/subscription/tuple/row-version/expiry-verified durable fence at authorization version zero; inconsistent retained evidence refuses the read instead of appearing absent. A committed confirmation takes precedence and makes this pre-row reference null. Navigation or replacement login may recover this identity through a fresh authenticated owner read, never earlier consent or proof. Resumption requires a separate explicit renewal action, fresh unchanged charge consent and primary authentication bound to `PRE_ROW_RENEWAL` with a distinct authorization request. Expired status is observational and never extends renewal eligibility. Recovery semantics remain owned by the [Stripe contract](./stripe-integration.md#first-invoice-confirmation-and-completion). -- `POST /reauthenticate` takes distinct stable evidence `requestId` and `confirmationRequestId` plus one enabled ordinary login secret over HTTPS. A proof usable for new billing consent requires `billingBinding` with `originalRequestId`, `expectedRowVersion`, `expectedAuthorizationVersion`, `acceptedTupleDigest`, `invoiceExpiresAt`, and `authorizationPurpose`; `confirmationRequestId` names that binding's authorization request. Use `INITIAL_CONFIRMATION` with the original request ID and version zero for opening proof, `PRE_ROW_RENEWAL` with the retained original ID and a distinct authorization request at version zero for pre-row recovery, or `FOLLOWUP_RENEWAL` for a later retained authorization version. Account returns a newly bound proof only after actual primary authentication and exact owner binding. A replayed unbound historical `evidenceId` remains non-authorizing for new consent. `SELF_SERVICE_GAME_CREATION` evidence is rejected for payment. The [Stripe owner contract](./stripe-integration.md#durable-opening-proof-and-explicit-pre-row-renewal) defines the binding and recovery behavior. +- `POST /reauthenticate` takes distinct stable evidence `requestId` and `confirmationRequestId` plus one enabled ordinary login secret over HTTPS. A new billing proof requires `billingBinding` with `originalRequestId`, `expectedRowVersion`, `expectedAuthorizationVersion`, `acceptedTupleDigest`, `invoiceExpiresAt`, and `authorizationPurpose`; `confirmationRequestId` names that binding's authorization request. Use `INITIAL_CONFIRMATION` with the original request ID and version zero for opening proof, `PRE_ROW_RENEWAL` with the retained original ID and a distinct authorization request at version zero for pre-row recovery, or `FOLLOWUP_RENEWAL` for a later retained authorization version. Account returns a newly bound proof only after actual primary authentication and exact owner binding. Omitting `billingBinding` is allowed only to replay the exact previously retained unbound historical request; it returns the original evidence and creates no new evidence. A fresh unbound billing request returns HTTP 409 before evidence is written, and any replayed unbound evidence remains non-authorizing for consent or payment. `SELF_SERVICE_GAME_CREATION` evidence is rejected for payment. The [Stripe owner contract](./stripe-integration.md#durable-opening-proof-and-explicit-pre-row-renewal) defines the binding and recovery behavior. - `POST /confirm` takes the immutable confirmation `requestId`, `expectedRowVersion`, `reauthenticationEvidenceId`, exact `acceptedTupleDigest` and explicit `acceptCharge=true`. The server resolves the retained commercial tuple; client amounts, instrument substitutions and provider defaults cannot change it. An exact retry retains the original operation and provider idempotency identity. Changed request fields conflict. - `POST /renew` takes the original confirmation `requestId`, distinct fresh `authorizationRequestId`, `expectedAuthorizationVersion`, original `expectedRowVersion`, fresh `reauthenticationEvidenceId`, unchanged `acceptedTupleDigest` and explicit `acceptCharge=true`. For pre-row renewal, use expected authorization version zero and `PRE_ROW_RENEWAL` proof from `/reauthenticate`; after a retained first consent, use the exact current version and `FOLLOWUP_RENEWAL` proof. Exact renewal replay is read-only; changed evidence, consent, payment identity or losing authorization version conflicts. Renewal never resets invoice expiry or provider command history. The [Stripe owner contract](./stripe-integration.md#durable-opening-proof-and-explicit-pre-row-renewal) owns the recovery behavior and single-command boundary. - The narrowly authorized owner response returns provider status and a client secret only for `requires_action`, with `Cache-Control: no-store`. Stripe.js `handleNextAction` completes provider authentication for that existing intent. A browser result never completes Account fulfillment; the owner polls status until the signed server completion has committed and independently read back. diff --git a/design/architecture/microservices/account-service/stripe-integration.md b/design/architecture/microservices/account-service/stripe-integration.md index af58f6aa50..9a5bdddb0e 100644 --- a/design/architecture/microservices/account-service/stripe-integration.md +++ b/design/architecture/microservices/account-service/stripe-integration.md @@ -44,7 +44,7 @@ The account-owned wallet contracts are also target state. Per-subscription instr ## First-Invoice Confirmation and Completion -The [isolated receiving composition](./configuration.md#isolated-first-invoice-receiving-configuration) registers the existing owner through actual Gateway/Account HTTPS and genuine Account-session authentication, plus a separate exact-byte signed-event adapter. This controlled-fixture-only source-level integration does not authorize intake of real provider or customer data, qualify a live provider, supply approved retention values or activate production billing. Handler registration is not permission to bypass the finite-retention, minimization, erasure, legal-hold, backup or provider-qualification gates above. +The [isolated receiving composition](./configuration.md#isolated-first-invoice-receiving-configuration) registers the existing owner through actual Gateway/Account HTTPS and genuine Account-session authentication, plus a separate exact-byte signed-event adapter. These default-off handlers are registered only for controlled fixtures and source-level integration; they do not enable intake of real provider or customer data. Actual provider and customer intake remains closed until the live provider and customer-data paths are separately qualified and the applicable retention, minimization, erasure, legal-hold, backup, source-custody and deployment prerequisites above are satisfied. Handler registration itself supplies none of those approvals or production capabilities. `DEFAULT_INCOMPLETE` creation and subscription polling do not confirm the initial PaymentIntent. Account first retains the exact existing first invoice, its sole existing PaymentIntent, canonical provider subscription/customer, explicitly selected saved instrument and reserved version, provider method, versioned commercial policy/quote, positive minor-unit amount, currency and provider mode. Provider linkage remains `provisioning` with durable `AWAITING_PAYMENT` work and grants no hosting authority. The instrument reservation remains held through Stripe's original 23-hour incomplete-subscription boundary and until explicit terminal cleanup; expiry never creates a replacement subscription, PaymentIntent or Checkout Session. @@ -62,6 +62,8 @@ An absent committed confirmation ID cannot authorize replacement consent, reques Before returning usable opening `HOSTING_FIRST_INVOICE_PAYMENT` reauthentication proof, Account durably retains one original-operation fence for the exact owned `AWAITING_PAYMENT` invoice. The immutable typed billing context and fence bind the authenticated Account, subscription and current subscription-row version, original operation ID, exact invoice tuple digest and original invoice expiry, authorization request identity and purpose, and expected authorization version. The current authenticated Account transaction verifies or exactly replays that context under the owner locks and retains the fence before returning the proof. A failed fence bind cannot redirect evidence to another invoice, operation, row version, or authorization purpose. Unbound historical billing evidence remains retained but cannot authorize a new first consent or pre-row renewal; a nullable confirmation ID from status is observational only. +Every new billing reauthentication request must carry the exact `billingBinding` for its intended authorization. A request with no binding can only replay the exact previously retained unbound historical request; it returns that same evidence without creating new evidence. A fresh unbound billing request is refused with HTTP 409 before evidence or an original-operation fence is written. Historical unbound evidence remains non-authorizing and cannot be used for first-invoice consent. + Original confirmation and an explicitly requested pre-row renewal serialize under the same Account owner/subscription locks and original-operation fence, preserving the established source/evidence/owner lock order. A pre-row renewal must name that exact original operation, a distinct authorization request, expected authorization version zero, fresh typed billing reauthentication for `PRE_ROW_RENEWAL`, and unchanged explicit charge consent. In one owner transaction, either the original confirmation or this renewal may create the sole first consent and first authorization/dispatch winner. If confirmation wins, renewal is stale and consumes nothing. If renewal wins, the original operation and opening evidence remain retained and unchanged, and the delayed original confirmation cannot replace the winning authorization. Losing, rolled-back, stale, changed, expired, or mismatched evidence consumes no reauthentication proof and authorizes no dispatch; rollback leaves the fence and original evidence intact. Exact retries replay the retained winner without another provider command, using the existing independent readback and single command claim/provider idempotency boundary. This path never creates a replacement subscription, invoice, PaymentIntent, charge, automatic renewal, or post-expiry activation. Existing post-row renewal remains the distinct follow-up path above, and old retained confirmations remain authoritative only for their existing scoped recovery. Production registration remains held by the category-specific retention/minimization, deletion, backup, source-custody and provider qualification prerequisites above. This production hold is distinct from registration of the default-off isolated receiving handlers, which does not enable production billing or hosted activation. Controlled SDK or SQL tests do not establish live Stripe/SCA support or deployment activation. diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index 747e7cbb3b..2e9f153fcc 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -344,7 +344,7 @@ paths: operationId: receiveHostingFirstInvoiceSignedEvent x-runtime-status: isolated_only_default_off summary: Receive an exact raw provider-signed first-invoice event - description: Actual HTTPS only. Single bounded signature and exact raw UTF-8 body; provider signature is independent of user authentication. Default production registration stays closed. + description: Actual HTTPS only. Single bounded signature and exact raw UTF-8 body; provider signature is independent of user authentication. This handler is default-off and registered only for controlled-fixture source integration. Actual provider/customer data intake requires separate live-provider and customer-data qualification plus the applicable retention, custody and deployment prerequisites; production registration remains closed. security: [] parameters: - name: Stripe-Signature @@ -411,7 +411,7 @@ paths: summary: Reauthenticate the current billing owner for first-invoice payment operationId: reauthenticateHostingFirstInvoice x-runtime-status: isolated_only_default_off - description: Actual ordinary primary authentication for HOSTING_FIRST_INVOICE_PAYMENT. No gameplay or game-creation proof accepted. + description: Actual ordinary primary authentication for HOSTING_FIRST_INVOICE_PAYMENT. A new billing proof requires an exact billingBinding. Omitting billingBinding only replays an exact previously retained unbound historical request; a fresh unbound billing request returns 409 without creating evidence, and historical unbound evidence cannot authorize consent. No gameplay or game-creation proof accepted. requestBody: required: true content: @@ -419,7 +419,7 @@ paths: schema: type: object additionalProperties: false - required: [requestId, confirmationRequestId, email, secret, billingBinding] + required: [requestId, confirmationRequestId, email, secret] properties: requestId: {type: string, format: uuid} confirmationRequestId: {type: string, format: uuid} @@ -428,7 +428,7 @@ paths: billingBinding: type: object additionalProperties: false - description: Required for a new billing proof. Bind the exact retained invoice and original operation; unbound historical evidence cannot authorize new consent. + description: Required for a new billing proof. Bind the exact retained invoice and original operation. Omission permits only exact replay of a previously retained unbound historical request and cannot create new evidence or authorize consent. required: [originalRequestId, expectedRowVersion, expectedAuthorizationVersion, acceptedTupleDigest, invoiceExpiresAt, authorizationPurpose] properties: originalRequestId: {type: string, format: uuid} @@ -448,7 +448,7 @@ paths: properties: evidenceId: {type: string, format: uuid} '401': {description: Current owner authentication or ordinary secret refused} - '409': {description: Exact current evidence unavailable or conflicting} + '409': {description: Fresh unbound billing request without evidence creation, exact binding refused, or exact current evidence unavailable} /billing/hosting/subscriptions/{subscriptionId}/first-invoice/confirm: parameters: - name: subscriptionId diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfig.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfig.java index cbbeaac0e0..d732e10aef 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfig.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfig.java @@ -43,10 +43,11 @@ static DefaultRequestRateLimiterArguments defaultRequestRateLimiterArguments( || !Set.of(REPLENISH_RATE, BURST_CAPACITY, REQUESTED_TOKENS).containsAll(args.keySet())) { throw invalidRateLimiterConfiguration(); } - return new DefaultRequestRateLimiterArguments( - parsePositiveInt(args.get(REPLENISH_RATE)), - parsePositiveLong(args.get(BURST_CAPACITY)), - parsePositiveInt(args.getOrDefault(REQUESTED_TOKENS, "1"))); + int replenishRate = parsePositiveInt(args.get(REPLENISH_RATE)); + long burstCapacity = parsePositiveLong(args.get(BURST_CAPACITY)); + int requestedTokens = parsePositiveInt(args.getOrDefault(REQUESTED_TOKENS, "1")); + if (requestedTokens > burstCapacity) throw invalidRateLimiterConfiguration(); + return new DefaultRequestRateLimiterArguments(replenishRate, burstCapacity, requestedTokens); } private static int parsePositiveInt(String value) { diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfigTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfigTest.java index 0f77b5684a..d2d1a92dac 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfigTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfigTest.java @@ -73,6 +73,40 @@ void preservesConfiguredRequestedTokensWhenPresent() { assertThat(arguments.requestedTokens()).isEqualTo(2); } + @Test + void rejectsRequestedTokensAboveBurstAndAllowsEqualityAtSupportedBounds() { + GatewayProperties oversizedRequest = new GatewayProperties(); + FilterDefinition oversizedLimiter = limiter("20", "40"); + oversizedLimiter.getArgs().put("redis-rate-limiter.requestedTokens", "41"); + oversizedRequest.setDefaultFilters(List.of(oversizedLimiter)); + + GatewayProperties equalityAtMaximumBounds = new GatewayProperties(); + FilterDefinition maximumLimiter = + limiter(Integer.toString(Integer.MAX_VALUE), Long.toString(Long.MAX_VALUE)); + maximumLimiter + .getArgs() + .put("redis-rate-limiter.requestedTokens", Integer.toString(Integer.MAX_VALUE)); + equalityAtMaximumBounds.setDefaultFilters(List.of(maximumLimiter)); + + GatewayProperties equality = new GatewayProperties(); + FilterDefinition equalityLimiter = limiter("20", "40"); + equalityLimiter.getArgs().put("redis-rate-limiter.requestedTokens", "40"); + equality.setDefaultFilters(List.of(equalityLimiter)); + + assertThatThrownBy( + () -> GatewayRateLimiterConfig.defaultRequestRateLimiterArguments(oversizedRequest)) + .isInstanceOf(IllegalStateException.class); + var arguments = + GatewayRateLimiterConfig.defaultRequestRateLimiterArguments(equalityAtMaximumBounds); + assertThat(arguments.replenishRate()).isEqualTo(Integer.MAX_VALUE); + assertThat(arguments.burstCapacity()).isEqualTo(Long.MAX_VALUE); + assertThat(arguments.requestedTokens()).isEqualTo(Integer.MAX_VALUE); + assertThat( + GatewayRateLimiterConfig.defaultRequestRateLimiterArguments(equality) + .requestedTokens()) + .isEqualTo(40); + } + @Test void rejectsMissingDuplicateOrNonpositiveDefaultRateLimiterConfiguration() { GatewayProperties missing = new GatewayProperties(); diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/controller/AccountCheckoutGatewayControllerTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/controller/AccountCheckoutGatewayControllerTest.java index df44598817..1757e2e2c8 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/controller/AccountCheckoutGatewayControllerTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/controller/AccountCheckoutGatewayControllerTest.java @@ -279,7 +279,8 @@ void webhookForwardsRawBytesAndOnlyMapsItsDedicatedPostRoute() { var authClient = mock(AccountControlUiAuthenticationClient.class); var checkoutClient = mock(AccountCheckoutHttpClient.class); var controller = new AccountCheckoutGatewayController(authClient, checkoutClient, properties()); - byte[] payload = "{\n\"id\":\"evt_raw\"\n}".getBytes(StandardCharsets.UTF_8); + byte[] payload = + " { \n \"id\" : \"evt_raw\" \t\n} \n".getBytes(StandardCharsets.UTF_8); when(checkoutClient.forward(eq(HttpMethod.POST), eq("/billing/hosting/webhook"), any(), any())) .thenReturn( Mono.just( @@ -299,8 +300,17 @@ void webhookForwardsRawBytesAndOnlyMapsItsDedicatedPostRoute() { assertThat(response).isNotNull(); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.ACCEPTED); assertThat(response.getHeaders().getCacheControl()).contains("no-store"); + var forwardedHeaders = org.mockito.ArgumentCaptor.forClass(HttpHeaders.class); + var forwardedBody = org.mockito.ArgumentCaptor.forClass(byte[].class); verify(checkoutClient) - .forward(eq(HttpMethod.POST), eq("/billing/hosting/webhook"), any(), any()); + .forward( + eq(HttpMethod.POST), + eq("/billing/hosting/webhook"), + forwardedHeaders.capture(), + forwardedBody.capture()); + assertThat(forwardedBody.getValue()).containsExactly(payload); + assertThat(forwardedHeaders.getValue().get("Stripe-Signature")) + .containsExactly("t=123,v1=signature"); verify(authClient, never()).login(any()); } diff --git a/web-client/src/account/AccountCheckoutRoute.test.tsx b/web-client/src/account/AccountCheckoutRoute.test.tsx index 92e526d245..423aca1034 100644 --- a/web-client/src/account/AccountCheckoutRoute.test.tsx +++ b/web-client/src/account/AccountCheckoutRoute.test.tsx @@ -399,7 +399,9 @@ describe('App-owned first-invoice route', () => { fireEvent.click(screen.getByRole('button', { name: 'Sign in' })); await screen.findByText( - 'Account sign-in is temporarily unavailable. Try again later.' + status === 429 + ? 'Account sign-in is temporarily unavailable. Try again later.' + : /Account sign-in could not be confirmed/ ); expect(api.login).toHaveBeenCalledOnce(); expect(vi.mocked(api.login).mock.calls[0][0].secret).toBe(''); @@ -413,6 +415,60 @@ describe('App-owned first-invoice route', () => { } ); + it('re-enters a consumed one-time code and explicitly recovers the original sign-in', async () => { + const { api } = setupApp(); + const login = vi.mocked(api.login); + let original: { requestId: string; callerContextId: string } | undefined; + login + .mockImplementationOnce( + async ({ requestId, callerContextId, secret }) => { + expect(secret).toBe('012345'); + original = { requestId, callerContextId }; + throw new AccountControlUiApiError(0); + } + ) + .mockImplementationOnce( + async ({ requestId, callerContextId, secret }) => { + if ( + !original || + requestId !== original.requestId || + callerContextId !== original.callerContextId || + secret !== '012345' + ) { + throw new AccountControlUiApiError(401); + } + return { + accountId, + authToken: 'header.payload.signature', + expiresAt: new Date(Date.now() + 60_000).toISOString(), + }; + } + ); + fireEvent.change(screen.getByLabelText('Account email'), { + target: { value: 'owner@example.com' }, + }); + const secret = screen.getByLabelText( + 'Primary authentication secret' + ) as HTMLInputElement; + fireEvent.change(secret, { target: { value: '012345' } }); + fireEvent.click(screen.getByRole('button', { name: 'Sign in' })); + + await screen.findByText(/re-enter the same secret and select Sign in/); + expect(secret.value).toBe(''); + expect(login).toHaveBeenCalledOnce(); + expect(login.mock.calls[0][0].secret).toBe(''); + expect( + (screen.getByRole('button', { name: 'Sign in' }) as HTMLButtonElement) + .disabled + ).toBe(true); + + fireEvent.change(secret, { target: { value: '012345' } }); + fireEvent.click(screen.getByRole('button', { name: 'Sign in' })); + await screen.findByText('in_existing'); + expect(login).toHaveBeenCalledTimes(2); + expect(login.mock.calls[1][0].secret).toBe(''); + }); + it.each(['navigation', 'replacement login'])( 'restores only the server original operation after %s before a confirmation row exists', async (interruption) => { diff --git a/web-client/src/account/AccountCheckoutRoute.tsx b/web-client/src/account/AccountCheckoutRoute.tsx index 5210dbfe6d..c4da4fcf03 100644 --- a/web-client/src/account/AccountCheckoutRoute.tsx +++ b/web-client/src/account/AccountCheckoutRoute.tsx @@ -330,17 +330,21 @@ function AccountLoginForm({ api, sessionStore, notice }: LoginFormProps) { await sessionStore.signIn(api, credentials); } catch (error) { if ( - error instanceof AccountControlUiApiError && - [0, 429, 502, 503].includes(error.status) + error instanceof ControlUiSessionError && + error.code === 'SESSION_REPLACED' ) { + setMessage('This sign-in attempt was replaced. Sign in again.'); + } else if (sessionStore.canRetrySignIn(credentials.email)) { setMessage( - 'Account sign-in is temporarily unavailable. Try again later.' + 'Account sign-in could not be confirmed. To retry now, re-enter the same secret and select Sign in.' ); } else if ( - error instanceof ControlUiSessionError && - error.code === 'SESSION_REPLACED' + error instanceof AccountControlUiApiError && + (error.uncertain || error.status === 429) ) { - setMessage('This sign-in attempt was replaced. Sign in again.'); + setMessage( + 'Account sign-in is temporarily unavailable. Try again later.' + ); } else { setMessage( 'Sign-in could not be completed. Check your email and primary authentication secret.' @@ -374,7 +378,17 @@ function AccountLoginForm({ api, sessionStore, notice }: LoginFormProps) { autoComplete="username" value={email} disabled={busy} - onChange={(event) => setEmail(event.target.value)} + onChange={(event) => { + const nextEmail = event.target.value; + if ( + nextEmail.trim() !== email.trim() && + sessionStore.canRetrySignIn(email.trim()) + ) { + setMessage(''); + } + sessionStore.discardLoginRecoveryIfEmailChanged(nextEmail.trim()); + setEmail(nextEmail); + }} slotProps={{ htmlInput: { maxLength: 254 } }} /> { ); }); + it('expires uncertain IDs at the original submission bound despite a second lost reply', async () => { + vi.useFakeTimers(); + const store = makeStore(); + const login = vi + .fn() + .mockRejectedValue(new AccountControlUiApiError(0)); + const api = { login }; + const email = 'owner@example.com'; + const submit = () => store.signIn(api, { email, secret: '012345' }); + + await expect(submit()).rejects.toMatchObject({ status: 0 }); + vi.advanceTimersByTime(59_999); + await expect(submit()).rejects.toMatchObject({ status: 0 }); + expect(login.mock.calls[1][0]).toEqual(login.mock.calls[0][0]); + + vi.advanceTimersByTime(1); + expect(store.canRetrySignIn(email)).toBe(false); + await expect(submit()).rejects.toMatchObject({ status: 0 }); + expect(login.mock.calls[2][0].requestId).not.toBe( + login.mock.calls[0][0].requestId + ); + expect(login.mock.calls[2][0].callerContextId).not.toBe( + login.mock.calls[0][0].callerContextId + ); + }); + + it.each(['email edit', 'sign-out', 'definitive rejection'])( + 'drops the uncertain original after %s', + async (invalidation) => { + const store = makeStore(); + const login = vi + .fn() + .mockRejectedValueOnce(new AccountControlUiApiError(0)) + .mockResolvedValue(successfulLogin()); + const api = { login }; + const email = 'owner@example.com'; + const submit = () => store.signIn(api, { email, secret: '012345' }); + + await expect(submit()).rejects.toMatchObject({ status: 0 }); + expect(store.canRetrySignIn(email)).toBe(true); + if (invalidation === 'email edit') { + store.discardLoginRecoveryIfEmailChanged('other@example.com'); + } else if (invalidation === 'sign-out') { + store.signOut(); + } else { + login.mockRejectedValueOnce(new AccountControlUiApiError(409)); + await expect(submit()).rejects.toMatchObject({ status: 409 }); + expect(login.mock.calls[1][0]).toEqual(login.mock.calls[0][0]); + } + + expect(store.canRetrySignIn(email)).toBe(false); + await submit(); + const fresh = login.mock.lastCall![0]; + expect(fresh.requestId).not.toBe(login.mock.calls[0][0].requestId); + expect(fresh.callerContextId).not.toBe( + login.mock.calls[0][0].callerContextId + ); + } + ); + it('rejects a buffered success body if the session changes before JSON is consumed', async () => { const fetchImpl = vi.fn().mockResolvedValue( new Response(JSON.stringify({ state: 'AWAITING_PAYMENT' }), { diff --git a/web-client/src/account/controlUiSession.ts b/web-client/src/account/controlUiSession.ts index d6d71ca744..69f31f1a29 100644 --- a/web-client/src/account/controlUiSession.ts +++ b/web-client/src/account/controlUiSession.ts @@ -1,4 +1,5 @@ import { + AccountControlUiApiError, maxControlUiSessionLifetimeMs, type AccountControlUiApi, type AccountControlUiLoginRequest, @@ -49,6 +50,12 @@ const ownerPath = /^\/api\/account\/billing\/hosting\/subscriptions\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/first-invoice(?:\/(reauthenticate|confirm|renew))?$/i; const maxOwnerRequestBytes = 16 * 1024; const maxOwnerResponseBytes = 64 * 1024; +const loginRecoveryWindowMs = 60_000; + +type LoginRecovery = Pick< + AccountControlUiLoginRequest, + 'requestId' | 'callerContextId' | 'email' +> & { expiresAt: number }; function secureOrigin(value: string): URL { let parsed: URL; @@ -244,6 +251,8 @@ export class ControlUiSessionStore { private bearer: string | null = null; private revision = 0; private loginController: AbortController | null = null; + private loginRecovery: LoginRecovery | null = null; + private loginRecoveryTimer: ReturnType | null = null; private expiryTimer: ReturnType | null = null; constructor(options: ControlUiSessionOptions) { @@ -387,14 +396,19 @@ export class ControlUiSessionStore { api: AccountControlUiApi, credentials: ControlUiCredentials ): Promise { + const retry = this.canRetrySignIn(credentials.email) + ? this.loginRecovery + : null; + // Account starts its recovery window at issuance, which follows the initial submission. + const expiresAt = retry?.expiresAt ?? this.now() + loginRecoveryWindowMs; const hadSession = this.snapshot !== null || this.bearer !== null; const revision = this.beginReplacement(); if (hadSession) this.emitSessionChange(); const controller = new AbortController(); this.loginController = controller; const request: AccountControlUiLoginRequest = { - requestId: this.idFactory(), - callerContextId: this.idFactory(), + requestId: retry?.requestId ?? this.idFactory(), + callerContextId: retry?.callerContextId ?? this.idFactory(), email: credentials.email, secret: credentials.secret, }; @@ -433,12 +447,43 @@ export class ControlUiSessionStore { throw new ControlUiSessionError('SESSION_REPLACED'); } this.loginController = null; + if ( + this.now() < expiresAt && + (!(error instanceof AccountControlUiApiError) || + error.uncertain || + (error.status === 429 && retry !== null)) + ) { + this.loginRecovery = { + requestId: request.requestId, + callerContextId: request.callerContextId, + email: request.email, + expiresAt, + }; + this.loginRecoveryTimer = setTimeout( + () => this.clearLoginRecovery(), + Math.max(0, expiresAt - this.now()) + ); + } throw error; } finally { request.secret = ''; } } + canRetrySignIn(email: string): boolean { + return ( + this.loginRecovery !== null && + this.loginRecovery.email === email && + this.now() < this.loginRecovery.expiresAt + ); + } + + discardLoginRecoveryIfEmailChanged(email: string): void { + if (this.loginRecovery && this.loginRecovery.email !== email) { + this.clearLoginRecovery(); + } + } + /** Clear only this browser's in-memory credentials; no remote logout is sent. */ signOut(): void { const hadSession = this.snapshot !== null || this.bearer !== null; @@ -462,6 +507,7 @@ export class ControlUiSessionStore { this.revision += 1; this.loginController?.abort(); this.loginController = null; + this.clearLoginRecovery(); this.abortRequests(); this.clearExpiryTimer(); this.snapshot = null; @@ -469,6 +515,12 @@ export class ControlUiSessionStore { return this.revision; } + private clearLoginRecovery(): void { + if (this.loginRecoveryTimer !== null) clearTimeout(this.loginRecoveryTimer); + this.loginRecoveryTimer = null; + this.loginRecovery = null; + } + private expireIfCurrent(identity: string, revision: number): void { if (this.revision !== revision || this.snapshot?.identity !== identity) { return; diff --git a/web-client/src/api/accountControlUi.test.ts b/web-client/src/api/accountControlUi.test.ts index 089fbe810c..20236ad1b3 100644 --- a/web-client/src/api/accountControlUi.test.ts +++ b/web-client/src/api/accountControlUi.test.ts @@ -1,6 +1,7 @@ -import { describe, expect, it, vi } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import { AccountControlUiApiError, + accountControlUiLoginTimeoutMs, createAccountControlUiApi, maxControlUiSessionLifetimeMs, type AccountControlUiLoginRequest, @@ -13,6 +14,10 @@ const callerContextId = '33333333-3333-4333-8333-333333333333'; const now = Date.parse('2026-11-07T12:00:00.000Z'); const authToken = 'header.payload.signature'; +afterEach(() => { + vi.useRealTimers(); +}); + function successfulLogin(expiresAt = new Date(now + 60_000).toISOString()) { return new Response( JSON.stringify({ @@ -140,6 +145,67 @@ describe('account control-ui login transport', () => { expect((error as Error).message).not.toContain('primary-secret'); }); + it('times out stalled fetch and discards a late successful response', async () => { + vi.useFakeTimers(); + let resolveFetch!: (response: Response) => void; + const fetchImpl = vi.fn().mockImplementation( + () => + new Promise((resolve) => { + resolveFetch = resolve; + }) + ); + const api = createAccountControlUiApi(origin, fetchImpl, () => now); + const failure = expect(api.login(loginRequest)).rejects.toMatchObject({ + status: 0, + uncertain: true, + }); + + await vi.advanceTimersByTimeAsync(accountControlUiLoginTimeoutMs); + await failure; + expect(fetchImpl.mock.calls[0][1]?.signal?.aborted).toBe(true); + const late = successfulLogin(); + const cancel = vi.spyOn(late.body!, 'cancel'); + resolveFetch(late); + await Promise.resolve(); + expect(cancel).toHaveBeenCalledOnce(); + expect(fetchImpl).toHaveBeenCalledOnce(); + }); + + it.each(['deadline', 'caller abort'])( + 'abandons a stalled response body on %s even if cancellation stalls', + async (interruption) => { + vi.useFakeTimers(); + const stalled = new Promise(() => {}); + const cancel = vi.fn(() => stalled); + const response = new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('{"status":"SUCCESS"')); + }, + cancel, + }), + { status: 200 } + ); + const fetchImpl = vi.fn().mockResolvedValue(response); + const api = createAccountControlUiApi(origin, fetchImpl, () => now); + const caller = new AbortController(); + const failure = expect( + api.login(loginRequest, caller.signal) + ).rejects.toMatchObject({ status: 0, uncertain: true }); + await vi.advanceTimersByTimeAsync(0); + expect(response.body?.locked).toBe(true); + + if (interruption === 'deadline') { + await vi.advanceTimersByTimeAsync(accountControlUiLoginTimeoutMs); + } else { + caller.abort(); + } + await failure; + expect(fetchImpl.mock.calls[0][1]?.signal?.aborted).toBe(true); + expect(cancel).toHaveBeenCalledOnce(); + } + ); + it('discards non-success response bodies and preserves only the status', async () => { const fetchImpl = vi .fn() diff --git a/web-client/src/api/accountControlUi.ts b/web-client/src/api/accountControlUi.ts index 30f8e6cbc9..83dceb8242 100644 --- a/web-client/src/api/accountControlUi.ts +++ b/web-client/src/api/accountControlUi.ts @@ -20,11 +20,16 @@ export interface AccountControlUiApi { export class AccountControlUiApiError extends Error { readonly status: number; + readonly uncertain: boolean; - constructor(status: number) { + constructor( + status: number, + uncertain = status < 400 || status === 408 || status >= 500 + ) { super('Account sign-in could not be completed.'); this.name = 'AccountControlUiApiError'; this.status = status; + this.uncertain = uncertain; } } @@ -33,6 +38,7 @@ const jwt = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/; const timestamp = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/; const maxLoginResponseBytes = 32 * 1024; +export const accountControlUiLoginTimeoutMs = 10_000; export const maxControlUiSessionLifetimeMs = 24 * 60 * 60 * 1000; function requireSecureOrigin(value: string): URL { @@ -70,31 +76,30 @@ function hasExactKeys(value: Record, keys: string[]): boolean { async function readBoundedJson( response: Response, - signal?: AbortSignal + signal: AbortSignal ): Promise { if (!response.body) throw new AccountControlUiApiError(0); const reader = response.body.getReader(); + const discard = () => void reader.cancel().catch(() => {}); + signal.addEventListener('abort', discard, { once: true }); const chunks: Uint8Array[] = []; let size = 0; try { for (;;) { - if (signal?.aborted) throw new AccountControlUiApiError(0); + if (signal.aborted) throw new AccountControlUiApiError(0); const { done, value } = await reader.read(); + if (signal.aborted) throw new AccountControlUiApiError(0); if (done) break; size += value.byteLength; - if (size > maxLoginResponseBytes) { - await reader.cancel(); - throw new AccountControlUiApiError(0); - } + if (size > maxLoginResponseBytes) throw new AccountControlUiApiError(0); chunks.push(value); } } catch { - try { - await reader.cancel(); - } catch { - // Do not expose a stream or transport error that could contain response data. - } + discard(); throw new AccountControlUiApiError(0); + } finally { + signal.removeEventListener('abort', discard); + reader.releaseLock(); } const bytes = new Uint8Array(size); @@ -170,7 +175,12 @@ export function createAccountControlUiApi( return { async login(request, signal) { - const url = new URL('/api/account/auth/login', currentOrigin()); + let url: URL; + try { + url = new URL('/api/account/auth/login', currentOrigin()); + } catch { + throw new AccountControlUiApiError(0, false); + } if ( !uuid.test(request.requestId) || !uuid.test(request.callerContextId) || @@ -182,12 +192,29 @@ export function createAccountControlUiApi( request.secret.length < 1 || request.secret.length > 1024 ) { - throw new AccountControlUiApiError(0); + throw new AccountControlUiApiError(0, false); } + if (signal?.aborted) throw new AccountControlUiApiError(0, false); - let response: Response; - try { - response = await fetchImpl(url, { + const controller = new AbortController(); + const abort = () => controller.abort(); + const deadline = performance.now() + accountControlUiLoginTimeoutMs; + const timer = setTimeout(abort, accountControlUiLoginTimeoutMs); + signal?.addEventListener('abort', abort, { once: true }); + const interrupted = new Promise((_, reject) => { + controller.signal.addEventListener( + 'abort', + () => reject(new AccountControlUiApiError(0)), + { once: true } + ); + }); + const assertWithinDeadline = () => { + if (performance.now() >= deadline) abort(); + if (controller.signal.aborted) throw new AccountControlUiApiError(0); + }; + + async function receive(): Promise { + const response = await fetchImpl(url, { method: 'POST', headers: { 'Content-Type': 'application/json', @@ -199,22 +226,32 @@ export function createAccountControlUiApi( redirect: 'error', referrerPolicy: 'no-referrer', mode: 'same-origin', - signal, + signal: controller.signal, }); - } catch { - throw new AccountControlUiApiError(0); - } - - if (response.status !== 200) { try { - await response.body?.cancel(); - } catch { - // The body is deliberately discarded; server text is never surfaced. + assertWithinDeadline(); + if (response.status !== 200) { + throw new AccountControlUiApiError(response.status); + } + } catch (error) { + // Discard rejected and late responses without waiting for stream cancellation. + void response.body?.cancel().catch(() => {}); + throw error; } - throw new AccountControlUiApiError(response.status); + const body = await readBoundedJson(response, controller.signal); + assertWithinDeadline(); + return parseLoginResult(body, now()); } - return parseLoginResult(await readBoundedJson(response, signal), now()); + try { + return await Promise.race([interrupted, receive()]); + } catch (error) { + if (error instanceof AccountControlUiApiError) throw error; + throw new AccountControlUiApiError(0); + } finally { + clearTimeout(timer); + signal?.removeEventListener('abort', abort); + } }, }; } From 1c7a25dc563afbc3116d4d1fcdf8825422fd0fc9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 13 Nov 2026 03:20:22 +1300 Subject: [PATCH 18/29] Preserve checkout owner request deadlines and signer failures --- .../account-service/api-contracts.md | 4 +- .../account-service/configuration.md | 2 + .../AccountHostingFirstInvoiceController.java | 2 + .../AccountCheckoutHttpAuthInterceptor.java | 2 + .../session/AccountControlUiSignerOwner.java | 15 +- ...untCheckoutReceivingConfigurationTest.java | 26 ++- ...ountHostingFirstInvoiceControllerTest.java | 5 + ...ccountCheckoutHttpAuthInterceptorTest.java | 7 +- .../AccountControlUiIssuanceWorkflowTest.java | 9 +- .../AccountControlUiSigningAndActorTest.java | 23 +++ .../src/account/controlUiSession.test.ts | 119 ++++++++++++++ web-client/src/account/controlUiSession.ts | 153 +++++++++++------- 12 files changed, 300 insertions(+), 67 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index d5fce6143b..595d9039bc 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -547,9 +547,9 @@ The private self-service game-creation reauthentication owner binds exact origin The isolated receiving login is public `POST /api/account/auth/login` at Gateway. Its bounded JSON body is `{requestId, callerContextId, email, secret}`, with non-nil request/context UUIDs and one enabled ordinary primary secret. Gateway authenticates Account's exact same-namespace URI SAN before releasing credentials over the narrow mTLS `AccountControlUiAuthenticationService/AuthLogin` RPC. Account permits only the exact same-namespace Gateway workload and delegates to its durable Account-only issuer and current-actor owners. Gateway's existing header-trust WebFilter supplies a process-private canonical source proof; the controller does not interpret public source headers as proof. The closed RPC requires one canonical literal client address and the fixed HTTP transport class, and Account carries that transient source into the sign-in owner. Missing Gateway proof returns no-store HTTP 503 before credential forwarding; absent, duplicate, malformed or unsupported wire source fields are rejected before issuance. Source metadata does not change the retained v1 credential-request MAC or reset its replay budget. Success is `{status: SUCCESS, data: {accountId, authToken, expiresAt}}`, with no-store headers. Exact retries retain the same issuance; changed input conflicts. Credential-bearing replay uses a constant-time MAC comparison and an Account-owned, serialized five-failure budget bound to the immutable original issuance operation and request. Failed comparisons commit independent immutable attempt records before returning the conflict; after five failures, that request is denied before credential-MAC access. Exact retries below the budget recover the original credential without primary reauthentication or another OTP consumption, and never reset the budget. Scope, caller or context conflicts and unavailable custody are not counted as credential failures. This short recovery-request budget changes neither Account security state nor other requests and does not replace the broader credential-abuse policy in [ADR 0034](../../decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md). The direct legacy Account HTTP login is rejected in this isolated mode and cannot provide a checkout fallback. Production legacy-login drift elsewhere remains unchanged. -The first-party `/account/subscriptions/{subscriptionId}/checkout` route obtains its bearer only from that login, holds it in memory, restricts authenticated requests to the exact owner endpoints, and unmounts checkout on expiry, local sign-out, session replacement or route departure. The browser bounds login dispatch and response-body consumption to ten seconds. An uncertain response lets the user re-enter the original secret and retry with the same request IDs for up to one minute from first submission. Only the original IDs, email and deadline remain in browser memory for that retry. Local sign-out clears this UI's credentials; it does not claim server-side token revocation. Navigation, Back/Forward, reload and remount never authorize a provider command. +The first-party `/account/subscriptions/{subscriptionId}/checkout` route obtains its bearer only from that login, holds it in memory, restricts authenticated requests to the exact owner endpoints, and unmounts checkout on expiry, local sign-out, session replacement or route departure. The browser bounds login dispatch and response-body consumption to ten seconds. An uncertain response lets the user re-enter the original secret and retry with the same request IDs for up to one minute from first submission. Only the original IDs, email and deadline remain in browser memory for that retry. Authenticated checkout requests use the same ten-second deadline across fetch and response-body consumption. The browser cancels expired requests, discards late responses and leaves payment retries under explicit user control. Local sign-out clears this UI's credentials; it does not claim server-side token revocation. Navigation, Back/Forward, reload and remount never authorize a provider command. -The Account-owned HTTPS owner surface is `/billing/hosting/subscriptions/{subscriptionId}/first-invoice`, externally prefixed by `/api/account`. It is an account-scoped billing-owner operation, not tenant-role authority: the exact current `control-ui` Account subject must own the subscription and selected instrument. Billing suspension does not remove this recovery surface. The handlers register only in the explicitly isolated, default-off controlled-fixture composition; this does not enable actual provider or customer-data intake. Live provider/customer qualification and the applicable retention, deletion, backup, custody and deployment prerequisites remain necessary before production intake, as defined by the [Stripe owner contract](./stripe-integration.md#first-invoice-confirmation-and-completion). +The Account-owned HTTPS owner surface is `/billing/hosting/subscriptions/{subscriptionId}/first-invoice`, externally prefixed by `/api/account`. When the protected signer source is unavailable, the owner endpoints return retryable HTTP 503 and preserve the browser’s current session for an explicit retry. It is an account-scoped billing-owner operation, not tenant-role authority: the exact current `control-ui` Account subject must own the subscription and selected instrument. Billing suspension does not remove this recovery surface. The handlers register only in the explicitly isolated, default-off controlled-fixture composition; this does not enable actual provider or customer-data intake. Live provider/customer qualification and the applicable retention, deletion, backup, custody and deployment prerequisites remain necessary before production intake, as defined by the [Stripe owner contract](./stripe-integration.md#first-invoice-confirmation-and-completion). - `GET` returns the exact existing invoice, PaymentIntent, selected instrument, amount, currency, immutable `tupleDigest`, expected current subscription row version, expiry, nullable retained `confirmationRequestId`, nullable server-verified `preRowOriginalRequestId`, current `authorizationVersion` (zero before first consent) and `AWAITING_PAYMENT` or `COMMITTED` state. `amount` is a positive decimal integer string in Stripe minor units, not a floating-point or major-unit amount. No client secret appears in status, URLs, logs or audit. A null `confirmationRequestId` means only that no confirmation row is currently committed; it does not prove that an original operation has stopped. That absence does not authorize a replacement request or charge. Before a confirmation row exists, `preRowOriginalRequestId` exposes only the original operation identity from an exact owner/subscription/tuple/row-version/expiry-verified durable fence at authorization version zero; inconsistent retained evidence refuses the read instead of appearing absent. A committed confirmation takes precedence and makes this pre-row reference null. Navigation or replacement login may recover this identity through a fresh authenticated owner read, never earlier consent or proof. Resumption requires a separate explicit renewal action, fresh unchanged charge consent and primary authentication bound to `PRE_ROW_RENEWAL` with a distinct authorization request. Expired status is observational and never extends renewal eligibility. Recovery semantics remain owned by the [Stripe contract](./stripe-integration.md#first-invoice-confirmation-and-completion). - `POST /reauthenticate` takes distinct stable evidence `requestId` and `confirmationRequestId` plus one enabled ordinary login secret over HTTPS. A new billing proof requires `billingBinding` with `originalRequestId`, `expectedRowVersion`, `expectedAuthorizationVersion`, `acceptedTupleDigest`, `invoiceExpiresAt`, and `authorizationPurpose`; `confirmationRequestId` names that binding's authorization request. Use `INITIAL_CONFIRMATION` with the original request ID and version zero for opening proof, `PRE_ROW_RENEWAL` with the retained original ID and a distinct authorization request at version zero for pre-row recovery, or `FOLLOWUP_RENEWAL` for a later retained authorization version. Account returns a newly bound proof only after actual primary authentication and exact owner binding. Omitting `billingBinding` is allowed only to replay the exact previously retained unbound historical request; it returns the original evidence and creates no new evidence. A fresh unbound billing request returns HTTP 409 before evidence is written, and any replayed unbound evidence remains non-authorizing for consent or payment. `SELF_SERVICE_GAME_CREATION` evidence is rejected for payment. The [Stripe owner contract](./stripe-integration.md#durable-opening-proof-and-explicit-pre-row-renewal) defines the binding and recovery behavior. diff --git a/design/architecture/microservices/account-service/configuration.md b/design/architecture/microservices/account-service/configuration.md index 6c8cd2e48e..abefe57862 100644 --- a/design/architecture/microservices/account-service/configuration.md +++ b/design/architecture/microservices/account-service/configuration.md @@ -77,6 +77,8 @@ Account requires explicit `firemud.grpc.workload-namespace`, `firemud.account.ch Gateway uses the same isolated profile/selector plus `firemud.account.checkout-receiving.workload-namespace`, `account-https-base-url` and `account-ca-cert-path`; its ordinary gRPC endpoint and file-backed mTLS client configuration identify Account independently. Gateway `firemud.account.checkout-receiving.rate-limit-decision-timeout-ms` defaults to 2,000 ms and must be between 1 and 30,000 ms. It bounds the deferred Redis rate-limit decision; expiry cancels that subscription and returns the existing no-store 503 without forwarding or accepting a late allow. Both incoming HTTP listeners must actually use TLS. Gateway forwards neither identity headers nor an asserted secure scheme. The frontend uses the current HTTPS origin and explicitly supplied public Stripe key; missing provider-authentication configuration refuses checkout. +Before using the isolated login listener with a real ingress, verify that direct clients and other workloads cannot reach it through an address trusted for forwarded headers. The selected ingress must replace client-supplied forwarding and canonical source headers before forwarding to Gateway. A matching private CIDR alone supplies no evidence of that topology. Retain exact listener reachability and header-replacement proof before qualifying the source for per-client abuse enforcement. + Separate versioned billing-purpose reauthentication policies and exact commercial policy rows remain necessary; absent rows refuse and migrations seed no defaults. Category-specific privacy/finance-approved finite retention, minimization, deletion, backup/provider consequences and deployed source custody remain unqualified activation obligations. No boolean in this receiving composition supplies those approvals. ## Canonical Gameplay LOGIN Receiving diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceController.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceController.java index f55a6178d0..1701311162 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceController.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceController.java @@ -136,6 +136,8 @@ public AccountHostingFirstInvoicePaymentService.Completion signedCompletion( @ExceptionHandler({ net.firedevops.firemud.accountservice.service.session.AccountControlUiRegistryReader .RegistryUnavailableException.class, + net.firedevops.firemud.accountservice.service.session.AccountControlUiSignerOwner + .SignerSourceUnavailableException.class, net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceUnavailableException.class, net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier .VerificationUnavailableException.class, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountCheckoutHttpAuthInterceptor.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountCheckoutHttpAuthInterceptor.java index 5cc3d0b282..b75c1ebbe4 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountCheckoutHttpAuthInterceptor.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountCheckoutHttpAuthInterceptor.java @@ -72,6 +72,8 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons | io.lettuce.core.RedisException | net.firedevops.firemud.accountservice.service.session.AccountControlUiRegistryReader .RegistryUnavailableException + | net.firedevops.firemud.accountservice.service.session.AccountControlUiSignerOwner + .SignerSourceUnavailableException | net.firedevops.firemud.common.security.AccountPublicJwksCache .SourceUnavailableException | net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerOwner.java index c982a8210a..acd3c2fe14 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerOwner.java @@ -53,8 +53,13 @@ public Capture requireOriginal(byte[] originalReceipt) { } private Capture capture(byte[] originalReceipt) { - var materializer = trust.current().orElseThrow(AccountControlUiSignerOwner::unavailable); - var publicApi = api.current(); + var materializer = trust.current().orElseThrow(SignerSourceUnavailableException::new); + AccountJwtJwksApiBinding.ParsedBinding publicApi; + try { + publicApi = api.current(); + } catch (AccountJwtJwksApiBinding.BindingRejectedException unavailable) { + throw new SignerSourceUnavailableException(); + } if (!materializer.environmentId().equals(publicApi.environmentId()) || !materializer.clusterId().equals(publicApi.clusterId()) || !materializer.namespace().equals(publicApi.namespace()) @@ -198,4 +203,10 @@ public String toString() { private static IllegalStateException unavailable() { return new IllegalStateException("Existing committed control-ui signer unavailable"); } + + public static final class SignerSourceUnavailableException extends IllegalStateException { + public SignerSourceUnavailableException() { + super("Protected control-ui signer source is unavailable"); + } + } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountCheckoutReceivingConfigurationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountCheckoutReceivingConfigurationTest.java index 48e4c4edff..0efeaac54d 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountCheckoutReceivingConfigurationTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountCheckoutReceivingConfigurationTest.java @@ -43,7 +43,22 @@ void defaultAndUnqualifiedSelectionRegisterNoReceivingOrSourceGraph() { } @Test - void productionProfilesNeverRegisterTheIsolatedAuthenticationReceiver() { + void productionProfilesNeverRegisterTheIsolatedAuthenticationReceiver() throws Exception { + var config = new AccountCheckoutReceivingConfiguration(); + var environment = + new MockEnvironment() + .withProperty("firemud.grpc.workload-namespace", "test") + .withProperty( + "firemud.account.checkout-receiving.private-signer-root", + Files.createDirectory(keys.resolve("profile-private")).toString()) + .withProperty( + "firemud.account.checkout-receiving.public-signer-root", + Files.createDirectory(keys.resolve("profile-public")).toString()) + .withProperty( + "firemud.account.checkout-receiving.control-ui-keyring-root", + Files.createDirectory(keys.resolve("profile-custody")).toString()); + environment.setActiveProfiles("isolated-checkout-receiving"); + assertThat(config.accountCheckoutReceivingProperties(environment)).isNotNull(); for (String profile : java.util.List.of("prod", "production")) { context .withPropertyValues( @@ -54,11 +69,10 @@ void productionProfilesNeverRegisterTheIsolatedAuthenticationReceiver() { assertThat(ctx).hasNotFailed(); assertThat(ctx).doesNotHaveBean(AccountControlUiAuthenticationGrpcService.class); }); - context - .withPropertyValues( - "spring.profiles.active=" + profile + ",isolated-checkout-receiving", - "firemud.account.checkout-receiving.enabled=true") - .run(ctx -> assertThat(ctx).hasFailed()); + environment.setActiveProfiles(profile, "isolated-checkout-receiving"); + assertThatThrownBy(() -> config.accountCheckoutReceivingProperties(environment)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Checkout receiving is restricted to isolated inputs"); } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceControllerTest.java index db26a74001..bc7a276c71 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceControllerTest.java @@ -128,6 +128,11 @@ void exactControllerExceptionMappingPreservesStatusAndNoStore( static Stream ownerFailures() { return Stream.of( + Arguments.of( + new net.firedevops.firemud.accountservice.service.session.AccountControlUiSignerOwner + .SignerSourceUnavailableException(), + 503, + "AUTH_UNAVAILABLE"), Arguments.of( new org.springframework.transaction.CannotCreateTransactionException( "private database connection detail"), diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountCheckoutHttpAuthInterceptorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountCheckoutHttpAuthInterceptorTest.java index 5b63250d47..2a5484d396 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountCheckoutHttpAuthInterceptorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountCheckoutHttpAuthInterceptorTest.java @@ -69,8 +69,9 @@ void forgedForwardedSchemeAndMissingOrRejectedBearerNeverReachOwner() throws Exc verifyNoInteractions(actors); request.setSecure(true); doThrow(new IllegalStateException("denied")).when(actors).authenticateAccount("rejected"); - assertThat(interceptor.preHandle(request, response, handler)).isFalse(); - assertThat(response.getStatus()).isEqualTo(401); + var secureResponse = new MockHttpServletResponse(); + assertThat(interceptor.preHandle(request, secureResponse, handler)).isFalse(); + assertThat(secureResponse.getStatus()).isEqualTo(401); } @ParameterizedTest @@ -108,6 +109,8 @@ static Stream unavailableAuthorities() { return Stream.of( registryFailure(() -> null), registryFailure(() -> mock(io.lettuce.core.api.StatefulRedisConnection.class)), + new net.firedevops.firemud.accountservice.service.session.AccountControlUiSignerOwner + .SignerSourceUnavailableException(), new net.firedevops.firemud.common.security.AccountPublicJwksCache .SourceUnavailableException(), new org.springframework.transaction.CannotCreateTransactionException( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java index f640043e2c..459a11e77a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java @@ -160,8 +160,13 @@ void changedDigestTenantOrCallerContextConflictsWithoutTerminalizingOriginal() { void replayCredentialMismatchCommitsFailureBeforeReportingConflictWithoutPrimaryAuthentication() { Fixture fixture = new Fixture(NOW.plusSeconds(30)); var original = fixture.existing(); + AtomicReference replayMacInput = new AtomicReference<>(); when(fixture.cryptography.requestDigest(anyString(), any(byte[].class))) - .thenReturn("changed-request-digest"); + .thenAnswer( + call -> { + replayMacInput.set(call.getArgument(1, byte[].class).clone()); + return "changed-request-digest"; + }); try (var ignored = fixture.withPeer(ISSUER)) { assertThatThrownBy( @@ -174,6 +179,8 @@ void replayCredentialMismatchCommitsFailureBeforeReportingConflictWithoutPrimary .isInstanceOf(AccountControlUiIssuanceService.IdempotencyConflictException.class); } + assertThat(AccountControlUiIssuanceRepository.object(replayMacInput.get())) + .containsEntry("secret", "wrong-secret"); var order = inOrder(fixture.operations, fixture.cryptography, fixture.transactions); order.verify(fixture.operations).lockReplayRequest(original.requestId); order.verify(fixture.operations).countReplayFailures(original); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java index 150705ceb2..3e17a33176 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java @@ -11,6 +11,7 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.math.BigInteger; @@ -58,6 +59,28 @@ class AccountControlUiSigningAndActorTest { private static KeyPair key; @TempDir Path temporary; + @Test + void unavailableProtectedSignerSourceHasItsOwnFailureType() { + var repository = + mock( + net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository + .class); + var source = + new net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding( + true, temporary.resolve("missing-binding").toString()); + var owner = + new AccountControlUiSignerOwner( + repository, + source, + new net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding(), + temporary, + temporary); + + assertThatThrownBy(() -> owner.requireOriginal(new byte[] {1})) + .isInstanceOf(AccountControlUiSignerOwner.SignerSourceUnavailableException.class); + verifyNoInteractions(repository); + } + @BeforeAll static void key() throws Exception { var generator = KeyPairGenerator.getInstance("RSA"); diff --git a/web-client/src/account/controlUiSession.test.ts b/web-client/src/account/controlUiSession.test.ts index 5ca14c9d7e..06dbdb763b 100644 --- a/web-client/src/account/controlUiSession.test.ts +++ b/web-client/src/account/controlUiSession.test.ts @@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { AccountControlUiApiError, + accountControlUiLoginTimeoutMs, type AccountControlUiApi, type AccountControlUiLoginRequest, } from '../api/accountControlUi'; @@ -264,6 +265,124 @@ describe('memory-only control-ui session owner', () => { expect(store.getSession()).toBeNull(); }); + it('times out a stalled owner fetch and ignores its late auth rejection', async () => { + vi.useFakeTimers(); + const pending = deferred(); + const fetchImpl = vi + .fn() + .mockReturnValueOnce(pending.promise) + .mockResolvedValueOnce( + new Response(JSON.stringify({ state: 'AWAITING_PAYMENT' }), { + status: 200, + }) + ); + const store = makeStore({ fetchImpl }); + const session = await store.signIn(loginApi(), { + email: 'owner@example.com', + secret: 'primary-secret', + }); + const { url, init } = getRequest(); + const request = store.authenticatedRequest(url, init); + const failure = expect(request).rejects.toMatchObject({ + code: 'REQUEST_FAILED', + }); + + await vi.advanceTimersByTimeAsync(accountControlUiLoginTimeoutMs); + await failure; + expect(fetchImpl.mock.calls[0][1]?.signal?.aborted).toBe(true); + expect(store.getSession()).toEqual(session); + + const lateUnauthorized = new Response('private auth details', { + status: 401, + }); + const cancelLateBody = vi.spyOn(lateUnauthorized.body!, 'cancel'); + pending.resolve(lateUnauthorized); + await Promise.resolve(); + await Promise.resolve(); + expect(cancelLateBody).toHaveBeenCalledOnce(); + + const recovered = await store.authenticatedRequest(url, init); + expect(await recovered.json()).toEqual({ state: 'AWAITING_PAYMENT' }); + expect(fetchImpl).toHaveBeenCalledTimes(2); + expect(store.getSession()).toEqual(session); + }); + + it('times out a stalled owner response body and cancels its reader', async () => { + vi.useFakeTimers(); + const cancel = vi.fn(); + const response = new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('{"state":')); + }, + cancel, + }), + { status: 200 } + ); + const fetchImpl = vi.fn().mockResolvedValue(response); + const store = makeStore({ fetchImpl }); + const session = await store.signIn(loginApi(), { + email: 'owner@example.com', + secret: 'primary-secret', + }); + const { url, init } = getRequest(); + const request = store.authenticatedRequest(url, init); + const failure = expect(request).rejects.toMatchObject({ + code: 'REQUEST_FAILED', + }); + await vi.advanceTimersByTimeAsync(0); + expect(response.body?.locked).toBe(true); + + await vi.advanceTimersByTimeAsync(accountControlUiLoginTimeoutMs); + await failure; + expect(fetchImpl.mock.calls[0][1]?.signal?.aborted).toBe(true); + expect(cancel).toHaveBeenCalledOnce(); + expect(store.getSession()).toEqual(session); + }); + + it('does not retry a timed-out payment write or deliver its late success', async () => { + vi.useFakeTimers(); + const pending = deferred(); + const fetchImpl = vi.fn().mockReturnValue(pending.promise); + const store = makeStore({ fetchImpl }); + const session = await store.signIn(loginApi(), { + email: 'owner@example.com', + secret: 'primary-secret', + }); + const url = new URL( + `/api/account/billing/hosting/subscriptions/${subscriptionId}/first-invoice/confirm`, + origin + ); + const request = store.authenticatedRequest(url, { + method: 'POST', + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ acceptCharge: true }), + }); + const failure = expect(request).rejects.toMatchObject({ + code: 'REQUEST_FAILED', + }); + + await vi.advanceTimersByTimeAsync(accountControlUiLoginTimeoutMs); + await failure; + expect(fetchImpl).toHaveBeenCalledOnce(); + expect(fetchImpl.mock.calls[0][1]?.signal?.aborted).toBe(true); + expect(store.getSession()).toEqual(session); + + const lateSuccess = new Response(JSON.stringify({ status: 'succeeded' }), { + status: 200, + }); + const cancelLateBody = vi.spyOn(lateSuccess.body!, 'cancel'); + pending.resolve(lateSuccess); + await Promise.resolve(); + await Promise.resolve(); + expect(cancelLateBody).toHaveBeenCalledOnce(); + expect(fetchImpl).toHaveBeenCalledOnce(); + expect(store.getSession()).toEqual(session); + }); + it('denies a stale owner response after sign-out even if fetch ignores abort', async () => { const pending = deferred(); const fetchImpl = vi.fn().mockReturnValue(pending.promise); diff --git a/web-client/src/account/controlUiSession.ts b/web-client/src/account/controlUiSession.ts index 69f31f1a29..85543ca2ed 100644 --- a/web-client/src/account/controlUiSession.ts +++ b/web-client/src/account/controlUiSession.ts @@ -1,5 +1,6 @@ import { AccountControlUiApiError, + accountControlUiLoginTimeoutMs, maxControlUiSessionLifetimeMs, type AccountControlUiApi, type AccountControlUiLoginRequest, @@ -115,27 +116,31 @@ async function readBoundedBytes( ): Promise { if (!response.body) return new Uint8Array(); const reader = response.body.getReader(); + const discard = () => { + void reader.cancel().catch(() => {}); + }; + signal.addEventListener('abort', discard, { once: true }); const chunks: Uint8Array[] = []; let size = 0; try { for (;;) { if (signal.aborted) throw new ControlUiSessionError('REQUEST_CANCELLED'); const { done, value } = await reader.read(); + if (signal.aborted) throw new ControlUiSessionError('REQUEST_CANCELLED'); if (done) break; size += value.byteLength; if (size > maxOwnerResponseBytes) { - await reader.cancel(); + discard(); throw new ControlUiSessionError('REQUEST_FAILED'); } chunks.push(value); } } catch { - try { - await reader.cancel(); - } catch { - // The response body is private Account data and is never surfaced here. - } + discard(); throw new ControlUiSessionError('REQUEST_FAILED'); + } finally { + signal.removeEventListener('abort', discard); + reader.releaseLock(); } const bytes = new Uint8Array(size); let offset = 0; @@ -146,6 +151,10 @@ async function readBoundedBytes( return bytes; } +function discardResponse(response: Response): void { + void response.body?.cancel().catch(() => {}); +} + function validateOwnerRequest( url: URL, init: RequestInit, @@ -300,6 +309,7 @@ export class ControlUiSessionStore { const controller = new AbortController(); const externalSignal = init.signal; + let deadlineExpired = false; const cancelFromCaller = () => controller.abort(); if (externalSignal?.aborted) controller.abort(); else @@ -326,67 +336,102 @@ export class ControlUiSessionStore { if (!isCurrent()) throw new ControlUiSessionError('SESSION_REPLACED'); }; - try { - assertCurrent(); - - const headers = new Headers(init.headers); - headers.set('Authorization', `Bearer ${bearer}`); - let response: Response; - try { - response = await this.fetchImpl(target, { - method, - headers, - ...(init.body !== undefined ? { body: init.body } : {}), - cache: 'no-store', - credentials: 'omit', - redirect: 'error', - referrerPolicy: 'no-referrer', - mode: 'same-origin', - signal: controller.signal, - }); - } catch { + const deadline = performance.now() + accountControlUiLoginTimeoutMs; + const deadlineTimer = setTimeout(() => { + deadlineExpired = true; + controller.abort(); + }, accountControlUiLoginTimeoutMs); + const assertWithinDeadline = () => { + if (performance.now() >= deadline) { + deadlineExpired = true; + controller.abort(); + } + if (controller.signal.aborted) { assertCurrent(); throw new ControlUiSessionError( - controller.signal.aborted ? 'REQUEST_CANCELLED' : 'REQUEST_FAILED' + deadlineExpired ? 'REQUEST_FAILED' : 'REQUEST_CANCELLED' ); } - + }; + try { assertCurrent(); - if (response.status === 401 || response.status === 403) { - this.clearIfCurrent(session.identity, revision); - throw new ControlUiSessionError('AUTH_REJECTED'); - } - if (!response.ok) { + assertWithinDeadline(); + + const interrupted = new Promise((_, reject) => { + controller.signal.addEventListener( + 'abort', + () => { + try { + assertWithinDeadline(); + } catch (error) { + reject(error); + } + }, + { once: true } + ); + }); + + const headers = new Headers(init.headers); + headers.set('Authorization', `Bearer ${bearer}`); + const receive = async (): Promise => { + let response: Response; try { - await response.body?.cancel(); + response = await this.fetchImpl(target, { + method, + headers, + ...(init.body !== undefined ? { body: init.body } : {}), + cache: 'no-store', + credentials: 'omit', + redirect: 'error', + referrerPolicy: 'no-referrer', + mode: 'same-origin', + signal: controller.signal, + }); } catch { - // Error bodies may contain sensitive provider or Account details. + assertCurrent(); + assertWithinDeadline(); + throw new ControlUiSessionError('REQUEST_FAILED'); } - assertCurrent(); - return new Response(null, { - status: response.status, - headers: { 'Cache-Control': 'no-store' }, - }); - } - if (response.status !== 200) { + try { - await response.body?.cancel(); - } catch { - // A success response outside the owner contract is discarded. + assertCurrent(); + assertWithinDeadline(); + } catch (error) { + discardResponse(response); + throw error; } + if (response.status === 401 || response.status === 403) { + discardResponse(response); + this.requests.delete(controller); + this.clearIfCurrent(session.identity, revision); + throw new ControlUiSessionError('AUTH_REJECTED'); + } + if (!response.ok) { + discardResponse(response); + return new Response(null, { + status: response.status, + headers: { 'Cache-Control': 'no-store' }, + }); + } + if (response.status !== 200) { + discardResponse(response); + throw new ControlUiSessionError('REQUEST_FAILED'); + } + + const bytes = await readBoundedBytes(response, controller.signal); assertCurrent(); - throw new ControlUiSessionError('REQUEST_FAILED'); - } + assertWithinDeadline(); + return guardedJsonResponse( + response.status, + bytes, + assertCurrent, + response.headers.get('content-type') ?? 'application/json' + ); + }; - const bytes = await readBoundedBytes(response, controller.signal); - assertCurrent(); - return guardedJsonResponse( - response.status, - bytes, - assertCurrent, - response.headers.get('content-type') ?? 'application/json' - ); + return await Promise.race([interrupted, receive()]); } finally { + clearTimeout(deadlineTimer); externalSignal?.removeEventListener('abort', cancelFromCaller); this.requests.delete(controller); } From 0a27f531bbee154562f1b2a7b852aa81b69294bd Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 13 Nov 2026 05:03:44 +1300 Subject: [PATCH 19/29] Fix Account reauthentication response OpenAPI structure --- services/account-service/src/main/resources/openapi.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index 2e9f153fcc..437d7f50cd 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -448,7 +448,8 @@ paths: properties: evidenceId: {type: string, format: uuid} '401': {description: Current owner authentication or ordinary secret refused} - '409': {description: Fresh unbound billing request without evidence creation, exact binding refused, or exact current evidence unavailable} + '409': + description: Fresh unbound billing request without evidence creation, exact binding refused, or exact current evidence unavailable /billing/hosting/subscriptions/{subscriptionId}/first-invoice/confirm: parameters: - name: subscriptionId From 963ef99c85c6753e6691cc50208c7444f29f0c3d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:46:12 +1300 Subject: [PATCH 20/29] Preserve exact historical billing replay in the isolated API schema --- services/account-service/src/main/resources/openapi.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index 4412ecc388..9e2f789e81 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -419,7 +419,7 @@ paths: schema: type: object additionalProperties: false - required: [requestId, confirmationRequestId, billingBinding, email, secret] + required: [requestId, confirmationRequestId, email, secret] properties: requestId: {type: string, format: uuid} confirmationRequestId: {type: string, format: uuid} From b39088dbc02d370fb64d9977e48df5ef0ba8dd22 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 13 Nov 2026 21:36:17 +1300 Subject: [PATCH 21/29] Stage checkout browser and its CI entrypoint on the ingress receiver --- .github/workflows/ci.yml | 4 - .../player-access-and-session.md | 10 +- web-client/package-lock.json | 754 --------------- web-client/package.json | 9 +- web-client/src/App.tsx | 27 +- .../src/account/AccountCheckoutRoute.test.tsx | 686 -------------- .../src/account/AccountCheckoutRoute.tsx | 422 --------- .../src/account/controlUiSession.test.ts | 543 ----------- web-client/src/account/controlUiSession.ts | 625 ------------- web-client/src/api/accountControlUi.test.ts | 264 ------ web-client/src/api/accountControlUi.ts | 257 ----- .../src/api/hostingFirstInvoice.test.ts | 313 ------- web-client/src/api/hostingFirstInvoice.ts | 340 ------- .../HostingFirstInvoiceCheckout.test.tsx | 874 ------------------ .../billing/HostingFirstInvoiceCheckout.tsx | 619 ------------- web-client/src/billing/hostingStripe.ts | 21 - 16 files changed, 9 insertions(+), 5759 deletions(-) delete mode 100644 web-client/src/account/AccountCheckoutRoute.test.tsx delete mode 100644 web-client/src/account/AccountCheckoutRoute.tsx delete mode 100644 web-client/src/account/controlUiSession.test.ts delete mode 100644 web-client/src/account/controlUiSession.ts delete mode 100644 web-client/src/api/accountControlUi.test.ts delete mode 100644 web-client/src/api/accountControlUi.ts delete mode 100644 web-client/src/api/hostingFirstInvoice.test.ts delete mode 100644 web-client/src/api/hostingFirstInvoice.ts delete mode 100644 web-client/src/billing/HostingFirstInvoiceCheckout.test.tsx delete mode 100644 web-client/src/billing/HostingFirstInvoiceCheckout.tsx delete mode 100644 web-client/src/billing/hostingStripe.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f9e4bda436..c90e3b83a9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1029,10 +1029,6 @@ jobs: npm run format -- -c working-directory: web-client - - name: Run first-invoice checkout regression tests - run: npm run test:checkout - working-directory: web-client - - name: Install pinned Chrome for Testing and ChromeDriver env: CHROME_FOR_TESTING_VERSION: ${{ steps.workflow-tool-versions.outputs.chrome-for-testing-version }} diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index e603da290a..32103b1b68 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -94,7 +94,7 @@ This receiver owns the [Stripe provisioner](../../../services/account-service/sr Focused source coverage includes `refusedDispatchCommitsLocalDeferralWithoutCallingProvider` and `refusedDispatchCannotHideStaleClaimSettlementFailure` in the composition units, and `displayRefreshAfterClaimRefusesDispatchButRetainedWorkReachesOperatorDeadline`, `displayRefreshAfterDispatchPreparationRefusesReadbackAndStillAllowsLocalDeadlineFailure`, and `displayRefreshBeforeInitialClaimRetainsTerminalFailureWithoutDispatch` in the dispatch physical suite. These changes do not establish new payment support or completed physical qualification; the execution limits above remain, and both components stay manually composed and unregistered, with the authenticated create producer, provider worker and public billing route held. -The separate Account first-invoice successor now prepares provider-linked `AWAITING_PAYMENT` without authority, exact versioned commercial invoice/intent/instrument binding, distinct billing-purpose primary reauthentication, durable explicit consent, one existing-intent confirmation and narrowly protected HTTPS Stripe.js handoff. Exact signed payment success and a fresh invoice read precede atomic receipt, audit, billing and tenant-authority completion; delayed read-only reconciliation preserves the historical authorization without renewing a command or disclosing an expired secret. That preparation left checkout unmounted; the subsequent isolated receiving composition below adds its Account-session producer and App route. The same owner prepares explicit fresh primary reauthentication and unchanged-consent renewal, append-only authorization-version fencing, and one durable command claim on the original payment operation. A crash before claim may resume only after a fresh explicit authorization; a claimed/ambiguous command is never resent. Renewal may resume the same intent's SCA handoff without changing any commercial/provider identity or extending invoice expiry. Focused renewal cases cover exact authorization/invoice expiry, replay, wrong operation/proof identity, changed consent, stale subscription/authorization fences, crash before claim, and ambiguous provider or claim outcomes. Canonical contracts remain [Account API](../../architecture/microservices/account-service/api-contracts.md#hosting-first-invoice-checkout) and [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md#first-invoice-confirmation-and-completion). The prior post-renewal local graph executed 54 selected Account unit cases and all main/unit/integration compilation, schema generation, enabled main/unit/integration Checkstyle and SpotBugs, and Java formatting with zero unit failures, errors or skips. That prior unmounted client/component run passed 32 cases, build, lint and formatting. Earlier 55-case Account and 29-case frontend results remain overlapping historical proof, not additional current coverage. Physical PostgreSQL/HTTPS migration and composition definitions compiled but were unexecuted in that historical post-renewal run because Docker was unavailable. The final Markdown gate passed; link checking remains unrun after an existing external URL denial. No skipped case establishes physical qualification. The paid first-invoice finding and accepted route finding remain open. Production registration, deletion, retention, backup/source custody and runtime activation remain held, with no live Stripe transaction or automatic provisioning charge. +The separate Account first-invoice successor now prepares provider-linked `AWAITING_PAYMENT` without authority, exact versioned commercial invoice/intent/instrument binding, distinct billing-purpose primary reauthentication, durable explicit consent, one existing-intent confirmation and narrowly protected HTTPS Stripe.js handoff. Exact signed payment success and a fresh invoice read precede atomic receipt, audit, billing and tenant-authority completion; delayed read-only reconciliation preserves the historical authorization without renewing a command or disclosing an expired secret. The isolated receiving composition in #3410 adds the Account-session producer. The first-party App route is carried by #3434. The same owner prepares explicit fresh primary reauthentication and unchanged-consent renewal, append-only authorization-version fencing, and one durable command claim on the original payment operation. A crash before claim may resume only after a fresh explicit authorization; a claimed/ambiguous command is never resent. Renewal may resume the same intent's SCA handoff without changing any commercial/provider identity or extending invoice expiry. Focused renewal cases cover exact authorization/invoice expiry, replay, wrong operation/proof identity, changed consent, stale subscription/authorization fences, crash before claim, and ambiguous provider or claim outcomes. Canonical contracts remain [Account API](../../architecture/microservices/account-service/api-contracts.md#hosting-first-invoice-checkout) and [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md#first-invoice-confirmation-and-completion). The prior post-renewal local graph executed 54 selected Account unit cases and all main/unit/integration compilation, schema generation, enabled main/unit/integration Checkstyle and SpotBugs, and Java formatting with zero unit failures, errors or skips. That prior unmounted client/component run passed 32 cases, build, lint and formatting. Earlier 55-case Account and 29-case frontend results remain overlapping historical proof, not additional current coverage. Physical PostgreSQL/HTTPS migration and composition definitions compiled but were unexecuted in that historical post-renewal run because Docker was unavailable. The final Markdown gate passed; link checking remains unrun after an existing external URL denial. No skipped case establishes physical qualification. The paid first-invoice finding and accepted route finding remain open. Production registration, deletion, retention, backup/source custody and runtime activation remain held, with no live Stripe transaction or automatic provisioning charge. Earlier rejected-bearer and uncertain-confirmation presentation proof passed eight controller/MVC cases and 34 browser/API cases. MVC exercises exact no-store 401 for the typed JWT rejection, preserves 400/409 mappings, and leaves typed verifier unavailability to the owning availability handler. The browser's original status-only hold is the baseline for the same-operation recovery proof below. Receiving retains its `AUTH_SESSION_REVOKED`/401 and `AUTH_UNAVAILABLE`/503 mappings, covered by nine current Account controller and MVC cases. @@ -110,15 +110,15 @@ The earlier published #3389 comparison deliberately left public facade and numer The #3408 receiving source adds the Account-owned original-operation fence and immutable typed billing reauthentication binding for an exact owned `AWAITING_PAYMENT` invoice. Original confirmation and explicit fresh same-operation pre-row renewal compete under the same owner and fence for one first-consent, authorization and dispatch winner. The original operation, invoice and opening evidence remain retained. The additive [V1043 migration](../../../services/account-service/src/main/resources/db/migration/V1043__hosting_first_invoice_operation_fence.sql) follows the verified V1042 frontier and preserves V1041/V1042. -Focused validation passes 29 Account units, 37 physical PostgreSQL and HTTPS cases, and 34 browser tests. The owner cases cover both first-winner outcomes, an already-arrived delayed original confirmation, competing and exact retries, rollback, stale/expired refusal, loss of the provider response, and one retained command claim. The V1042 witness preserves the legacy unbound billing row and its `xmin` through V1043 and refuses a substitute typed binding. The browser sends typed opening and follow-up proof, and offers explicit version-zero renewal only for the same invoice and original operation retained from a successful opening proof. An observational null confirmation ID alone provides no recovery identity. Registered receiving proof is owned by #3410. Payment activation, registration, retention/deletion/backup, source custody and the separate retained-entitlement activation obligation remain held. The provider and deployment are controlled fixtures in this proof. +Focused validation passes 29 Account units, 37 physical PostgreSQL and HTTPS cases, and 34 browser tests. The owner cases cover both first-winner outcomes, an already-arrived delayed original confirmation, competing and exact retries, rollback, stale/expired refusal, loss of the provider response, and one retained command claim. The V1042 witness preserves the legacy unbound billing row and its `xmin` through V1043 and refuses a substitute typed binding. The browser sends typed opening and follow-up proof, and offers explicit version-zero renewal only for the same invoice and original operation retained from a successful opening proof. An observational null confirmation ID alone provides no recovery identity. The registered Account and Gateway receiving proof is owned by #3410. The mounted browser checkout and its proof are carried by #3434. Payment activation, registration, retention/deletion/backup, source custody and the separate retained-entitlement activation obligation remain held. The provider and deployment are controlled fixtures in this proof. ### Isolated registered checkout receiving -The next Account first-invoice extension composes actual registered Gateway HTTPS handlers, pre-disclosure verified Account mTLS login, the durable Account-only issuer/current actor, exact-method owner authentication and a bounded raw signed-event adapter. The Account-only source has no tenant/legal collaborator. Checkout imports the same pure protected JWKS source owner as other Account consumers and defines no competing API/client/trusted-source graph. The first-party App owns a memory-only session and subscription checkout route; expiry, local sign-out, replacement and navigation unmount it, with no automatic confirmation. +The next Account first-invoice extension composes actual registered Gateway HTTPS handlers, pre-disclosure verified Account mTLS login, the durable Account-only issuer/current actor, exact-method owner authentication and a bounded raw signed-event adapter. The Account-only source has no tenant/legal collaborator. Checkout imports the same pure protected JWKS source owner as other Account consumers and defines no competing API/client/trusted-source graph. The #3434 first-party App owns a memory-only session and subscription checkout route. Expiry, local sign-out, replacement and navigation unmount it, with no automatic confirmation. -Historical receiving proof passed 170 backend cases on its earlier source: two channel-factory, five codec, 27 Gateway and 136 Account cases, with zero failures, errors or skips. That run included three real loopback mTLS cases, including refusal of a CA-trusted wrong workload before any primary request or credential, and five verified HTTPS cases including no retry after an uncertain checkout POST. These historical counts exclude later channel-factory TLS-builder, HTTPS error-body and isolated rate-limiter coverage; they do not describe the current suites or prove the later changes. Affected production/unit/integration compilation and enabled Java formatting, Checkstyle and SpotBugs pass. The memory-only UI passes all 55 selected checkout cases, build, lint and scoped formatting; these overlap earlier component coverage rather than add to it. These sources use explicit isolated signer-platform, policy, custody, provider and PKI inputs. The qualified core signed-completion/guard repair from parent `77890399` is carried. Its separate physical HTTPS signed-completion, confirmed-guard and migration proof passed on that parent. The registered Gateway→Account→Redis/PostgreSQL receiving-chain test now passes its actual HTTPS/mTLS and physical PostgreSQL/Coordination composition, including exact signed-provider-success completion and token-revocation refusal. Its non-Boot Gateway context supplies the same named token-bucket script resource as normal Gateway auto-configuration; Redis rate execution is a deterministic admitted upstream input, while the actual configured adapter and filter run. The same scoped invocation passes 40 Gateway configuration/limiter cases, including error/malformed-result refusal without forwarding. These 41 fresh cases are component proof with controlled signer-platform, policy, custody, provider and PKI inputs; they do not establish live Redis rate execution or fresh-image/runtime qualification. It starts from a controlled existing `AWAITING_PAYMENT` operation, not a newly supported subscription-create route. Fresh-image runtime proof, production registration/activation, approved finite category-specific retention/minimization/deletion/backup/provider treatment, genuine custody and live provider qualification remain held. Link validation was unrun for that historical receiving proof; later scoped documentation runs retain their own attribution. +Historical receiving proof passed 170 backend cases on its earlier source: two channel-factory, five codec, 27 Gateway and 136 Account cases, with zero failures, errors or skips. That run included three real loopback mTLS cases, including refusal of a CA-trusted wrong workload before any primary request or credential, and five verified HTTPS cases including no retry after an uncertain checkout POST. These historical counts exclude later channel-factory TLS-builder, HTTPS error-body and isolated rate-limiter coverage; they do not describe the current suites or prove the later changes. Affected production/unit/integration compilation and enabled Java formatting, Checkstyle and SpotBugs pass. The earlier combined source passed 55 selected memory-only UI checkout cases, build, lint and scoped formatting. Those cases overlap the earlier component coverage. These sources use explicit isolated signer-platform, policy, custody, provider and PKI inputs. The qualified core signed-completion/guard repair from parent `77890399` is carried. Its separate physical HTTPS signed-completion, confirmed-guard and migration proof passed on that parent. The registered Gateway→Account→Redis/PostgreSQL receiving-chain test now passes its actual HTTPS/mTLS and physical PostgreSQL/Coordination composition, including exact signed-provider-success completion and token-revocation refusal. Its non-Boot Gateway context supplies the same named token-bucket script resource as normal Gateway auto-configuration; Redis rate execution is a deterministic admitted upstream input, while the actual configured adapter and filter run. The same scoped invocation passes 40 Gateway configuration/limiter cases, including error/malformed-result refusal without forwarding. These 41 fresh cases are component proof with controlled signer-platform, policy, custody, provider and PKI inputs; they do not establish live Redis rate execution or fresh-image/runtime qualification. It starts from a controlled existing `AWAITING_PAYMENT` operation, not a newly supported subscription-create route. Fresh-image runtime proof, production registration/activation, approved finite category-specific retention/minimization/deletion/backup/provider treatment, genuine custody and live provider qualification remain held. Link validation was unrun for that historical receiving proof; later scoped documentation runs retain their own attribution. -The current receiving proof passes two registered Gateway-to-Account cases over actual HTTPS and mTLS with PostgreSQL and Redis. The first retains ordinary confirmation. The second obtains typed opening proof, observes no confirmation row, explicitly renews the exact original operation with fresh reauthentication, replays that authorization, and refuses the superseded original confirmation. Both retain one provider command and require exact signed completion. The current browser selection passes 61 cases with build, lint and scoped formatting. The fixtures retain controlled provider, custody and peer inputs, with production registration and activation held. +The current receiving proof passes two registered Gateway-to-Account cases over actual HTTPS and mTLS with PostgreSQL and Redis. The first retains ordinary confirmation. The second obtains typed opening proof, observes no confirmation row, explicitly renews the exact original operation with fresh reauthentication, replays that authorization, and refuses the superseded original confirmation. Both retain one provider command and require exact signed completion. The combined receiving and browser source passed 61 selected browser cases with build, lint and scoped formatting. The browser test definitions and CI step are carried by #3434. The fixtures retain controlled provider, custody and peer inputs, with production registration and activation held. The bounded #3410 trusted-source preparation now carries the existing Gateway canonical HTTP address through a process-private exchange proof and the closed authenticated `AuthLogin` wire into Account's sign-in owner. Missing proof refuses before credential forwarding; missing or malformed wire source refuses before issuance. Retained credential-request digests, exact-result recovery and the independent five-failure replay budget are unchanged. Source, receiver, production-isolation and changed-source replay test definitions are updated; the bounded cached-API qualification below covers the complete edited Java files and selected unit classes, not physical receiving or full-tree proof. The accepted shared credential-abuse finding remains open: the Account-owned policy, effective versioned policy inputs and Cache/Rate-Limit Redis enforcement from [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md) are not implemented. Account owns that next step, including the Account-global subject/key scope and approved policy limits; this patch supplies neither a stub limiter nor synthetic tenant/policy values. Gateway IP limiting and request-local replay accounting remain separate. The existing isolated profile and explicit opt-in remain mandatory on both services, with default/production login activation held until shared enforcement and its denial/outage proof are available. diff --git a/web-client/package-lock.json b/web-client/package-lock.json index 0a39350cbf..63cd0c549e 100644 --- a/web-client/package-lock.json +++ b/web-client/package-lock.json @@ -11,7 +11,6 @@ "@emotion/react": "^11.14.0", "@emotion/styled": "^11.14.1", "@mui/material": "^9.0.1", - "@stripe/stripe-js": "^10.2.1", "@tanstack/react-query": "^5.100.13", "react": "^19.2.6", "react-dom": "^19.2.6" @@ -19,7 +18,6 @@ "devDependencies": { "@axe-core/cli": "^4.11.3", "@eslint/js": "^10.0.0", - "@testing-library/react": "^16.3.3", "@types/react": "^19.2.15", "@types/react-dom": "^19.2.3", "@vitejs/plugin-react": "^6.0.2", @@ -27,13 +25,11 @@ "eslint-plugin-react-hooks": "^7.1.1", "eslint-plugin-react-refresh": "^0.5.2", "globals": "^17.6.0", - "jsdom": "^31.0.0", "prettier": "^3.8.3", "serve": "^14.2.6", "typescript": "~6.0.3", "typescript-eslint": "^8.59.4", "vite": "^8.0.16", - "vitest": "^5.1.0", "wait-on": "^9.0.10" } }, @@ -626,24 +622,6 @@ "node": "^20.19.0 || ^22.13.0 || >=24" } }, - "node_modules/@exodus/bytes": { - "version": "1.16.0", - "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz", - "integrity": "sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^20.19.0 || ^22.12.0 || >=24.0.0" - }, - "peerDependencies": { - "@noble/hashes": "^1.8.0 || ^2.0.0" - }, - "peerDependenciesMeta": { - "@noble/hashes": { - "optional": true - } - } - }, "node_modules/@hapi/address": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/@hapi/address/-/address-5.1.1.tgz", @@ -1348,15 +1326,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@stripe/stripe-js": { - "version": "10.2.1", - "resolved": "https://registry.npmjs.org/@stripe/stripe-js/-/stripe-js-10.2.1.tgz", - "integrity": "sha512-diHeR1/FeWZZzuFXEvkjRMzydgKEpxUTrKEUxSV8NcpeZY3Kl8C4Gerw/JSMK+3oXsBRJtgkG7ckviQJ651moA==", - "license": "MIT", - "engines": { - "node": ">=12.16" - } - }, "node_modules/@tanstack/query-core": { "version": "5.107.1", "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.107.1.tgz", @@ -1396,81 +1365,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@testing-library/dom": { - "version": "10.4.2", - "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.2.tgz", - "integrity": "sha512-yzr2S9HyAIdhz2/6qHgbs665Q7PKVcDF05vsOlHPxG1mo36gKVesdYVeDLnXgfjJ03CrKRk08knc6+E/9m8v2Q==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.10.4", - "@babel/runtime": "^7.12.5", - "@types/aria-query": "^5.0.1", - "aria-query": "5.3.0", - "dom-accessibility-api": "^0.5.9", - "lz-string": "^1.5.0", - "picocolors": "1.1.1", - "pretty-format": "^27.0.2" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@testing-library/react": { - "version": "16.3.3", - "resolved": "https://registry.npmjs.org/@testing-library/react/-/react-16.3.3.tgz", - "integrity": "sha512-Uo193NgQbPMz6lrrhtRQQFcMC6Re/ELLFbbuVL30WDlZxlpZf9/lMHTAVxPRLw1q1iu9OJmR1c2BLiENRstdBg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/runtime": "^7.12.5" - }, - "engines": { - "node": ">=18" - }, - "peerDependencies": { - "@testing-library/dom": "^10.0.0", - "@types/react": "^18.0.0 || ^19.0.0", - "@types/react-dom": "^18.0.0 || ^19.0.0", - "react": "^18.0.0 || ^19.0.0", - "react-dom": "^18.0.0 || ^19.0.0" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@types/aria-query": { - "version": "5.0.4", - "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz", - "integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==", - "dev": true, - "license": "MIT", - "peer": true - }, - "node_modules/@types/chai": { - "version": "5.2.3", - "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", - "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/deep-eql": "*", - "assertion-error": "^2.0.1" - } - }, - "node_modules/@types/deep-eql": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", - "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", - "dev": true, - "license": "MIT" - }, "node_modules/@types/esrecurse": { "version": "4.3.1", "resolved": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz", @@ -1805,44 +1699,6 @@ } } }, - "node_modules/@vitest/mocker": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.1.0.tgz", - "integrity": "sha512-5umB9/jlWcqVS6fsrFmv5Gdnpu6wAUio/lEOwAmvB7v+lFo/IW2B9FhAD0p19GCULTgMzLCdUmuCDCnAzWgppQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/trace-mapping": "0.3.31", - "@vitest/spy": "5.1.0", - "estree-walker": "^3.0.3", - "magic-string": "^1.4.3" - }, - "funding": { - "url": "https://opencollective.com/vitest" - }, - "peerDependencies": { - "msw": "^2.4.9 || ^3.0.0", - "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" - }, - "peerDependenciesMeta": { - "msw": { - "optional": true - }, - "vite": { - "optional": true - } - } - }, - "node_modules/@vitest/spy": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.1.0.tgz", - "integrity": "sha512-2DPO5OMHWKrBngC+fCmTQqemNF0gidRhp3lxbBmRhW+M1XJrfgPpqNqWVevXtn2f2ufD5ZaR1B6B641aAlcX5A==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://opencollective.com/vitest" - } - }, "node_modules/@zeit/schemas": { "version": "2.36.0", "resolved": "https://registry.npmjs.org/@zeit/schemas/-/schemas-2.36.0.tgz", @@ -2001,27 +1857,6 @@ "dev": true, "license": "MIT" }, - "node_modules/aria-query": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.0.tgz", - "integrity": "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==", - "dev": true, - "license": "Apache-2.0", - "peer": true, - "dependencies": { - "dequal": "^2.0.3" - } - }, - "node_modules/assertion-error": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", - "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - } - }, "node_modules/ast-types": { "version": "0.13.4", "resolved": "https://registry.npmjs.org/ast-types/-/ast-types-0.13.4.tgz", @@ -2113,33 +1948,6 @@ "node": ">=10.0.0" } }, - "node_modules/bcp-47": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/bcp-47/-/bcp-47-2.1.2.tgz", - "integrity": "sha512-wsv86UuNFuPnVieKLyECTT+CP1WSAHeoIg5P3xu2kA9Z+7fVPoKt7dxzSeEhtJel0AI+NW3fIW3KtTKQKUCngg==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-alphabetical": "^2.0.0", - "is-alphanumerical": "^2.0.0", - "is-decimal": "^2.0.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/bcp-47-match": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/bcp-47-match/-/bcp-47-match-2.0.3.tgz", - "integrity": "sha512-JtTezzbAibu8G0R9op9zb3vcWZd9JF6M0xOYGPn0fNCd7wOpRB1mU2mH9T8gaBGbAAyIIVgB2G7xG0GP98zMAQ==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, "node_modules/boxen": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/boxen/-/boxen-7.0.0.tgz", @@ -2291,16 +2099,6 @@ ], "license": "CC-BY-4.0" }, - "node_modules/chai": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", - "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - } - }, "node_modules/chalk": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.0.1.tgz", @@ -2624,20 +2422,6 @@ "node": ">= 20" } }, - "node_modules/data-urls": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-8.0.0.tgz", - "integrity": "sha512-JQUCCK+/CAGbGGx618PlFZMXH81Jtj7t73CHv9dd/zVWvxgGT2zLFRjnKb+Ng46GIwcy+f7f88qd4duqllK+WQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "whatwg-mimetype": "^5.0.0", - "whatwg-url": "^17.1.2" - }, - "engines": { - "node": "^22.14.0 || >=24.0.0" - } - }, "node_modules/debug": { "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", @@ -2655,13 +2439,6 @@ } } }, - "node_modules/decimal.js": { - "version": "10.6.0", - "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", - "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", - "dev": true, - "license": "MIT" - }, "node_modules/deep-extend": { "version": "0.6.0", "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", @@ -2707,17 +2484,6 @@ "node": ">=0.4.0" } }, - "node_modules/dequal": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", - "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=6" - } - }, "node_modules/detect-libc": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", @@ -2728,14 +2494,6 @@ "node": ">=8" } }, - "node_modules/dom-accessibility-api": { - "version": "0.5.16", - "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz", - "integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==", - "dev": true, - "license": "MIT", - "peer": true - }, "node_modules/dom-helpers": { "version": "5.2.1", "resolved": "https://registry.npmjs.org/dom-helpers/-/dom-helpers-5.2.1.tgz", @@ -2795,19 +2553,6 @@ "dev": true, "license": "MIT" }, - "node_modules/entities": { - "version": "9.0.0", - "resolved": "https://registry.npmjs.org/entities/-/entities-9.0.0.tgz", - "integrity": "sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=20.19.0" - }, - "funding": { - "url": "https://github.com/fb55/entities?sponsor=1" - } - }, "node_modules/error-ex": { "version": "1.3.4", "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.4.tgz", @@ -2836,13 +2581,6 @@ "node": ">= 0.4" } }, - "node_modules/es-module-lexer": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", - "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", - "dev": true, - "license": "MIT" - }, "node_modules/es-object-atoms": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", @@ -3116,16 +2854,6 @@ "node": ">=4.0" } }, - "node_modules/estree-walker": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", - "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/estree": "^1.0.0" - } - }, "node_modules/esutils": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", @@ -3136,16 +2864,6 @@ "node": ">=0.10.0" } }, - "node_modules/expect-type": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", - "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=12.0.0" - } - }, "node_modules/fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", @@ -3522,19 +3240,6 @@ "dev": true, "license": "MIT" }, - "node_modules/html-encoding-sniffer": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-7.0.0.tgz", - "integrity": "sha512-UikN5yr7xsCDAq87Or5or0PAlD3HJJOKVzM05az588WnpDJ4Ux7a2A53Qi6gofGg2/EtvF/H4hCi/TXfCW4Y6w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@exodus/bytes": "^1.15.1" - }, - "engines": { - "node": "^22.13.0 || >=24.0.0" - } - }, "node_modules/http-proxy-agent": { "version": "9.1.0", "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-9.1.0.tgz", @@ -3651,32 +3356,6 @@ "node": ">=4" } }, - "node_modules/is-alphabetical": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-2.0.1.tgz", - "integrity": "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/is-alphanumerical": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/is-alphanumerical/-/is-alphanumerical-2.0.1.tgz", - "integrity": "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-alphabetical": "^2.0.0", - "is-decimal": "^2.0.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, "node_modules/is-arrayish": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", @@ -3698,17 +3377,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/is-decimal": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/is-decimal/-/is-decimal-2.0.1.tgz", - "integrity": "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, "node_modules/is-extglob": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", @@ -3755,13 +3423,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/is-potential-custom-element-name": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", - "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", - "dev": true, - "license": "MIT" - }, "node_modules/is-url": { "version": "1.2.4", "resolved": "https://registry.npmjs.org/is-url/-/is-url-1.2.4.tgz", @@ -3823,54 +3484,6 @@ "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", "license": "MIT" }, - "node_modules/jsdom": { - "version": "31.0.0", - "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-31.0.0.tgz", - "integrity": "sha512-xAkhD9z1eyFC5+QUi9K24CaZJgdCQ2GOGLW1GdVDoQvkp/AxEH9TQ0pAplPOlIiV92hfcgnFOADZypbjgbBT6Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@exodus/bytes": "^1.16.0", - "bcp-47": "^2.1.2", - "bcp-47-match": "^2.0.3", - "data-urls": "^8.0.0", - "decimal.js": "^10.6.0", - "html-encoding-sniffer": "^7.0.0", - "is-potential-custom-element-name": "^1.0.1", - "lru-cache": "^11.5.3", - "parse5": "^8.1.0", - "parse5-parser-stream": "^8.1.0", - "saxes": "^6.0.0", - "tough-cookie": "^6.0.2", - "undici": "^8.12.3", - "w3c-xmlserializer": "^6.0.0", - "webidl-conversions": "^8.0.1", - "whatwg-mimetype": "^5.0.0", - "whatwg-url": "^17.3.0", - "xml-name-validator": "^5.0.0" - }, - "engines": { - "node": "^22.22.2 || ^24.15.0 || >=26.0.0" - }, - "peerDependencies": { - "@napi-rs/canvas": "^1.0.13" - }, - "peerDependenciesMeta": { - "@napi-rs/canvas": { - "optional": true - } - } - }, - "node_modules/jsdom/node_modules/lru-cache": { - "version": "11.5.3", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", - "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": "20 || >=22" - } - }, "node_modules/jsesc": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", @@ -4287,27 +3900,6 @@ "yallist": "^3.0.2" } }, - "node_modules/lz-string": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz", - "integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==", - "dev": true, - "license": "MIT", - "peer": true, - "bin": { - "lz-string": "bin/bin.js" - } - }, - "node_modules/magic-string": { - "version": "1.4.5", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", - "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/sourcemap-codec": "^1.6.0" - } - }, "node_modules/math-intrinsics": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", @@ -4438,20 +4030,6 @@ "node": ">=0.10.0" } }, - "node_modules/obug": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz", - "integrity": "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==", - "dev": true, - "funding": [ - "https://github.com/sponsors/sxzz", - "https://opencollective.com/debug" - ], - "license": "MIT", - "engines": { - "node": ">=12.20.0" - } - }, "node_modules/on-headers": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.1.0.tgz", @@ -4611,32 +4189,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/parse5": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.1.0.tgz", - "integrity": "sha512-sq3qBFpee5jeocbFbO48VHlGr8sT7mbXS0vxlKN6sottBtJzrOG3998sr0llSZcQAGgfpdmEYAIZE0P9z0dE8w==", - "dev": true, - "license": "MIT", - "dependencies": { - "entities": "^9.0.0" - }, - "funding": { - "url": "https://github.com/inikulin/parse5?sponsor=1" - } - }, - "node_modules/parse5-parser-stream": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/parse5-parser-stream/-/parse5-parser-stream-8.1.0.tgz", - "integrity": "sha512-58MPfNTA+DsIzro41rU94xghnu/h2N4yEPdPdGPlZVHM/QvA5jlVGYVo7IzlHbFLHYx3cZUnr9s9HBrA0tEYyw==", - "dev": true, - "license": "MIT", - "dependencies": { - "parse5": "^8.0.0" - }, - "funding": { - "url": "https://github.com/inikulin/parse5?sponsor=1" - } - }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -4760,55 +4312,6 @@ "url": "https://github.com/prettier/prettier?sponsor=1" } }, - "node_modules/pretty-format": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz", - "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "ansi-regex": "^5.0.1", - "ansi-styles": "^5.0.0", - "react-is": "^17.0.1" - }, - "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" - } - }, - "node_modules/pretty-format/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/pretty-format/node_modules/ansi-styles": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", - "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/pretty-format/node_modules/react-is": { - "version": "17.0.2", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", - "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==", - "dev": true, - "license": "MIT", - "peer": true - }, "node_modules/process-nextick-args": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", @@ -5153,19 +4656,6 @@ "dev": true, "license": "MIT" }, - "node_modules/saxes": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", - "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", - "dev": true, - "license": "ISC", - "dependencies": { - "xmlchars": "^2.2.0" - }, - "engines": { - "node": ">=v12.22.7" - } - }, "node_modules/scheduler": { "version": "0.28.0", "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", @@ -5438,13 +4928,6 @@ "node": ">=0.10.0" } }, - "node_modules/std-env": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz", - "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==", - "dev": true, - "license": "MIT" - }, "node_modules/string_decoder": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", @@ -5566,16 +5049,6 @@ "dev": true, "license": "MIT" }, - "node_modules/tinybench": { - "version": "6.2.3", - "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.3.tgz", - "integrity": "sha512-Al01C2JIBnO2CXCAPbpAl6sUiOZHeThGtHYNTa51JRw9PyWOCdr+9Ong05R4qg/Sk3+H645E8ov1h2c58ityNw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=20.0.0" - } - }, "node_modules/tinyclip": { "version": "0.1.15", "resolved": "https://registry.npmjs.org/tinyclip/-/tinyclip-0.1.15.tgz", @@ -5586,16 +5059,6 @@ "node": "^16.14.0 || >= 17.3.0" } }, - "node_modules/tinyexec": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", - "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - } - }, "node_modules/tinyglobby": { "version": "0.2.17", "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", @@ -5613,26 +5076,6 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, - "node_modules/tldts": { - "version": "7.4.19", - "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.19.tgz", - "integrity": "sha512-48dH6aSpQnpbzDUc4vIQZ1VjB8tkK+e8c1yx05/SZK+rkssgjEOlxDd/yU8/a4vGYQ9vRgJr9dwMq9TJ0b3X2Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "tldts-core": "^7.4.19" - }, - "bin": { - "tldts": "bin/cli.js" - } - }, - "node_modules/tldts-core": { - "version": "7.4.20", - "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.20.tgz", - "integrity": "sha512-C630TWXZCZmLq0F2bW4QqwnaaxCQ/svpAqvJwnC4JvgEM5ohhBnGsEzTLSOXcN+xjz+kEaHS5uoWIw2klnqd0A==", - "dev": true, - "license": "MIT" - }, "node_modules/tmp": { "version": "0.2.7", "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.7.tgz", @@ -5643,32 +5086,6 @@ "node": ">=14.14" } }, - "node_modules/tough-cookie": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.1.0.tgz", - "integrity": "sha512-FTxc8u8Kl2tz0Lat1u8ksvcy8bwHRyEMawwTWybo51JqaC6O7SvfuhAKg+Ld6VqyIe2QRJBzY9HA7y2WyFRT2w==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "tldts": "^7.0.5" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/tr46": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-7.0.0.tgz", - "integrity": "sha512-BcDSDW+SIGWVOns1Zm6Yg91q9AEj7eaID0QDY9oIqJD1A8dscNwMcl9Sms2DeuWCNov1X0/oXanHGYQBSLwZsg==", - "dev": true, - "license": "MIT", - "dependencies": { - "punycode": "^2.3.1" - }, - "engines": { - "node": "^22.14.0 || >=24.0.0" - } - }, "node_modules/ts-api-utils": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", @@ -5753,16 +5170,6 @@ "typescript": ">=4.8.4 <6.1.0" } }, - "node_modules/undici": { - "version": "8.12.4", - "resolved": "https://registry.npmjs.org/undici/-/undici-8.12.4.tgz", - "integrity": "sha512-8Mx+uNKKER2bA4AdtedkqRbwUCIJFr2nJckXRe5yrDqzePqwLP7VNcctN8/XdmDSbF7mS+jJKIszlL+vbam1VA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=22.19.0" - } - }, "node_modules/update-browserslist-db": { "version": "1.3.4", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.4.tgz", @@ -5910,102 +5317,6 @@ } } }, - "node_modules/vitest": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.1.0.tgz", - "integrity": "sha512-MzmNFnrwa8v8lF1bLxw3UJ4EREwVOVb75VqJZmUDRjJ6EluK/x9th7qTbaeDk41WxE1GxWqmTXcdsfobfH5sOA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/chai": "^5.2.2", - "@vitest/mocker": "5.1.0", - "chai": "^6.3.0", - "es-module-lexer": "^2.3.2", - "expect-type": "^1.4.0", - "magic-string": "^1.4.3", - "obug": "^3.0.0", - "picomatch": "^4.0.7", - "std-env": "^4.3.0", - "tinybench": "^6.2.2", - "tinyexec": "^1.3.1", - "tinyglobby": "^0.2.17", - "why-is-node-running": "3.2.1" - }, - "bin": { - "vitest": "vitest.mjs" - }, - "engines": { - "node": "^22.12.0 || ^24.0.0 || >=26.0.0" - }, - "funding": { - "url": "https://opencollective.com/vitest" - }, - "peerDependencies": { - "@edge-runtime/vm": "*", - "@opentelemetry/api": "^1.9.0", - "@types/node": "^22.0.0 || >=24.0.0", - "@vitest/browser-playwright": "5.1.0", - "@vitest/browser-preview": "5.1.0", - "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", - "@vitest/coverage-istanbul": "5.1.0", - "@vitest/coverage-v8": "5.1.0", - "@vitest/ui": "5.1.0", - "happy-dom": "*", - "jsdom": "*", - "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" - }, - "peerDependenciesMeta": { - "@edge-runtime/vm": { - "optional": true - }, - "@opentelemetry/api": { - "optional": true - }, - "@types/node": { - "optional": true - }, - "@vitest/browser-playwright": { - "optional": true - }, - "@vitest/browser-preview": { - "optional": true - }, - "@vitest/browser-webdriverio": { - "optional": true - }, - "@vitest/coverage-istanbul": { - "optional": true - }, - "@vitest/coverage-v8": { - "optional": true - }, - "@vitest/ui": { - "optional": true - }, - "happy-dom": { - "optional": true - }, - "jsdom": { - "optional": true - }, - "vite": { - "optional": false - } - } - }, - "node_modules/w3c-xmlserializer": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-6.0.0.tgz", - "integrity": "sha512-4Nsy8K5Tr6SPDH9jhKJOHf7ChDrc1zufZTVSF7x72hwuEXBqxqk9G6cK+K2NRUtB3iELRJqjXb4JPDMBjMTl2Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "xml-name-validator": "^5.0.0" - }, - "engines": { - "node": "^22.22.2 || ^24.15.0 || >=26.0.0" - } - }, "node_modules/wait-on": { "version": "9.5.1", "resolved": "https://registry.npmjs.org/wait-on/-/wait-on-9.5.1.tgz", @@ -6025,41 +5336,6 @@ "node": ">=20.0.0" } }, - "node_modules/webidl-conversions": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz", - "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=20" - } - }, - "node_modules/whatwg-mimetype": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz", - "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=20" - } - }, - "node_modules/whatwg-url": { - "version": "17.3.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-17.3.0.tgz", - "integrity": "sha512-KwOAJrpf+GTgBvcBQJcP38sMF0DsQKdwtG+TxM2pW44P6E5k0hDbWrDmyuJDIF0Uef0aQq0ZoJs+5oI+k8ddhg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@exodus/bytes": "^1.16.0", - "tr46": "^7.0.0", - "webidl-conversions": "^8.0.1" - }, - "engines": { - "node": "^22.14.0 || >=24.0.0" - } - }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", @@ -6076,19 +5352,6 @@ "node": ">= 8" } }, - "node_modules/why-is-node-running": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz", - "integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==", - "dev": true, - "license": "MIT", - "bin": { - "why-is-node-running": "cli.js" - }, - "engines": { - "node": ">=20.11" - } - }, "node_modules/widest-line": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/widest-line/-/widest-line-4.0.1.tgz", @@ -6155,23 +5418,6 @@ } } }, - "node_modules/xml-name-validator": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", - "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=18" - } - }, - "node_modules/xmlchars": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", - "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", - "dev": true, - "license": "MIT" - }, "node_modules/yallist": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", diff --git a/web-client/package.json b/web-client/package.json index ef4bc038f7..d94ca5c183 100644 --- a/web-client/package.json +++ b/web-client/package.json @@ -10,22 +10,19 @@ "preview": "vite preview", "format": "prettier --check \"src/**/*.{ts,tsx}\"", "format:fix": "prettier --write \"src/**/*.{ts,tsx}\"", - "accessibility": "npm run build && npx serve dist -l 5000 & npx wait-on http://localhost:5000/index.html && npx axe http://localhost:5000/index.html --chrome-options=\"--no-sandbox\" --exit", - "test:checkout": "vitest run src/billing/HostingFirstInvoiceCheckout.test.tsx src/api/hostingFirstInvoice.test.ts src/api/accountControlUi.test.ts src/account/controlUiSession.test.ts src/account/AccountCheckoutRoute.test.tsx" + "accessibility": "npm run build && npx serve dist -l 5000 & npx wait-on http://localhost:5000/index.html && npx axe http://localhost:5000/index.html --chrome-options=\"--no-sandbox\" --exit" }, "dependencies": { + "@tanstack/react-query": "^5.100.13", "@emotion/react": "^11.14.0", "@emotion/styled": "^11.14.1", "@mui/material": "^9.0.1", - "@stripe/stripe-js": "^10.2.1", - "@tanstack/react-query": "^5.100.13", "react": "^19.2.6", "react-dom": "^19.2.6" }, "devDependencies": { "@axe-core/cli": "^4.11.3", "@eslint/js": "^10.0.0", - "@testing-library/react": "^16.3.3", "@types/react": "^19.2.15", "@types/react-dom": "^19.2.3", "@vitejs/plugin-react": "^6.0.2", @@ -33,13 +30,11 @@ "eslint-plugin-react-hooks": "^7.1.1", "eslint-plugin-react-refresh": "^0.5.2", "globals": "^17.6.0", - "jsdom": "^31.0.0", "prettier": "^3.8.3", "serve": "^14.2.6", "typescript": "~6.0.3", "typescript-eslint": "^8.59.4", "vite": "^8.0.16", - "vitest": "^5.1.0", "wait-on": "^9.0.10" } } diff --git a/web-client/src/App.tsx b/web-client/src/App.tsx index 9a5dbef7ab..1941b252ea 100644 --- a/web-client/src/App.tsx +++ b/web-client/src/App.tsx @@ -1,38 +1,15 @@ -import { useEffect, useState } from 'react'; +import { useState } from 'react'; import Button from '@mui/material/Button'; import GameEditor from './GameEditor'; import ScriptEditor from './ScriptEditor'; -import AccountCheckoutRoute, { - type AccountCheckoutRouteProps, -} from './account/AccountCheckoutRoute'; import reactLogo from './assets/react.svg'; import viteLogo from '/vite.svg'; import './App.css'; -export interface AppProps { - accountCheckoutRouteProps?: Omit; -} - -function App({ accountCheckoutRouteProps }: AppProps = {}) { - const [pathname, setPathname] = useState(() => window.location.pathname); +function App() { const [count, setCount] = useState(0); const [mode, setMode] = useState<'demo' | 'game' | 'script'>('demo'); - useEffect(() => { - const updatePathname = () => setPathname(window.location.pathname); - window.addEventListener('popstate', updatePathname); - return () => window.removeEventListener('popstate', updatePathname); - }, []); - - if (pathname.startsWith('/account/')) { - return ( - - ); - } - return ( <>
diff --git a/web-client/src/account/AccountCheckoutRoute.test.tsx b/web-client/src/account/AccountCheckoutRoute.test.tsx deleted file mode 100644 index 423aca1034..0000000000 --- a/web-client/src/account/AccountCheckoutRoute.test.tsx +++ /dev/null @@ -1,686 +0,0 @@ -// @vitest-environment jsdom -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { - act, - cleanup, - fireEvent, - render, - screen, - waitFor, -} from '@testing-library/react'; -import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; -import App from '../App'; -import { - AccountControlUiApiError, - type AccountControlUiApi, -} from '../api/accountControlUi'; -import type { HostingStripe } from '../billing/hostingStripe'; -import { - createControlUiSessionStore, - type ControlUiSessionStore, -} from './controlUiSession'; - -const origin = 'https://gateway.example.test'; -const subscriptionId = '11111111-1111-4111-8111-111111111111'; -const accountId = '22222222-2222-4222-8222-222222222222'; -const checkoutPath = `/account/subscriptions/${subscriptionId}/checkout`; -const stores = new Set(); - -const firstInvoice = { - subscriptionId, - invoiceId: 'in_existing', - paymentIntentId: 'pi_existing', - paymentInstrumentId: '33333333-3333-4333-8333-333333333333', - amount: '1299', - currency: 'usd', - tupleDigest: `sha256:${'a'.repeat(64)}`, - expectedRowVersion: 3, - state: 'AWAITING_PAYMENT', - expiresAt: '2099-01-01T00:00:00Z', - confirmationRequestId: null, - preRowOriginalRequestId: null, - authorizationVersion: 0, -}; - -function makeIds() { - const ids = [ - '44444444-4444-4444-8444-444444444444', - '55555555-5555-4555-8555-555555555555', - '66666666-6666-4666-8666-666666666666', - '77777777-7777-4777-8777-777777777777', - '88888888-8888-4888-8888-888888888888', - ]; - let index = 0; - return () => ids[index++] ?? '99999999-9999-4999-8999-999999999999'; -} - -function deferred() { - let resolve!: (value: T) => void; - const promise = new Promise((done) => { - resolve = done; - }); - return { promise, resolve }; -} - -function setupApp( - options: { - key?: string; - invoiceStatus?: number; - loadStripeClient?: (publishableKey: string) => Promise; - } = {} -) { - const queries = new QueryClient({ - defaultOptions: { - queries: { retry: false }, - mutations: { retry: false }, - }, - }); - const clearQueryCache = vi.fn(() => queries.clear()); - const fetchImpl = vi - .fn() - .mockImplementation(async (input, init) => { - const url = input instanceof URL ? input : new URL(String(input)); - if ( - url.pathname === - `/api/account/billing/hosting/subscriptions/${subscriptionId}/first-invoice` && - (init?.method ?? 'GET') === 'GET' - ) { - if (options.invoiceStatus && options.invoiceStatus !== 200) { - return new Response('private owner response', { - status: options.invoiceStatus, - }); - } - return new Response(JSON.stringify(firstInvoice), { - status: 200, - headers: { 'Content-Type': 'application/json' }, - }); - } - return new Response('private owner response', { status: 404 }); - }); - const sessionStore = createControlUiSessionStore({ - origin: () => origin, - fetchImpl, - idFactory: makeIds(), - clearQueryCache, - }); - stores.add(sessionStore); - const api: AccountControlUiApi = { - login: vi.fn().mockResolvedValue({ - accountId, - authToken: 'header.payload.signature', - expiresAt: new Date(Date.now() + 60 * 60 * 1000).toISOString(), - }), - }; - const stripe: HostingStripe = { - handleNextAction: vi.fn().mockResolvedValue({}), - }; - const loadStripeClient = - options.loadStripeClient ?? vi.fn().mockResolvedValue(stripe); - window.history.replaceState({}, '', checkoutPath); - const view = render( - - - - ); - return { - ...view, - api, - queries, - clearQueryCache, - fetchImpl, - sessionStore, - loadStripeClient, - }; -} - -async function signIn() { - fireEvent.change(screen.getByLabelText('Account email'), { - target: { value: 'owner@example.com' }, - }); - fireEvent.change(screen.getByLabelText('Primary authentication secret'), { - target: { value: 'primary-secret' }, - }); - fireEvent.click(screen.getByRole('button', { name: 'Sign in' })); - await screen.findByText('in_existing'); -} - -afterEach(() => { - cleanup(); - for (const store of stores) store.signOut(); - stores.clear(); - window.history.replaceState({}, '', '/'); - vi.restoreAllMocks(); -}); - -describe('App-owned first-invoice route', () => { - it('renders the login form, loads only the existing owner invoice, and signs out locally', async () => { - const { api, fetchImpl, clearQueryCache } = setupApp(); - expect( - screen.getByRole('heading', { name: 'Sign in to Account' }) - ).toBeTruthy(); - await signIn(); - - expect(api.login).toHaveBeenCalledOnce(); - expect(fetchImpl).toHaveBeenCalledOnce(); - expect(fetchImpl.mock.calls[0][0]).toEqual( - new URL( - `/api/account/billing/hosting/subscriptions/${subscriptionId}/first-invoice`, - origin - ) - ); - expect( - new Headers(fetchImpl.mock.calls[0][1]?.headers).get('authorization') - ).toBe('Bearer header.payload.signature'); - expect( - fetchImpl.mock.calls.some(([input]) => - String(input).includes('/first-invoice/confirm') - ) - ).toBe(false); - - fireEvent.click(screen.getByRole('button', { name: 'Sign out' })); - await screen.findByRole('heading', { name: 'Sign in to Account' }); - expect( - screen.getByText(/Account token revocation is not available here/) - ).toBeTruthy(); - expect(clearQueryCache).toHaveBeenCalled(); - expect( - fetchImpl.mock.calls.some(([input]) => - String(input).includes('/auth/logout') - ) - ).toBe(false); - }); - - it('keeps Account status recovery available when the Vite key is missing', async () => { - const loadStripeClient = vi.fn(); - const { fetchImpl } = setupApp({ key: '', loadStripeClient }); - await signIn(); - expect(screen.getByText(/publishable key is not configured/)).toBeTruthy(); - expect(loadStripeClient).not.toHaveBeenCalled(); - fireEvent.click( - screen.getByRole('button', { name: 'Check Account status' }) - ); - await waitFor(() => expect(fetchImpl).toHaveBeenCalledTimes(2)); - expect( - fetchImpl.mock.calls.every( - ([, init]) => (init?.method ?? 'GET') === 'GET' - ) - ).toBe(true); - }); - - it('reads and refreshes Account status while Stripe loading fails', async () => { - const loadStripeClient = vi - .fn() - .mockRejectedValue(new Error('script blocked')); - const { fetchImpl } = setupApp({ loadStripeClient }); - await signIn(); - await screen.findByText(/Stripe authentication is unavailable/); - fireEvent.click( - screen.getByRole('button', { name: 'Check Account status' }) - ); - await waitFor(() => expect(fetchImpl).toHaveBeenCalledTimes(2)); - expect( - fetchImpl.mock.calls.every( - ([, init]) => (init?.method ?? 'GET') === 'GET' - ) - ).toBe(true); - }); - - it('reads and refreshes Account status while Stripe loading is pending', async () => { - const loading = deferred(); - const loadStripeClient = vi.fn().mockReturnValue(loading.promise); - const { fetchImpl } = setupApp({ loadStripeClient }); - await signIn(); - expect( - screen.getByText('Loading secure payment authentication.') - ).toBeTruthy(); - fireEvent.click( - screen.getByRole('button', { name: 'Check Account status' }) - ); - await waitFor(() => expect(fetchImpl).toHaveBeenCalledTimes(2)); - expect( - fetchImpl.mock.calls.every( - ([, init]) => (init?.method ?? 'GET') === 'GET' - ) - ).toBe(true); - }); - - it.each(['unchanged', 'replaced key', 'replaced loader'])( - 'binds an in-flight confirmation to its %s Stripe loading context', - async (contextChange) => { - const loading = deferred(); - const replacementLoading = deferred(); - const confirmation = deferred(); - const stripe: HostingStripe = { - handleNextAction: vi.fn().mockResolvedValue({}), - }; - const replacement: HostingStripe = { - handleNextAction: vi.fn().mockResolvedValue({}), - }; - const loader = vi - .fn() - .mockReturnValueOnce(loading.promise) - .mockReturnValue(replacementLoading.promise); - const replacementLoader = vi - .fn() - .mockReturnValue(replacementLoading.promise); - const { api, fetchImpl, queries, rerender, sessionStore } = setupApp({ - loadStripeClient: loader, - }); - const read = fetchImpl.getMockImplementation()!; - fetchImpl.mockImplementation(async (input, init) => { - if (String(input).endsWith('/reauthenticate')) { - return new Response( - JSON.stringify({ - evidenceId: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', - }), - { status: 200 } - ); - } - if (String(input).endsWith('/confirm')) return confirmation.promise; - return read(input, init); - }); - await signIn(); - fireEvent.change(screen.getByLabelText('Account email'), { - target: { value: 'owner@example.com' }, - }); - fireEvent.change(screen.getByLabelText('Primary authentication secret'), { - target: { value: 'primary-secret' }, - }); - fireEvent.click(screen.getByRole('checkbox')); - fireEvent.click( - screen.getByRole('button', { name: 'Authorize first-invoice charge' }) - ); - await waitFor(() => - expect( - fetchImpl.mock.calls.filter(([input]) => - String(input).endsWith('/confirm') - ) - ).toHaveLength(1) - ); - - if (contextChange !== 'unchanged') { - rerender( - - - - ); - } - await act(async () => { - loading.resolve(stripe); - await loading.promise; - }); - if (contextChange !== 'unchanged') { - expect( - screen.getByText('Loading secure payment authentication.') - ).toBeTruthy(); - await act(async () => { - replacementLoading.resolve(replacement); - await replacementLoading.promise; - }); - } - await waitFor(() => - expect( - screen.queryByText('Loading secure payment authentication.') - ).toBeNull() - ); - await act(async () => { - confirmation.resolve( - new Response( - JSON.stringify({ - status: 'requires_action', - clientSecret: 'pi_existing_secret_ephemeral', - }), - { status: 200 } - ) - ); - await confirmation.promise; - }); - if (contextChange === 'unchanged') { - await waitFor(() => - expect(stripe.handleNextAction).toHaveBeenCalledExactlyOnceWith({ - clientSecret: 'pi_existing_secret_ephemeral', - }) - ); - } else { - await screen.findByText( - /Stripe authentication is unavailable. Check Account status/ - ); - expect(stripe.handleNextAction).not.toHaveBeenCalled(); - } - expect(replacement.handleNextAction).not.toHaveBeenCalled(); - expect( - fetchImpl.mock.calls.filter(([input]) => - String(input).endsWith('/confirm') - ) - ).toHaveLength(1); - expect( - fetchImpl.mock.calls.some(([input]) => String(input).endsWith('/renew')) - ).toBe(false); - expect(screen.queryByText(/Account confirmed and committed/)).toBeNull(); - expect(document.body.textContent).not.toContain( - 'pi_existing_secret_ephemeral' - ); - } - ); - - it.each([0, 429, 502, 503])( - 'shows safe temporary feedback for sign-in status %i without retrying', - async (status) => { - const { api } = setupApp(); - vi.mocked(api.login).mockRejectedValue( - new AccountControlUiApiError(status) - ); - fireEvent.change(screen.getByLabelText('Account email'), { - target: { value: 'owner@example.com' }, - }); - fireEvent.change(screen.getByLabelText('Primary authentication secret'), { - target: { value: 'primary-secret' }, - }); - fireEvent.click(screen.getByRole('button', { name: 'Sign in' })); - - await screen.findByText( - status === 429 - ? 'Account sign-in is temporarily unavailable. Try again later.' - : /Account sign-in could not be confirmed/ - ); - expect(api.login).toHaveBeenCalledOnce(); - expect(vi.mocked(api.login).mock.calls[0][0].secret).toBe(''); - expect( - ( - screen.getByLabelText( - 'Primary authentication secret' - ) as HTMLInputElement - ).value - ).toBe(''); - } - ); - - it('re-enters a consumed one-time code and explicitly recovers the original sign-in', async () => { - const { api } = setupApp(); - const login = vi.mocked(api.login); - let original: { requestId: string; callerContextId: string } | undefined; - login - .mockImplementationOnce( - async ({ requestId, callerContextId, secret }) => { - expect(secret).toBe('012345'); - original = { requestId, callerContextId }; - throw new AccountControlUiApiError(0); - } - ) - .mockImplementationOnce( - async ({ requestId, callerContextId, secret }) => { - if ( - !original || - requestId !== original.requestId || - callerContextId !== original.callerContextId || - secret !== '012345' - ) { - throw new AccountControlUiApiError(401); - } - return { - accountId, - authToken: 'header.payload.signature', - expiresAt: new Date(Date.now() + 60_000).toISOString(), - }; - } - ); - fireEvent.change(screen.getByLabelText('Account email'), { - target: { value: 'owner@example.com' }, - }); - const secret = screen.getByLabelText( - 'Primary authentication secret' - ) as HTMLInputElement; - fireEvent.change(secret, { target: { value: '012345' } }); - fireEvent.click(screen.getByRole('button', { name: 'Sign in' })); - - await screen.findByText(/re-enter the same secret and select Sign in/); - expect(secret.value).toBe(''); - expect(login).toHaveBeenCalledOnce(); - expect(login.mock.calls[0][0].secret).toBe(''); - expect( - (screen.getByRole('button', { name: 'Sign in' }) as HTMLButtonElement) - .disabled - ).toBe(true); - - fireEvent.change(secret, { target: { value: '012345' } }); - fireEvent.click(screen.getByRole('button', { name: 'Sign in' })); - await screen.findByText('in_existing'); - expect(login).toHaveBeenCalledTimes(2); - expect(login.mock.calls[1][0].secret).toBe(''); - }); - - it.each(['navigation', 'replacement login'])( - 'restores only the server original operation after %s before a confirmation row exists', - async (interruption) => { - const { fetchImpl } = setupApp(); - let original: string | null = null; - const openingEvidence = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'; - const freshEvidence = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'; - const proofs: Array> = []; - const renewals: Array> = []; - let confirmations = 0; - fetchImpl.mockImplementation(async (input, init) => { - const path = new URL(String(input)).pathname; - if ((init?.method ?? 'GET') === 'GET') { - return Response.json({ - ...firstInvoice, - preRowOriginalRequestId: original, - }); - } - const body = JSON.parse(String(init?.body)) as Record; - if (path.endsWith('/reauthenticate')) { - proofs.push(body); - const binding = body.billingBinding as Record; - if (original === null) original = binding.originalRequestId as string; - return Response.json({ - evidenceId: proofs.length === 1 ? openingEvidence : freshEvidence, - }); - } - if (path.endsWith('/confirm')) { - confirmations += 1; - return new Response(null, { status: 409 }); - } - if (path.endsWith('/renew')) { - renewals.push(body); - return Response.json({ status: 'processing', clientSecret: null }); - } - return new Response(null, { status: 404 }); - }); - await signIn(); - async function authorize() { - fireEvent.change(screen.getByLabelText('Account email'), { - target: { value: 'owner@example.com' }, - }); - fireEvent.change( - screen.getByLabelText('Primary authentication secret'), - { target: { value: 'fresh-primary-secret' } } - ); - fireEvent.click(screen.getByRole('checkbox')); - fireEvent.click( - screen.getByRole('button', { - name: /Authorize first-invoice charge|Resume exact confirmation/, - }) - ); - } - await authorize(); - await screen.findByRole('button', { name: 'Renew exact authorization' }); - expect(proofs).toHaveLength(1); - expect(confirmations).toBe(1); - if (interruption === 'navigation') { - act(() => { - window.history.pushState({}, '', '/'); - window.dispatchEvent(new PopStateEvent('popstate')); - }); - await screen.findByRole('heading', { name: 'Vite + React' }); - act(() => { - window.history.pushState({}, '', checkoutPath); - window.dispatchEvent(new PopStateEvent('popstate')); - }); - } else { - fireEvent.click(screen.getByRole('button', { name: 'Sign out' })); - await screen.findByRole('heading', { name: 'Sign in to Account' }); - await signIn(); - } - const renew = await screen.findByRole('button', { - name: 'Renew exact authorization', - }); - expect(screen.queryByRole('checkbox')).toBeNull(); - expect( - screen.queryByLabelText('Primary authentication secret') - ).toBeNull(); - expect(proofs).toHaveLength(1); - expect(renewals).toHaveLength(0); - fireEvent.click(renew); - expect((screen.getByRole('checkbox') as HTMLInputElement).checked).toBe( - false - ); - expect( - ( - screen.getByLabelText( - 'Primary authentication secret' - ) as HTMLInputElement - ).value - ).toBe(''); - await authorize(); - await waitFor(() => expect(renewals).toHaveLength(1)); - expect(confirmations).toBe(1); - expect(proofs).toHaveLength(2); - expect(renewals[0]).toMatchObject({ - requestId: original, - expectedAuthorizationVersion: 0, - reauthenticationEvidenceId: freshEvidence, - acceptCharge: true, - }); - expect(renewals[0].authorizationRequestId).not.toBe(original); - expect(proofs[1].requestId).not.toBe(proofs[0].requestId); - expect(proofs[1].billingBinding).toMatchObject({ - originalRequestId: original, - authorizationPurpose: 'PRE_ROW_RENEWAL', - expectedAuthorizationVersion: 0, - }); - } - ); - - it('handles browser Back and Forward by remounting read-only checkout without confirming', async () => { - const { fetchImpl } = setupApp(); - await signIn(); - expect(fetchImpl).toHaveBeenCalledOnce(); - - window.history.pushState({}, '', '/'); - window.dispatchEvent(new PopStateEvent('popstate')); - expect( - await screen.findByRole('heading', { name: 'Vite + React' }) - ).toBeTruthy(); - - window.history.pushState({}, '', checkoutPath); - window.dispatchEvent(new PopStateEvent('popstate')); - await screen.findByText('in_existing'); - await waitFor(() => expect(fetchImpl).toHaveBeenCalledTimes(2)); - expect( - fetchImpl.mock.calls.some(([input]) => - String(input).includes('/first-invoice/confirm') - ) - ).toBe(false); - }); - - it('preserves Account recovery and ignores replaced Stripe context without confirming', async () => { - const stripeA: HostingStripe = { handleNextAction: vi.fn() }; - const stripeB: HostingStripe = { handleNextAction: vi.fn() }; - const stripeC: HostingStripe = { handleNextAction: vi.fn() }; - const loadA = vi.fn().mockResolvedValue(stripeA); - const { api, fetchImpl, queries, rerender, sessionStore } = setupApp({ - loadStripeClient: loadA, - }); - await signIn(); - expect(screen.getByText('Hosting first invoice')).toBeTruthy(); - - const loadBDeferred = deferred(); - const loadB = vi.fn().mockReturnValue(loadBDeferred.promise); - const renderWith = ( - key: string, - loadStripeClient: (publishableKey: string) => Promise - ) => - rerender( - - - - ); - - renderWith('pk_test_replaced', loadB); - expect(screen.getByText('Hosting first invoice')).toBeTruthy(); - expect( - screen.getByText('Loading secure payment authentication.') - ).toBeTruthy(); - await waitFor(() => expect(loadB).toHaveBeenCalledWith('pk_test_replaced')); - - const loadCDeferred = deferred(); - const loadC = vi.fn().mockReturnValue(loadCDeferred.promise); - renderWith('pk_test_replacedagain', loadC); - await waitFor(() => - expect(loadC).toHaveBeenCalledWith('pk_test_replacedagain') - ); - - await act(async () => { - loadBDeferred.resolve(stripeB); - await loadBDeferred.promise; - }); - expect(screen.getByText('Hosting first invoice')).toBeTruthy(); - expect( - screen.getByText('Loading secure payment authentication.') - ).toBeTruthy(); - - await act(async () => { - loadCDeferred.resolve(stripeC); - await loadCDeferred.promise; - }); - await screen.findByText('in_existing'); - expect( - fetchImpl.mock.calls.some(([input]) => String(input).includes('/confirm')) - ).toBe(false); - expect(stripeA.handleNextAction).not.toHaveBeenCalled(); - expect(stripeB.handleNextAction).not.toHaveBeenCalled(); - expect(stripeC.handleNextAction).not.toHaveBeenCalled(); - }); - - it('unmounts the checkout and returns to login when Account rejects the current bearer', async () => { - const { sessionStore, fetchImpl } = setupApp({ invoiceStatus: 403 }); - fireEvent.change(screen.getByLabelText('Account email'), { - target: { value: 'owner@example.com' }, - }); - fireEvent.change(screen.getByLabelText('Primary authentication secret'), { - target: { value: 'primary-secret' }, - }); - fireEvent.click(screen.getByRole('button', { name: 'Sign in' })); - await waitFor(() => expect(fetchImpl).toHaveBeenCalledOnce()); - await waitFor(() => expect(sessionStore.getSession()).toBeNull()); - await screen.findByRole('heading', { name: 'Sign in to Account' }); - expect(screen.queryByText('Hosting first invoice')).toBeNull(); - }); -}); diff --git a/web-client/src/account/AccountCheckoutRoute.tsx b/web-client/src/account/AccountCheckoutRoute.tsx deleted file mode 100644 index c4da4fcf03..0000000000 --- a/web-client/src/account/AccountCheckoutRoute.tsx +++ /dev/null @@ -1,422 +0,0 @@ -import { - useEffect, - useLayoutEffect, - useMemo, - useRef, - useState, - useSyncExternalStore, - type FormEvent, -} from 'react'; -import Alert from '@mui/material/Alert'; -import Box from '@mui/material/Box'; -import Button from '@mui/material/Button'; -import CircularProgress from '@mui/material/CircularProgress'; -import Stack from '@mui/material/Stack'; -import TextField from '@mui/material/TextField'; -import Typography from '@mui/material/Typography'; -import { useQueryClient } from '@tanstack/react-query'; -import { - AccountControlUiApiError, - createAccountControlUiApi, - type AccountControlUiApi, -} from '../api/accountControlUi'; -import { createFirstInvoiceClient } from '../api/hostingFirstInvoice'; -import HostingFirstInvoiceCheckout from '../billing/HostingFirstInvoiceCheckout'; -import { - loadHostingStripe, - type HostingStripe, -} from '../billing/hostingStripe'; -import { queryClient } from '../api/queryClient'; -import { - ControlUiSessionError, - createControlUiSessionStore, - type ControlUiCredentials, - type ControlUiSessionStore, -} from './controlUiSession'; - -const subscriptionRoute = - /^\/account\/subscriptions\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/checkout\/?$/i; -const publishableKeyPattern = /^pk_(test|live)_[A-Za-z0-9]+$/; - -export interface AccountCheckoutRouteProps { - pathname: string; - sessionStore?: ControlUiSessionStore; - api?: AccountControlUiApi; - stripePublishableKey?: string; - loadStripeClient?: (publishableKey: string) => Promise; -} - -const defaultSessionStore = createControlUiSessionStore({ - origin: () => window.location.origin, - fetchImpl: (input, init) => fetch(input, init), - clearQueryCache: () => queryClient.clear(), -}); -const defaultLoginApi = createAccountControlUiApi( - () => window.location.origin, - (input, init) => fetch(input, init) -); - -function parseSubscriptionId(pathname: string): string | null { - const match = subscriptionRoute.exec(pathname); - return match?.[1].toLowerCase() ?? null; -} - -export default function AccountCheckoutRoute({ - pathname, - sessionStore = defaultSessionStore, - api = defaultLoginApi, - stripePublishableKey = import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY, - loadStripeClient = loadHostingStripe, -}: AccountCheckoutRouteProps) { - const subscriptionId = parseSubscriptionId(pathname); - const publishableKey = stripePublishableKey ?? ''; - - if (!subscriptionId) { - return ( - - This account checkout route is invalid. - - ); - } - - return ( - - ); -} - -interface ActiveRouteProps { - subscriptionId: string; - sessionStore: ControlUiSessionStore; - api: AccountControlUiApi; - stripePublishableKey: string; - loadStripeClient: (publishableKey: string) => Promise; -} - -function ActiveAccountCheckoutRoute({ - subscriptionId, - sessionStore, - api, - stripePublishableKey, - loadStripeClient, -}: ActiveRouteProps) { - const queryClient = useQueryClient(); - const session = useSyncExternalStore( - sessionStore.subscribe, - sessionStore.getSession, - () => null - ); - const previousIdentity = useRef(session?.identity ?? null); - const [signoutNotice, setSignoutNotice] = useState(''); - - useLayoutEffect(() => { - const nextIdentity = session?.identity ?? null; - if (previousIdentity.current !== nextIdentity) { - // A cache belongs to one memory-only authority identity. Clear it before - // the next route's passive query effects can run. - queryClient.clear(); - previousIdentity.current = nextIdentity; - } - }, [queryClient, session?.identity]); - - if (!session) { - return ( - - ); - } - - return ( - - - - - - Hosting checkout - - - Signed in to Account {session.accountId} - - - - - - Sign out clears this browser's in-memory session. It does not - revoke the Account token or cancel a confirmation already sent. - - - - - ); -} - -interface CheckoutProps { - subscriptionId: string; - sessionStore: ControlUiSessionStore; - sessionIdentity: string; - stripePublishableKey: string; - loadStripeClient: (publishableKey: string) => Promise; -} - -type StripeLoadResult = - | { - sessionIdentity: string; - publishableKey: string; - loader: CheckoutProps['loadStripeClient']; - status: 'ready'; - stripe: HostingStripe; - } - | { - sessionIdentity: string; - publishableKey: string; - loader: CheckoutProps['loadStripeClient']; - status: 'unavailable'; - }; - -function CheckoutForSession({ - subscriptionId, - sessionStore, - sessionIdentity, - stripePublishableKey, - loadStripeClient, -}: CheckoutProps) { - const [stripeLoadResult, setStripeLoadResult] = - useState(null); - const stripeContext = useMemo( - () => ({ - sessionIdentity, - publishableKey: stripePublishableKey, - loader: loadStripeClient, - }), - [sessionIdentity, stripePublishableKey, loadStripeClient] - ); - const client = useMemo( - () => - createFirstInvoiceClient( - sessionStore.getGatewayOrigin(), - sessionStore.authenticatedRequest - ), - [sessionStore] - ); - - useEffect(() => { - let current = true; - if (!publishableKeyPattern.test(stripePublishableKey)) return; - void Promise.resolve() - .then(() => loadStripeClient(stripePublishableKey)) - .then( - (loaded) => { - if (current) { - setStripeLoadResult({ - sessionIdentity, - publishableKey: stripePublishableKey, - loader: loadStripeClient, - status: 'ready', - stripe: loaded, - }); - } - }, - () => { - if (current) { - setStripeLoadResult({ - sessionIdentity, - publishableKey: stripePublishableKey, - loader: loadStripeClient, - status: 'unavailable', - }); - } - } - ); - return () => { - current = false; - }; - }, [loadStripeClient, sessionIdentity, stripePublishableKey]); - - const matchingResult = - stripeLoadResult?.sessionIdentity === sessionIdentity && - stripeLoadResult.publishableKey === stripePublishableKey && - stripeLoadResult.loader === loadStripeClient - ? stripeLoadResult - : null; - - return ( - - {!publishableKeyPattern.test(stripePublishableKey) ? ( - - Stripe authentication is unavailable because the publishable key is - not configured. Account status recovery remains available. - - ) : matchingResult?.status === 'unavailable' ? ( - - Stripe authentication is unavailable. Account status recovery remains - available. - - ) : matchingResult?.status !== 'ready' ? ( - - - Loading secure payment authentication. - - ) : null} - - - ); -} - -interface LoginFormProps { - api: AccountControlUiApi; - sessionStore: ControlUiSessionStore; - notice: string; -} - -function AccountLoginForm({ api, sessionStore, notice }: LoginFormProps) { - const [email, setEmail] = useState(''); - const [secret, setSecret] = useState(''); - const [busy, setBusy] = useState(false); - const [message, setMessage] = useState(''); - const locked = useRef(false); - - async function submit(event: FormEvent) { - event.preventDefault(); - if (locked.current || busy) return; - locked.current = true; - setBusy(true); - setMessage(''); - const credentials: ControlUiCredentials = { - email: email.trim(), - secret, - }; - setSecret(''); - try { - await sessionStore.signIn(api, credentials); - } catch (error) { - if ( - error instanceof ControlUiSessionError && - error.code === 'SESSION_REPLACED' - ) { - setMessage('This sign-in attempt was replaced. Sign in again.'); - } else if (sessionStore.canRetrySignIn(credentials.email)) { - setMessage( - 'Account sign-in could not be confirmed. To retry now, re-enter the same secret and select Sign in.' - ); - } else if ( - error instanceof AccountControlUiApiError && - (error.uncertain || error.status === 429) - ) { - setMessage( - 'Account sign-in is temporarily unavailable. Try again later.' - ); - } else { - setMessage( - 'Sign-in could not be completed. Check your email and primary authentication secret.' - ); - } - } finally { - credentials.secret = ''; - locked.current = false; - setBusy(false); - } - } - - return ( - - void submit(event)} - > - - Sign in to Account - - - Sign in to review the existing hosting invoice. Sign-in does not - authorize a payment. - - {notice && {notice}} - { - const nextEmail = event.target.value; - if ( - nextEmail.trim() !== email.trim() && - sessionStore.canRetrySignIn(email.trim()) - ) { - setMessage(''); - } - sessionStore.discardLoginRecoveryIfEmailChanged(nextEmail.trim()); - setEmail(nextEmail); - }} - slotProps={{ htmlInput: { maxLength: 254 } }} - /> - setSecret(event.target.value)} - slotProps={{ htmlInput: { maxLength: 1024 } }} - /> - - {message && ( - - {message} - - )} - - Sign out clears this browser's in-memory session. It does not - confirm server-side token revocation. - - - - ); -} diff --git a/web-client/src/account/controlUiSession.test.ts b/web-client/src/account/controlUiSession.test.ts deleted file mode 100644 index 06dbdb763b..0000000000 --- a/web-client/src/account/controlUiSession.test.ts +++ /dev/null @@ -1,543 +0,0 @@ -// @vitest-environment jsdom -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { - AccountControlUiApiError, - accountControlUiLoginTimeoutMs, - type AccountControlUiApi, - type AccountControlUiLoginRequest, -} from '../api/accountControlUi'; -import { - ControlUiSessionError, - createControlUiSessionStore, -} from './controlUiSession'; - -const origin = 'https://gateway.example.test'; -const accountId = '11111111-1111-4111-8111-111111111111'; -const subscriptionId = '22222222-2222-4222-8222-222222222222'; -const authToken = 'header.payload.signature'; -const stores = new Set>(); - -function deferred() { - let resolve!: (value: T) => void; - const promise = new Promise((done) => { - resolve = done; - }); - return { promise, resolve }; -} - -function ids() { - const values = [ - '33333333-3333-4333-8333-333333333333', - '44444444-4444-4444-8444-444444444444', - '55555555-5555-4555-8555-555555555555', - '66666666-6666-4666-8666-666666666666', - '77777777-7777-4777-8777-777777777777', - '88888888-8888-4888-8888-888888888888', - '99999999-9999-4999-8999-999999999999', - ]; - let index = 0; - return () => values[index++] ?? 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'; -} - -function successfulLogin( - expiresAt = new Date(Date.now() + 60_000).toISOString() -) { - return { - accountId, - authToken, - expiresAt, - }; -} - -function makeStore( - options: { - fetchImpl?: typeof fetch; - now?: () => number; - clearQueryCache?: () => void; - } = {} -) { - const store = createControlUiSessionStore({ - origin: () => origin, - fetchImpl: options.fetchImpl ?? vi.fn(), - now: options.now, - idFactory: ids(), - clearQueryCache: options.clearQueryCache, - }); - stores.add(store); - return store; -} - -function loginApi(result = successfulLogin()): AccountControlUiApi { - return { - login: vi.fn().mockResolvedValue(result), - }; -} - -function getRequest( - url = new URL( - `/api/account/billing/hosting/subscriptions/${subscriptionId}/first-invoice`, - origin - ) -) { - return { - url, - init: { method: 'GET', headers: { Accept: 'application/json' } }, - }; -} - -afterEach(() => { - for (const store of stores) store.signOut(); - stores.clear(); - vi.useRealTimers(); - vi.restoreAllMocks(); -}); - -describe('memory-only control-ui session owner', () => { - it('uses one login attempt with stable IDs and attaches the current bearer only to the exact owner read', async () => { - const fetchImpl = vi.fn().mockResolvedValue( - new Response(JSON.stringify({ state: 'AWAITING_PAYMENT' }), { - status: 200, - }) - ); - const store = makeStore({ fetchImpl }); - const sentLoginRequests: AccountControlUiLoginRequest[] = []; - const login = vi - .fn() - .mockImplementation(async (request) => { - sentLoginRequests.push({ ...request }); - return successfulLogin(); - }); - const api: AccountControlUiApi = { login }; - - const session = await store.signIn(api, { - email: 'owner@example.com', - secret: 'primary-secret', - }); - const [loginRequest] = sentLoginRequests; - expect(login).toHaveBeenCalledOnce(); - expect(loginRequest).toMatchObject({ - requestId: expect.stringMatching(/^[0-9a-f-]{36}$/i), - callerContextId: expect.stringMatching(/^[0-9a-f-]{36}$/i), - email: 'owner@example.com', - secret: 'primary-secret', - }); - expect(login.mock.calls[0][0].secret).toBe(''); - expect(session).not.toHaveProperty('authToken'); - - const { url, init } = getRequest(); - const response = await store.authenticatedRequest(url, init); - expect(await response.json()).toEqual({ state: 'AWAITING_PAYMENT' }); - expect(fetchImpl).toHaveBeenCalledOnce(); - const [sentUrl, sentInit] = fetchImpl.mock.calls[0]; - expect(sentUrl).toEqual(url); - expect(new Headers(sentInit?.headers).get('authorization')).toBe( - `Bearer ${authToken}` - ); - expect(sentInit).toMatchObject({ - method: 'GET', - credentials: 'omit', - cache: 'no-store', - redirect: 'error', - referrerPolicy: 'no-referrer', - mode: 'same-origin', - }); - expect(window.localStorage.length).toBe(0); - expect(window.sessionStorage.length).toBe(0); - }); - - it('rejects cross-origin, non-HTTPS, wrong-route, and caller-supplied bearer requests before dispatch', async () => { - const fetchImpl = vi.fn(); - const store = makeStore({ fetchImpl }); - await store.signIn(loginApi(), { - email: 'owner@example.com', - secret: 'primary-secret', - }); - - const cases = [ - getRequest( - new URL( - `/api/account/billing/hosting/subscriptions/${subscriptionId}/first-invoice`, - 'https://attacker.example.test' - ) - ), - getRequest( - new URL( - `/api/account/billing/hosting/subscriptions/${subscriptionId}/first-invoice`, - 'http://gateway.example.test' - ) - ), - getRequest(new URL('/api/account/auth/logout', origin)), - { - ...getRequest(), - init: { - method: 'GET', - headers: { - Accept: 'application/json', - Authorization: 'Bearer caller-supplied', - }, - }, - }, - ]; - - for (const { url, init } of cases) { - await expect( - store.authenticatedRequest(url, init) - ).rejects.toBeInstanceOf(ControlUiSessionError); - } - expect(fetchImpl).not.toHaveBeenCalled(); - }); - - it('clears local auth and query state on expiry and sign-out', async () => { - vi.useFakeTimers(); - const clearQueryCache = vi.fn(); - const store = makeStore({ clearQueryCache }); - await store.signIn(loginApi(), { - email: 'owner@example.com', - secret: 'primary-secret', - }); - expect(store.getSession()).not.toBeNull(); - - vi.advanceTimersByTime(60_001); - expect(store.getSession()).toBeNull(); - expect(clearQueryCache).toHaveBeenCalled(); - - const secondStore = makeStore({ clearQueryCache }); - await secondStore.signIn(loginApi(), { - email: 'owner@example.com', - secret: 'primary-secret', - }); - const countBeforeSignOut = clearQueryCache.mock.calls.length; - secondStore.signOut(); - expect(secondStore.getSession()).toBeNull(); - expect(clearQueryCache.mock.calls.length).toBe(countBeforeSignOut + 1); - }); - - it('rearms expiry when the wall clock rolls back before the timer fires', async () => { - const initialTime = 1_700_000_000_000; - let now = initialTime; - vi.useFakeTimers({ now: initialTime }); - const clearQueryCache = vi.fn(); - const store = makeStore({ - now: () => now, - clearQueryCache, - }); - await store.signIn( - loginApi(successfulLogin(new Date(initialTime + 60_000).toISOString())), - { email: 'owner@example.com', secret: 'primary-secret' } - ); - const clearQueryCacheCalls = clearQueryCache.mock.calls.length; - - now = initialTime - 100_000; - vi.advanceTimersByTime(60_000); - - expect(store.getSession()).not.toBeNull(); - expect(clearQueryCache.mock.calls.length).toBe(clearQueryCacheCalls); - - now = initialTime + 60_000; - vi.advanceTimersByTime(160_000); - - expect(store.getSession()).toBeNull(); - expect(clearQueryCache.mock.calls.length).toBe(clearQueryCacheCalls + 1); - }); - - it('keeps an ordinary 503 session but clears it after an authentication rejection', async () => { - const fetchImpl = vi - .fn() - .mockResolvedValue( - new Response('private error details', { status: 503 }) - ); - const store = makeStore({ fetchImpl }); - await store.signIn(loginApi(), { - email: 'owner@example.com', - secret: 'primary-secret', - }); - const { url, init } = getRequest(); - const unavailable = await store.authenticatedRequest(url, init); - expect(unavailable.status).toBe(503); - expect(store.getSession()).not.toBeNull(); - - fetchImpl.mockResolvedValue( - new Response('private error details', { status: 401 }) - ); - await expect(store.authenticatedRequest(url, init)).rejects.toMatchObject({ - code: 'AUTH_REJECTED', - }); - expect(store.getSession()).toBeNull(); - }); - - it('times out a stalled owner fetch and ignores its late auth rejection', async () => { - vi.useFakeTimers(); - const pending = deferred(); - const fetchImpl = vi - .fn() - .mockReturnValueOnce(pending.promise) - .mockResolvedValueOnce( - new Response(JSON.stringify({ state: 'AWAITING_PAYMENT' }), { - status: 200, - }) - ); - const store = makeStore({ fetchImpl }); - const session = await store.signIn(loginApi(), { - email: 'owner@example.com', - secret: 'primary-secret', - }); - const { url, init } = getRequest(); - const request = store.authenticatedRequest(url, init); - const failure = expect(request).rejects.toMatchObject({ - code: 'REQUEST_FAILED', - }); - - await vi.advanceTimersByTimeAsync(accountControlUiLoginTimeoutMs); - await failure; - expect(fetchImpl.mock.calls[0][1]?.signal?.aborted).toBe(true); - expect(store.getSession()).toEqual(session); - - const lateUnauthorized = new Response('private auth details', { - status: 401, - }); - const cancelLateBody = vi.spyOn(lateUnauthorized.body!, 'cancel'); - pending.resolve(lateUnauthorized); - await Promise.resolve(); - await Promise.resolve(); - expect(cancelLateBody).toHaveBeenCalledOnce(); - - const recovered = await store.authenticatedRequest(url, init); - expect(await recovered.json()).toEqual({ state: 'AWAITING_PAYMENT' }); - expect(fetchImpl).toHaveBeenCalledTimes(2); - expect(store.getSession()).toEqual(session); - }); - - it('times out a stalled owner response body and cancels its reader', async () => { - vi.useFakeTimers(); - const cancel = vi.fn(); - const response = new Response( - new ReadableStream({ - start(controller) { - controller.enqueue(new TextEncoder().encode('{"state":')); - }, - cancel, - }), - { status: 200 } - ); - const fetchImpl = vi.fn().mockResolvedValue(response); - const store = makeStore({ fetchImpl }); - const session = await store.signIn(loginApi(), { - email: 'owner@example.com', - secret: 'primary-secret', - }); - const { url, init } = getRequest(); - const request = store.authenticatedRequest(url, init); - const failure = expect(request).rejects.toMatchObject({ - code: 'REQUEST_FAILED', - }); - await vi.advanceTimersByTimeAsync(0); - expect(response.body?.locked).toBe(true); - - await vi.advanceTimersByTimeAsync(accountControlUiLoginTimeoutMs); - await failure; - expect(fetchImpl.mock.calls[0][1]?.signal?.aborted).toBe(true); - expect(cancel).toHaveBeenCalledOnce(); - expect(store.getSession()).toEqual(session); - }); - - it('does not retry a timed-out payment write or deliver its late success', async () => { - vi.useFakeTimers(); - const pending = deferred(); - const fetchImpl = vi.fn().mockReturnValue(pending.promise); - const store = makeStore({ fetchImpl }); - const session = await store.signIn(loginApi(), { - email: 'owner@example.com', - secret: 'primary-secret', - }); - const url = new URL( - `/api/account/billing/hosting/subscriptions/${subscriptionId}/first-invoice/confirm`, - origin - ); - const request = store.authenticatedRequest(url, { - method: 'POST', - headers: { - Accept: 'application/json', - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ acceptCharge: true }), - }); - const failure = expect(request).rejects.toMatchObject({ - code: 'REQUEST_FAILED', - }); - - await vi.advanceTimersByTimeAsync(accountControlUiLoginTimeoutMs); - await failure; - expect(fetchImpl).toHaveBeenCalledOnce(); - expect(fetchImpl.mock.calls[0][1]?.signal?.aborted).toBe(true); - expect(store.getSession()).toEqual(session); - - const lateSuccess = new Response(JSON.stringify({ status: 'succeeded' }), { - status: 200, - }); - const cancelLateBody = vi.spyOn(lateSuccess.body!, 'cancel'); - pending.resolve(lateSuccess); - await Promise.resolve(); - await Promise.resolve(); - expect(cancelLateBody).toHaveBeenCalledOnce(); - expect(fetchImpl).toHaveBeenCalledOnce(); - expect(store.getSession()).toEqual(session); - }); - - it('denies a stale owner response after sign-out even if fetch ignores abort', async () => { - const pending = deferred(); - const fetchImpl = vi.fn().mockReturnValue(pending.promise); - const store = makeStore({ fetchImpl }); - await store.signIn(loginApi(), { - email: 'owner@example.com', - secret: 'primary-secret', - }); - const { url, init } = getRequest(); - const request = store.authenticatedRequest(url, init); - await Promise.resolve(); - expect(fetchImpl).toHaveBeenCalledOnce(); - - store.signOut(); - pending.resolve( - new Response(JSON.stringify({ state: 'COMMITTED' }), { status: 200 }) - ); - await expect(request).rejects.toMatchObject({ code: 'SESSION_REPLACED' }); - expect(store.getSession()).toBeNull(); - }); - - it('aborts and denies old owner work when a signed-in identity is replaced', async () => { - const pending = deferred(); - const fetchImpl = vi.fn().mockReturnValue(pending.promise); - const clearQueryCache = vi.fn(); - const store = makeStore({ fetchImpl, clearQueryCache }); - await store.signIn(loginApi(), { - email: 'first@example.com', - secret: 'first-secret', - }); - const oldSession = store.getSession(); - const { url, init } = getRequest(); - const request = store.authenticatedRequest(url, init); - expect(fetchImpl).toHaveBeenCalledOnce(); - - const nextSession = await store.signIn( - loginApi({ - accountId, - authToken: 'next.header.signature', - expiresAt: new Date(Date.now() + 60_000).toISOString(), - }), - { email: 'second@example.com', secret: 'second-secret' } - ); - pending.resolve( - new Response(JSON.stringify({ state: 'COMMITTED' }), { status: 200 }) - ); - - await expect(request).rejects.toMatchObject({ code: 'SESSION_REPLACED' }); - expect(oldSession?.identity).not.toBe(nextSession.identity); - expect(store.getSession()?.identity).toBe(nextSession.identity); - expect(clearQueryCache.mock.calls.length).toBeGreaterThanOrEqual(3); - }); - - it('denies a stale login response when a newer attempt replaces it', async () => { - const earlier = deferred>(); - const login = vi - .fn() - .mockReturnValueOnce(earlier.promise) - .mockResolvedValueOnce(successfulLogin()); - const store = makeStore(); - const api: AccountControlUiApi = { login }; - - const first = store - .signIn(api, { email: 'first@example.com', secret: 'first-secret' }) - .catch((error: unknown) => error); - const second = await store.signIn(api, { - email: 'second@example.com', - secret: 'second-secret', - }); - earlier.resolve(successfulLogin()); - - expect(await first).toMatchObject({ code: 'SESSION_REPLACED' }); - expect(store.getSession()?.identity).toBe(second.identity); - expect(login).toHaveBeenCalledTimes(2); - expect(login.mock.calls[0][0].requestId).not.toBe( - login.mock.calls[1][0].requestId - ); - }); - - it('expires uncertain IDs at the original submission bound despite a second lost reply', async () => { - vi.useFakeTimers(); - const store = makeStore(); - const login = vi - .fn() - .mockRejectedValue(new AccountControlUiApiError(0)); - const api = { login }; - const email = 'owner@example.com'; - const submit = () => store.signIn(api, { email, secret: '012345' }); - - await expect(submit()).rejects.toMatchObject({ status: 0 }); - vi.advanceTimersByTime(59_999); - await expect(submit()).rejects.toMatchObject({ status: 0 }); - expect(login.mock.calls[1][0]).toEqual(login.mock.calls[0][0]); - - vi.advanceTimersByTime(1); - expect(store.canRetrySignIn(email)).toBe(false); - await expect(submit()).rejects.toMatchObject({ status: 0 }); - expect(login.mock.calls[2][0].requestId).not.toBe( - login.mock.calls[0][0].requestId - ); - expect(login.mock.calls[2][0].callerContextId).not.toBe( - login.mock.calls[0][0].callerContextId - ); - }); - - it.each(['email edit', 'sign-out', 'definitive rejection'])( - 'drops the uncertain original after %s', - async (invalidation) => { - const store = makeStore(); - const login = vi - .fn() - .mockRejectedValueOnce(new AccountControlUiApiError(0)) - .mockResolvedValue(successfulLogin()); - const api = { login }; - const email = 'owner@example.com'; - const submit = () => store.signIn(api, { email, secret: '012345' }); - - await expect(submit()).rejects.toMatchObject({ status: 0 }); - expect(store.canRetrySignIn(email)).toBe(true); - if (invalidation === 'email edit') { - store.discardLoginRecoveryIfEmailChanged('other@example.com'); - } else if (invalidation === 'sign-out') { - store.signOut(); - } else { - login.mockRejectedValueOnce(new AccountControlUiApiError(409)); - await expect(submit()).rejects.toMatchObject({ status: 409 }); - expect(login.mock.calls[1][0]).toEqual(login.mock.calls[0][0]); - } - - expect(store.canRetrySignIn(email)).toBe(false); - await submit(); - const fresh = login.mock.lastCall![0]; - expect(fresh.requestId).not.toBe(login.mock.calls[0][0].requestId); - expect(fresh.callerContextId).not.toBe( - login.mock.calls[0][0].callerContextId - ); - } - ); - - it('rejects a buffered success body if the session changes before JSON is consumed', async () => { - const fetchImpl = vi.fn().mockResolvedValue( - new Response(JSON.stringify({ state: 'AWAITING_PAYMENT' }), { - status: 200, - }) - ); - const store = makeStore({ fetchImpl }); - await store.signIn(loginApi(), { - email: 'owner@example.com', - secret: 'primary-secret', - }); - const { url, init } = getRequest(); - const response = await store.authenticatedRequest(url, init); - store.signOut(); - await expect(response.json()).rejects.toMatchObject({ - code: 'SESSION_REPLACED', - }); - }); -}); diff --git a/web-client/src/account/controlUiSession.ts b/web-client/src/account/controlUiSession.ts deleted file mode 100644 index 85543ca2ed..0000000000 --- a/web-client/src/account/controlUiSession.ts +++ /dev/null @@ -1,625 +0,0 @@ -import { - AccountControlUiApiError, - accountControlUiLoginTimeoutMs, - maxControlUiSessionLifetimeMs, - type AccountControlUiApi, - type AccountControlUiLoginRequest, - type AccountControlUiLoginResult, -} from '../api/accountControlUi'; - -export interface ControlUiSessionView { - readonly identity: string; - readonly accountId: string; - readonly expiresAt: string; -} - -export interface ControlUiCredentials { - email: string; - secret: string; -} - -export type ControlUiSessionErrorCode = - | 'SESSION_REQUIRED' - | 'SESSION_EXPIRED' - | 'SESSION_REPLACED' - | 'AUTH_REJECTED' - | 'REQUEST_CANCELLED' - | 'REQUEST_FAILED' - | 'INVALID_RESPONSE'; - -export class ControlUiSessionError extends Error { - readonly code: ControlUiSessionErrorCode; - - constructor(code: ControlUiSessionErrorCode) { - super('The account session is unavailable.'); - this.name = 'ControlUiSessionError'; - this.code = code; - } -} - -export interface ControlUiSessionOptions { - origin: () => string; - fetchImpl?: typeof fetch; - now?: () => number; - idFactory?: () => string; - clearQueryCache?: () => void; -} - -const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; -const jwt = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/; -const ownerPath = - /^\/api\/account\/billing\/hosting\/subscriptions\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/first-invoice(?:\/(reauthenticate|confirm|renew))?$/i; -const maxOwnerRequestBytes = 16 * 1024; -const maxOwnerResponseBytes = 64 * 1024; -const loginRecoveryWindowMs = 60_000; - -type LoginRecovery = Pick< - AccountControlUiLoginRequest, - 'requestId' | 'callerContextId' | 'email' -> & { expiresAt: number }; - -function secureOrigin(value: string): URL { - let parsed: URL; - try { - parsed = new URL(value); - } catch { - throw new ControlUiSessionError('REQUEST_FAILED'); - } - if ( - parsed.protocol !== 'https:' || - parsed.username || - parsed.password || - parsed.pathname !== '/' || - parsed.search || - parsed.hash - ) { - throw new ControlUiSessionError('REQUEST_FAILED'); - } - return parsed; -} - -function checkedLoginResult( - result: AccountControlUiLoginResult, - now: number -): number { - if ( - typeof result.accountId !== 'string' || - !uuid.test(result.accountId) || - typeof result.authToken !== 'string' || - result.authToken.length > 16_384 || - !jwt.test(result.authToken) || - typeof result.expiresAt !== 'string' - ) { - throw new ControlUiSessionError('INVALID_RESPONSE'); - } - const expiry = Date.parse(result.expiresAt); - if ( - !Number.isFinite(expiry) || - expiry <= now || - expiry - now > maxControlUiSessionLifetimeMs - ) { - throw new ControlUiSessionError('INVALID_RESPONSE'); - } - return expiry; -} - -function makeUuid(): string { - if (!globalThis.crypto?.randomUUID) { - throw new ControlUiSessionError('REQUEST_FAILED'); - } - return globalThis.crypto.randomUUID(); -} - -async function readBoundedBytes( - response: Response, - signal: AbortSignal -): Promise { - if (!response.body) return new Uint8Array(); - const reader = response.body.getReader(); - const discard = () => { - void reader.cancel().catch(() => {}); - }; - signal.addEventListener('abort', discard, { once: true }); - const chunks: Uint8Array[] = []; - let size = 0; - try { - for (;;) { - if (signal.aborted) throw new ControlUiSessionError('REQUEST_CANCELLED'); - const { done, value } = await reader.read(); - if (signal.aborted) throw new ControlUiSessionError('REQUEST_CANCELLED'); - if (done) break; - size += value.byteLength; - if (size > maxOwnerResponseBytes) { - discard(); - throw new ControlUiSessionError('REQUEST_FAILED'); - } - chunks.push(value); - } - } catch { - discard(); - throw new ControlUiSessionError('REQUEST_FAILED'); - } finally { - signal.removeEventListener('abort', discard); - reader.releaseLock(); - } - const bytes = new Uint8Array(size); - let offset = 0; - for (const chunk of chunks) { - bytes.set(chunk, offset); - offset += chunk.byteLength; - } - return bytes; -} - -function discardResponse(response: Response): void { - void response.body?.cancel().catch(() => {}); -} - -function validateOwnerRequest( - url: URL, - init: RequestInit, - origin: URL -): string { - if ( - url.protocol !== 'https:' || - url.origin !== origin.origin || - url.username || - url.password || - url.search || - url.hash - ) { - throw new ControlUiSessionError('REQUEST_FAILED'); - } - const match = ownerPath.exec(url.pathname); - if (!match) throw new ControlUiSessionError('REQUEST_FAILED'); - const expectedMethod = match[2] ? 'POST' : 'GET'; - const method = (init.method ?? 'GET').toUpperCase(); - if (method !== expectedMethod) - throw new ControlUiSessionError('REQUEST_FAILED'); - if (method === 'GET' && init.body != null) { - throw new ControlUiSessionError('REQUEST_FAILED'); - } - if ( - method === 'POST' && - (typeof init.body !== 'string' || init.body.length > maxOwnerRequestBytes) - ) { - throw new ControlUiSessionError('REQUEST_FAILED'); - } - - let headers: Headers; - try { - headers = new Headers(init.headers); - } catch { - throw new ControlUiSessionError('REQUEST_FAILED'); - } - if (headers.has('authorization')) { - throw new ControlUiSessionError('REQUEST_FAILED'); - } - for (const [name, value] of headers.entries()) { - if ( - name.toLowerCase() !== 'accept' && - name.toLowerCase() !== 'content-type' - ) { - throw new ControlUiSessionError('REQUEST_FAILED'); - } - if ( - name.toLowerCase() === 'content-type' && - value.toLowerCase() !== 'application/json' - ) { - throw new ControlUiSessionError('REQUEST_FAILED'); - } - } - if (method === 'POST' && headers.get('content-type') !== 'application/json') { - throw new ControlUiSessionError('REQUEST_FAILED'); - } - return method; -} - -function guardedJsonResponse( - status: number, - bytes: Uint8Array, - assertCurrent: () => void, - contentType: string -): Response { - const body = new ArrayBuffer(bytes.byteLength); - new Uint8Array(body).set(bytes); - const response = new Response(body, { - status, - headers: { - 'Content-Type': contentType, - 'Cache-Control': 'no-store', - }, - }); - const json = response.json.bind(response); - Object.defineProperty(response, 'json', { - configurable: false, - value: async () => { - assertCurrent(); - const value = await json(); - assertCurrent(); - return value; - }, - }); - return response; -} - -/** - * Memory-only owner for the current Account control-ui token. It is intentionally - * narrower than a general API client: only the exact first-invoice owner paths - * can receive the bearer, and local sign-out makes no server revocation claim. - */ -export class ControlUiSessionStore { - private readonly listeners = new Set<() => void>(); - private readonly requests = new Set(); - private readonly origin: () => string; - private readonly fetchImpl: typeof fetch; - private readonly now: () => number; - private readonly idFactory: () => string; - private readonly clearQueryCache?: () => void; - private snapshot: ControlUiSessionView | null = null; - private bearer: string | null = null; - private revision = 0; - private loginController: AbortController | null = null; - private loginRecovery: LoginRecovery | null = null; - private loginRecoveryTimer: ReturnType | null = null; - private expiryTimer: ReturnType | null = null; - - constructor(options: ControlUiSessionOptions) { - this.origin = options.origin; - this.fetchImpl = options.fetchImpl ?? fetch; - this.now = options.now ?? Date.now; - this.idFactory = options.idFactory ?? makeUuid; - this.clearQueryCache = options.clearQueryCache; - } - - readonly getSession = (): ControlUiSessionView | null => { - if (this.snapshot && this.now() >= Date.parse(this.snapshot.expiresAt)) { - return null; - } - return this.snapshot; - }; - - readonly getGatewayOrigin = (): string => secureOrigin(this.origin()).origin; - - readonly subscribe = (listener: () => void): (() => void) => { - this.listeners.add(listener); - return () => this.listeners.delete(listener); - }; - - readonly authenticatedRequest = async ( - input: URL, - init: RequestInit - ): Promise => { - let target: URL; - let origin: URL; - let method: string; - try { - origin = secureOrigin(this.origin()); - target = new URL(input.href); - method = validateOwnerRequest(target, init, origin); - } catch (error) { - if (error instanceof ControlUiSessionError) throw error; - throw new ControlUiSessionError('REQUEST_FAILED'); - } - - const session = this.requireCurrentSession(); - const revision = this.revision; - const bearer = this.bearer; - if (!bearer) throw new ControlUiSessionError('SESSION_REQUIRED'); - - const controller = new AbortController(); - const externalSignal = init.signal; - let deadlineExpired = false; - const cancelFromCaller = () => controller.abort(); - if (externalSignal?.aborted) controller.abort(); - else - externalSignal?.addEventListener('abort', cancelFromCaller, { - once: true, - }); - this.requests.add(controller); - - const isCurrent = () => - this.revision === revision && - this.snapshot?.identity === session.identity && - this.bearer === bearer && - this.now() < Date.parse(session.expiresAt); - const assertCurrent = () => { - if ( - this.revision === revision && - this.snapshot?.identity === session.identity && - this.bearer === bearer && - this.now() >= Date.parse(session.expiresAt) - ) { - this.clearIfCurrent(session.identity, revision); - throw new ControlUiSessionError('SESSION_EXPIRED'); - } - if (!isCurrent()) throw new ControlUiSessionError('SESSION_REPLACED'); - }; - - const deadline = performance.now() + accountControlUiLoginTimeoutMs; - const deadlineTimer = setTimeout(() => { - deadlineExpired = true; - controller.abort(); - }, accountControlUiLoginTimeoutMs); - const assertWithinDeadline = () => { - if (performance.now() >= deadline) { - deadlineExpired = true; - controller.abort(); - } - if (controller.signal.aborted) { - assertCurrent(); - throw new ControlUiSessionError( - deadlineExpired ? 'REQUEST_FAILED' : 'REQUEST_CANCELLED' - ); - } - }; - try { - assertCurrent(); - assertWithinDeadline(); - - const interrupted = new Promise((_, reject) => { - controller.signal.addEventListener( - 'abort', - () => { - try { - assertWithinDeadline(); - } catch (error) { - reject(error); - } - }, - { once: true } - ); - }); - - const headers = new Headers(init.headers); - headers.set('Authorization', `Bearer ${bearer}`); - const receive = async (): Promise => { - let response: Response; - try { - response = await this.fetchImpl(target, { - method, - headers, - ...(init.body !== undefined ? { body: init.body } : {}), - cache: 'no-store', - credentials: 'omit', - redirect: 'error', - referrerPolicy: 'no-referrer', - mode: 'same-origin', - signal: controller.signal, - }); - } catch { - assertCurrent(); - assertWithinDeadline(); - throw new ControlUiSessionError('REQUEST_FAILED'); - } - - try { - assertCurrent(); - assertWithinDeadline(); - } catch (error) { - discardResponse(response); - throw error; - } - if (response.status === 401 || response.status === 403) { - discardResponse(response); - this.requests.delete(controller); - this.clearIfCurrent(session.identity, revision); - throw new ControlUiSessionError('AUTH_REJECTED'); - } - if (!response.ok) { - discardResponse(response); - return new Response(null, { - status: response.status, - headers: { 'Cache-Control': 'no-store' }, - }); - } - if (response.status !== 200) { - discardResponse(response); - throw new ControlUiSessionError('REQUEST_FAILED'); - } - - const bytes = await readBoundedBytes(response, controller.signal); - assertCurrent(); - assertWithinDeadline(); - return guardedJsonResponse( - response.status, - bytes, - assertCurrent, - response.headers.get('content-type') ?? 'application/json' - ); - }; - - return await Promise.race([interrupted, receive()]); - } finally { - clearTimeout(deadlineTimer); - externalSignal?.removeEventListener('abort', cancelFromCaller); - this.requests.delete(controller); - } - }; - - async signIn( - api: AccountControlUiApi, - credentials: ControlUiCredentials - ): Promise { - const retry = this.canRetrySignIn(credentials.email) - ? this.loginRecovery - : null; - // Account starts its recovery window at issuance, which follows the initial submission. - const expiresAt = retry?.expiresAt ?? this.now() + loginRecoveryWindowMs; - const hadSession = this.snapshot !== null || this.bearer !== null; - const revision = this.beginReplacement(); - if (hadSession) this.emitSessionChange(); - const controller = new AbortController(); - this.loginController = controller; - const request: AccountControlUiLoginRequest = { - requestId: retry?.requestId ?? this.idFactory(), - callerContextId: retry?.callerContextId ?? this.idFactory(), - email: credentials.email, - secret: credentials.secret, - }; - - try { - const result = await api.login(request, controller.signal); - if ( - controller.signal.aborted || - this.revision !== revision || - this.loginController !== controller - ) { - throw new ControlUiSessionError('SESSION_REPLACED'); - } - - const expiry = checkedLoginResult(result, this.now()); - const identity = this.idFactory(); - if (!uuid.test(identity)) - throw new ControlUiSessionError('INVALID_RESPONSE'); - const next: ControlUiSessionView = Object.freeze({ - identity, - accountId: result.accountId, - expiresAt: result.expiresAt, - }); - this.snapshot = next; - this.bearer = result.authToken; - this.scheduleExpiry(next.identity, revision, expiry); - this.loginController = null; - this.emitSessionChange(); - return next; - } catch (error) { - if ( - controller.signal.aborted || - this.revision !== revision || - this.loginController !== controller - ) { - throw new ControlUiSessionError('SESSION_REPLACED'); - } - this.loginController = null; - if ( - this.now() < expiresAt && - (!(error instanceof AccountControlUiApiError) || - error.uncertain || - (error.status === 429 && retry !== null)) - ) { - this.loginRecovery = { - requestId: request.requestId, - callerContextId: request.callerContextId, - email: request.email, - expiresAt, - }; - this.loginRecoveryTimer = setTimeout( - () => this.clearLoginRecovery(), - Math.max(0, expiresAt - this.now()) - ); - } - throw error; - } finally { - request.secret = ''; - } - } - - canRetrySignIn(email: string): boolean { - return ( - this.loginRecovery !== null && - this.loginRecovery.email === email && - this.now() < this.loginRecovery.expiresAt - ); - } - - discardLoginRecoveryIfEmailChanged(email: string): void { - if (this.loginRecovery && this.loginRecovery.email !== email) { - this.clearLoginRecovery(); - } - } - - /** Clear only this browser's in-memory credentials; no remote logout is sent. */ - signOut(): void { - const hadSession = this.snapshot !== null || this.bearer !== null; - this.beginReplacement(); - if (hadSession) this.emitSessionChange(); - } - - private requireCurrentSession(): ControlUiSessionView { - if (this.snapshot && this.now() >= Date.parse(this.snapshot.expiresAt)) { - const { identity } = this.snapshot; - this.clearIfCurrent(identity, this.revision); - throw new ControlUiSessionError('SESSION_EXPIRED'); - } - if (!this.snapshot || !this.bearer) { - throw new ControlUiSessionError('SESSION_REQUIRED'); - } - return this.snapshot; - } - - private beginReplacement(): number { - this.revision += 1; - this.loginController?.abort(); - this.loginController = null; - this.clearLoginRecovery(); - this.abortRequests(); - this.clearExpiryTimer(); - this.snapshot = null; - this.bearer = null; - return this.revision; - } - - private clearLoginRecovery(): void { - if (this.loginRecoveryTimer !== null) clearTimeout(this.loginRecoveryTimer); - this.loginRecoveryTimer = null; - this.loginRecovery = null; - } - - private expireIfCurrent(identity: string, revision: number): void { - if (this.revision !== revision || this.snapshot?.identity !== identity) { - return; - } - const expiry = Date.parse(this.snapshot.expiresAt); - if (this.now() >= expiry) this.clearIfCurrent(identity, revision); - else this.scheduleExpiry(identity, revision, expiry); - } - - private clearIfCurrent(identity: string, revision: number): void { - if (this.revision !== revision || this.snapshot?.identity !== identity) { - return; - } - this.beginReplacement(); - this.emitSessionChange(); - } - - private scheduleExpiry( - identity: string, - revision: number, - expiry: number - ): void { - this.clearExpiryTimer(); - this.expiryTimer = setTimeout( - () => { - this.expiryTimer = null; - this.expireIfCurrent(identity, revision); - }, - Math.max(0, expiry - this.now()) - ); - } - - private clearExpiryTimer(): void { - if (this.expiryTimer !== null) clearTimeout(this.expiryTimer); - this.expiryTimer = null; - } - - private abortRequests(): void { - for (const controller of this.requests) controller.abort(); - this.requests.clear(); - } - - private emitSessionChange(): void { - try { - this.clearQueryCache?.(); - } catch { - // Cache clearing must not restore or retain the invalidated token. - } - for (const listener of this.listeners) listener(); - } -} - -export function createControlUiSessionStore( - options: ControlUiSessionOptions -): ControlUiSessionStore { - return new ControlUiSessionStore(options); -} diff --git a/web-client/src/api/accountControlUi.test.ts b/web-client/src/api/accountControlUi.test.ts deleted file mode 100644 index 20236ad1b3..0000000000 --- a/web-client/src/api/accountControlUi.test.ts +++ /dev/null @@ -1,264 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { - AccountControlUiApiError, - accountControlUiLoginTimeoutMs, - createAccountControlUiApi, - maxControlUiSessionLifetimeMs, - type AccountControlUiLoginRequest, -} from './accountControlUi'; - -const origin = 'https://gateway.example.test'; -const accountId = '11111111-1111-4111-8111-111111111111'; -const requestId = '22222222-2222-4222-8222-222222222222'; -const callerContextId = '33333333-3333-4333-8333-333333333333'; -const now = Date.parse('2026-11-07T12:00:00.000Z'); -const authToken = 'header.payload.signature'; - -afterEach(() => { - vi.useRealTimers(); -}); - -function successfulLogin(expiresAt = new Date(now + 60_000).toISOString()) { - return new Response( - JSON.stringify({ - status: 'SUCCESS', - data: { accountId, authToken, expiresAt }, - }), - { status: 200, headers: { 'Content-Type': 'application/json' } } - ); -} - -const loginRequest: AccountControlUiLoginRequest = { - requestId, - callerContextId, - email: 'owner@example.com', - secret: 'primary-secret', -}; - -const invalidResponses: Array<[string, () => unknown]> = [ - [ - 'extra response field', - () => ({ - status: 'SUCCESS', - data: { - accountId, - authToken, - expiresAt: new Date(now + 60_000).toISOString(), - }, - debug: 'unexpected', - }), - ], - [ - 'wrong status', - () => ({ - status: 'FAILED', - data: { - accountId, - authToken, - expiresAt: new Date(now + 60_000).toISOString(), - }, - }), - ], - [ - 'non-JWT bearer', - () => ({ - status: 'SUCCESS', - data: { - accountId, - authToken: 'not-a-jwt', - expiresAt: new Date(now + 60_000).toISOString(), - }, - }), - ], - [ - 'expired session', - () => ({ - status: 'SUCCESS', - data: { - accountId, - authToken, - expiresAt: new Date(now - 1).toISOString(), - }, - }), - ], - [ - 'unbounded session lifetime', - () => ({ - status: 'SUCCESS', - data: { - accountId, - authToken, - expiresAt: new Date( - now + maxControlUiSessionLifetimeMs + 1 - ).toISOString(), - }, - }), - ], -]; - -describe('account control-ui login transport', () => { - it('posts one stable request to the same-origin HTTPS Account route without cookies', async () => { - const fetchImpl = vi - .fn() - .mockResolvedValue(successfulLogin()); - const api = createAccountControlUiApi(origin, fetchImpl, () => now); - - await expect(api.login(loginRequest)).resolves.toEqual({ - accountId, - authToken, - expiresAt: new Date(now + 60_000).toISOString(), - }); - - expect(fetchImpl).toHaveBeenCalledOnce(); - const [input, init] = fetchImpl.mock.calls[0]; - expect(input).toEqual(new URL('/api/account/auth/login', origin)); - expect(init).toMatchObject({ - method: 'POST', - cache: 'no-store', - credentials: 'omit', - redirect: 'error', - referrerPolicy: 'no-referrer', - mode: 'same-origin', - }); - expect(JSON.parse(String(init?.body))).toEqual(loginRequest); - expect(init?.headers).toEqual({ - 'Content-Type': 'application/json', - Accept: 'application/json', - }); - }); - - it('does not retry a transport failure or expose secret or server text', async () => { - const fetchImpl = vi - .fn() - .mockRejectedValue(new Error('primary-secret leaked by transport')); - const api = createAccountControlUiApi(origin, fetchImpl, () => now); - - let error: unknown; - try { - await api.login(loginRequest); - } catch (caught) { - error = caught; - } - expect(fetchImpl).toHaveBeenCalledOnce(); - expect(error).toBeInstanceOf(AccountControlUiApiError); - expect(error).toMatchObject({ status: 0 }); - expect((error as Error).message).not.toContain('primary-secret'); - }); - - it('times out stalled fetch and discards a late successful response', async () => { - vi.useFakeTimers(); - let resolveFetch!: (response: Response) => void; - const fetchImpl = vi.fn().mockImplementation( - () => - new Promise((resolve) => { - resolveFetch = resolve; - }) - ); - const api = createAccountControlUiApi(origin, fetchImpl, () => now); - const failure = expect(api.login(loginRequest)).rejects.toMatchObject({ - status: 0, - uncertain: true, - }); - - await vi.advanceTimersByTimeAsync(accountControlUiLoginTimeoutMs); - await failure; - expect(fetchImpl.mock.calls[0][1]?.signal?.aborted).toBe(true); - const late = successfulLogin(); - const cancel = vi.spyOn(late.body!, 'cancel'); - resolveFetch(late); - await Promise.resolve(); - expect(cancel).toHaveBeenCalledOnce(); - expect(fetchImpl).toHaveBeenCalledOnce(); - }); - - it.each(['deadline', 'caller abort'])( - 'abandons a stalled response body on %s even if cancellation stalls', - async (interruption) => { - vi.useFakeTimers(); - const stalled = new Promise(() => {}); - const cancel = vi.fn(() => stalled); - const response = new Response( - new ReadableStream({ - start(controller) { - controller.enqueue(new TextEncoder().encode('{"status":"SUCCESS"')); - }, - cancel, - }), - { status: 200 } - ); - const fetchImpl = vi.fn().mockResolvedValue(response); - const api = createAccountControlUiApi(origin, fetchImpl, () => now); - const caller = new AbortController(); - const failure = expect( - api.login(loginRequest, caller.signal) - ).rejects.toMatchObject({ status: 0, uncertain: true }); - await vi.advanceTimersByTimeAsync(0); - expect(response.body?.locked).toBe(true); - - if (interruption === 'deadline') { - await vi.advanceTimersByTimeAsync(accountControlUiLoginTimeoutMs); - } else { - caller.abort(); - } - await failure; - expect(fetchImpl.mock.calls[0][1]?.signal?.aborted).toBe(true); - expect(cancel).toHaveBeenCalledOnce(); - } - ); - - it('discards non-success response bodies and preserves only the status', async () => { - const fetchImpl = vi - .fn() - .mockResolvedValue( - new Response('sensitive internal response', { status: 503 }) - ); - const api = createAccountControlUiApi(origin, fetchImpl, () => now); - - await expect(api.login(loginRequest)).rejects.toMatchObject({ - name: 'AccountControlUiApiError', - status: 503, - message: 'Account sign-in could not be completed.', - }); - expect(fetchImpl).toHaveBeenCalledOnce(); - }); - - it.each(invalidResponses)( - 'rejects %s response data', - async (_name, makeBody) => { - const fetchImpl = vi - .fn() - .mockResolvedValue( - new Response(JSON.stringify(makeBody()), { status: 200 }) - ); - const api = createAccountControlUiApi(origin, fetchImpl, () => now); - await expect(api.login(loginRequest)).rejects.toBeInstanceOf( - AccountControlUiApiError - ); - } - ); - - it('rejects insecure origins before dispatch', async () => { - const fetchImpl = vi.fn(); - expect(() => - createAccountControlUiApi('http://gateway.example.test', fetchImpl) - ).toThrow('same-origin HTTPS'); - const api = createAccountControlUiApi( - () => 'http://gateway.example.test', - fetchImpl - ); - await expect(api.login(loginRequest)).rejects.toBeInstanceOf(Error); - expect(fetchImpl).not.toHaveBeenCalled(); - }); - - it('rejects oversized response bodies', async () => { - const oversized = (await successfulLogin().text()) + ' '.repeat(40 * 1024); - const fetchImpl = vi - .fn() - .mockResolvedValue(new Response(oversized, { status: 200 })); - const api = createAccountControlUiApi(origin, fetchImpl, () => now); - - await expect(api.login(loginRequest)).rejects.toBeInstanceOf( - AccountControlUiApiError - ); - }); -}); diff --git a/web-client/src/api/accountControlUi.ts b/web-client/src/api/accountControlUi.ts deleted file mode 100644 index 83dceb8242..0000000000 --- a/web-client/src/api/accountControlUi.ts +++ /dev/null @@ -1,257 +0,0 @@ -export interface AccountControlUiLoginRequest { - requestId: string; - callerContextId: string; - email: string; - secret: string; -} - -export interface AccountControlUiLoginResult { - accountId: string; - authToken: string; - expiresAt: string; -} - -export interface AccountControlUiApi { - login( - request: AccountControlUiLoginRequest, - signal?: AbortSignal - ): Promise; -} - -export class AccountControlUiApiError extends Error { - readonly status: number; - readonly uncertain: boolean; - - constructor( - status: number, - uncertain = status < 400 || status === 408 || status >= 500 - ) { - super('Account sign-in could not be completed.'); - this.name = 'AccountControlUiApiError'; - this.status = status; - this.uncertain = uncertain; - } -} - -const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; -const jwt = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/; -const timestamp = - /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/; -const maxLoginResponseBytes = 32 * 1024; -export const accountControlUiLoginTimeoutMs = 10_000; -export const maxControlUiSessionLifetimeMs = 24 * 60 * 60 * 1000; - -function requireSecureOrigin(value: string): URL { - let origin: URL; - try { - origin = new URL(value); - } catch { - throw new Error('A same-origin HTTPS Gateway URL is required.'); - } - if ( - origin.protocol !== 'https:' || - origin.username || - origin.password || - origin.pathname !== '/' || - origin.search || - origin.hash - ) { - throw new Error('A same-origin HTTPS Gateway URL is required.'); - } - return origin; -} - -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value); -} - -function hasExactKeys(value: Record, keys: string[]): boolean { - const actual = Object.keys(value).sort(); - const expected = [...keys].sort(); - return ( - actual.length === expected.length && - actual.every((key, index) => key === expected[index]) - ); -} - -async function readBoundedJson( - response: Response, - signal: AbortSignal -): Promise { - if (!response.body) throw new AccountControlUiApiError(0); - const reader = response.body.getReader(); - const discard = () => void reader.cancel().catch(() => {}); - signal.addEventListener('abort', discard, { once: true }); - const chunks: Uint8Array[] = []; - let size = 0; - try { - for (;;) { - if (signal.aborted) throw new AccountControlUiApiError(0); - const { done, value } = await reader.read(); - if (signal.aborted) throw new AccountControlUiApiError(0); - if (done) break; - size += value.byteLength; - if (size > maxLoginResponseBytes) throw new AccountControlUiApiError(0); - chunks.push(value); - } - } catch { - discard(); - throw new AccountControlUiApiError(0); - } finally { - signal.removeEventListener('abort', discard); - reader.releaseLock(); - } - - const bytes = new Uint8Array(size); - let offset = 0; - for (const chunk of chunks) { - bytes.set(chunk, offset); - offset += chunk.byteLength; - } - - try { - const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes); - return JSON.parse(text) as unknown; - } catch { - throw new AccountControlUiApiError(0); - } -} - -function parseLoginResult( - value: unknown, - now: number -): AccountControlUiLoginResult { - if ( - !isRecord(value) || - !hasExactKeys(value, ['status', 'data']) || - value.status !== 'SUCCESS' || - !isRecord(value.data) || - !hasExactKeys(value.data, ['accountId', 'authToken', 'expiresAt']) - ) { - throw new AccountControlUiApiError(0); - } - - const { accountId, authToken, expiresAt } = value.data; - if ( - typeof accountId !== 'string' || - !uuid.test(accountId) || - typeof authToken !== 'string' || - authToken.length > 16_384 || - !jwt.test(authToken) || - typeof expiresAt !== 'string' || - !timestamp.test(expiresAt) - ) { - throw new AccountControlUiApiError(0); - } - - const expiry = Date.parse(expiresAt); - if ( - !Number.isFinite(expiry) || - expiry <= now || - expiry - now > maxControlUiSessionLifetimeMs - ) { - throw new AccountControlUiApiError(0); - } - - return { accountId, authToken, expiresAt }; -} - -/** - * Builds the only login transport used by the account checkout route. The - * caller supplies the browser's current origin, never an API URL from a form. - */ -export function createAccountControlUiApi( - origin: string | (() => string), - fetchImpl: typeof fetch = fetch, - now: () => number = Date.now -): AccountControlUiApi { - if (typeof origin === 'string') requireSecureOrigin(origin); - - function currentOrigin(): URL { - return requireSecureOrigin( - typeof origin === 'function' ? origin() : origin - ); - } - - return { - async login(request, signal) { - let url: URL; - try { - url = new URL('/api/account/auth/login', currentOrigin()); - } catch { - throw new AccountControlUiApiError(0, false); - } - if ( - !uuid.test(request.requestId) || - !uuid.test(request.callerContextId) || - typeof request.email !== 'string' || - request.email.length < 3 || - request.email.length > 254 || - request.email.trim() !== request.email || - typeof request.secret !== 'string' || - request.secret.length < 1 || - request.secret.length > 1024 - ) { - throw new AccountControlUiApiError(0, false); - } - if (signal?.aborted) throw new AccountControlUiApiError(0, false); - - const controller = new AbortController(); - const abort = () => controller.abort(); - const deadline = performance.now() + accountControlUiLoginTimeoutMs; - const timer = setTimeout(abort, accountControlUiLoginTimeoutMs); - signal?.addEventListener('abort', abort, { once: true }); - const interrupted = new Promise((_, reject) => { - controller.signal.addEventListener( - 'abort', - () => reject(new AccountControlUiApiError(0)), - { once: true } - ); - }); - const assertWithinDeadline = () => { - if (performance.now() >= deadline) abort(); - if (controller.signal.aborted) throw new AccountControlUiApiError(0); - }; - - async function receive(): Promise { - const response = await fetchImpl(url, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Accept: 'application/json', - }, - body: JSON.stringify(request), - cache: 'no-store', - credentials: 'omit', - redirect: 'error', - referrerPolicy: 'no-referrer', - mode: 'same-origin', - signal: controller.signal, - }); - try { - assertWithinDeadline(); - if (response.status !== 200) { - throw new AccountControlUiApiError(response.status); - } - } catch (error) { - // Discard rejected and late responses without waiting for stream cancellation. - void response.body?.cancel().catch(() => {}); - throw error; - } - const body = await readBoundedJson(response, controller.signal); - assertWithinDeadline(); - return parseLoginResult(body, now()); - } - - try { - return await Promise.race([interrupted, receive()]); - } catch (error) { - if (error instanceof AccountControlUiApiError) throw error; - throw new AccountControlUiApiError(0); - } finally { - clearTimeout(timer); - signal?.removeEventListener('abort', abort); - } - }, - }; -} diff --git a/web-client/src/api/hostingFirstInvoice.test.ts b/web-client/src/api/hostingFirstInvoice.test.ts deleted file mode 100644 index f94a8947f0..0000000000 --- a/web-client/src/api/hostingFirstInvoice.test.ts +++ /dev/null @@ -1,313 +0,0 @@ -import { describe, expect, it, vi } from 'vitest'; -import { - createFirstInvoiceClient, - FirstInvoiceError, - formatFirstInvoiceAmount, - sameCharge, - type FirstInvoice, -} from './hostingFirstInvoice'; - -const subscriptionId = '11111111-1111-4111-8111-111111111111'; -const invoice: FirstInvoice = { - subscriptionId, - invoiceId: 'in_existing', - paymentIntentId: 'pi_existing', - paymentInstrumentId: '22222222-2222-4222-8222-222222222222', - amount: '1299', - currency: 'usd', - tupleDigest: `sha256:${'a'.repeat(64)}`, - expectedRowVersion: 3, - state: 'AWAITING_PAYMENT', - expiresAt: '2099-01-01T00:00:00Z', - confirmationRequestId: null, - preRowOriginalRequestId: null, - authorizationVersion: 0, -}; - -describe('first-invoice owner API', () => { - it('renews only the original operation with a separately fenced authorization body', async () => { - const authenticated = vi.fn().mockResolvedValue( - Response.json({ - status: 'AUTHORIZED_NOT_CONFIRMED', - clientSecret: null, - }) - ); - const client = createFirstInvoiceClient( - 'https://game.example', - authenticated - ); - const renewal = { - requestId: '44444444-4444-4444-8444-444444444444', - authorizationRequestId: '55555555-5555-4555-8555-555555555555', - expectedAuthorizationVersion: 1, - expectedRowVersion: 3, - reauthenticationEvidenceId: '33333333-3333-4333-8333-333333333333', - acceptedTupleDigest: invoice.tupleDigest, - acceptCharge: true as const, - }; - expect( - await client.renew(subscriptionId, invoice.paymentIntentId, renewal) - ).toEqual({ status: 'AUTHORIZED_NOT_CONFIRMED', clientSecret: null }); - expect(authenticated.mock.calls[0][0].pathname).toBe( - `/api/account/billing/hosting/subscriptions/${subscriptionId}/first-invoice/renew` - ); - expect(JSON.parse(authenticated.mock.calls[0][1].body)).toEqual(renewal); - }); - it('uses the authenticated injection, exact Gateway route, and no-store HTTPS without URL credentials', async () => { - const authenticated = vi.fn().mockResolvedValue(Response.json(invoice)); - const client = createFirstInvoiceClient( - 'https://game.example', - authenticated - ); - expect(await client.read(subscriptionId)).toEqual(invoice); - const [url, init] = authenticated.mock.calls[0]; - expect(url.href).toBe( - `https://game.example/api/account/billing/hosting/subscriptions/${subscriptionId}/first-invoice` - ); - expect(url.search).toBe(''); - expect(init).toMatchObject({ - method: 'GET', - cache: 'no-store', - credentials: 'omit', - redirect: 'error', - referrerPolicy: 'no-referrer', - }); - expect(init.headers).not.toHaveProperty('Authorization'); - }); - - it.each([ - 'http://game.example', - 'https://token@game.example', - 'https://game.example/?token=x', - 'https://game.example/#x', - 'https://game.example/path', - ])('refuses an unsafe Gateway origin %s', (origin) => { - expect(() => createFirstInvoiceClient(origin, vi.fn())).toThrow( - 'HTTPS Gateway origin' - ); - }); - - it('sends billing reauth and consent in bodies only, preserving exact request identity', async () => { - const evidenceId = '33333333-3333-4333-8333-333333333333'; - const authenticated = vi - .fn() - .mockResolvedValueOnce(Response.json({ evidenceId })) - .mockResolvedValueOnce( - Response.json({ - status: 'requires_action', - clientSecret: 'pi_existing_secret_ephemeral', - }) - ); - const client = createFirstInvoiceClient( - 'https://game.example', - authenticated - ); - const reauth = { - requestId: '44444444-4444-4444-8444-444444444444', - confirmationRequestId: '55555555-5555-4555-8555-555555555555', - billingBinding: { - originalRequestId: '55555555-5555-4555-8555-555555555555', - expectedRowVersion: invoice.expectedRowVersion, - expectedAuthorizationVersion: 0, - acceptedTupleDigest: invoice.tupleDigest, - invoiceExpiresAt: invoice.expiresAt, - authorizationPurpose: 'INITIAL_CONFIRMATION' as const, - }, - email: 'owner@example.com', - secret: 'primary-secret', - }; - expect(await client.reauthenticate(subscriptionId, reauth)).toEqual({ - evidenceId, - }); - const consent = { - requestId: reauth.confirmationRequestId, - expectedRowVersion: 3, - reauthenticationEvidenceId: evidenceId, - acceptedTupleDigest: invoice.tupleDigest, - acceptCharge: true as const, - }; - await expect( - client.confirm(subscriptionId, 'pi_existing', consent) - ).resolves.toEqual({ - status: 'requires_action', - clientSecret: 'pi_existing_secret_ephemeral', - }); - expect(JSON.parse(authenticated.mock.calls[0][1].body)).toEqual(reauth); - expect(JSON.parse(authenticated.mock.calls[1][1].body)).toEqual(consent); - expect(authenticated.mock.calls.map(([url]) => url.search)).toEqual([ - '', - '', - ]); - }); - - it('does not expose provider error bodies or raw transport errors', async () => { - const response = new Response('pi_existing_secret_private', { - status: 500, - }); - const authenticated = vi - .fn() - .mockResolvedValueOnce(response) - .mockRejectedValueOnce(new Error('primary-secret')); - const client = createFirstInvoiceClient( - 'https://game.example', - authenticated - ); - await expect(client.read(subscriptionId)).rejects.toEqual( - new FirstInvoiceError(500) - ); - expect(response.bodyUsed).toBe(false); - await expect(client.read(subscriptionId)).rejects.toEqual( - new FirstInvoiceError(0) - ); - }); - - it('retains only known Account reauthentication error codes', async () => { - const authenticated = vi.fn().mockResolvedValue( - Response.json( - { - status: 'ERROR', - error: { - code: 'AUTH_INVALID_CREDENTIALS', - message: 'private credential detail', - }, - }, - { status: 401 } - ) - ); - const client = createFirstInvoiceClient( - 'https://game.example', - authenticated - ); - - await expect(client.read(subscriptionId)).rejects.toEqual( - new FirstInvoiceError(401, 'AUTH_INVALID_CREDENTIALS') - ); - }); - - it('refuses another intent secret, secret on non-action status, and unknown status', async () => { - const authenticated = vi.fn(); - const client = createFirstInvoiceClient( - 'https://game.example', - authenticated - ); - for (const handoff of [ - { status: 'requires_action', clientSecret: 'pi_other_secret_private' }, - { status: 'succeeded', clientSecret: 'pi_existing_secret_private' }, - { status: 'canceled', clientSecret: null }, - ]) { - authenticated.mockResolvedValueOnce(Response.json(handoff)); - await expect( - client.confirm(subscriptionId, 'pi_existing', { - requestId: subscriptionId, - expectedRowVersion: 3, - reauthenticationEvidenceId: subscriptionId, - acceptedTupleDigest: invoice.tupleDigest, - acceptCharge: true, - }) - ).rejects.toBeInstanceOf(FirstInvoiceError); - } - }); - - it('refuses malformed owner tuples and strips unexpected secret fields', async () => { - const authenticated = vi.fn(); - const client = createFirstInvoiceClient( - 'https://game.example', - authenticated - ); - for (const changes of [ - { subscriptionId: 'another' }, - { amount: 1299 }, - { amount: '12.99' }, - { expectedRowVersion: Number.MAX_SAFE_INTEGER + 1 }, - { state: 'PAID' }, - { currency: 'USD' }, - { confirmationRequestId: 'untrusted' }, - { preRowOriginalRequestId: undefined }, - { preRowOriginalRequestId: 'untrusted' }, - { preRowOriginalRequestId: subscriptionId, authorizationVersion: 1 }, - { - preRowOriginalRequestId: subscriptionId, - confirmationRequestId: subscriptionId, - }, - { preRowOriginalRequestId: subscriptionId, state: 'COMMITTED' }, - ]) { - authenticated.mockResolvedValueOnce( - Response.json({ ...invoice, ...changes }) - ); - await expect(client.read(subscriptionId)).rejects.toBeInstanceOf( - FirstInvoiceError - ); - } - authenticated.mockResolvedValueOnce( - Response.json({ ...invoice, clientSecret: 'private' }) - ); - expect(await client.read(subscriptionId)).not.toHaveProperty( - 'clientSecret' - ); - }); - - it('reads only the verified pre-row reference without restoring proof', async () => { - const authenticated = vi.fn().mockResolvedValue( - Response.json({ - ...invoice, - preRowOriginalRequestId: subscriptionId, - reauthenticationEvidenceId: 'private-proof', - }) - ); - const client = createFirstInvoiceClient( - 'https://game.example', - authenticated - ); - const result = await client.read(subscriptionId); - expect(result.preRowOriginalRequestId).toBe(subscriptionId); - expect(result.confirmationRequestId).toBeNull(); - expect(result).not.toHaveProperty('reauthenticationEvidenceId'); - }); - - it('accepts a canceled owner projection without retained payment authorization', async () => { - const authenticated = vi - .fn() - .mockResolvedValue(Response.json({ ...invoice, state: 'CANCELED' })); - const client = createFirstInvoiceClient( - 'https://game.example', - authenticated - ); - - await expect(client.read(subscriptionId)).resolves.toMatchObject({ - state: 'CANCELED', - confirmationRequestId: null, - preRowOriginalRequestId: null, - }); - }); - - it('compares all consent-bearing display fields and row version', () => { - expect(sameCharge(invoice, { ...invoice })).toBe(true); - for (const changes of [ - { amount: '1300' }, - { invoiceId: 'in_other' }, - { paymentIntentId: 'pi_other' }, - { paymentInstrumentId: subscriptionId }, - { currency: 'nzd' }, - { expectedRowVersion: 4 }, - { expiresAt: '2098-01-01T00:00:00Z' }, - { tupleDigest: `sha256:${'b'.repeat(64)}` }, - ]) { - expect(sameCharge(invoice, { ...invoice, ...changes })).toBe(false); - } - }); - - it.each([ - ['1299', 'usd', 'USD 12.99'], - ['1', 'nzd', 'NZD 0.01'], - ['1299', 'jpy', 'JPY 1299'], - ['1000', 'kwd', 'KWD 1.000'], - ['100', 'isk', 'ISK 1.00'], - ['100', 'ugx', 'UGX 1.00'], - ['9223372036854775807', 'usd', 'USD 92233720368547758.07'], - ])( - 'preserves exact minor-unit amount %s %s', - (amount, currency, expected) => { - expect(formatFirstInvoiceAmount(amount, currency)).toBe(expected); - } - ); -}); diff --git a/web-client/src/api/hostingFirstInvoice.ts b/web-client/src/api/hostingFirstInvoice.ts deleted file mode 100644 index 0f094c9d2b..0000000000 --- a/web-client/src/api/hostingFirstInvoice.ts +++ /dev/null @@ -1,340 +0,0 @@ -/** Account owns authorization, the exact charge tuple, and payment completion. */ -export interface FirstInvoice { - subscriptionId: string; - invoiceId: string; - paymentIntentId: string; - paymentInstrumentId: string; - /** Positive integer decimal string in Stripe minor units, never a JS number. */ - amount: string; - currency: string; - tupleDigest: string; - expectedRowVersion: number; - state: 'AWAITING_PAYMENT' | 'COMMITTED' | 'CANCELED'; - expiresAt: string; - confirmationRequestId: string | null; - /** Server-verified original identity only, never restored consent or proof. */ - preRowOriginalRequestId: string | null; - authorizationVersion: number; -} - -export interface BillingReauthentication { - requestId: string; - confirmationRequestId: string; - billingBinding: { - originalRequestId: string; - expectedRowVersion: number; - expectedAuthorizationVersion: number; - acceptedTupleDigest: string; - invoiceExpiresAt: string; - authorizationPurpose: - 'INITIAL_CONFIRMATION' | 'PRE_ROW_RENEWAL' | 'FOLLOWUP_RENEWAL'; - }; - email: string; - secret: string; -} - -export interface FirstInvoiceConsent { - requestId: string; - expectedRowVersion: number; - reauthenticationEvidenceId: string; - acceptedTupleDigest: string; - acceptCharge: true; -} - -export interface FirstInvoiceHandoff { - status: string; - clientSecret: string | null; -} - -export interface FirstInvoiceRenewal extends FirstInvoiceConsent { - authorizationRequestId: string; - expectedAuthorizationVersion: number; -} - -export interface FirstInvoiceClient { - read(subscriptionId: string, signal?: AbortSignal): Promise; - reauthenticate( - subscriptionId: string, - request: BillingReauthentication - ): Promise<{ evidenceId: string }>; - confirm( - subscriptionId: string, - paymentIntentId: string, - request: FirstInvoiceConsent - ): Promise; - renew( - subscriptionId: string, - paymentIntentId: string, - request: FirstInvoiceRenewal - ): Promise; -} - -/** - * Supply only the real control-ui session owner's request function. It must - * attach its current memory-only bearer, reject expiry/revocation, and never - * log or persist request/response bodies. A gameplay token is not authority. - * This module neither creates a session nor accepts a pasted bearer token. - */ -export type ControlUiAuthenticatedRequest = ( - url: URL, - init: RequestInit -) => Promise; - -export class FirstInvoiceError extends Error { - readonly status: number; - readonly code: 'AUTH_INVALID_CREDENTIALS' | 'INVALID_CREDENTIALS' | null; - - constructor( - status: number, - code: 'AUTH_INVALID_CREDENTIALS' | 'INVALID_CREDENTIALS' | null = null - ) { - super('Account could not confirm the checkout result.'); - this.name = 'FirstInvoiceError'; - this.status = status; - this.code = code; - } -} - -async function authenticationErrorCode( - response: Response -): Promise { - try { - const body = record(await response.clone().json()); - const error = record(body.error); - return error.code === 'AUTH_INVALID_CREDENTIALS' || - error.code === 'INVALID_CREDENTIALS' - ? error.code - : null; - } catch { - return null; - } -} - -const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; - -function requireUuid(value: string): void { - if (!uuid.test(value)) throw new FirstInvoiceError(0); -} - -function record(value: unknown): Record { - if (typeof value !== 'object' || value === null || Array.isArray(value)) { - throw new FirstInvoiceError(0); - } - return value as Record; -} - -function invoice(value: unknown, subscriptionId: string): FirstInvoice { - const data = record(value); - if ( - data.subscriptionId !== subscriptionId || - typeof data.invoiceId !== 'string' || - !/^in_[A-Za-z0-9]+$/.test(data.invoiceId) || - typeof data.paymentIntentId !== 'string' || - !/^pi_[A-Za-z0-9]+$/.test(data.paymentIntentId) || - typeof data.paymentInstrumentId !== 'string' || - !uuid.test(data.paymentInstrumentId) || - typeof data.amount !== 'string' || - !/^[1-9][0-9]*$/.test(data.amount) || - typeof data.currency !== 'string' || - !/^[a-z]{3}$/.test(data.currency) || - typeof data.tupleDigest !== 'string' || - !/^sha256:[a-f0-9]{64}$/.test(data.tupleDigest) || - !Number.isSafeInteger(data.expectedRowVersion) || - (data.expectedRowVersion as number) < 0 || - !Number.isSafeInteger(data.authorizationVersion) || - (data.authorizationVersion as number) < 0 || - (data.state !== 'AWAITING_PAYMENT' && - data.state !== 'COMMITTED' && - data.state !== 'CANCELED') || - typeof data.expiresAt !== 'string' || - !Number.isFinite(Date.parse(data.expiresAt)) || - (data.confirmationRequestId !== null && - (typeof data.confirmationRequestId !== 'string' || - !uuid.test(data.confirmationRequestId))) || - (data.preRowOriginalRequestId !== null && - (typeof data.preRowOriginalRequestId !== 'string' || - !uuid.test(data.preRowOriginalRequestId) || - data.confirmationRequestId !== null || - data.authorizationVersion !== 0 || - data.state !== 'AWAITING_PAYMENT')) - ) { - throw new FirstInvoiceError(0); - } - // Copy only the public owner projection, never an unexpected secret field. - return { - subscriptionId, - invoiceId: data.invoiceId, - paymentIntentId: data.paymentIntentId, - paymentInstrumentId: data.paymentInstrumentId, - amount: data.amount, - currency: data.currency, - tupleDigest: data.tupleDigest, - expectedRowVersion: data.expectedRowVersion as number, - state: data.state, - expiresAt: data.expiresAt, - confirmationRequestId: data.confirmationRequestId as string | null, - preRowOriginalRequestId: data.preRowOriginalRequestId as string | null, - authorizationVersion: data.authorizationVersion as number, - }; -} - -export function createFirstInvoiceClient( - gatewayOrigin: string, - authenticatedRequest: ControlUiAuthenticatedRequest -): FirstInvoiceClient { - const origin = new URL(gatewayOrigin); - if ( - origin.protocol !== 'https:' || - origin.username || - origin.password || - origin.pathname !== '/' || - origin.search || - origin.hash - ) { - throw new Error('An HTTPS Gateway origin is required.'); - } - - async function request( - subscriptionId: string, - suffix: string, - body?: BillingReauthentication | FirstInvoiceConsent | FirstInvoiceRenewal, - signal?: AbortSignal - ): Promise { - requireUuid(subscriptionId); - const url = new URL( - `/api/account/billing/hosting/subscriptions/${subscriptionId}/first-invoice${suffix}`, - origin - ); - let response: Response; - try { - response = await authenticatedRequest(url, { - method: body ? 'POST' : 'GET', - headers: { - 'Content-Type': 'application/json', - Accept: 'application/json', - }, - cache: 'no-store', - credentials: 'omit', - redirect: 'error', - referrerPolicy: 'no-referrer', - signal, - ...(body ? { body: JSON.stringify(body) } : {}), - }); - } catch { - throw new FirstInvoiceError(0); - } - if (!response.ok) { - // Retain only Account's two known reauthentication codes, never the error message/body. - const code = - response.status === 401 - ? await authenticationErrorCode(response) - : null; - throw new FirstInvoiceError(response.status, code); - } - try { - return await response.json(); - } catch { - throw new FirstInvoiceError(0); - } - } - - async function handoff( - subscriptionId: string, - paymentIntentId: string, - suffix: string, - body: FirstInvoiceConsent | FirstInvoiceRenewal - ): Promise { - const data = record(await request(subscriptionId, suffix, body)); - if ( - typeof data.status !== 'string' || - ![ - 'requires_action', - 'processing', - 'succeeded', - 'requires_confirmation', - 'requires_payment_method', - 'AUTHORIZED_NOT_CONFIRMED', - ].includes(data.status) || - (data.status === 'requires_action' - ? typeof data.clientSecret !== 'string' || - !data.clientSecret.startsWith(`${paymentIntentId}_secret_`) - : data.clientSecret !== null) - ) - throw new FirstInvoiceError(0); - return { - status: data.status, - clientSecret: data.clientSecret as string | null, - }; - } - - return { - read: async (subscriptionId, signal) => - invoice( - await request(subscriptionId, '', undefined, signal), - subscriptionId - ), - reauthenticate: async (subscriptionId, body) => { - const data = record( - await request(subscriptionId, '/reauthenticate', body) - ); - if (typeof data.evidenceId !== 'string' || !uuid.test(data.evidenceId)) { - throw new FirstInvoiceError(0); - } - return { evidenceId: data.evidenceId }; - }, - confirm: (subscriptionId, paymentIntentId, body) => - handoff(subscriptionId, paymentIntentId, '/confirm', body), - renew: (subscriptionId, paymentIntentId, body) => - handoff(subscriptionId, paymentIntentId, '/renew', body), - }; -} - -/** Comparison includes the displayed fields, not only the opaque owner digest. */ -export function sameCharge(a: FirstInvoice, b: FirstInvoice): boolean { - return ( - a.subscriptionId === b.subscriptionId && - a.invoiceId === b.invoiceId && - a.paymentIntentId === b.paymentIntentId && - a.paymentInstrumentId === b.paymentInstrumentId && - a.amount === b.amount && - a.currency === b.currency && - a.tupleDigest === b.tupleDigest && - a.expectedRowVersion === b.expectedRowVersion && - a.expiresAt === b.expiresAt - ); -} - -/** Stripe charge units, including ISK/UGX's two-decimal compatibility rule. */ -export function formatFirstInvoiceAmount( - amount: string, - currency: string -): string { - const zeroDecimal = new Set([ - 'bif', - 'clp', - 'djf', - 'gnf', - 'jpy', - 'kmf', - 'krw', - 'mga', - 'pyg', - 'rwf', - 'vnd', - 'vuv', - 'xaf', - 'xof', - 'xpf', - ]); - const threeDecimal = new Set(['bhd', 'jod', 'kwd', 'omr', 'tnd']); - const digits = zeroDecimal.has(currency) - ? 0 - : threeDecimal.has(currency) - ? 3 - : 2; - const padded = amount.padStart(digits + 1, '0'); - const quantity = digits - ? `${padded.slice(0, -digits)}.${padded.slice(-digits)}` - : padded; - return `${currency.toUpperCase()} ${quantity}`; -} diff --git a/web-client/src/billing/HostingFirstInvoiceCheckout.test.tsx b/web-client/src/billing/HostingFirstInvoiceCheckout.test.tsx deleted file mode 100644 index 0d19b291fb..0000000000 --- a/web-client/src/billing/HostingFirstInvoiceCheckout.test.tsx +++ /dev/null @@ -1,874 +0,0 @@ -// @vitest-environment jsdom -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { - act, - cleanup, - fireEvent, - render, - screen, - waitFor, -} from '@testing-library/react'; -import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; -import type { PaymentIntent } from '@stripe/stripe-js'; -import HostingFirstInvoiceCheckout from './HostingFirstInvoiceCheckout'; -import { - FirstInvoiceError, - type FirstInvoice, - type FirstInvoiceClient, -} from '../api/hostingFirstInvoice'; -import type { HostingStripe } from './hostingStripe'; - -const initial: FirstInvoice = { - subscriptionId: '11111111-1111-4111-8111-111111111111', - invoiceId: 'in_existing', - paymentIntentId: 'pi_existing', - paymentInstrumentId: '22222222-2222-4222-8222-222222222222', - amount: '1299', - currency: 'usd', - tupleDigest: `sha256:${'a'.repeat(64)}`, - expectedRowVersion: 3, - state: 'AWAITING_PAYMENT', - expiresAt: '2099-01-01T00:00:00Z', - confirmationRequestId: null, - preRowOriginalRequestId: null, - authorizationVersion: 0, -}; - -function deferred() { - let resolve!: (value: T) => void; - const promise = new Promise((done) => { - resolve = done; - }); - return { promise, resolve }; -} - -function setup(value: FirstInvoice = initial, stripeAvailable = true) { - let current = value; - let stripeContext = {}; - const client = { - read: vi - .fn() - .mockImplementation(async () => ({ ...current })), - reauthenticate: vi - .fn() - .mockResolvedValue({ - evidenceId: '33333333-3333-4333-8333-333333333333', - }), - renew: vi.fn().mockResolvedValue({ - status: 'requires_action', - clientSecret: 'pi_existing_secret_ephemeral', - }), - confirm: vi.fn().mockResolvedValue({ - status: 'requires_action', - clientSecret: 'pi_existing_secret_ephemeral', - }), - }; - const stripe = { - handleNextAction: vi - .fn() - .mockResolvedValue({ - paymentIntent: { - id: 'pi_existing', - status: 'succeeded', - } as PaymentIntent, - }), - }; - const queries = new QueryClient({ - defaultOptions: { queries: { retry: false }, mutations: { retry: false } }, - }); - const view = render( - - - - ); - return { - client, - stripe, - replaceStripe: (next: HostingStripe | null, context = stripeContext) => { - stripeContext = context; - view.rerender( - - - - ); - }, - setCurrent: (next: FirstInvoice) => { - current = next; - }, - }; -} - -async function consent() { - await screen.findByText('in_existing'); - fireEvent.change(screen.getByLabelText('Account email'), { - target: { value: 'owner@example.com' }, - }); - fireEvent.change(screen.getByLabelText('Primary authentication secret'), { - target: { value: 'primary-secret' }, - }); - fireEvent.click(screen.getByRole('checkbox')); - return screen.getByRole('button', { - name: /Authorize first-invoice charge|Resume exact confirmation/, - }); -} - -afterEach(() => { - cleanup(); - vi.restoreAllMocks(); -}); - -describe('owner first-invoice checkout', () => { - it('keeps Account recovery available if Stripe is unavailable for next action', async () => { - const { client, stripe } = setup(initial, false); - fireEvent.click(await consent()); - await screen.findByText( - /Stripe authentication is unavailable. Check Account status/ - ); - expect(client.confirm).toHaveBeenCalledTimes(1); - expect(stripe.handleNextAction).not.toHaveBeenCalled(); - await waitFor(() => - expect( - ( - screen.getByRole('button', { - name: 'Check Account status', - }) as HTMLButtonElement - ).disabled - ).toBe(false) - ); - const reads = client.read.mock.calls.length; - fireEvent.click( - screen.getByRole('button', { name: 'Check Account status' }) - ); - await waitFor(() => expect(client.read).toHaveBeenCalledTimes(reads + 1)); - expect(client.confirm).toHaveBeenCalledTimes(1); - expect(client.renew).not.toHaveBeenCalled(); - expect(document.body.textContent).not.toContain( - 'pi_existing_secret_ephemeral' - ); - }); - - it('uses the first Stripe handle loaded while the original confirmation is in flight', async () => { - const { client, stripe, replaceStripe } = setup(initial, false); - const confirmation = deferred<{ status: string; clientSecret: string }>(); - client.confirm.mockReturnValue(confirmation.promise); - fireEvent.click(await consent()); - await waitFor(() => expect(client.confirm).toHaveBeenCalledTimes(1)); - replaceStripe(stripe); - await act(async () => - confirmation.resolve({ - status: 'requires_action', - clientSecret: 'pi_existing_secret_ephemeral', - }) - ); - await waitFor(() => - expect(stripe.handleNextAction).toHaveBeenCalledExactlyOnceWith({ - clientSecret: 'pi_existing_secret_ephemeral', - }) - ); - expect(client.confirm).toHaveBeenCalledTimes(1); - expect(client.reauthenticate).toHaveBeenCalledTimes(1); - expect(client.renew).not.toHaveBeenCalled(); - expect(screen.queryByText(/Account confirmed and committed/)).toBeNull(); - expect(document.body.textContent).not.toContain( - 'pi_existing_secret_ephemeral' - ); - }); - - it.each(['handle', 'context'])( - 'refuses a replaced Stripe %s after its first handle loads in flight', - async (replacementKind) => { - const { client, stripe, replaceStripe } = setup(initial, false); - const confirmation = deferred<{ status: string; clientSecret: string }>(); - client.confirm.mockReturnValue(confirmation.promise); - fireEvent.click(await consent()); - await waitFor(() => expect(client.confirm).toHaveBeenCalledTimes(1)); - replaceStripe(stripe); - const replacement = { - handleNextAction: vi.fn(), - }; - if (replacementKind === 'handle') { - replaceStripe(replacement); - replaceStripe(stripe); - } else { - replaceStripe(stripe, {}); - } - await act(async () => - confirmation.resolve({ - status: 'requires_action', - clientSecret: 'pi_existing_secret_ephemeral', - }) - ); - await screen.findByText( - /Stripe authentication is unavailable. Check Account status/ - ); - expect(stripe.handleNextAction).not.toHaveBeenCalled(); - expect(replacement.handleNextAction).not.toHaveBeenCalled(); - expect(client.confirm).toHaveBeenCalledTimes(1); - expect(client.renew).not.toHaveBeenCalled(); - } - ); - - it('preserves the original confirmation but refuses a replaced Stripe handle', async () => { - const { client, stripe, replaceStripe } = setup(); - const confirmation = deferred<{ status: string; clientSecret: string }>(); - client.confirm.mockReturnValue(confirmation.promise); - fireEvent.click(await consent()); - await waitFor(() => expect(client.confirm).toHaveBeenCalledTimes(1)); - const original = client.confirm.mock.calls[0][2].requestId; - const replacement = { - handleNextAction: vi.fn(), - }; - replaceStripe(replacement); - await act(async () => - confirmation.resolve({ - status: 'requires_action', - clientSecret: 'pi_existing_secret_ephemeral', - }) - ); - await screen.findByText( - /Stripe authentication is unavailable. Check Account status/ - ); - expect(stripe.handleNextAction).not.toHaveBeenCalled(); - expect(replacement.handleNextAction).not.toHaveBeenCalled(); - expect(client.confirm.mock.calls[0][2].requestId).toBe(original); - expect(client.confirm).toHaveBeenCalledTimes(1); - expect(client.renew).not.toHaveBeenCalled(); - }); - - it('requires exact invoice/instrument/amount consent and primary reauth, locking duplicate clicks', async () => { - const { client, stripe } = setup(); - await screen.findByText('in_existing'); - expect( - screen.queryByRole('button', { name: 'Renew exact authorization' }) - ).toBeNull(); - expect( - ( - screen.getByRole('button', { - name: 'Authorize first-invoice charge', - }) as HTMLButtonElement - ).disabled - ).toBe(true); - const button = await consent(); - const confirmation = deferred<{ - status: string; - clientSecret: string | null; - }>(); - client.confirm.mockReturnValue(confirmation.promise); - fireEvent.click(button); - fireEvent.click(button); - await waitFor(() => expect(client.confirm).toHaveBeenCalledTimes(1)); - const reauth = client.reauthenticate.mock.calls[0][1]; - const request = client.confirm.mock.calls[0][2]; - expect(reauth).toMatchObject({ - email: 'owner@example.com', - secret: 'primary-secret', - confirmationRequestId: request.requestId, - billingBinding: { - originalRequestId: request.requestId, - expectedRowVersion: initial.expectedRowVersion, - expectedAuthorizationVersion: 0, - acceptedTupleDigest: initial.tupleDigest, - invoiceExpiresAt: initial.expiresAt, - authorizationPurpose: 'INITIAL_CONFIRMATION', - }, - }); - expect(reauth.requestId).not.toBe(request.requestId); - expect(request).toMatchObject({ - expectedRowVersion: 3, - acceptedTupleDigest: initial.tupleDigest, - acceptCharge: true, - }); - expect( - ( - screen.getByLabelText( - 'Primary authentication secret' - ) as HTMLInputElement - ).value - ).toBe(''); - await act(async () => - confirmation.resolve({ - status: 'requires_action', - clientSecret: 'pi_existing_secret_ephemeral', - }) - ); - await waitFor(() => - expect(stripe.handleNextAction).toHaveBeenCalledExactlyOnceWith({ - clientSecret: 'pi_existing_secret_ephemeral', - }) - ); - expect(screen.queryByText(/Account confirmed and committed/)).toBeNull(); - expect(document.body.textContent).not.toContain( - 'pi_existing_secret_ephemeral' - ); - }); - - it('lets the owner correct a refused primary secret with a fresh reauth request ID', async () => { - const { client } = setup(); - client.reauthenticate.mockRejectedValueOnce( - new FirstInvoiceError(401, 'AUTH_INVALID_CREDENTIALS') - ); - const button = await consent(); - fireEvent.click(button); - - await screen.findByText( - 'Account refused the primary authentication secret. Check the email and secret, then review and authorize this exact charge again.' - ); - expect(client.confirm).not.toHaveBeenCalled(); - const refusedRequestId = client.reauthenticate.mock.calls[0][1].requestId; - - fireEvent.change(screen.getByLabelText('Primary authentication secret'), { - target: { value: 'corrected-secret' }, - }); - fireEvent.click(screen.getByRole('checkbox')); - fireEvent.click(button); - - await waitFor(() => expect(client.confirm).toHaveBeenCalledOnce()); - expect(client.reauthenticate.mock.calls[1][1].requestId).not.toBe( - refusedRequestId - ); - }); - - it('keeps the same reauth request ID after an unknown response', async () => { - const { client } = setup(); - client.reauthenticate - .mockRejectedValueOnce(new FirstInvoiceError(0)) - .mockResolvedValueOnce({ - evidenceId: '55555555-5555-4555-8555-555555555555', - }); - const button = await consent(); - fireEvent.click(button); - - await screen.findByText( - 'The result is unknown. Check Account status or retry this same confirmation. Do not start another payment.' - ); - const uncertainRequestId = client.reauthenticate.mock.calls[0][1].requestId; - - fireEvent.change(screen.getByLabelText('Primary authentication secret'), { - target: { value: 'primary-secret' }, - }); - fireEvent.click(button); - - await waitFor(() => expect(client.confirm).toHaveBeenCalledOnce()); - expect(client.reauthenticate.mock.calls[1][1].requestId).toBe( - uncertainRequestId - ); - }); - - it.each(['processing', 'succeeded'])( - 'keeps provider %s pending until independent Account COMMITTED read', - async (status) => { - const { client, stripe, setCurrent } = setup(); - client.confirm.mockResolvedValue({ status, clientSecret: null }); - fireEvent.click(await consent()); - await waitFor(() => expect(client.confirm).toHaveBeenCalledOnce()); - await screen.findByText( - 'Waiting for Account to verify and commit payment completion.' - ); - expect(stripe.handleNextAction).not.toHaveBeenCalled(); - expect(screen.queryByText(/Account confirmed and committed/)).toBeNull(); - setCurrent({ ...initial, state: 'COMMITTED', expectedRowVersion: 4 }); - fireEvent.click( - screen.getByRole('button', { name: 'Check Account status' }) - ); - await screen.findByText( - 'Account confirmed and committed this first-invoice payment.' - ); - expect(screen.queryByRole('checkbox')).toBeNull(); - } - ); - - it('refuses a stale tuple before primary authentication or provider dispatch', async () => { - const { client, setCurrent } = setup(); - const button = await consent(); - setCurrent({ ...initial, amount: '1500', expectedRowVersion: 4 }); - fireEvent.click(button); - await screen.findByText( - 'The invoice changed or expired. Review the current details again.' - ); - expect(client.reauthenticate).not.toHaveBeenCalled(); - expect(client.confirm).not.toHaveBeenCalled(); - expect((screen.getByRole('checkbox') as HTMLInputElement).checked).toBe( - false - ); - expect(screen.getByText('USD 15.00 (1500 minor units)')).toBeTruthy(); - }); - - it('retries an ambiguous confirmation with exactly the same IDs, tuple, and evidence', async () => { - const { client } = setup(); - client.confirm - .mockRejectedValueOnce(new Error('private provider response')) - .mockResolvedValueOnce({ status: 'processing', clientSecret: null }); - fireEvent.click(await consent()); - await screen.findByText( - 'The result is unknown. Check Account status or retry this same confirmation. Do not start another payment.' - ); - fireEvent.click( - screen.getByRole('button', { name: 'Resume exact confirmation' }) - ); - await waitFor(() => expect(client.confirm).toHaveBeenCalledTimes(2)); - expect(client.confirm.mock.calls[1]).toEqual(client.confirm.mock.calls[0]); - expect(client.reauthenticate).toHaveBeenCalledOnce(); - expect(document.body.textContent).not.toContain( - 'private provider response' - ); - }); - - it.each([409, 410])( - 'explicitly renews the same original operation after status %i and no confirmation row', - async (status) => { - const { client, stripe, setCurrent } = setup(); - client.confirm - .mockRejectedValueOnce(new Error('private uncertain response')) - .mockRejectedValueOnce(new FirstInvoiceError(status)); - fireEvent.click(await consent()); - await screen.findByText( - 'The result is unknown. Check Account status or retry this same confirmation. Do not start another payment.' - ); - const original = client.confirm.mock.calls[0][2]; - setCurrent({ ...initial, preRowOriginalRequestId: original.requestId }); - fireEvent.click( - screen.getByRole('button', { name: 'Resume exact confirmation' }) - ); - await screen.findByText( - 'Your earlier confirmation is unresolved. You can explicitly renew authorization for this same invoice and original payment operation.' - ); - expect(client.confirm.mock.calls[1]).toEqual( - client.confirm.mock.calls[0] - ); - expect(screen.queryByRole('checkbox')).toBeNull(); - expect( - screen.queryByLabelText('Primary authentication secret') - ).toBeNull(); - expect( - screen.getByRole('button', { name: 'Renew exact authorization' }) - ).toBeTruthy(); - - for (let count = 0; count < 2; count += 1) { - const reads = client.read.mock.calls.length; - fireEvent.click( - screen.getByRole('button', { name: 'Check Account status' }) - ); - await waitFor(() => - expect(client.read.mock.calls.length).toBeGreaterThan(reads) - ); - await waitFor(() => - expect( - ( - screen.getByRole('button', { - name: 'Check Account status', - }) as HTMLButtonElement - ).disabled - ).toBe(false) - ); - } - expect(client.confirm).toHaveBeenCalledTimes(2); - expect(client.reauthenticate).toHaveBeenCalledOnce(); - expect(client.renew).not.toHaveBeenCalled(); - expect(stripe.handleNextAction).not.toHaveBeenCalled(); - expect(document.body.textContent).not.toContain( - 'private uncertain response' - ); - - // A different invoice tuple cannot borrow the original operation's authority. - setCurrent({ ...initial, paymentIntentId: 'pi_changed' }); - fireEvent.click( - screen.getByRole('button', { name: 'Check Account status' }) - ); - await screen.findByText('pi_changed'); - expect( - screen.queryByRole('button', { name: 'Renew exact authorization' }) - ).toBeNull(); - setCurrent({ ...initial, preRowOriginalRequestId: original.requestId }); - fireEvent.click( - screen.getByRole('button', { name: 'Check Account status' }) - ); - const renewal = await screen.findByRole('button', { - name: 'Renew exact authorization', - }); - expect(client.reauthenticate).toHaveBeenCalledOnce(); - expect(client.renew).not.toHaveBeenCalled(); - client.reauthenticate.mockResolvedValueOnce({ - evidenceId: '55555555-5555-4555-8555-555555555555', - }); - client.renew.mockResolvedValue({ - status: 'processing', - clientSecret: null, - }); - fireEvent.click(renewal); - fireEvent.change(screen.getByLabelText('Account email'), { - target: { value: 'owner@example.com' }, - }); - fireEvent.change(screen.getByLabelText('Primary authentication secret'), { - target: { value: 'fresh-secret' }, - }); - fireEvent.click(screen.getByRole('checkbox')); - fireEvent.click( - screen.getByRole('button', { name: 'Resume exact confirmation' }) - ); - await waitFor(() => expect(client.renew).toHaveBeenCalledOnce()); - expect(client.renew.mock.calls[0][2]).toMatchObject({ - requestId: original.requestId, - acceptedTupleDigest: original.acceptedTupleDigest, - expectedRowVersion: original.expectedRowVersion, - expectedAuthorizationVersion: 0, - reauthenticationEvidenceId: '55555555-5555-4555-8555-555555555555', - acceptCharge: true, - }); - const renewRequest = client.renew.mock.calls[0][2]; - const renewalProof = client.reauthenticate.mock.calls[1][1]; - expect(renewRequest.authorizationRequestId).not.toBe(original.requestId); - expect(renewalProof.confirmationRequestId).toBe( - renewRequest.authorizationRequestId - ); - expect(renewalProof.requestId).not.toBe( - client.reauthenticate.mock.calls[0][1].requestId - ); - expect(renewalProof.billingBinding).toEqual({ - originalRequestId: original.requestId, - expectedRowVersion: original.expectedRowVersion, - expectedAuthorizationVersion: 0, - acceptedTupleDigest: original.acceptedTupleDigest, - invoiceExpiresAt: initial.expiresAt, - authorizationPurpose: 'PRE_ROW_RENEWAL', - }); - expect(client.confirm).toHaveBeenCalledTimes(2); - expect(stripe.handleNextAction).not.toHaveBeenCalled(); - } - ); - - it('does not dispatch after local close interrupts primary reauthentication', async () => { - const { client } = setup(); - const proof = deferred<{ evidenceId: string }>(); - client.reauthenticate.mockReturnValue(proof.promise); - fireEvent.click(await consent()); - await waitFor(() => expect(client.reauthenticate).toHaveBeenCalledOnce()); - fireEvent.click(screen.getByRole('button', { name: 'Close checkout' })); - await act(async () => - proof.resolve({ evidenceId: '33333333-3333-4333-8333-333333333333' }) - ); - expect(client.confirm).not.toHaveBeenCalled(); - expect(screen.getByText(/Checkout closed/)).toBeTruthy(); - fireEvent.click(screen.getByRole('button', { name: 'Resume checkout' })); - await screen.findByText('in_existing'); - expect((screen.getByRole('checkbox') as HTMLInputElement).checked).toBe( - false - ); - }); - - it('close after dispatch does not imply cancellation, and resumes the same operation', async () => { - const { client, stripe } = setup(); - const reply = deferred<{ status: string; clientSecret: string | null }>(); - client.confirm - .mockReturnValueOnce(reply.promise) - .mockResolvedValueOnce({ status: 'processing', clientSecret: null }); - fireEvent.click(await consent()); - await waitFor(() => expect(client.confirm).toHaveBeenCalledOnce()); - fireEvent.click(screen.getByRole('button', { name: 'Close checkout' })); - await act(async () => - reply.resolve({ - status: 'requires_action', - clientSecret: 'pi_existing_secret_ephemeral', - }) - ); - expect(stripe.handleNextAction).not.toHaveBeenCalled(); - fireEvent.click(screen.getByRole('button', { name: 'Resume checkout' })); - await screen.findByText('in_existing'); - fireEvent.click(screen.getByRole('checkbox')); - fireEvent.click( - screen.getByRole('button', { name: 'Resume exact confirmation' }) - ); - await waitFor(() => expect(client.confirm).toHaveBeenCalledTimes(2)); - expect(client.confirm.mock.calls[1]).toEqual(client.confirm.mock.calls[0]); - }); - - it('does not convert Stripe dismissal/error into success or expose provider text', async () => { - const { stripe } = setup(); - stripe.handleNextAction.mockResolvedValue({ - error: { type: 'api_error', message: 'private client secret' }, - }); - fireEvent.click(await consent()); - await screen.findByText( - 'Stripe authentication was not completed. Check Account status or resume the same confirmation.' - ); - expect(screen.queryByText(/Account confirmed and committed/)).toBeNull(); - expect(document.body.textContent).not.toContain('private client secret'); - }); - - it('keeps reload of a retained confirmation read-only without a fresh payment or proof', async () => { - const retainedId = '44444444-4444-4444-8444-444444444444'; - const { client, stripe } = setup({ - ...initial, - confirmationRequestId: retainedId, - }); - await screen.findByText('in_existing'); - expect( - screen.getByText(/Account retained an earlier confirmation/) - ).toBeTruthy(); - expect(screen.queryByLabelText('Primary authentication secret')).toBeNull(); - expect(screen.queryByRole('checkbox')).toBeNull(); - fireEvent.click( - screen.getByRole('button', { name: 'Check Account status' }) - ); - await waitFor(() => - expect(client.read.mock.calls.length).toBeGreaterThan(1) - ); - expect(client.reauthenticate).not.toHaveBeenCalled(); - expect(client.confirm).not.toHaveBeenCalled(); - expect(stripe.handleNextAction).not.toHaveBeenCalled(); - }); - - it('holds an authorized-but-unconfirmed result without repeating provider work', async () => { - const { client, stripe } = setup(); - client.confirm.mockResolvedValue({ - status: 'AUTHORIZED_NOT_CONFIRMED', - clientSecret: null, - }); - fireEvent.click(await consent()); - await screen.findByText( - /Account retained the authorization, but provider confirmation is unresolved/ - ); - expect(screen.queryByRole('checkbox')).toBeNull(); - expect( - screen.queryByRole('button', { name: 'Resume exact confirmation' }) - ).toBeNull(); - expect(stripe.handleNextAction).not.toHaveBeenCalled(); - expect(client.confirm).toHaveBeenCalledOnce(); - }); - - it('cannot turn a vanished retained operation into new initial consent', async () => { - const { client, setCurrent } = setup({ - ...initial, - confirmationRequestId: '44444444-4444-4444-8444-444444444444', - authorizationVersion: 1, - }); - fireEvent.click( - await screen.findByRole('button', { name: 'Renew exact authorization' }) - ); - const authorize = await consent(); - setCurrent(initial); - fireEvent.click(authorize); - await screen.findByText( - 'Account no longer exposes the original operation. Check its status before renewing authorization.' - ); - expect(client.reauthenticate).not.toHaveBeenCalled(); - expect(client.confirm).not.toHaveBeenCalled(); - expect(client.renew).not.toHaveBeenCalled(); - }); - - it('refuses a changed original reference during the fresh consent readback', async () => { - const original = '44444444-4444-4444-8444-444444444444'; - const { client, setCurrent } = setup({ - ...initial, - preRowOriginalRequestId: original, - }); - fireEvent.click( - await screen.findByRole('button', { name: 'Renew exact authorization' }) - ); - const authorize = await consent(); - setCurrent({ - ...initial, - preRowOriginalRequestId: '55555555-5555-4555-8555-555555555555', - }); - fireEvent.click(authorize); - await screen.findByText( - 'Account retained a different original operation. Review its status before explicitly renewing authorization.' - ); - expect(client.reauthenticate).not.toHaveBeenCalled(); - expect(client.confirm).not.toHaveBeenCalled(); - expect(client.renew).not.toHaveBeenCalled(); - }); - - it('requires an explicit renewal click, fresh proof and consent while preserving the original payment identity', async () => { - const original = '44444444-4444-4444-8444-444444444444'; - const { client, stripe } = setup({ - ...initial, - confirmationRequestId: original, - authorizationVersion: 2, - }); - await screen.findByText('in_existing'); - expect(client.renew).not.toHaveBeenCalled(); - fireEvent.click( - screen.getByRole('button', { name: 'Renew exact authorization' }) - ); - fireEvent.change(screen.getByLabelText('Account email'), { - target: { value: 'owner@example.com' }, - }); - fireEvent.change(screen.getByLabelText('Primary authentication secret'), { - target: { value: 'fresh-secret' }, - }); - fireEvent.click(screen.getByRole('checkbox')); - fireEvent.click( - screen.getByRole('button', { name: 'Resume exact confirmation' }) - ); - await waitFor(() => expect(client.renew).toHaveBeenCalledOnce()); - const renewed = client.renew.mock.calls[0][2]; - expect(renewed).toMatchObject({ - requestId: original, - expectedAuthorizationVersion: 2, - acceptedTupleDigest: initial.tupleDigest, - expectedRowVersion: initial.expectedRowVersion, - acceptCharge: true, - }); - expect(renewed.authorizationRequestId).not.toBe(original); - expect(client.reauthenticate.mock.calls[0][1]).toMatchObject({ - confirmationRequestId: renewed.authorizationRequestId, - billingBinding: { - originalRequestId: original, - expectedRowVersion: initial.expectedRowVersion, - expectedAuthorizationVersion: 2, - acceptedTupleDigest: initial.tupleDigest, - invoiceExpiresAt: initial.expiresAt, - authorizationPurpose: 'FOLLOWUP_RENEWAL', - }, - secret: 'fresh-secret', - }); - expect(client.confirm).not.toHaveBeenCalled(); - await waitFor(() => expect(stripe.handleNextAction).toHaveBeenCalledOnce()); - }); - - it.each(['pre-row', 'post-row'])( - 'does not offer %s authorization renewal after the original invoice expires', - async (phase) => { - setup({ - ...initial, - confirmationRequestId: - phase === 'post-row' ? '44444444-4444-4444-8444-444444444444' : null, - preRowOriginalRequestId: - phase === 'pre-row' ? '44444444-4444-4444-8444-444444444444' : null, - authorizationVersion: phase === 'post-row' ? 1 : 0, - expiresAt: '2000-01-01T00:00:00Z', - }); - await screen.findByText('in_existing'); - expect( - screen.queryByRole('button', { name: 'Renew exact authorization' }) - ).toBeNull(); - } - ); - it('recovers the server-retained original after reload with explicit pre-row renewal', async () => { - const original = '44444444-4444-4444-8444-444444444444'; - const { client } = setup({ - ...initial, - preRowOriginalRequestId: original, - }); - const renew = await screen.findByRole('button', { - name: 'Renew exact authorization', - }); - expect(client.reauthenticate).not.toHaveBeenCalled(); - fireEvent.click(renew); - fireEvent.change(screen.getByLabelText('Account email'), { - target: { value: 'owner@example.com' }, - }); - fireEvent.change(screen.getByLabelText('Primary authentication secret'), { - target: { value: 'fresh-secret' }, - }); - fireEvent.click(screen.getByRole('checkbox')); - fireEvent.click( - screen.getByRole('button', { name: 'Resume exact confirmation' }) - ); - await waitFor(() => expect(client.renew).toHaveBeenCalledOnce()); - const request = client.renew.mock.calls[0][2]; - expect(request).toMatchObject({ - requestId: original, - expectedAuthorizationVersion: 0, - }); - expect(request.authorizationRequestId).not.toBe(original); - expect(client.reauthenticate.mock.calls[0][1].billingBinding).toMatchObject( - { - originalRequestId: original, - authorizationPurpose: 'PRE_ROW_RENEWAL', - } - ); - expect(client.confirm).not.toHaveBeenCalled(); - }); - - it('requires fresh explicit renewal when another tab wins before dispatch', async () => { - const original = '44444444-4444-4444-8444-444444444444'; - const retained = { - ...initial, - confirmationRequestId: original, - authorizationVersion: 2, - }; - const { client, setCurrent } = setup(retained); - client.reauthenticate.mockImplementationOnce(async () => { - setCurrent({ ...retained, authorizationVersion: 3 }); - throw new FirstInvoiceError(409); - }); - - async function explicitlyRenew() { - fireEvent.click( - await screen.findByRole('button', { name: 'Renew exact authorization' }) - ); - fireEvent.change(screen.getByLabelText('Account email'), { - target: { value: 'owner@example.com' }, - }); - fireEvent.change(screen.getByLabelText('Primary authentication secret'), { - target: { value: 'fresh-secret' }, - }); - fireEvent.click(screen.getByRole('checkbox')); - fireEvent.click( - screen.getByRole('button', { name: 'Resume exact confirmation' }) - ); - } - - await explicitlyRenew(); - await screen.findByText(/Account refused this renewal/); - expect(client.renew).not.toHaveBeenCalled(); - expect(client.confirm).not.toHaveBeenCalled(); - await waitFor(() => expect(client.read).toHaveBeenCalledTimes(3)); - - await explicitlyRenew(); - await waitFor(() => expect(client.renew).toHaveBeenCalledOnce()); - expect(client.renew.mock.calls[0][2]).toMatchObject({ - requestId: original, - expectedAuthorizationVersion: 3, - }); - expect(client.reauthenticate.mock.calls[1][1].billingBinding).toMatchObject( - { - originalRequestId: original, - expectedAuthorizationVersion: 3, - } - ); - expect(client.reauthenticate.mock.calls[1][1].requestId).not.toBe( - client.reauthenticate.mock.calls[0][1].requestId - ); - expect(client.confirm).not.toHaveBeenCalled(); - }); - - it('shows a canceled checkout without payment authorization', async () => { - const { client } = setup({ ...initial, state: 'CANCELED' }); - await screen.findByText(/Account recorded this checkout as canceled/); - expect(screen.queryByRole('checkbox')).toBeNull(); - expect( - screen.queryByRole('button', { name: 'Renew exact authorization' }) - ).toBeNull(); - expect(client.reauthenticate).not.toHaveBeenCalled(); - }); - - it('keeps expired checkout read-only and owner-session refusals non-authorizing', async () => { - const { client } = setup({ ...initial, expiresAt: '2000-01-01T00:00:00Z' }); - await screen.findByText( - 'This checkout has expired. Only Account status recovery is available.' - ); - expect((screen.getByRole('checkbox') as HTMLInputElement).disabled).toBe( - true - ); - client.read.mockRejectedValue(new FirstInvoiceError(403)); - fireEvent.click( - screen.getByRole('button', { name: 'Check Account status' }) - ); - await screen.findByText( - 'The owner invoice is unavailable. No payment completion is confirmed.' - ); - expect(client.confirm).not.toHaveBeenCalled(); - }); -}); diff --git a/web-client/src/billing/HostingFirstInvoiceCheckout.tsx b/web-client/src/billing/HostingFirstInvoiceCheckout.tsx deleted file mode 100644 index 54f47ad751..0000000000 --- a/web-client/src/billing/HostingFirstInvoiceCheckout.tsx +++ /dev/null @@ -1,619 +0,0 @@ -import { useEffect, useId, useLayoutEffect, useRef, useState } from 'react'; -import { useQuery } from '@tanstack/react-query'; -import Alert from '@mui/material/Alert'; -import Box from '@mui/material/Box'; -import Button from '@mui/material/Button'; -import Checkbox from '@mui/material/Checkbox'; -import FormControlLabel from '@mui/material/FormControlLabel'; -import Stack from '@mui/material/Stack'; -import TextField from '@mui/material/TextField'; -import Typography from '@mui/material/Typography'; -import { - FirstInvoiceError, - formatFirstInvoiceAmount, - sameCharge, - type FirstInvoice, - type FirstInvoiceClient, -} from '../api/hostingFirstInvoice'; -import type { HostingStripe } from './hostingStripe'; - -interface Props { - subscriptionId: string; - client: FirstInvoiceClient; - stripeContext: object; - stripe: HostingStripe | null; -} - -interface Attempt { - invoice: FirstInvoice; - requestId: string; - reauthenticationRequestId: string; - evidenceId?: string; - dispatched: boolean; - authorizationRequestId?: string; -} - -/** - * Mount under QueryClientProvider only from the App-owned account checkout - * route, after its memory-only control-ui session is active. The route keys - * this component by session identity and subscription so either change unmounts - * it; mounting, remounting, or browser navigation never authorizes a payment. - */ -export default function HostingFirstInvoiceCheckout({ - subscriptionId, - client, - stripeContext, - stripe, -}: Props) { - const queryId = useId(); - const [accepted, setAccepted] = useState(null); - const [email, setEmail] = useState(''); - const [secret, setSecret] = useState(''); - const [message, setMessage] = useState(''); - const [busy, setBusy] = useState(false); - const [pending, setPending] = useState(false); - const [evidenceReady, setEvidenceReady] = useState(false); - const [held, setHeld] = useState(false); - const [renewing, setRenewing] = useState(false); - const [closed, setClosed] = useState(false); - const [now, setNow] = useState(Date.now); - const attempt = useRef(null); - const locked = useRef(false); - const operation = useRef(0); - const currentStripe = useRef({ context: stripeContext, stripe }); - - useLayoutEffect(() => { - const current = currentStripe.current; - if ( - current.context !== stripeContext || - (current.stripe !== null && current.stripe !== stripe) - ) { - currentStripe.current = { context: stripeContext, stripe }; - } else { - // A first load may finish in flight; replacing its context or handle - // invalidates the old binding even if that context or handle returns. - current.stripe = stripe; - } - }, [stripeContext, stripe]); - - useEffect(() => { - const tick = window.setInterval(() => setNow(Date.now()), 1000); - return () => { - window.clearInterval(tick); - operation.current += 1; - }; - }, []); - - const query = useQuery({ - // Per-mount cache scope prevents another session's owner projection reuse. - queryKey: ['hosting-first-invoice', queryId, subscriptionId], - queryFn: ({ signal }) => client.read(subscriptionId, signal), - staleTime: 0, - gcTime: 0, - retry: false, - refetchOnWindowFocus: true, - enabled: !closed, - refetchInterval: (current) => - !closed && - current.state.data?.state === 'AWAITING_PAYMENT' && - (pending || - current.state.data?.confirmationRequestId || - current.state.data?.preRowOriginalRequestId) - ? 3000 - : false, - }); - - const invoice = query.data; - const committed = invoice?.state === 'COMMITTED' && !query.isError; - const canceled = invoice?.state === 'CANCELED'; - const expired = invoice ? now >= Date.parse(invoice.expiresAt) : true; - const consented = Boolean( - invoice && accepted && sameCharge(invoice, accepted) && !expired - ); - const recovering = Boolean( - pending || - invoice?.confirmationRequestId || - invoice?.preRowOriginalRequestId - ); - const preRowOriginal = - invoice && - invoice.confirmationRequestId === null && - invoice.authorizationVersion === 0 && - invoice.preRowOriginalRequestId - ? { invoice, requestId: invoice.preRowOriginalRequestId } - : null; - - // Reload never authorizes provider work. Renewal requires a separate explicit owner action. - const readOnlyRecovery = - held || - Boolean( - (invoice?.confirmationRequestId || preRowOriginal) && - !evidenceReady && - !renewing - ); - - function renewAuthorization() { - attempt.current = preRowOriginal - ? { - invoice: preRowOriginal.invoice, - requestId: preRowOriginal.requestId, - authorizationRequestId: crypto.randomUUID(), - reauthenticationRequestId: crypto.randomUUID(), - dispatched: false, - } - : null; - setAccepted(null); - setEvidenceReady(false); - setHeld(false); - setRenewing(true); - setEmail(''); - setSecret(''); - setMessage( - 'Review this same invoice and authorize it again with fresh primary authentication. A previously claimed payment command will not be resent.' - ); - } - - function close() { - operation.current += 1; - setClosed(true); - setSecret(''); - setEmail(''); - setAccepted(null); - // Closing is local dismissal, never a provider cancel/refund operation. - } - - async function submit() { - // A ref, not only a disabled button, excludes same-turn duplicate clicks. - if ( - locked.current || - !invoice || - !accepted || - !consented || - committed || - canceled || - readOnlyRecovery - ) - return; - locked.current = true; - setBusy(true); - const currentOperation = ++operation.current; - const active = () => operation.current === currentOperation; - const submittedStripe = currentStripe.current; - const credentials = { email, secret }; - setSecret(''); - setMessage('Checking the current Account invoice before confirmation.'); - - try { - const current = await query.refetch({ throwOnError: true }); - if (!active()) return; - const latest = current.data; - if (latest && latest.state !== 'AWAITING_PAYMENT') return; - if ( - !latest || - !sameCharge(latest, accepted) || - Date.now() >= Date.parse(latest.expiresAt) - ) { - setAccepted(null); - setMessage( - 'The invoice changed or expired. Review the current details again.' - ); - return; - } - let retained = attempt.current; - if (retained && !sameCharge(retained.invoice, latest)) { - // Never turn an uncertain old charge into a replacement confirmation. - if (retained.dispatched) { - setMessage( - 'The earlier confirmation needs Account reconciliation. No new charge was requested.' - ); - return; - } - retained = null; - } - if (!retained) { - if ( - renewing && - !latest.confirmationRequestId && - !latest.preRowOriginalRequestId - ) { - setHeld(true); - setRenewing(false); - setAccepted(null); - setEvidenceReady(false); - setMessage( - 'Account no longer exposes the original operation. Check its status before renewing authorization.' - ); - return; - } - if ( - (latest.confirmationRequestId || latest.preRowOriginalRequestId) && - !renewing - ) { - setHeld(true); - setRenewing(false); - setAccepted(null); - setMessage( - 'Account retained an existing confirmation. Review and explicitly renew authorization to resume this same invoice.' - ); - return; - } - retained = { - invoice: latest, - requestId: - latest.confirmationRequestId ?? - latest.preRowOriginalRequestId ?? - crypto.randomUUID(), - ...(latest.confirmationRequestId || latest.preRowOriginalRequestId - ? { authorizationRequestId: crypto.randomUUID() } - : {}), - reauthenticationRequestId: crypto.randomUUID(), - dispatched: false, - }; - attempt.current = retained; - } - const preRowRenewal = retained.invoice.authorizationVersion === 0; - if ( - latest.preRowOriginalRequestId !== null && - latest.preRowOriginalRequestId !== retained.requestId - ) { - attempt.current = null; - setHeld(true); - setRenewing(false); - setAccepted(null); - setEvidenceReady(false); - setMessage( - 'Account retained a different original operation. Review its status before explicitly renewing authorization.' - ); - return; - } - if ( - retained.authorizationRequestId && - !retained.dispatched && - (latest.confirmationRequestId !== - (preRowRenewal ? null : retained.requestId) || - latest.authorizationVersion !== - retained.invoice.authorizationVersion || - (preRowRenewal && - latest.preRowOriginalRequestId !== retained.requestId)) - ) { - attempt.current = null; - setHeld(true); - setRenewing(false); - setEvidenceReady(false); - setAccepted(null); - setMessage( - 'Account retained a confirmation while you were reviewing this invoice. Check its status and explicitly renew the current authorization.' - ); - return; - } - if (!retained.evidenceId) { - setMessage( - 'Verifying your primary authentication for this exact charge.' - ); - const proof = await client.reauthenticate(subscriptionId, { - requestId: retained.reauthenticationRequestId, - confirmationRequestId: - retained.authorizationRequestId ?? retained.requestId, - billingBinding: { - originalRequestId: retained.requestId, - expectedRowVersion: retained.invoice.expectedRowVersion, - expectedAuthorizationVersion: retained.invoice.authorizationVersion, - acceptedTupleDigest: retained.invoice.tupleDigest, - invoiceExpiresAt: retained.invoice.expiresAt, - authorizationPurpose: !retained.authorizationRequestId - ? 'INITIAL_CONFIRMATION' - : retained.invoice.authorizationVersion === 0 - ? 'PRE_ROW_RENEWAL' - : 'FOLLOWUP_RENEWAL', - }, - ...credentials, - }); - retained.evidenceId = proof.evidenceId; - if (!active()) return; - setEvidenceReady(true); - } - if (Date.now() >= Date.parse(latest.expiresAt)) { - setAccepted(null); - setMessage('The invoice expired. No new confirmation was sent.'); - return; - } - retained.dispatched = true; - setPending(true); - setMessage( - 'Confirmation requested. Account has not confirmed payment completion.' - ); - const consent = { - requestId: retained.requestId, - expectedRowVersion: retained.invoice.expectedRowVersion, - reauthenticationEvidenceId: retained.evidenceId, - acceptedTupleDigest: retained.invoice.tupleDigest, - acceptCharge: true as const, - }; - const handoff = retained.authorizationRequestId - ? await client.renew(subscriptionId, latest.paymentIntentId, { - ...consent, - authorizationRequestId: retained.authorizationRequestId, - expectedAuthorizationVersion: retained.invoice.authorizationVersion, - }) - : await client.confirm(subscriptionId, latest.paymentIntentId, consent); - if (!active()) return; - if (handoff.status === 'AUTHORIZED_NOT_CONFIRMED') { - setHeld(true); - setRenewing(false); - setAccepted(null); - setMessage( - 'Account retained the authorization, but provider confirmation is unresolved. Only status recovery is available. No replacement charge was requested.' - ); - } else if (handoff.status === 'requires_action' && handoff.clientSecret) { - const loadedStripe = submittedStripe.stripe; - if (!loadedStripe || currentStripe.current !== submittedStripe) { - setMessage( - 'Stripe authentication is unavailable. Check Account status or explicitly resume this same confirmation when authentication is available.' - ); - await query.refetch(); - return; - } - setMessage( - 'Complete the Stripe authentication prompt for this invoice.' - ); - // The server already confirmed this exact intent. Never confirm/create another. - const result = await loadedStripe.handleNextAction({ - clientSecret: handoff.clientSecret, - }); - if (!active()) return; - setMessage( - result.error - ? 'Stripe authentication was not completed. Check Account status or resume the same confirmation.' - : 'Stripe authentication returned. Waiting for Account to verify and commit payment completion.' - ); - } else { - setMessage( - 'Waiting for Account to verify and commit payment completion.' - ); - } - await query.refetch(); - } catch (error) { - if (!active()) return; - if ( - error instanceof FirstInvoiceError && - [401, 403].includes(error.status) - ) { - setAccepted(null); - if (attempt.current?.dispatched) setHeld(true); - if (error.code === 'AUTH_INVALID_CREDENTIALS') { - const failedAttempt = attempt.current; - if ( - failedAttempt && - !failedAttempt.evidenceId && - !failedAttempt.dispatched - ) { - failedAttempt.reauthenticationRequestId = crypto.randomUUID(); - } - setMessage( - 'Account refused the primary authentication secret. Check the email and secret, then review and authorize this exact charge again.' - ); - } else if (error.code === 'INVALID_CREDENTIALS') { - setMessage( - 'Account could not match this reauthentication retry to its original credentials. Check Account status before explicitly renewing authorization.' - ); - } else { - setMessage( - 'The current control-ui session or billing-owner authority was refused. Sign in again through the account flow.' - ); - } - } else if ( - error instanceof FirstInvoiceError && - [409, 410].includes(error.status) - ) { - setAccepted(null); - const failedAttempt = attempt.current; - if (failedAttempt?.dispatched) { - setHeld(true); - } else if ( - error.status === 409 && - failedAttempt?.authorizationRequestId - ) { - attempt.current = null; - setHeld(true); - setRenewing(false); - setEvidenceReady(false); - setMessage( - 'Account refused this renewal. Check the invoice status and explicitly renew the current authorization.' - ); - await query.refetch(); - return; - } - setMessage( - 'Account refused stale or expired checkout evidence. Refresh and review the invoice. Any earlier confirmation remains unresolved.' - ); - await query.refetch(); - } else { - setMessage( - 'The result is unknown. Check Account status or retry this same confirmation. Do not start another payment.' - ); - } - } finally { - credentials.email = ''; - credentials.secret = ''; - locked.current = false; - setBusy(false); - } - } - - if (closed) { - return ( - - - Checkout closed. Closing does not cancel a confirmation already sent. - - - - ); - } - - return ( - - - - Hosting first invoice - - {query.isPending && ( - Loading the owner invoice. - )} - {query.isError && ( - - The owner invoice is unavailable. No payment completion is - confirmed. - - )} - {invoice && ( - <> - -
Subscription
-
{invoice.subscriptionId}
-
Invoice
-
{invoice.invoiceId}
-
Amount due now
-
- {formatFirstInvoiceAmount(invoice.amount, invoice.currency)} ( - {invoice.amount} minor units) -
-
Bound payment instrument
-
{invoice.paymentInstrumentId}
-
Existing payment intent
-
{invoice.paymentIntentId}
-
Checkout expires
-
{invoice.expiresAt}
-
- {committed ? ( - - Account confirmed and committed this first-invoice payment. - - ) : canceled ? ( - - Account recorded this checkout as canceled. Payment - authorization is closed. - - ) : ( - <> - - {recovering - ? 'A confirmation may already be in progress. Resume only this same invoice and payment intent. ' - : ''} - Stripe or browser success does not activate hosting. Account - must verify provider evidence and commit completion. - - {expired && ( - - This checkout has expired. Only Account status recovery is - available. - - )} - {readOnlyRecovery ? ( - - {invoice.confirmationRequestId ? ( - <> - Account retained an earlier confirmation. Only status - recovery is automatic. Explicit fresh authorization can - resume this same invoice, but cannot resend an uncertain - payment command. - - ) : preRowOriginal ? ( - <> - Your earlier confirmation is unresolved. You can - explicitly renew authorization for this same invoice and - original payment operation. - - ) : ( - <> - Your earlier confirmation is unresolved. Check Account - status for this same payment. Do not start another - payment. Authorization cannot safely be renewed yet. - - )} - - ) : ( - <> - setEmail(event.target.value)} - slotProps={{ htmlInput: { maxLength: 254 } }} - /> - setSecret(event.target.value)} - helperText="Use the primary factor required by your account. It is sent only to Account over HTTPS." - slotProps={{ htmlInput: { maxLength: 1024 } }} - /> - - setAccepted(checked ? invoice : null) - } - /> - } - label={`I authorize the exact ${formatFirstInvoiceAmount(invoice.amount, invoice.currency)} charge (${invoice.amount} minor units) for invoice ${invoice.invoiceId} using instrument ${invoice.paymentInstrumentId}.`} - /> - - - )} - - )} - - )} - {!committed && !canceled && message && ( - {message} - )} - - {readOnlyRecovery && - !committed && - !canceled && - !expired && - (invoice?.confirmationRequestId || preRowOriginal) && ( - - )} - - - -
-
- ); -} diff --git a/web-client/src/billing/hostingStripe.ts b/web-client/src/billing/hostingStripe.ts deleted file mode 100644 index 7d590d488f..0000000000 --- a/web-client/src/billing/hostingStripe.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { loadStripe } from '@stripe/stripe-js/pure'; -import type { Stripe } from '@stripe/stripe-js'; - -/** No intent creation/confirmation capability is exposed to checkout. */ -export interface HostingStripe { - handleNextAction(options: { - clientSecret: string; - }): ReturnType; -} - -/** Call from the real control-ui composition with its public Stripe key. */ -export async function loadHostingStripe( - publishableKey: string -): Promise { - if (!/^pk_(test|live)_[A-Za-z0-9]+$/.test(publishableKey)) { - throw new Error('A Stripe publishable key is required.'); - } - const stripe = await loadStripe(publishableKey); - if (!stripe) throw new Error('Stripe authentication is unavailable.'); - return { handleNextAction: (options) => stripe.handleNextAction(options) }; -} From d9a615b4743315b4618c29adf8f4d9bcf01a1a68 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 14 Nov 2026 07:29:32 +1300 Subject: [PATCH 22/29] Close checkout review gaps in body deadlines and retained billing replay --- .../AccountHostingFirstInvoiceController.java | 11 +++- ...ountHostingFirstInvoicePaymentService.java | 20 ++++++ .../AccountRecentReauthenticationService.java | 24 +++++++ ...tpsCompositionPostgresIntegrationTest.java | 12 ++-- ...authenticationPostgresIntegrationTest.java | 54 ++++++++++++++- ...ountHostingFirstInvoiceControllerTest.java | 53 +++++++++++++++ .../AccountCheckoutGatewayController.java | 25 ++++++- .../src/main/resources/openapi.yaml | 6 ++ .../AccountCheckoutGatewayControllerTest.java | 66 +++++++++++++++++++ 9 files changed, 260 insertions(+), 11 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceController.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceController.java index 7f5a19e9b8..c592279dc1 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceController.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceController.java @@ -52,7 +52,16 @@ public ResponseEntity reauthenticate( @RequestBody ReauthenticationRequest request) { String token = bearer(transport, authorization); if (request.billingBinding() == null) { - throw new IllegalStateException("Exact first-invoice billing binding required"); + // Pre-binding evidence has no invoice context. Account permits only its exact retained, + // credential-bound replay; the result cannot authorize payment or write an invoice fence. + return noStore( + new ReauthenticationResponse( + payments.replayHistoricalUnboundReauthentication( + token, + request.requestId(), + request.confirmationRequestId(), + request.email(), + request.secret()))); } var binding = request.billingBinding(); return noStore( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoicePaymentService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoicePaymentService.java index be4f2d0ac0..f165a9ca40 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoicePaymentService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoicePaymentService.java @@ -138,6 +138,26 @@ public UUID reauthenticate( return evidence.evidenceId(); } + /** Returns only an exact, credential-bound replay of retained pre-binding billing evidence. */ + public UUID replayHistoricalUnboundReauthentication( + String bearer, + UUID reauthenticationRequestId, + UUID authorizationRequestId, + String email, + String secret) { + outsideSql(); + var actor = actors.authenticateAccount(bearer); + var request = + new AccountRecentReauthenticationService.Request( + reauthenticationRequestId, + actor.accountId(), + AccountRecentReauthenticationPolicy.BILLING_PURPOSE, + authorizationRequestId, + email, + secret); + return reauthentication.replayHistoricalUnboundBilling(request, actors, bearer).evidenceId(); + } + /** * Explicit consent names the immutable tuple shown to the owner; browser success grants nothing. */ diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationService.java index 78e6265c8c..81d1c104c3 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationService.java @@ -106,6 +106,30 @@ AccountRecentReauthenticationEvidence reauthenticateAndBindBilling( })); } + /** + * Replays only exact retained pre-binding billing evidence under the current Account actor. A + * missing request still reaches the existing null-context refusal before primary authentication, + * evidence insertion, or any billing-operation write. + */ + AccountRecentReauthenticationEvidence replayHistoricalUnboundBilling( + Request request, AccountControlUiActorService actors, String bearer) { + Objects.requireNonNull(request, "Account reauthentication request is required"); + Objects.requireNonNull(actors, "Current Account actor owner is required"); + if (!AccountRecentReauthenticationPolicy.BILLING_PURPOSE.equals(request.purpose) + || request.billingContext != null) { + throw conflict(); + } + return reauthenticate( + request, + action -> + actors.withCurrentAccount( + bearer, + actor -> { + if (!request.accountId.equals(actor.accountId())) throw conflict(); + return action.get(); + })); + } + private AccountRecentReauthenticationEvidence reauthenticate( Request request, Function, Attempt> retainInOwnerTransaction) { Objects.requireNonNull(request, "Account reauthentication request is required"); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoiceHttpsCompositionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoiceHttpsCompositionPostgresIntegrationTest.java index 8b7c00e918..8e823ba3bb 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoiceHttpsCompositionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoiceHttpsCompositionPostgresIntegrationTest.java @@ -419,6 +419,12 @@ void actualHttpsOwnerConsentScaAndExactSignedCompletionGrantAuthorityOnlyAfterRe .path("state") .asText()) .isEqualTo("AWAITING_PAYMENT"); + // The current renewal can no longer redisclose the pending SCA secret after expiry. + hosting.clock().advance(Duration.ofMinutes(6)); + var expired = https.request("POST", path + "/renew", issued.compact(), renewal); + assertThat(expired.statusCode()).isEqualTo(409); + assertThat(expired.body()).doesNotContain("clientSecret", "secret_"); + assertThat(hosting.firstInvoiceConfirmations()).isEqualTo(1); // Even provider success/browser return remains pending until exact signed completion. hosting.firstInvoiceStatus("succeeded"); hosting.providerStatus("active"); @@ -428,12 +434,6 @@ void actualHttpsOwnerConsentScaAndExactSignedCompletionGrantAuthorityOnlyAfterRe .asText()) .isEqualTo("AWAITING_PAYMENT"); assertNoReceipt(hosting); - // Expired authorization cannot redisclose the secret or issue another payment command. - hosting.clock().advance(Duration.ofMinutes(6)); - var expired = https.request("POST", path + "/confirm", issued.compact(), consent); - assertThat(expired.statusCode()).isEqualTo(409); - assertThat(expired.body()).doesNotContain("clientSecret", "secret_"); - assertThat(hosting.firstInvoiceConfirmations()).isEqualTo(1); String signedPayload = hosting.signedSuccessPayload(); String signedHeader = hosting.signedSuccessHeader(); long auditBefore = diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java index 2e112fd3a6..8a01b40ef3 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java @@ -2,10 +2,14 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import de.mkammerer.argon2.Argon2Factory; import java.io.IOException; +import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -26,6 +30,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; import java.util.function.Supplier; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge; @@ -1273,6 +1278,23 @@ void firstInvoiceFenceMigrationPreservesUnboundBillingEvidenceWithoutAuthorizing UUID requestId = UUID.randomUUID(); UUID operationId = UUID.randomUUID(); String purpose = AccountRecentReauthenticationPolicy.BILLING_PURPOSE; + byte[] identity = + AccountRecentReauthenticationRepository.requestPayload( + requestId, account.getAccountUuid(), purpose, operationId); + byte[] email = account.getEmail().getBytes(StandardCharsets.UTF_8); + byte[] secret = PASSWORD.getBytes(StandardCharsets.UTF_8); + byte[] credentials = + ByteBuffer.allocate(12 + identity.length + email.length + secret.length) + .putInt(identity.length) + .put(identity) + .putInt(email.length) + .put(email) + .putInt(secret.length) + .put(secret) + .array(); + var crypto = + new AccountControlUiResponseCryptography(new AccountControlUiKeyring(c.custody), c.clock); + String mac = crypto.recentReauthenticationRequestMac("mac1", credentials); UUID evidenceId = c.tx( () -> { @@ -1286,7 +1308,7 @@ void firstInvoiceFenceMigrationPreservesUnboundBillingEvidenceWithoutAuthorizing account.getAccountUuid(), purpose, operationId, - "a".repeat(64)); + mac); return id; }); Record original = c.evidenceRow(evidenceId); @@ -1298,6 +1320,36 @@ void firstInvoiceFenceMigrationPreservesUnboundBillingEvidenceWithoutAuthorizing assertThat(retained.evidenceId()).isEqualTo(evidenceId); assertThat(retained.billingContext()).isNull(); + var actors = mock(AccountControlUiActorService.class); + var actor = mock(AccountControlUiActorService.AccountAuthenticatedActor.class); + when(actor.accountId()).thenReturn(account.getAccountUuid()); + when(actors.withCurrentAccount(eq("current-token"), any())) + .thenAnswer( + invocation -> { + Function action = + invocation.getArgument(1); + return c.tx(() -> action.apply(actor)); + }); + var exact = + new AccountRecentReauthenticationService.Request( + requestId, + account.getAccountUuid(), + purpose, + operationId, + account.getEmail(), + PASSWORD); + assertThat( + c.service.replayHistoricalUnboundBilling(exact, actors, "current-token").evidenceId()) + .isEqualTo(evidenceId); + var wrongSecret = + new AccountRecentReauthenticationService.Request( + requestId, account.getAccountUuid(), purpose, operationId, account.getEmail(), "wrong"); + assertThatThrownBy( + () -> c.service.replayHistoricalUnboundBilling(wrongSecret, actors, "current-token")) + .isInstanceOf(AuthenticationException.class); + assertThat(c.count("SELECT count(*) FROM account_recent_reauthentication_replay_failures")) + .isOne(); + var binding = new AccountRecentReauthenticationEvidence.BillingContext( account.getAccountUuid(), diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceControllerTest.java index bc7a276c71..3d48628df4 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceControllerTest.java @@ -3,7 +3,9 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import jakarta.servlet.http.HttpServletRequest; @@ -74,6 +76,57 @@ void ownerStatusSerializesTheObservationalOriginalReferenceWithNoStore() throws .doesNotExist()); } + @Test + void unboundReauthenticationRoutesOnlyToExactHistoricalReplay() throws Exception { + var service = mock(AccountHostingFirstInvoicePaymentService.class); + UUID subscription = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + UUID authorizationRequestId = UUID.randomUUID(); + UUID evidenceId = UUID.randomUUID(); + when(service.replayHistoricalUnboundReauthentication( + "controlled-bearer", + requestId, + authorizationRequestId, + "owner@example.test", + "controlled-secret")) + .thenReturn(evidenceId); + + registeredController(service) + .perform( + org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post( + "/billing/hosting/subscriptions/" + + subscription + + "/first-invoice/reauthenticate") + .secure(true) + .header("Authorization", "Bearer controlled-bearer") + .contentType(org.springframework.http.MediaType.APPLICATION_JSON) + .content( + "{\"requestId\":\"" + + requestId + + "\",\"confirmationRequestId\":\"" + + authorizationRequestId + + "\",\"email\":\"owner@example.test\"" + + ",\"secret\":\"controlled-secret\"}")) + .andExpect( + org.springframework.test.web.servlet.result.MockMvcResultMatchers.status().isOk()) + .andExpect( + org.springframework.test.web.servlet.result.MockMvcResultMatchers.header() + .string("Cache-Control", "no-store")) + .andExpect( + org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath( + "$.evidenceId") + .value(evidenceId.toString())); + + verify(service) + .replayHistoricalUnboundReauthentication( + "controlled-bearer", + requestId, + authorizationRequestId, + "owner@example.test", + "controlled-secret"); + verifyNoMoreInteractions(service); + } + @Test void dependencyUnavailabilityIsNotReportedAsRevocationAndNeverDisclosesSecrets() { var controller = diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/controller/AccountCheckoutGatewayController.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/controller/AccountCheckoutGatewayController.java index fbad4dd21b..f79b4747a7 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/controller/AccountCheckoutGatewayController.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/controller/AccountCheckoutGatewayController.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.springcloudgateway.controller; import java.nio.charset.StandardCharsets; +import java.time.Duration; import java.time.Instant; import java.util.Objects; import java.util.UUID; @@ -50,6 +51,7 @@ havingValue = "true") public final class AccountCheckoutGatewayController { private static final int MAX_LOGIN_BODY_BYTES = 8 * 1024; + private static final Duration REQUEST_BODY_TIMEOUT = Duration.ofSeconds(5); private static final JsonMapper JSON = JsonMapper.builder() .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) @@ -151,7 +153,10 @@ public Mono> login(ServerWebExchange exchange) { }) .onErrorResume( DataBufferLimitException.class, - oversized -> Mono.just(jsonResponse(HttpStatus.PAYLOAD_TOO_LARGE, errorJson("ERROR")))); + oversized -> Mono.just(jsonResponse(HttpStatus.PAYLOAD_TOO_LARGE, errorJson("ERROR")))) + .onErrorResume( + RequestBodyTimeoutException.class, + timedOut -> Mono.just(jsonResponse(HttpStatus.REQUEST_TIMEOUT, errorJson("ERROR")))); } @GetMapping("/billing/hosting/subscriptions/{subscriptionId}/first-invoice") @@ -195,7 +200,10 @@ public Mono> receiveStripeWebhook(ServerWebExchange excha .flatMap(body -> forwardBytes(exchange, HttpMethod.POST, "/billing/hosting/webhook", body)) .onErrorResume( DataBufferLimitException.class, - oversized -> Mono.just(jsonResponse(HttpStatus.PAYLOAD_TOO_LARGE, errorJson("ERROR")))); + oversized -> Mono.just(jsonResponse(HttpStatus.PAYLOAD_TOO_LARGE, errorJson("ERROR")))) + .onErrorResume( + RequestBodyTimeoutException.class, + timedOut -> Mono.just(jsonResponse(HttpStatus.REQUEST_TIMEOUT, errorJson("ERROR")))); } private Mono> postSubscriptionAction( @@ -221,7 +229,10 @@ private Mono> forward( .flatMap(body -> forwardBytes(exchange, method, path, body)) .onErrorResume( DataBufferLimitException.class, - oversized -> Mono.just(jsonResponse(HttpStatus.PAYLOAD_TOO_LARGE, errorJson("ERROR")))); + oversized -> Mono.just(jsonResponse(HttpStatus.PAYLOAD_TOO_LARGE, errorJson("ERROR")))) + .onErrorResume( + RequestBodyTimeoutException.class, + timedOut -> Mono.just(jsonResponse(HttpStatus.REQUEST_TIMEOUT, errorJson("ERROR")))); } private Mono> forwardBytes( @@ -237,10 +248,18 @@ private static Mono boundedBody(ServerWebExchange exchange, int maximumB return Mono.error(new DataBufferLimitException("Request body exceeds the route limit")); } return DataBufferUtils.join(exchange.getRequest().getBody(), maximumBytes) + .timeout( + REQUEST_BODY_TIMEOUT, Mono.defer(() -> Mono.error(new RequestBodyTimeoutException()))) .map(AccountCheckoutGatewayController::readAndRelease) .defaultIfEmpty(new byte[0]); } + private static final class RequestBodyTimeoutException extends RuntimeException { + private RequestBodyTimeoutException() { + super("Request body exceeded its deadline"); + } + } + private static byte[] readAndRelease(DataBuffer buffer) { try { byte[] bytes = new byte[buffer.readableByteCount()]; diff --git a/services/spring-cloud-gateway/src/main/resources/openapi.yaml b/services/spring-cloud-gateway/src/main/resources/openapi.yaml index 8267596468..4bd6f8a815 100644 --- a/services/spring-cloud-gateway/src/main/resources/openapi.yaml +++ b/services/spring-cloud-gateway/src/main/resources/openapi.yaml @@ -77,6 +77,7 @@ paths: expiresAt: {type: string, format: date-time} '400': {description: Invalid bounded request or actual HTTPS required} '401': {description: Primary authentication denied} + '408': {description: Gateway did not receive the complete request body within five seconds} '409': {description: Account login request conflicts with retained idempotency evidence} '413': {description: Login request exceeds the Gateway body limit} '415': {description: Login requires an application/json request} @@ -98,6 +99,7 @@ paths: '200': {description: No-store Account owner result under the Account first-invoice API contract} '400': {description: Malformed request} '401': {description: Current control-ui owner authority required} + '408': {description: Gateway did not receive the complete request body within five seconds} '409': {description: Exact retained evidence refused or outcome uncertain} '413': {description: Request exceeds the subscription-operation body limit} '429': {description: Receiving rate limit exceeded} @@ -143,6 +145,7 @@ paths: '200': {description: No-store Account owner result under the Account first-invoice API contract} '400': {description: Malformed request} '401': {description: Current control-ui owner authority required} + '408': {description: Gateway did not receive the complete request body within five seconds} '409': {description: Exact retained evidence refused or outcome uncertain} '413': {description: Request exceeds the subscription-operation body limit} '415': {description: Action requires an application/json request} @@ -178,6 +181,7 @@ paths: '200': {description: No-store Account owner result under the Account first-invoice API contract} '400': {description: Malformed request} '401': {description: Current control-ui owner authority required} + '408': {description: Gateway did not receive the complete request body within five seconds} '409': {description: Exact retained evidence refused or outcome uncertain} '413': {description: Request exceeds the subscription-operation body limit} '415': {description: Action requires an application/json request} @@ -215,6 +219,7 @@ paths: '200': {description: No-store Account owner result under the Account first-invoice API contract} '400': {description: Malformed request} '401': {description: Current control-ui owner authority required} + '408': {description: Gateway did not receive the complete request body within five seconds} '409': {description: Exact retained evidence refused or outcome uncertain} '413': {description: Request exceeds the subscription-operation body limit} '415': {description: Action requires an application/json request} @@ -251,6 +256,7 @@ paths: '200': {description: No-store Account completion state} '400': {description: Invalid signed event} '401': {description: Account rejected provider-event authentication} + '408': {description: Gateway did not receive the complete request body within five seconds} '409': {description: Account could not accept this event against retained state} '413': {description: Request exceeds the webhook body limit} '429': {description: Receiving rate limit exceeded} diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/controller/AccountCheckoutGatewayControllerTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/controller/AccountCheckoutGatewayControllerTest.java index fb905bb378..5d24807308 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/controller/AccountCheckoutGatewayControllerTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/controller/AccountCheckoutGatewayControllerTest.java @@ -8,9 +8,13 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import io.netty.buffer.ByteBufAllocator; +import io.netty.buffer.Unpooled; import java.net.URI; import java.nio.charset.StandardCharsets; +import java.time.Duration; import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; import net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec; import net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec.Authenticated; import net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec.Request; @@ -22,7 +26,10 @@ import net.firedevops.firemud.springcloudgateway.filter.HeaderTrustFilter; import net.firedevops.firemud.springcloudgateway.filter.TcpProxyTrustPolicy; import org.junit.jupiter.api.Test; +import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DefaultDataBufferFactory; +import org.springframework.core.io.buffer.NettyDataBufferFactory; +import org.springframework.core.io.buffer.PooledDataBuffer; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; @@ -33,7 +40,9 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; class AccountCheckoutGatewayControllerTest { private static final UUID REQUEST_ID = UUID.fromString("1ca7f2e5-1362-4ac8-9312-38bbf73bc33f"); @@ -182,6 +191,26 @@ void mapsRetainedRequestInputConflictsToSafeHttpConflict() { verifyNoCheckoutCalls(checkoutClient); } + @Test + void mapsLoginRpcTimeoutToUnavailableInsteadOfRequestBodyTimeout() throws Exception { + var authClient = mock(AccountControlUiAuthenticationClient.class); + var checkoutClient = mock(AccountCheckoutHttpClient.class); + var controller = new AccountCheckoutGatewayController(authClient, checkoutClient, properties()); + var unavailableType = + AccountControlUiAuthenticationClient.AuthenticationUnavailableException.class; + var unavailableConstructor = unavailableType.getDeclaredConstructor(); + unavailableConstructor.setAccessible(true); + when(authClient.login(any())).thenThrow(unavailableConstructor.newInstance()); + + var response = controller.login(secureExchange("/api/account/auth/login", loginJson())).block(); + + assertThat(response).isNotNull(); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); + assertThat(response.getHeaders().getCacheControl()).contains("no-store"); + verify(authClient).login(any()); + verifyNoCheckoutCalls(checkoutClient); + } + @Test void redactsCredentialAndTokenFromTransientLoginRecordDiagnostics() throws Exception { Class dataType = @@ -229,6 +258,43 @@ void rejectsDuplicateUnknownAndOversizedLoginJsonWithoutCallingAccount() { verifyNoCheckoutCalls(checkoutClient); } + @Test + void stalledChunkedWebhookBodyTimesOutCancelsAndReleasesWithoutForwarding() { + var authClient = mock(AccountControlUiAuthenticationClient.class); + var checkoutClient = mock(AccountCheckoutHttpClient.class); + var controller = new AccountCheckoutGatewayController(authClient, checkoutClient, properties()); + var stalledBuffer = + new NettyDataBufferFactory(ByteBufAllocator.DEFAULT) + .wrap(Unpooled.copiedBuffer("{", StandardCharsets.UTF_8)); + var sourceCancelled = new AtomicBoolean(); + Flux stalledBody = + Flux.concat(Mono.just(stalledBuffer), Flux.never()) + .doOnCancel(() -> sourceCancelled.set(true)); + var request = + MockServerHttpRequest.post("https://localhost/api/account/billing/hosting/webhook") + .sslInfo(mock(SslInfo.class)) + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .header("Stripe-Signature", "t=123,v1=signature") + .body(stalledBody); + var exchange = MockServerWebExchange.from(request); + + StepVerifier.withVirtualTime(() -> controller.receiveStripeWebhook(exchange)) + .thenAwait(Duration.ofSeconds(5)) + .assertNext( + response -> { + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.REQUEST_TIMEOUT); + assertThat(response.getHeaders().getCacheControl()).contains("no-store"); + assertThat(new String(response.getBody(), StandardCharsets.UTF_8)) + .isEqualTo("{\"status\":\"ERROR\"}"); + }) + .verifyComplete(); + + assertThat(sourceCancelled).isTrue(); + assertThat(((PooledDataBuffer) stalledBuffer).isAllocated()).isFalse(); + verifyNoCheckoutCalls(checkoutClient); + verify(authClient, never()).login(any()); + } + @Test void forwardsOnlyExactCheckoutRoutesAndSetsNoStoreOnProxyResponses() { var authClient = mock(AccountControlUiAuthenticationClient.class); From ceb7c48c40cb3d264ce1bcd4ca6994269011a9c0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 14 Nov 2026 08:35:42 +1300 Subject: [PATCH 23/29] Apply the Account and Gateway login review fixes --- ...untControlUiAuthenticationGrpcService.java | 3 +- .../AccountControlUiIssuanceService.java | 16 +++- ...ountHostingFirstInvoicePaymentService.java | 8 +- ...tingFirstInvoiceWebhookControllerTest.java | 6 +- ...tingFirstInvoicePaymentRepositoryTest.java | 4 +- ...ontrolUiAuthenticationGrpcServiceTest.java | 24 ++++++ .../AccountControlUiIssuanceWorkflowTest.java | 29 +++++++ ...HostingFirstInvoicePaymentServiceTest.java | 18 +++++ .../AccountControlUiAuthenticationClient.java | 50 ++++-------- ...ControlUiAuthenticationClientMtlsTest.java | 81 +++++++++++++++++++ 10 files changed, 196 insertions(+), 43 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcService.java index 1bab9ab103..cd2970b348 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcService.java @@ -78,7 +78,8 @@ public void authLogin(AuthLoginRequest wire, StreamObserver r } finally { Arrays.fill(compact, (byte) 0); } - } catch (AuthenticationException denied) { + } catch (AuthenticationException + | AccountControlUiIssuanceService.PermanentRecoveryDenialException denied) { response.onNext(AccountControlUiAuthenticationGrpcCodec.toResponse(request, null)); response.onCompleted(); } catch (AccountControlUiIssuanceService.IdempotencyConflictException conflict) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java index adb7b3145c..f8c543d619 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java @@ -325,15 +325,20 @@ private IssuedCredential issueInternal(Invocation request) { // Persist denial first; ambiguous/missing Redis evidence leaves REVOKING, never success. var failed = transaction.execute(ignored -> operations.beginRecoveryFailure(permanent.original)); - if (failed != null && "REVOKING".equals(failed.status)) { + if (failed == null) { + throw denied(); + } + if ("REVOKING".equals(failed.status)) { var receipt = registry.revoke(failed); transaction.execute( ignored -> { operations.finishRecoveryFailure(failed, receipt); return null; }); + } else if (!java.util.List.of("FAILED", "REVOKED").contains(failed.status)) { + throw denied(); } - throw denied(); + throw new PermanentRecoveryDenialException(); } finally { Arrays.fill(exactRequest, (byte) 0); } @@ -371,6 +376,13 @@ public IdempotencyConflictException() { } } + /** Signals a retained original credential that can no longer be recovered. */ + public static final class PermanentRecoveryDenialException extends RuntimeException { + public PermanentRecoveryDenialException() { + super("Control-ui original credential recovery is permanently denied"); + } + } + private Prepared current( AccountControlUiIssuanceRepository.Stored original, java.util.Optional environment) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoicePaymentService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoicePaymentService.java index f165a9ca40..d647149138 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoicePaymentService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoicePaymentService.java @@ -297,7 +297,13 @@ public Completion completeSigned(String payload, String signature) var candidate = transaction.execute(status -> payments.candidateForSignedEvent(event)); if (candidate == null) { var invoice = transaction.execute(status -> payments.unconsentedCanceledInvoice(event)); - if (invoice == null) return new Completion("IGNORED", null); + if (invoice == null) { + // A verified first-invoice success without local confirmation linkage may become + // correlatable after the local owner catches up. Keep Stripe delivery retryable instead + // of acknowledging an event that has only been retained as immutable intake. + return new Completion( + "payment_intent.succeeded".equals(event.eventType()) ? "RECONCILING" : "IGNORED", null); + } var observed = provider.observe(invoice); var outcome = Objects.requireNonNull( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceWebhookControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceWebhookControllerTest.java index 4e819479cd..afaba2ed7a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceWebhookControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceWebhookControllerTest.java @@ -65,12 +65,10 @@ void exactLateConflictClassificationIsAcknowledgedForOperatorReconciliation() th } @Test - void retainedButNonterminalCompletionIsNotAcknowledgedAsProcessed() throws Exception { + void unresolvedCompletionWithoutLocalRequestIdIsNotAcknowledgedAsProcessed() throws Exception { var payments = mock(AccountHostingFirstInvoicePaymentService.class); when(payments.completeSigned("{}", "t=1,v1=controlled")) - .thenReturn( - new AccountHostingFirstInvoicePaymentService.Completion( - "RECONCILING", UUID.randomUUID())); + .thenReturn(new AccountHostingFirstInvoicePaymentService.Completion("RECONCILING", null)); var result = new AccountHostingFirstInvoiceWebhookController(payments) .receive(request("{}".getBytes(StandardCharsets.UTF_8))); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingFirstInvoicePaymentRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingFirstInvoicePaymentRepositoryTest.java index 7f3977b841..2492f1b499 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingFirstInvoicePaymentRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingFirstInvoicePaymentRepositoryTest.java @@ -53,9 +53,9 @@ void ownerReadRecoversOnlyTheExactPreRowIdentityEvenAfterExpiryWithoutMutation() verify(f.dsl, never()).execute(anyString(), any(Object[].class)); f.fencePresent = false; assertThat(f.read()).isNull(); + + f.fencePresent = true; f.confirmation = UUID.randomUUID(); - f.version = 2; - f.commandClaimed = true; assertThat(f.read()).isNull(); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcServiceTest.java index 0929f3d591..702dd20fa7 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcServiceTest.java @@ -128,6 +128,30 @@ void primaryDenialIsAClosedResultAndNamespaceConflictNeverAuthenticates() { verifyNoInteractions(actors); } + @Test + void permanentRecoveryDenialIsAClosedLoginResult() { + var issuer = mock(AccountControlUiIssuanceService.class); + var actors = mock(AccountControlUiActorService.class); + when(issuer.issueAccount(any())) + .thenThrow(new AccountControlUiIssuanceService.PermanentRecoveryDenialException()); + var receiver = new AccountControlUiAuthenticationGrpcService(issuer, actors, "test"); + var request = request("test"); + var denied = new Result(); + + gateway() + .run( + () -> + receiver.authLogin( + AccountControlUiAuthenticationGrpcCodec.toRequest(request), denied)); + + assertThat(denied.failureCode).isNull(); + assertThat(denied.completed).isTrue(); + assertThat(denied.value.getStatusList()) + .containsExactly( + AccountControlUiAuthLoginStatus.ACCOUNT_CONTROL_UI_AUTH_LOGIN_STATUS_DENIED); + verifyNoInteractions(actors); + } + @Test void overlongSecretIsInvalidArgumentBeforeIssuance() { var issuer = mock(AccountControlUiIssuanceService.class); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java index 459a11e77a..9868b4c353 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java @@ -634,6 +634,35 @@ void expiredOriginalPersistsRevokingIntentBeforeUnavailableRegistryAndNeverRetur .seal(any(byte[].class), any(byte[].class), any(Instant.class)); } + @Test + void expiredOriginalReturnsPermanentDenialOnlyAfterRevocationIsRetained() { + Fixture fixture = new Fixture(NOW.minusSeconds(1)); + var original = fixture.existing(); + var revoking = fixture.stored("REVOKING", original.recoveryExpiry, original.tokenHash); + var receipt = mock(AccountControlUiCoordination.Receipt.class); + when(fixture.operations.beginRecoveryFailure(original)).thenReturn(revoking); + when(fixture.registry.revoke(revoking)).thenReturn(receipt); + + try (var ignored = fixture.withPeer(ISSUER)) { + assertThatThrownBy( + () -> + fixture + .service() + .issue( + fixture.request(fixture.tenant, fixture.context, "test-only-secret"), + fixture.environment)) + .isInstanceOf(AccountControlUiIssuanceService.PermanentRecoveryDenialException.class); + } + + var order = inOrder(fixture.operations, fixture.registry); + order.verify(fixture.operations).beginRecoveryFailure(original); + order.verify(fixture.registry).revoke(revoking); + order.verify(fixture.operations).finishRecoveryFailure(revoking, receipt); + verifyNoInteractions(fixture.primary, fixture.signers); + verify(fixture.cryptography, never()) + .open(any(byte[].class), any(byte[].class), any(Instant.class)); + } + private static AccountControlUiIssuanceRepository.Committed committed( AccountControlUiIssuanceRepository.Stored stored) throws Exception { var constructor = diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoicePaymentServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoicePaymentServiceTest.java index 3f05863759..5c682f4aba 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoicePaymentServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoicePaymentServiceTest.java @@ -184,6 +184,7 @@ void exactLatePaidConflictReplayNeverReadsProviderOrChangesLifecycle() throws Ex @Test void unrelatedSignedEventIsRetainedWithoutDispatchOrLifecycleWork() throws Exception { var event = mock(StripeHostingWebhookVerifier.VerifiedEvent.class); + when(event.eventType()).thenReturn("customer.updated"); when(verifier.verify("signed", "header")).thenReturn(event); assertThat(service.completeSigned("signed", "header")) @@ -194,6 +195,23 @@ void unrelatedSignedEventIsRetainedWithoutDispatchOrLifecycleWork() throws Excep verifyNoInteractions(provider, lifecycle, actors, reauthentication); } + @Test + void unmatchedVerifiedPaymentIntentSuccessRemainsRetryableWithoutLocalOperation() + throws Exception { + var event = mock(StripeHostingWebhookVerifier.VerifiedEvent.class); + when(event.eventType()).thenReturn("payment_intent.succeeded"); + when(verifier.verify("signed", "header")).thenReturn(event); + + assertThat(service.completeSigned("signed", "header")) + .isEqualTo(new AccountHostingFirstInvoicePaymentService.Completion("RECONCILING", null)); + + verify(inbox).retainOrReplay(event); + verify(payments).retainedSignedConflictRequestId(event); + verify(payments).candidateForSignedEvent(event); + verify(payments).unconsentedCanceledInvoice(event); + verifyNoInteractions(provider, lifecycle, actors, reauthentication); + } + @Test void verifiedUnconsentedLatePaymentRecordsOnlyOperatorConflict() throws Exception { var event = mock(StripeHostingWebhookVerifier.VerifiedEvent.class); diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/client/AccountControlUiAuthenticationClient.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/client/AccountControlUiAuthenticationClient.java index 1af223a273..10a8be0dfd 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/client/AccountControlUiAuthenticationClient.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/client/AccountControlUiAuthenticationClient.java @@ -8,6 +8,7 @@ import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; import net.firedevops.firemud.account.v1.AccountControlUiAuthenticationServiceGrpc; +import net.firedevops.firemud.account.v1.AuthLoginResponse; import net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec; import net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec.Request; import net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec.Result; @@ -27,8 +28,6 @@ public final class AccountControlUiAuthenticationClient private static final long CALL_DEADLINE_SECONDS = 5L; private final String workloadNamespace; - private volatile boolean initialized; - private volatile boolean closed; public AccountControlUiAuthenticationClient( ServiceEndpointsProperties endpoints, @@ -49,13 +48,8 @@ public AccountControlUiAuthenticationClient( /** Initializes only when the isolated receiving profile explicitly enables this client. */ public synchronized void init() throws SSLException, IOException { - if (closed) throw new IllegalStateException("Account authentication client is closed"); - if (initialized) return; - initReloadingClient(); - if (stub() == null) { - throw new IllegalStateException("Account authentication stub is unavailable"); - } - initialized = true; + initOnce( + "Account authentication client is closed", "Account authentication stub is unavailable"); } /** Sends one exact authentication request without a retry or credential-bearing diagnostics. */ @@ -65,12 +59,14 @@ public Result login(Request request) { throw new IllegalArgumentException("Control-UI caller namespace does not match Gateway"); } var wireRequest = AccountControlUiAuthenticationGrpcCodec.toRequest(request); + AuthLoginResponse wireResponse; try { - var wireResponse = - requireStub() - .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) - .authLogin(wireRequest); - return AccountControlUiAuthenticationGrpcCodec.requireResponse(request, wireResponse); + wireResponse = + withPublishedInitializedStub( + "Account authentication stub is unavailable", + stub -> + stub.withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .authLogin(wireRequest)); } catch (StatusRuntimeException unavailable) { if (unavailable.getStatus().getCode() == Status.Code.ALREADY_EXISTS) { throw new AuthenticationConflictException(); @@ -81,6 +77,13 @@ public Result login(Request request) { throw new AuthenticationUnavailableException(); } catch (IllegalArgumentException malformed) { throw new IllegalStateException("Account authentication response was invalid"); + } catch (IllegalStateException unavailable) { + throw new AuthenticationUnavailableException(); + } + try { + return AccountControlUiAuthenticationGrpcCodec.requireResponse(request, wireResponse); + } catch (IllegalArgumentException malformed) { + throw new IllegalStateException("Account authentication response was invalid"); } } @@ -107,25 +110,6 @@ protected String defaultTarget() { .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)); } - @Override - public void close() throws IOException { - synchronized (this) { - closed = true; - initialized = false; - } - super.close(); - } - - private AccountControlUiAuthenticationServiceGrpc - .AccountControlUiAuthenticationServiceBlockingStub - requireStub() { - var currentStub = stub(); - if (closed || !initialized || currentStub == null) { - throw new AuthenticationUnavailableException(); - } - return currentStub; - } - private static GrpcChannelFactory nonRetryingChannelFactory(GrpcChannelFactory delegate) { Objects.requireNonNull(delegate, "Account authentication requires a gRPC channel factory"); return new GrpcChannelFactory() { diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/client/AccountControlUiAuthenticationClientMtlsTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/client/AccountControlUiAuthenticationClientMtlsTest.java index e5eab6ef57..6f1d5d0b5a 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/client/AccountControlUiAuthenticationClientMtlsTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/client/AccountControlUiAuthenticationClientMtlsTest.java @@ -3,8 +3,13 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import io.grpc.ManagedChannel; import io.grpc.Server; import io.grpc.ServerInterceptors; import io.grpc.Status; @@ -16,6 +21,8 @@ import java.net.InetSocketAddress; import java.nio.file.Path; import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; @@ -164,6 +171,46 @@ void mapsRetainedRequestInputConflictWithoutForwardingGrpcErrorDetails() throws assertThat(observed.get()).isEqualTo(request()); } + @Test + void certificateReloadKeepsTheSelectedChannelUntilLoginReturns() throws Exception { + var observed = new AtomicReference(); + var peer = new AtomicReference(); + var entered = new CountDownLatch(1); + var release = new CountDownLatch(1); + AtomicInteger handlers = startServer("account-server", observed, peer, null, entered, release); + client = newClient(server.getPort()); + var selectedChannel = new AtomicReference(); + doAnswer( + call -> { + ManagedChannel built = (ManagedChannel) call.callRealMethod(); + selectedChannel.compareAndSet(null, built); + return built; + }) + .when(channelFactory) + .buildNonRetryingChannel( + anyString(), anyInt(), any(CommonGrpcClientProperties.class), anyBoolean()); + client.init(); + + try (var executor = Executors.newSingleThreadExecutor()) { + var result = executor.submit(() -> client.login(request())); + try { + assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); + ManagedChannel original = selectedChannel.get(); + assertThat(original).isNotNull(); + + reloadClientChannel(); + + assertThat(original.isShutdown()).isFalse(); + } finally { + release.countDown(); + } + + assertThat(result.get(5, TimeUnit.SECONDS).outcome()).isEqualTo(Outcome.SUCCESS); + assertThat(handlers).hasValue(1); + assertThat(selectedChannel.get().isShutdown()).isTrue(); + } + } + private AtomicInteger startServer( String serverIdentityAlias, AtomicReference observed, @@ -188,6 +235,17 @@ private AtomicInteger startServer( AtomicReference peer, Status.Code failureCode) throws Exception { + return startServer(serverIdentityAlias, observed, peer, failureCode, null, null); + } + + private AtomicInteger startServer( + String serverIdentityAlias, + AtomicReference observed, + AtomicReference peer, + Status.Code failureCode, + CountDownLatch entered, + CountDownLatch release) + throws Exception { var serverIdentity = pki.identity(serverIdentityAlias); AtomicInteger handlers = new AtomicInteger(); AccountControlUiAuthenticationServiceGrpc.AccountControlUiAuthenticationServiceImplBase @@ -202,6 +260,23 @@ public void authLogin( peer.set(GrpcPeerIdentity.current()); Request request = AccountControlUiAuthenticationGrpcCodec.parseRequest(wireRequest); observed.set(request); + if (entered != null) { + entered.countDown(); + try { + if (!release.await(10, TimeUnit.SECONDS)) { + responseObserver.onError( + Status.DEADLINE_EXCEEDED + .withDescription("Controlled test response timeout") + .asRuntimeException()); + return; + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + responseObserver.onError( + Status.CANCELLED.withCause(interrupted).asRuntimeException()); + return; + } + } if (failureCode != null) { responseObserver.onError( Status.fromCode(failureCode) @@ -230,6 +305,12 @@ public void authLogin( return handlers; } + private void reloadClientChannel() throws ReflectiveOperationException { + var reload = client.getClass().getSuperclass().getDeclaredMethod("reloadChannel"); + reload.setAccessible(true); + reload.invoke(client); + } + private AccountControlUiAuthenticationClient newClient(int port) throws Exception { var endpoints = new ServiceEndpointsProperties(); endpoints.setAccountService("localhost:" + port); From c486b62a6a09cb7a6a5c47d964a6fe171b0bebb9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 14 Nov 2026 09:39:43 +1300 Subject: [PATCH 24/29] Retry signed success only for exact retained first invoices --- .../account-service/runtime-and-data.md | 2 +- .../account-service/stripe-integration.md | 4 +- ...tHostingFirstInvoicePaymentRepository.java | 16 ++++++ ...ountHostingFirstInvoicePaymentService.java | 9 ++-- ...iptionDispatchPostgresIntegrationTest.java | 50 +++++++++++++++++++ ...HostingFirstInvoicePaymentServiceTest.java | 20 +++++++- 6 files changed, 91 insertions(+), 10 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index fbb147d6c6..f030b78ae5 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -432,7 +432,7 @@ V1003 preserves canonical predecessor SQL and retained owner rows; it never back ### First-invoice completion ownership -The [Stripe owner contract](./stripe-integration.md#first-invoice-confirmation-and-completion) owns the immutable provider-linked first invoice, explicit billing consent, signed success and separate completion journal. `provisioning`/`AWAITING_PAYMENT` is never positive runtime authority. The first authorizing receipt must carry exact signed paid-invoice fulfillment; its receipt, audit, billing outbox and tenant authority outbox commit atomically and require independent current-source readback. The webhook inbox remains immutable intake and is not a processing ledger. V1041 creates completion storage and guards without backfilling retained positive lifecycle rows; rows without exact first-payment and completion evidence remain unqualified. Forward V1046.1 refuses upgrade when any current `trialing`, `active`, `past_due` or `grace` subscription lacks its immutable first-invoice completion. It neither demotes the subscription nor synthesizes payment evidence. The migration takes a write-conflicting subscription-table lock before inspecting retained rows and installing a deferred final-row consistency trigger; positive state and its genuine completion can commit together, while later writers cannot commit a new gap. A blocked upgrade preserves existing rows and receipts and requires separately authorized evidence-preserving resolution before retry. Account V1047 remains the downstream control-ui replay-failure budget migration. The manually composed lifecycle owner provides a read-only, time-bounded prerequisite inspection; database failures and unresolved rows keep activation held. A clear inspection is only a snapshot: it does not fence concurrent writers, grant registration, reconstruct historical payment evidence or replace the remaining live-target qualification. See the [Stripe owner contract](./stripe-integration.md#first-invoice-confirmation-and-completion) and [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Retention, minimization, deletion, backup and source-custody registration holds continue to apply. +The [Stripe owner contract](./stripe-integration.md#first-invoice-confirmation-and-completion) owns the immutable provider-linked first invoice, explicit billing consent, signed success and separate completion journal. `provisioning`/`AWAITING_PAYMENT` is never positive runtime authority. The first authorizing receipt must carry exact signed paid-invoice fulfillment; its receipt, audit, billing outbox and tenant authority outbox commit atomically and require independent current-source readback. The webhook inbox remains immutable intake and is not a processing ledger. V1041 creates completion storage and guards without backfilling retained positive lifecycle rows; rows without exact first-payment and completion evidence remain unqualified. Forward V1046.1 refuses upgrade when any current `trialing`, `active`, `past_due` or `grace` subscription lacks its immutable first-invoice completion. It neither demotes the subscription nor synthesizes payment evidence. The migration takes a write-conflicting subscription-table lock before inspecting retained rows and installing a deferred final-row consistency trigger; positive state and its genuine completion can commit together, while later writers cannot commit a new gap. A blocked upgrade preserves existing rows and receipts and requires separately authorized evidence-preserving resolution before retry. Account V1047 remains the downstream control-ui replay-failure budget migration. The manually composed lifecycle owner provides a read-only, time-bounded prerequisite inspection; database failures and unresolved rows keep activation held. A clear inspection is only a snapshot: it does not fence concurrent writers, grant registration, reconstruct historical payment evidence or replace the remaining live-target qualification. See the [Stripe owner contract](./stripe-integration.md#first-invoice-confirmation-and-completion) and [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). The [real provider intake prerequisites](./stripe-integration.md#billing-owner-source-registration-prerequisites) govern retention, minimization, erasure, backup and source custody. The default-off controlled receiving fixture does not qualify real provider or customer intake. The local additive [V1043 candidate](../../../../services/account-service/src/main/resources/db/migration/V1043__hosting_first_invoice_operation_fence.sql) extends Account's existing recent-reauthentication evidence with all-or-none typed billing-context fields and a canonical digest, and adds the immutable per-subscription `subscription_first_invoice_operation_fences` owner table. The fence retains the original operation, Account, invoice tuple digest, expected subscription-row version, original invoice expiry, opening evidence identity and binding digest; older evidence remains unbackfilled and unchanged, with no authority inferred from a null context. The migration follows the verified V1042 frontier and preserves V1041/V1042. The [Stripe owner contract](./stripe-integration.md#durable-opening-proof-and-explicit-pre-row-renewal) owns behavior; the [API contract](./api-contracts.md#hosting-first-invoice-checkout) records only its wire consequences. diff --git a/design/architecture/microservices/account-service/stripe-integration.md b/design/architecture/microservices/account-service/stripe-integration.md index c33300702e..cdf2cbc2c4 100644 --- a/design/architecture/microservices/account-service/stripe-integration.md +++ b/design/architecture/microservices/account-service/stripe-integration.md @@ -19,7 +19,7 @@ The future direction in [ADR 0179](../../decisions/adr-0179-firemud-managed-crea ### Billing owner source registration prerequisites -The verified event inbox contains complete provider payloads that may contain personal data. Registering its intake requires a category-specific finite schedule and minimization/erasure behavior under [ADR 0050's canonical retention registry](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md#canonical-retention-registry), including permitted retention, access, legal holds, account deletion and backup treatment. [Account erasure](../../decisions/adr-0043-global-account-lifecycle-and-bounded-erasure-workflow.md) preserves only the authorized minimum billing evidence; account deletion must not blindly delete unresolved provider evidence. +The verified event inbox contains complete provider payloads that may contain personal data. Before enabling intake of real provider or customer data, Account requires a category-specific finite schedule and minimization/erasure behavior under [ADR 0050's canonical retention registry](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md#canonical-retention-registry), including permitted retention, access, legal holds, account deletion and backup treatment. [Account erasure](../../decisions/adr-0043-global-account-lifecycle-and-bounded-erasure-workflow.md) preserves only the authorized minimum billing evidence; account deletion must not blindly delete unresolved provider evidence. The current append-only inbox has no processing terminal, guarded payload minimization/erasure path or approved retention schedule. Production intake remains closed until those owner paths and their physical proof exist; the isolated receiving composition below does not qualify them. Its immutable raw-payload retention is an unresolved preparation boundary, not an indefinite production retention policy; no TTL or deletion bypass is inferred from this slice. @@ -52,7 +52,7 @@ The current commercial owner supports only an exact positive first-invoice amoun Payment requires genuine billing-purpose recent ordinary reauthentication and explicit owner consent for the retained tuple through the [owner API](./api-contracts.md#hosting-first-invoice-checkout). An append-only authorization attempt and independent readback precede provider work. Confirmation retrieves that invoice and intent first, then atomically claims the operation's single durable command permission under current owner, reauthentication, policy, subscription-row and authorization-version fences before confirming the existing unconfirmed intent with the selected method and original retained idempotency key. The owner-only Stripe.js next-action handoff is disclosed only within the current authorization window. No provider charge is dispatched by provisioning. Customer defaults, default sources, new PaymentIntents and Checkout Sessions are prohibited. The held first-invoice composition uses a dedicated Stripe transport with a two-second connection timeout, a five-second whole-response deadline and bounded JSON body consumption. A deadline cancels the exchange and leaves any claimed command outcome uncertain under the original identity. -Only a verified signed `payment_intent.succeeded` event, matched to the exact retained customer/method/amount/amount-received/currency/mode and independently re-read paid invoice/intent, may supply first-payment evidence. `invoice.paid` alone, an active subscription fixture, a browser callback or a client-supplied success flag is insufficient. The immutable webhook inbox remains intake only. Separate append-only success and completion journals retain the tuple, original consent, event digest and exact lifecycle receipt identity; processing never mutates the inbox or treats its `PENDING` marker as a completion flag. +Only a verified signed `payment_intent.succeeded` event, matched to the exact retained customer/method/amount/amount-received/currency/mode and independently re-read paid invoice/intent, may supply first-payment evidence. `invoice.paid` alone, an active subscription fixture, a browser callback or a client-supplied success flag is insufficient. The immutable webhook inbox remains intake only. The supported confirmation path retains the exact invoice and PaymentIntent binding before consent can authorize a charge. A signed success without a retained first-invoice binding stays in intake and does not enter first-invoice completion. An exact retained first-invoice success with pending confirmation linkage remains retryable under the same event identity. Separate append-only success and completion journals retain the tuple, original consent, event digest and exact lifecycle receipt identity; processing never mutates the inbox or treats its `PENDING` marker as a completion flag. The Account lifecycle transaction atomically commits the exact completion, hosting receipt, audit/observation evidence, billing sequence/outbox and tenant authority-generation/outbox. Independent receipt/current-source and completion-journal reads follow commit. A lost provider response or local commit failure remains on the same operation. An exact owner retry is read-only and cannot send another confirmation; if the intent still requires confirmation, it reports `AUTHORIZED_NOT_CONFIRMED`. Recovery of that held outcome or expired client-secret disclosure requires a separately explicit fresh primary reauthentication and unchanged charge consent. Its distinct authorization request is append-only and compare-and-set against the current authorization version on the original payment operation. It preserves the original invoice, PaymentIntent, subscription, instrument, quote, amount/currency, provider idempotency key, lifecycle and audit identities. The new attempt supersedes older disclosure/command permissions without rewriting the original consent. It may recover a crash before any durable command claim, but it cannot repeat an already claimed command, even if the provider still reports `requires_confirmation`. A crash or ambiguous commit after that claim remains nonterminal and read-only until exact provider evidence or audited remediation resolves it. The same fresh authorization may redisclose the existing intent's `requires_action` secret; it does not create or confirm another intent. Authorization expiry never extends the original incomplete-subscription expiry. Read-only reconciliation and authorization expiry follow [ADR 0045's authorization-linearization contract](../../decisions/adr-0045-ordinary-login-factors-and-https-sensitive-action-step-up.md#handoff-authorization-linearization); neither a delayed event nor an expired handoff permits a new charge or changed tuple. A paid-but-unfulfilled result remains non-authorizing until that exact atomic fulfillment succeeds or audited remediation resolves it. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingFirstInvoicePaymentRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingFirstInvoicePaymentRepository.java index 26e5d57373..1e78745a0c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingFirstInvoicePaymentRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingFirstInvoicePaymentRepository.java @@ -768,6 +768,22 @@ public ConfirmationDispatch candidateForSignedEvent(VerifiedEvent verified) { return dispatch(row, invoice, false, false); } + /** Verifies retained first-invoice linkage without establishing consent or payment authority. */ + public boolean hasSignedFirstInvoiceLinkage(VerifiedEvent verified) { + transaction(); + if (!"payment_intent.succeeded".equals(verified.eventType())) return false; + String intent = + JSON.readTree(verified.rawPayload()).path("data").path("object").path("id").asText(); + Record row = + dsl.fetchOne( + "SELECT subscription_id, captured_at FROM subscription_first_invoices WHERE payment_intent_id = ?", + intent); + if (row == null) return false; + var invoice = Objects.requireNonNull(find(row.get("subscription_id", UUID.class))); + requireSignedTuple(verified, instant(row, "captured_at"), invoice); + return true; + } + public UUID retainedSignedConflictRequestId(VerifiedEvent verified) { transaction(); return new AccountHostingFirstInvoicePaymentConflictRepository(dsl) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoicePaymentService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoicePaymentService.java index d647149138..7339a6d056 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoicePaymentService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoicePaymentService.java @@ -298,11 +298,10 @@ public Completion completeSigned(String payload, String signature) if (candidate == null) { var invoice = transaction.execute(status -> payments.unconsentedCanceledInvoice(event)); if (invoice == null) { - // A verified first-invoice success without local confirmation linkage may become - // correlatable after the local owner catches up. Keep Stripe delivery retryable instead - // of acknowledging an event that has only been retained as immutable intake. - return new Completion( - "payment_intent.succeeded".equals(event.eventType()) ? "RECONCILING" : "IGNORED", null); + boolean linked = + Boolean.TRUE.equals( + transaction.execute(status -> payments.hasSignedFirstInvoiceLinkage(event))); + return new Completion(linked ? "RECONCILING" : "IGNORED", null); } var observed = provider.observe(invoice); var outcome = diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java index c154ef624c..0bd6376e9a 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java @@ -41,6 +41,9 @@ import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.FenceRejectedException; import net.firedevops.firemud.accountservice.service.AccountHostingSubscriptionProvisioningService; import net.firedevops.firemud.accountservice.service.StripeWebhookIntakeService; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiActorService; +import net.firedevops.firemud.accountservice.service.session.AccountHostingFirstInvoicePaymentService; +import net.firedevops.firemud.accountservice.service.session.AccountRecentReauthenticationService; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; @@ -75,6 +78,53 @@ class AccountHostingSubscriptionDispatchPostgresIntegrationTest { private static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @Test + void signedSuccessRetriesOnlyWhenItMatchesTheRetainedFirstInvoice() throws Exception { + var source = unpaidCancellationDataSource(null); + var hosting = CanonicalHostingSubscriptionTestFixture.create(source); + var checkout = hosting.awaitFirstInvoice(); + var payments = + new AccountHostingFirstInvoicePaymentService( + mock(AccountControlUiActorService.class), + mock(AccountRecentReauthenticationService.class), + hosting.firstInvoiceRepository(), + new StripeEventInboxRepository(hosting.dsl()), + checkout.provider(), + checkout.verifier(), + hosting.service(), + new DataSourceTransactionManager(source)); + + var invoicesBefore = + hosting.dsl().fetch("SELECT *, xmin::text FROM subscription_first_invoices"); + var linked = checkout.signedSuccess(); + assertThat(payments.completeSigned(linked.payload(), linked.signature()).state()) + .isEqualTo("RECONCILING"); + + String unrelatedPayload = + linked + .payload() + .replace(checkout.invoice().paymentIntentId(), "pi_unrelated") + .replace("evt_" + checkout.invoice().paymentIntentId().substring(3), "evt_unrelated"); + var unrelated = checkout.signWebhookPayload(unrelatedPayload); + assertThat(payments.completeSigned(unrelated.payload(), unrelated.signature()).state()) + .isEqualTo("IGNORED"); + + assertThat( + hosting + .dsl() + .fetch("SELECT raw_payload FROM stripe_event_inbox") + .getValues("raw_payload", byte[].class)) + .extracting(bytes -> new String(bytes, StandardCharsets.UTF_8)) + .containsExactlyInAnyOrder(linked.payload(), unrelated.payload()); + assertThat(hosting.dsl().fetch("SELECT *, xmin::text FROM subscription_first_invoices")) + .isEqualTo(invoicesBefore); + assertThat(hosting.firstInvoiceConfirmations()).isZero(); + assertThat(hosting.dsl().fetchCount(DSL.table("subscription_first_invoice_success_evidence"))) + .isZero(); + assertThat(hosting.dsl().fetchCount(DSL.table("subscription_first_invoice_completions"))) + .isZero(); + } + @ParameterizedTest @ValueSource(booleans = {false, true}) void firstRetainedExactSignedSuccessBlocksBothUnpaidCancellationPaths(boolean claimed) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoicePaymentServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoicePaymentServiceTest.java index 5c682f4aba..61788df42f 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoicePaymentServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoicePaymentServiceTest.java @@ -196,11 +196,11 @@ void unrelatedSignedEventIsRetainedWithoutDispatchOrLifecycleWork() throws Excep } @Test - void unmatchedVerifiedPaymentIntentSuccessRemainsRetryableWithoutLocalOperation() - throws Exception { + void linkedFirstInvoiceSuccessRemainsRetryableWithoutLocalConfirmation() throws Exception { var event = mock(StripeHostingWebhookVerifier.VerifiedEvent.class); when(event.eventType()).thenReturn("payment_intent.succeeded"); when(verifier.verify("signed", "header")).thenReturn(event); + when(payments.hasSignedFirstInvoiceLinkage(event)).thenReturn(true); assertThat(service.completeSigned("signed", "header")) .isEqualTo(new AccountHostingFirstInvoicePaymentService.Completion("RECONCILING", null)); @@ -209,6 +209,22 @@ void unmatchedVerifiedPaymentIntentSuccessRemainsRetryableWithoutLocalOperation( verify(payments).retainedSignedConflictRequestId(event); verify(payments).candidateForSignedEvent(event); verify(payments).unconsentedCanceledInvoice(event); + verify(payments).hasSignedFirstInvoiceLinkage(event); + verifyNoInteractions(provider, lifecycle, actors, reauthentication); + } + + @Test + void unrelatedPaymentIntentSuccessIsRetainedAndAcknowledged() throws Exception { + var event = mock(StripeHostingWebhookVerifier.VerifiedEvent.class); + when(event.eventType()).thenReturn("payment_intent.succeeded"); + when(verifier.verify("signed", "header")).thenReturn(event); + when(payments.hasSignedFirstInvoiceLinkage(event)).thenReturn(false); + + assertThat(service.completeSigned("signed", "header")) + .isEqualTo(new AccountHostingFirstInvoicePaymentService.Completion("IGNORED", null)); + + verify(inbox).retainOrReplay(event); + verify(payments).hasSignedFirstInvoiceLinkage(event); verifyNoInteractions(provider, lifecycle, actors, reauthentication); } From 41da5252fd5ff7baacaa2fa19d80dff2c72d8b37 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 14 Nov 2026 10:26:52 +1300 Subject: [PATCH 25/29] Prove overlapping Account billing verification and exact rollback --- ...tpsCompositionPostgresIntegrationTest.java | 347 ++++++++++++++++++ 1 file changed, 347 insertions(+) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoiceHttpsCompositionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoiceHttpsCompositionPostgresIntegrationTest.java index 8e823ba3bb..c20b71171a 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoiceHttpsCompositionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoiceHttpsCompositionPostgresIntegrationTest.java @@ -2,7 +2,15 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; +import de.mkammerer.argon2.Argon2; +import de.mkammerer.argon2.Argon2Factory; import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture; import java.net.URI; import java.net.http.HttpClient; @@ -11,14 +19,18 @@ import java.nio.file.Files; import java.nio.file.Path; import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import javax.net.ssl.SSLContext; import net.firedevops.firemud.accountservice.controller.AccountHostingFirstInvoiceController; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; @@ -29,8 +41,10 @@ import org.apache.coyote.http11.AbstractHttp11Protocol; import org.apache.tomcat.util.net.SSLHostConfig; import org.apache.tomcat.util.net.SSLHostConfigCertificate; +import org.jooq.Record; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.mockito.MockedStatic; import org.springframework.context.annotation.Configuration; import org.springframework.web.context.support.GenericWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; @@ -100,6 +114,227 @@ class AccountHostingFirstInvoiceHttpsCompositionPostgresIntegrationTest { @TempDir Path temporary; + @Test + void billingReauthenticationDoesNotHoldIssuerSourceAcrossOtpVerificationAndRollsBackBindFailure() + throws Exception { + try (var owners = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary)) { + var first = owners.issueCertifiedAccount(PASSWORD); + var second = owners.issueCertifiedAccount(PASSWORD); + var dataSource = Objects.requireNonNull(first.sources().manager.getDataSource()); + var firstHosting = + CanonicalHostingSubscriptionTestFixture.createAwaitingPayment( + dataSource, first.account()); + var secondHosting = + CanonicalHostingSubscriptionTestFixture.createAwaitingPayment( + dataSource, second.account()); + var reauthentication = + new AccountRecentReauthenticationService( + first.sources().primary, + first.sources().accounts, + new AccountAuthorityGenerationRepository(firstHosting.dsl()), + new AccountRecentReauthenticationRepository(firstHosting.dsl()), + new AccountRecentReauthenticationPolicyRepository(firstHosting.dsl()), + first.sources().manager, + firstHosting.clock(), + new AccountControlUiResponseCryptography( + new AccountControlUiKeyring(temporary.resolve("custody")), firstHosting.clock())); + var payments = + new AccountHostingFirstInvoicePaymentService( + first.actors(), + reauthentication, + firstHosting.firstInvoiceRepository(), + new StripeEventInboxRepository(firstHosting.dsl()), + firstHosting.firstInvoiceProvider(), + firstHosting.webhookVerifier(), + firstHosting.service(), + first.sources().manager); + + // The second issuance must not make the first Account actor stale; both are current inputs + // to the same billing owner and share the Account ISSUER producer source. + assertThat(first.actors().authenticateAccount(first.compact()).accountId()) + .isEqualTo(first.account().getAccountUuid()); + assertThat(second.actors().authenticateAccount(second.compact()).accountId()) + .isEqualTo(second.account().getAccountUuid()); + first.sources().installGlobalOtp(first.account(), "test-only-paused-billing-otp"); + var firstTuple = + payments.describeOwner(first.compact(), firstHosting.creation().subscriptionId()); + var secondTuple = + payments.describeOwner(second.compact(), secondHosting.creation().subscriptionId()); + UUID firstReauthenticationRequest = UUID.randomUUID(); + UUID firstAuthorizationRequest = UUID.randomUUID(); + UUID secondReauthenticationRequest = UUID.randomUUID(); + UUID secondAuthorizationRequest = UUID.randomUUID(); + String otpBefore = otpRowImage(firstHosting, first.account().getId()); + Map firstBillingBefore = + firstInvoiceRowImages(firstHosting, firstTuple.subscriptionId()); + + firstHosting + .dsl() + .execute( + "CREATE FUNCTION fixture_refuse_paused_reauthentication_binding() RETURNS trigger " + + "LANGUAGE plpgsql AS $$ BEGIN IF NEW.subscription_id = '" + + firstTuple.subscriptionId() + + "'::uuid THEN RAISE EXCEPTION 'controlled paused billing reauthentication bind rollback' " + + "USING ERRCODE = '23514'; END IF; RETURN NEW; END; $$"); + firstHosting + .dsl() + .execute( + "CREATE TRIGGER fixture_refuse_paused_reauthentication_binding BEFORE INSERT " + + "ON subscription_first_invoice_operation_fences FOR EACH ROW " + + "EXECUTE FUNCTION fixture_refuse_paused_reauthentication_binding()"); + CountDownLatch verificationPaused = new CountDownLatch(1); + CountDownLatch releaseVerification = new CountDownLatch(1); + try (var requestExecutor = Executors.newSingleThreadExecutor()) { + var firstAttempt = + requestExecutor.submit( + () -> + reauthenticateWithPausedFirstVerification( + payments, + first, + firstTuple, + firstReauthenticationRequest, + firstAuthorizationRequest, + "test-only-paused-billing-otp", + verificationPaused, + releaseVerification)); + try { + assertThat(verificationPaused.await(30, TimeUnit.SECONDS)).isTrue(); + + // The existing HTTPS test exercises the registered controller route. This direct owner + // call gives deterministic control over the KDF worker: Account 2 must finish while + // Account 1's primary-auth path is stopped inside Argon2. Under the old order, Account 1 + // retains the shared ISSUER lock and this call refuses at NOWAIT. + UUID secondEvidence = + reauthenticateInitialInvoice( + payments, + second, + secondTuple, + secondReauthenticationRequest, + secondAuthorizationRequest, + PASSWORD); + assertThat(secondEvidence).isNotNull(); + assertThat( + firstHosting + .dsl() + .fetchSingle( + "SELECT account_uuid, reauthentication_evidence_id FROM " + + "subscription_first_invoice_operation_fences WHERE subscription_id = ?", + secondTuple.subscriptionId()) + .get("account_uuid", UUID.class)) + .isEqualTo(second.account().getAccountUuid()); + assertThat( + firstHosting + .dsl() + .fetchSingle( + "SELECT reauthentication_evidence_id FROM " + + "subscription_first_invoice_operation_fences WHERE subscription_id = ?", + secondTuple.subscriptionId()) + .get("reauthentication_evidence_id", UUID.class)) + .isEqualTo(secondEvidence); + } finally { + releaseVerification.countDown(); + } + + assertThatThrownBy(() -> firstAttempt.get(60, TimeUnit.SECONDS)) + .isInstanceOf(ExecutionException.class) + .satisfies( + failure -> + assertThat(throwableMessages(failure)) + .contains("controlled paused billing reauthentication bind rollback")); + } finally { + firstHosting + .dsl() + .execute( + "DROP TRIGGER fixture_refuse_paused_reauthentication_binding " + + "ON subscription_first_invoice_operation_fences"); + firstHosting + .dsl() + .execute("DROP FUNCTION fixture_refuse_paused_reauthentication_binding()"); + } + + assertThat(otpRowImage(firstHosting, first.account().getId())).isEqualTo(otpBefore); + assertThat(firstInvoiceRowImages(firstHosting, firstTuple.subscriptionId())) + .isEqualTo(firstBillingBefore); + assertThat( + firstHosting + .dsl() + .fetchSingle( + "SELECT count(*) FROM account_recent_reauthentication_evidence WHERE request_id = ?", + firstReauthenticationRequest) + .get(0, Long.class)) + .isZero(); + assertThat( + firstHosting + .dsl() + .fetchSingle( + "SELECT count(*) FROM account_recent_reauthentication_replay_credentials " + + "WHERE request_id = ?", + firstReauthenticationRequest) + .get(0, Long.class)) + .isZero(); + assertThat( + firstHosting + .dsl() + .fetchSingle( + "SELECT count(*) FROM account_recent_reauthentication_consumptions " + + "WHERE creation_operation_id = ?", + firstAuthorizationRequest) + .get(0, Long.class)) + .isZero(); + assertThat( + firstHosting + .dsl() + .fetchSingle( + "SELECT count(*) FROM subscription_first_invoice_operation_fences " + + "WHERE subscription_id = ?", + firstTuple.subscriptionId()) + .get(0, Long.class)) + .isZero(); + assertThat( + firstHosting + .dsl() + .fetchSingle( + "SELECT evidence.xmin::text AS evidence_xmin, proof.xmin::text AS proof_xmin, " + + "fence.xmin::text AS fence_xmin, evidence.billing_context_digest, " + + "fence.binding_digest FROM account_recent_reauthentication_evidence evidence " + + "JOIN account_recent_reauthentication_replay_credentials proof " + + "ON proof.evidence_id = evidence.evidence_id " + + "JOIN subscription_first_invoice_operation_fences fence " + + "ON fence.reauthentication_evidence_id = evidence.evidence_id " + + "WHERE evidence.evidence_id = ?", + firstHosting + .dsl() + .fetchSingle( + "SELECT reauthentication_evidence_id FROM " + + "subscription_first_invoice_operation_fences WHERE subscription_id = ?", + secondTuple.subscriptionId()) + .get("reauthentication_evidence_id", UUID.class))) + .satisfies( + row -> { + assertThat(row.get("evidence_xmin", String.class)) + .isEqualTo(row.get("proof_xmin", String.class)) + .isEqualTo(row.get("fence_xmin", String.class)); + assertThat(row.get("billing_context_digest", String.class)) + .isEqualTo(row.get("binding_digest", String.class)); + }); + assertThat( + firstHosting + .dsl() + .fetchSingle( + "SELECT count(*) FROM account_recent_reauthentication_evidence WHERE request_id = ?", + secondReauthenticationRequest) + .get(0, Long.class)) + .isOne(); + } + } + @Test void actualHttpsOwnerConsentScaAndExactSignedCompletionGrantAuthorityOnlyAfterReadback() throws Exception { @@ -962,6 +1197,118 @@ CREATE FUNCTION fixture_refuse_opening_fence() RETURNS trigger LANGUAGE plpgsql } } + private static UUID reauthenticateInitialInvoice( + AccountHostingFirstInvoicePaymentService payments, + AccountControlUiOriginalOrderFixture.IssuedAccount issued, + AccountHostingFirstInvoicePaymentService.OwnerView tuple, + UUID reauthenticationRequestId, + UUID authorizationRequestId, + String secret) { + return payments.reauthenticate( + issued.compact(), + tuple.subscriptionId(), + reauthenticationRequestId, + authorizationRequestId, + authorizationRequestId, + tuple.expectedRowVersion(), + tuple.authorizationVersion(), + tuple.tupleDigest(), + tuple.expiresAt(), + AccountRecentReauthenticationEvidence.BillingAuthorizationPurpose.INITIAL_CONFIRMATION, + issued.account().getEmail(), + secret); + } + + /** Runs the real service call on one controlled worker with a thread-local Argon2 pause. */ + private static UUID reauthenticateWithPausedFirstVerification( + AccountHostingFirstInvoicePaymentService payments, + AccountControlUiOriginalOrderFixture.IssuedAccount issued, + AccountHostingFirstInvoicePaymentService.OwnerView tuple, + UUID reauthenticationRequestId, + UUID authorizationRequestId, + String secret, + CountDownLatch verificationPaused, + CountDownLatch releaseVerification) { + Argon2 delegate = Argon2Factory.create(); + Argon2 controlled = mock(Argon2.class); + AtomicBoolean pauseFirstVerification = new AtomicBoolean(true); + when(controlled.verify(anyString(), any(char[].class))) + .thenAnswer( + invocation -> { + if (pauseFirstVerification.compareAndSet(true, false)) { + verificationPaused.countDown(); + if (!releaseVerification.await(60, TimeUnit.SECONDS)) { + throw new IllegalStateException( + "Paused Account Argon2 verification was not released"); + } + } + return delegate.verify(invocation.getArgument(0), invocation.getArgument(1)); + }); + doAnswer( + invocation -> { + delegate.wipeArray(invocation.getArgument(0)); + return null; + }) + .when(controlled) + .wipeArray(any(char[].class)); + try (MockedStatic factory = mockStatic(Argon2Factory.class)) { + factory.when(Argon2Factory::create).thenReturn(controlled); + return reauthenticateInitialInvoice( + payments, issued, tuple, reauthenticationRequestId, authorizationRequestId, secret); + } + } + + private static String otpRowImage( + CanonicalHostingSubscriptionTestFixture.Fixture hosting, Long accountId) { + Record row = + hosting + .dsl() + .fetchOne( + "SELECT to_jsonb(challenge)::text AS row_image, challenge.xmin::text AS row_xmin " + + "FROM account_email_login_challenge challenge WHERE account_id = ?", + accountId); + return row == null + ? "" + : row.get("row_image", String.class) + "\n" + row.get("row_xmin", String.class); + } + + private static Map firstInvoiceRowImages( + CanonicalHostingSubscriptionTestFixture.Fixture hosting, UUID subscriptionId) { + Map images = new LinkedHashMap<>(); + for (String table : + List.of( + "subscription_first_invoices", + "subscription_first_invoice_operation_fences", + "subscription_first_invoice_confirmations", + "subscription_first_invoice_authorizations", + "subscription_first_invoice_dispatches", + "subscription_first_invoice_command_claims")) { + Record row = + hosting + .dsl() + .fetchOne( + "SELECT to_jsonb(billing_row)::text AS row_image, billing_row.xmin::text AS row_xmin " + + "FROM " + + table + + " billing_row WHERE subscription_id = ?", + subscriptionId); + images.put( + table, + row == null + ? "" + : row.get("row_image", String.class) + "\n" + row.get("row_xmin", String.class)); + } + return Map.copyOf(images); + } + + private static String throwableMessages(Throwable failure) { + StringBuilder messages = new StringBuilder(); + for (Throwable current = failure; current != null; current = current.getCause()) { + if (current.getMessage() != null) messages.append(current.getMessage()).append('\n'); + } + return messages.toString(); + } + private static long consumptionCount( CanonicalHostingSubscriptionTestFixture.Fixture hosting, UUID evidenceId) { return hosting From 442b94f43d162c75552212c9eeef468399404b35 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 14 Nov 2026 18:41:48 +1300 Subject: [PATCH 26/29] Fix Account authority responses and Gateway login schema --- services/account-service/src/main/resources/openapi.yaml | 4 ++++ services/spring-cloud-gateway/src/main/resources/openapi.yaml | 2 ++ 2 files changed, 6 insertions(+) diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index 9e2f789e81..1ed7b8e596 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -401,6 +401,7 @@ paths: authorizationVersion: {type: integer, format: int64, minimum: 0} '401': {description: Protected current control-ui owner authentication required} '409': {description: Exact evidence refused; prior provider outcome may remain uncertain} + '503': {description: AUTH_UNAVAILABLE; Account authentication authority is temporarily unavailable} /billing/hosting/subscriptions/{subscriptionId}/first-invoice/reauthenticate: parameters: - name: subscriptionId @@ -450,6 +451,7 @@ paths: '401': {description: Current owner authentication or ordinary secret refused} '409': description: Fresh unbound billing request without evidence creation, exact binding refused, or exact current evidence unavailable + '503': {description: AUTH_UNAVAILABLE; Account authentication authority is temporarily unavailable} /billing/hosting/subscriptions/{subscriptionId}/first-invoice/confirm: parameters: - name: subscriptionId @@ -490,6 +492,7 @@ paths: '401': {description: Protected current control-ui owner authentication required} '409': {description: Exact evidence refused; preserve the original operation and uncertain outcome} '502': {description: FIRST_INVOICE_PROVIDER_UNCERTAIN; preserve original operation and poll status} + '503': {description: AUTH_UNAVAILABLE; Account authentication authority is temporarily unavailable} /billing/hosting/subscriptions/{subscriptionId}/first-invoice/renew: parameters: - name: subscriptionId @@ -532,6 +535,7 @@ paths: '401': {description: Protected current control-ui owner authentication required} '409': {description: Exact evidence refused; preserve the original operation and uncertain outcome} '502': {description: FIRST_INVOICE_PROVIDER_UNCERTAIN; preserve original operation and poll status} + '503': {description: AUTH_UNAVAILABLE; Account authentication authority is temporarily unavailable} /ping: get: summary: Health check endpoint diff --git a/services/spring-cloud-gateway/src/main/resources/openapi.yaml b/services/spring-cloud-gateway/src/main/resources/openapi.yaml index 4bd6f8a815..6ab3436a33 100644 --- a/services/spring-cloud-gateway/src/main/resources/openapi.yaml +++ b/services/spring-cloud-gateway/src/main/resources/openapi.yaml @@ -65,11 +65,13 @@ paths: application/json: schema: type: object + additionalProperties: false required: [status, data] properties: status: {type: string, enum: [SUCCESS]} data: type: object + additionalProperties: false required: [accountId, authToken, expiresAt] properties: accountId: {type: string, format: uuid} From 9a0716a2d0807112e8dc48051f05e92639102e8a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 15 Nov 2026 02:23:04 +1300 Subject: [PATCH 27/29] docs(authz): distinguish retained first-invoice reads from mutations --- .../system-architecture-authz-route-matrix.md | 6 +- ...ystem-architecture-authz-route-matrix.yaml | 5 +- .../validation/check-authz-route-matrix.py | 19 ++++-- .../test_check_authz_route_matrix.py | 58 ++++++++++++++----- 4 files changed, 64 insertions(+), 24 deletions(-) diff --git a/design/architecture/system-architecture-authz-route-matrix.md b/design/architecture/system-architecture-authz-route-matrix.md index 29fbe98bec..d57c17e912 100644 --- a/design/architecture/system-architecture-authz-route-matrix.md +++ b/design/architecture/system-architecture-authz-route-matrix.md @@ -298,4 +298,8 @@ The matrix should be expanded as service API surfaces evolve. Service docs may i The four prepared HTTPS owner routes `GET /billing/hosting/subscriptions/{subscriptionId}/first-invoice`, `POST .../reauthenticate` `POST .../confirm` and `POST .../renew` are `account_scoped`, bound to the exact current subscription billing owner and selected Account instrument, rather than a tenant-admin role. They preserve billing recovery when gameplay is unavailable and confer no tenant or gameplay authority. The [Account API contract](./microservices/account-service/api-contracts.md#hosting-first-invoice-checkout) owns request, explicit consent and no-store client-secret semantics. The explicit isolated receiving composition registers these four exact handlers while production remains closed; their production matrix status stays `target_not_currently_routable` and activation gates remain held. Its login RPC accepts only the certificate-derived same-namespace Gateway peer, and its separate signed webhook adapter accepts provider signature authority rather than an end-user token. -These routes require two distinct Account-owned live checks. `current_subscription_owner` re-reads the exact subscription's current billing owner and requires it to match the authenticated Account subject. `exact_reserved_instrument` re-reads the Account instrument reserved for that first invoice and requires the same instrument identity and reserved version; a customer default or replacement is not a substitute. These checks are not gameplay `binding_ownership` or the weaker payment-instrument `explicit_per_subscription_binding`. The existing matrix validator requires both checks on each of the four held routes, with focused regression vectors for every route/check pair. +All four routes retain the live `issuer_generation`, `account_generation` and `current_subscription_owner` checks. The owner check re-reads the exact subscription's current billing owner and requires it to match the authenticated Account subject; a retained invoice never authorizes a previous owner. + +The read-only GET uses `retained_first_invoice_binding`: Account verifies the exact original invoice, subscription, owner/customer/instrument identity and immutable reserved version against retained creation and reservation evidence. It does not require the current wallet row version to equal the original reserved version or the instrument to remain attachable. A released reservation is accepted only for the current canceled subscription with the matching retained terminal-resolution identity. This lets the current owner read `CANCELED` after unpaid cancellation and later instrument unavailability/version advancement, without substituting a default/replacement instrument, reopening payment or granting mutation authority. Missing or contradictory retained evidence remains a refusal. + +The three POST routes retain `exact_reserved_instrument` and their existing purpose-bound reauthentication, exact consent and command fences. They cannot use the GET's retained-read contract to authorize new provider work. These checks are not gameplay `binding_ownership` or the weaker payment-instrument `explicit_per_subscription_binding`. The matrix validator enforces common live identity/owner checks and the distinct GET/POST binding contracts while all four routes remain held. diff --git a/design/architecture/system-architecture-authz-route-matrix.yaml b/design/architecture/system-architecture-authz-route-matrix.yaml index 13aca1cabb..7a1b6e6c88 100644 --- a/design/architecture/system-architecture-authz-route-matrix.yaml +++ b/design/architecture/system-architecture-authz-route-matrix.yaml @@ -348,6 +348,7 @@ required_live_check_vocabulary: # Account-owned first-invoice recovery re-reads the exact subscription owner and held instrument. - current_subscription_owner - exact_reserved_instrument + - retained_first_invoice_binding - current_account_roles - current_automation_policy - current_global_role @@ -3245,8 +3246,8 @@ routes: subject_binding: authenticated_current_subscription_billing_owner tenant_billing_authority_generation_applies: false membership_authority_generation_applies: false - required_live_checks: [issuer_generation, account_generation, current_subscription_owner, exact_reserved_instrument] - mutation_contract: current_owner_exact_subscription_and_instrument + required_live_checks: [issuer_generation, account_generation, current_subscription_owner, retained_first_invoice_binding] + mutation_contract: current_owner_read_only_exact_retained_invoice_and_reservation implementation_status: known_drift: - Owner controller is registered only in explicit isolated receiving; production provider, retention, deletion, backup and custody activation gates remain held. diff --git a/dev-tools/validation/check-authz-route-matrix.py b/dev-tools/validation/check-authz-route-matrix.py index ecb260e1f2..23e54d2e2b 100644 --- a/dev-tools/validation/check-authz-route-matrix.py +++ b/dev-tools/validation/check-authz-route-matrix.py @@ -146,7 +146,6 @@ "issuer_generation", "account_generation", "current_subscription_owner", - "exact_reserved_instrument", } REQUIRED_FIELD_PATTERN = re.compile(r"^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$") ROUTE_STATUS_VALUES = { @@ -5489,16 +5488,26 @@ def validate_first_invoice_routes( continue label = f"account-service {route_name}" if route.get("route_status") != "target_not_currently_routable": - append_unique_error( - errors, f"{label} must remain target_not_currently_routable" - ) + append_unique_error(errors, f"{label} must remain target_not_currently_routable") checks = route_live_checks(route, label, errors, live_checks_cache) - missing = sorted(FIRST_INVOICE_REQUIRED_LIVE_CHECKS - checks) + is_read = route_name == FIRST_INVOICE_ROUTES[0] + binding_check = "retained_first_invoice_binding" if is_read else "exact_reserved_instrument" + required = FIRST_INVOICE_REQUIRED_LIVE_CHECKS | {binding_check} + missing = sorted(required - checks) if missing: append_unique_error( errors, f"{label} is missing required first-invoice live checks: {missing}", ) + if is_read and "exact_reserved_instrument" in checks: + append_unique_error(errors, f"{label} must use retained read binding, not live instrument eligibility") + if ( + is_read + and route.get("mutation_contract") != "current_owner_read_only_exact_retained_invoice_and_reservation" + ): + append_unique_error(errors, f"{label} must retain the read-only exact invoice/reservation contract") + if not is_read and "retained_first_invoice_binding" in checks: + append_unique_error(errors, f"{label} cannot substitute retained read binding for mutation authority") def applicability_value( diff --git a/dev-tools/validation/test_check_authz_route_matrix.py b/dev-tools/validation/test_check_authz_route_matrix.py index 8dbcb379de..23a59032fd 100644 --- a/dev-tools/validation/test_check_authz_route_matrix.py +++ b/dev-tools/validation/test_check_authz_route_matrix.py @@ -19,7 +19,6 @@ "issuer_generation", "account_generation", "current_subscription_owner", - "exact_reserved_instrument", } EXPECTED_FIRST_INVOICE_ROUTES = ( "GET /billing/hosting/subscriptions/{subscriptionId}/first-invoice", @@ -162,26 +161,28 @@ def test_first_invoice_routes_require_current_owner_and_generations(self): ) for route_name in EXPECTED_FIRST_INVOICE_ROUTES: with self.subTest(route=route_name): - document = self.validator.yaml.safe_load( - MATRIX.read_text(encoding="utf-8") - ) + document = self.validator.yaml.safe_load(MATRIX.read_text(encoding="utf-8")) route = route_for(document, "account-service", route_name) - self.assertEqual( - "target_not_currently_routable", route["route_status"] - ) + self.assertEqual("target_not_currently_routable", route["route_status"]) self.assertTrue( - EXPECTED_FIRST_INVOICE_LIVE_CHECKS.issubset( - route["required_live_checks"] - ) + ( + EXPECTED_FIRST_INVOICE_LIVE_CHECKS + | { + "retained_first_invoice_binding" + if route_name.startswith("GET ") + else "exact_reserved_instrument" + } + ).issubset(route["required_live_checks"]) ) def test_first_invoice_live_checks_cannot_be_omitted_or_aliased(self): for route_name in EXPECTED_FIRST_INVOICE_ROUTES: - for required_check in EXPECTED_FIRST_INVOICE_LIVE_CHECKS: + required = EXPECTED_FIRST_INVOICE_LIVE_CHECKS | { + "retained_first_invoice_binding" if route_name.startswith("GET ") else "exact_reserved_instrument" + } + for required_check in required: with self.subTest(route=route_name, check=required_check): - document = self.validator.yaml.safe_load( - MATRIX.read_text(encoding="utf-8") - ) + document = self.validator.yaml.safe_load(MATRIX.read_text(encoding="utf-8")) route = route_for(document, "account-service", route_name) route["required_live_checks"].remove(required_check) route["required_live_checks"].append( @@ -194,13 +195,38 @@ def test_first_invoice_live_checks_cannot_be_omitted_or_aliased(self): self.assertTrue( any( - f"account-service {route_name} is missing required " - "first-invoice live checks" in error + f"account-service {route_name} is missing required first-invoice live checks" in error for error in errors ), errors, ) + def test_first_invoice_read_binding_cannot_be_made_a_live_instrument_gate(self): + document = self.validator.yaml.safe_load(MATRIX.read_text(encoding="utf-8")) + route = route_for(document, "account-service", EXPECTED_FIRST_INVOICE_ROUTES[0]) + route["required_live_checks"].append("exact_reserved_instrument") + self.assertTrue( + any("must use retained read binding" in error for error in validate_document(self.validator, document)) + ) + route["required_live_checks"].remove("exact_reserved_instrument") + route["mutation_contract"] = "current_owner_exact_subscription_and_instrument" + self.assertTrue( + any("read-only exact invoice/reservation" in error for error in validate_document(self.validator, document)) + ) + + def test_first_invoice_mutations_cannot_reuse_read_binding(self): + for route_name in EXPECTED_FIRST_INVOICE_ROUTES[1:]: + with self.subTest(route=route_name): + document = self.validator.yaml.safe_load(MATRIX.read_text(encoding="utf-8")) + route = route_for(document, "account-service", route_name) + route["required_live_checks"].append("retained_first_invoice_binding") + self.assertTrue( + any( + "cannot substitute retained read binding" in error + for error in validate_document(self.validator, document) + ) + ) + def test_first_invoice_routes_cannot_be_promoted_while_held(self): for route_name in EXPECTED_FIRST_INVOICE_ROUTES: with self.subTest(route=route_name): From 7926f66a0fa9254b6ed49abdc820cdb5d657ab14 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 15 Nov 2026 06:13:33 +1300 Subject: [PATCH 28/29] Align account recovery tests with retained denial and payment conflict --- ...ngSubscriptionDispatchPostgresIntegrationTest.java | 11 ++++++++--- ...nerIntakeAuthorizationPostgresIntegrationTest.java | 3 ++- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java index 903ec675da..9ca1e29e96 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java @@ -79,7 +79,7 @@ class AccountHostingSubscriptionDispatchPostgresIntegrationTest { new PostgreSQLContainer<>(TestContainerImages.postgres()); @Test - void signedSuccessRetriesOnlyWhenItMatchesTheRetainedFirstInvoice() throws Exception { + void unconsentedSignedSuccessRetainsOperatorConflictOnlyForExactInvoice() throws Exception { var source = unpaidCancellationDataSource(null); var hosting = CanonicalHostingSubscriptionTestFixture.create(source); var checkout = hosting.awaitFirstInvoice(); @@ -97,8 +97,13 @@ void signedSuccessRetriesOnlyWhenItMatchesTheRetainedFirstInvoice() throws Excep var invoicesBefore = hosting.dsl().fetch("SELECT *, xmin::text FROM subscription_first_invoices"); var linked = checkout.signedSuccess(); - assertThat(payments.completeSigned(linked.payload(), linked.signature()).state()) - .isEqualTo("RECONCILING"); + var completion = payments.completeSigned(linked.payload(), linked.signature()); + assertThat(completion.state()).isEqualTo("OPERATOR_RECONCILIATION_REQUIRED"); + assertThat(completion.requestId()).isEqualTo(checkout.invoice().creationRequestId()); + assertThat(payments.completeSigned(linked.payload(), linked.signature())).isEqualTo(completion); + assertThat( + hosting.dsl().fetchCount(DSL.table("subscription_first_invoice_unconsented_paid_events"))) + .isEqualTo(1); String unrelatedPayload = linked diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java index 9625545da1..cf307b5d35 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java @@ -639,7 +639,8 @@ void expiredPreliminaryRecoveryAcceptsRetainedExpiredIssuersAndKeepsFinalAuthori assertThat(revoking.status).isEqualTo("REVOKING"); } else { serviceClock.advance(Duration.ofSeconds(31)); - assertThatThrownBy(fixture::issueCreator).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(fixture::issueCreator) + .isInstanceOf(AccountControlUiIssuanceService.PermanentRecoveryDenialException.class); } assertThat( f.dsl From 60b99820e6285e3285506fb3b80d732c9567eeeb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 15 Nov 2026 06:15:45 +1300 Subject: [PATCH 29/29] Format account conflict assertion --- ...untHostingSubscriptionDispatchPostgresIntegrationTest.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java index 9ca1e29e96..078d034097 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java @@ -102,7 +102,9 @@ void unconsentedSignedSuccessRetainsOperatorConflictOnlyForExactInvoice() throws assertThat(completion.requestId()).isEqualTo(checkout.invoice().creationRequestId()); assertThat(payments.completeSigned(linked.payload(), linked.signature())).isEqualTo(completion); assertThat( - hosting.dsl().fetchCount(DSL.table("subscription_first_invoice_unconsented_paid_events"))) + hosting + .dsl() + .fetchCount(DSL.table("subscription_first_invoice_unconsented_paid_events"))) .isEqualTo(1); String unrelatedPayload =