diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 6376e12b00..857e13fa6a 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -539,15 +539,21 @@ 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 isolated checkout receiving slice #3410 owns the HTTPS controller and browser composition. This Account producer keeps registration held. Route activation requires a physical Gateway-to-Account proof that Account observes a secure request through the authenticated owner transport. A direct Account TLS test supplies only the Account listener proof; 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. 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. -- `GET` returns the exact existing invoice, PaymentIntent, selected instrument, amount, currency, immutable `tupleDigest`, expected current subscription row version, expiry, nullable retained `confirmationRequestId`, nullable retained `openingRequestId` before first consent, current `authorizationVersion` (zero before first consent) and `AWAITING_PAYMENT`, `COMMITTED`, or terminal unpaid `CANCELED` state. A canceled checkout offers no payment authorization. `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. When `openingRequestId` is present, explicit pre-row renewal must use that exact original operation. That absence does not authorize a replacement request or charge. 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. +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`. 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. Deployment qualification requires that the authenticated Gateway-to-Account HTTPS transport leaves Account observing a secure request. 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`, `COMMITTED`, or terminal unpaid `CANCELED` state. A canceled checkout offers no payment authorization. `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. - `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. - 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 c14a3d6e58..abefe57862 100644 --- a/design/architecture/microservices/account-service/configuration.md +++ b/design/architecture/microservices/account-service/configuration.md @@ -69,9 +69,17 @@ 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 a controlled-fixture-only isolated receiving composition. It does not authorize intake of real provider or customer data, production billing intake, 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. All three roots must be existing mounted directories with absolute normalized paths. Startup resolves their physical paths and refuses missing or unresolvable roots and custody equality or ancestor/descendant overlap with either signer root, including symlink aliases. This startup check does not protect against privileged later mount replacement. 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. 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/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 52a47c7956..f030b78ae5 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -432,6 +432,8 @@ 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. + +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 c07a713860..16bf095988 100644 --- a/design/architecture/microservices/account-service/stripe-integration.md +++ b/design/architecture/microservices/account-service/stripe-integration.md @@ -19,9 +19,9 @@ 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. 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,19 +38,21 @@ 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. 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. 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. 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. @@ -62,9 +64,13 @@ If the invocation that won the committed command claim observes authorization ex 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. New opening evidence and the exact operation fence commit in the same owner transaction. A failed fence bind rolls back that evidence and cannot redirect it 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. -The held lifecycle owner may settle an exact provider-linked unpaid checkout from fresh terminal cancellation evidence when the retained first invoice has no signed success evidence. An `incomplete_expired` subscription requires a fresh read of the original void invoice with zero paid and an independent read of its exact canceled PaymentIntent with zero received. A claimed checkout also requires those two provider reads and the exact durable expiry-before-confirm observation. The owner rechecks the claim and absence of signed success under the subscription lock. The claimed path retains its typed evidence in the same transaction as the negative lifecycle receipt, terminal provisioning state and exact instrument reservation release. Exact replay returns that committed outcome. Ambiguous, stale, mismatched or paid evidence keeps the reservation held. A paid first invoice whose provider subscription was canceled before first fulfillment retains its payment evidence and produces exact lifecycle operator work before any hosting receipt or instrument release. A verified exact payment that arrives after a committed unpaid cancellation is retained as an operator reconciliation conflict linked to the original cancellation, including when no local confirmation exists. An independently verified success event for the same payment can reference that conflict after fresh exact paid readback. Replaying either retained event returns the same conflict without new provider reads. A verified exact success before local confirmation or committed cancellation instead retains an immutable operator obligation keyed to the original creation request and exact signed event. Replay returns that same obligation without provider access; cancellation remains safely blocked by paid evidence, and a new confirmation cannot consume the unresolved obligation. The conflict does not reopen fulfillment or authorize a refund. 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. +The held lifecycle owner may settle an exact provider-linked unpaid checkout from fresh terminal cancellation evidence when the retained first invoice has no signed success evidence. An `incomplete_expired` subscription requires a fresh read of the original void invoice with zero paid and an independent read of its exact canceled PaymentIntent with zero received. A claimed checkout also requires those two provider reads and the exact durable expiry-before-confirm observation. The owner rechecks the claim and absence of signed success under the subscription lock. The claimed path retains its typed evidence in the same transaction as the negative lifecycle receipt, terminal provisioning state and exact instrument reservation release. Exact replay returns that committed outcome. Ambiguous, stale, mismatched or paid evidence keeps the reservation held. A paid first invoice whose provider subscription was canceled before first fulfillment retains its payment evidence and produces exact lifecycle operator work before any hosting receipt or instrument release. A verified exact payment that arrives after a committed unpaid cancellation is retained as an operator reconciliation conflict linked to the original cancellation, including when no local confirmation exists. An independently verified success event for the same payment can reference that conflict after fresh exact paid readback. Replaying either retained event returns the same conflict without new provider reads. A verified exact success before local confirmation or committed cancellation instead retains an immutable operator obligation keyed to the original creation request and exact signed event. Replay returns that same obligation without provider access; cancellation remains safely blocked by paid evidence, and a new confirmation cannot consume the unresolved obligation. The conflict does not reopen fulfillment or authorize a refund. + +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/microservices/account-service/subscription-management.md b/design/architecture/microservices/account-service/subscription-management.md index 277ac57fad..39a821aa66 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. The [owner-authorized first-invoice flow](./stripe-integration.md#first-invoice-confirmation-and-completion) is the only permitted charge in this state. -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/microservices/spring-cloud-gateway/client-behavior.md b/design/architecture/microservices/spring-cloud-gateway/client-behavior.md index 18fd6c25bd..ffc3e1c96d 100644 --- a/design/architecture/microservices/spring-cloud-gateway/client-behavior.md +++ b/design/architecture/microservices/spring-cloud-gateway/client-behavior.md @@ -65,7 +65,7 @@ Unless explicitly described as current behavior, the sections below define the t The canonical external allowlist stops there. World Management, Entity Management, Game Logic, and Automation & Scripting do not expose direct Gateway-routed external APIs in the base architecture unless a dedicated design update extends the allowlist. -Gateway routes strip the first two path segments before forwarding these REST families to their owning services. For example, `GET /api/admin/admission-pointers` is forwarded to Logging & Admin as `/admission-pointers`, and `/api/account/auth/login` is forwarded to Account as `/auth/login`. The admission-pointer route is GET-only, so mutation, preparation, and prepared-cutover writes are not forwarded. `/api/session/ping` is forwarded as the current public HTTP control-plane route, while `/ws/game/**` remains the separate gameplay WebSocket path. Published `/assets/**` delivery is target-only pending a separate approved public origin/provisioner; the current Gateway has no route for it, and private MinIO is not public delivery. +Gateway routes strip the first two path segments before forwarding these REST families to their owning services. For example, `GET /api/admin/admission-pointers` is forwarded to Logging & Admin as `/admission-pointers`. The explicitly selected isolated checkout composition instead handles `POST /api/account/auth/login` in its Gateway controller and sends the authenticated typed Account RPC described in [Account API Contracts](../account-service/api-contracts.md#hosting-first-invoice-checkout); it requires the header-trust WebFilter's private canonical HTTP source proof rather than trusting an incoming source header. The admission-pointer route is GET-only, so mutation, preparation, and prepared-cutover writes are not forwarded. `/api/session/ping` is forwarded as the current public HTTP control-plane route, while `/ws/game/**` remains the separate gameplay WebSocket path. Published `/assets/**` delivery is target-only pending a separate approved public origin/provisioner; the current Gateway has no route for it, and private MinIO is not public delivery. These public prefixes are route families, not blanket permission to expose every service-local path under the same subtree: diff --git a/design/architecture/system-architecture-authz-route-matrix.md b/design/architecture/system-architecture-authz-route-matrix.md index ba17905378..d57c17e912 100644 --- a/design/architecture/system-architecture-authz-route-matrix.md +++ b/design/architecture/system-architecture-authz-route-matrix.md @@ -293,3 +293,13 @@ For every first public-production text entry, the target command sequence is `LO 7. Global roles alone never bypass this flow or grant gameplay admission/connect-token issuance without the same live checks. The matrix should be expanded as service API surfaces evolve. Service docs may include local excerpts, but this file is the canonical policy for declared entries; current omissions remain an explicit inventory drift/gap until source-stable coverage and validation complete the registry. + +### 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 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. + +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 721fbbcc52..7a1b6e6c88 100644 --- a/design/architecture/system-architecture-authz-route-matrix.yaml +++ b/design/architecture/system-architecture-authz-route-matrix.yaml @@ -345,6 +345,10 @@ required_live_check_vocabulary: - csrf # Live Account-owned generation reread for control-plane authority. - current_account_generation + # 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 @@ -1756,6 +1760,30 @@ 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 + 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] + 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 @@ -3205,6 +3233,78 @@ routes: required_live_checks: [issuer_generation, account_generation, current_global_role, role_appropriate_assurance] roles: any_of: [support, platformAdmin] + - service: account-service + route: GET /billing/hosting/subscriptions/{subscriptionId}/first-invoice + scope: account + classification: account_scoped + route_status: target_not_currently_routable + accepted_token_profiles: [control-ui] + issued_token_state: current_exact_active_control_ui_registry_record + token_type: control_plane_user + token_issuer: firemud-account-service + token_audience: control-ui + 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, 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. + - service: account-service + route: POST /billing/hosting/subscriptions/{subscriptionId}/first-invoice/reauthenticate + scope: account + classification: account_scoped + route_status: target_not_currently_routable + accepted_token_profiles: [control-ui] + issued_token_state: current_exact_active_control_ui_registry_record + token_type: control_plane_user + token_issuer: firemud-account-service + token_audience: control-ui + 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_and_actual_billing_purpose_primary_authentication + implementation_status: + known_drift: + - 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 + classification: account_scoped + route_status: target_not_currently_routable + accepted_token_profiles: [control-ui] + issued_token_state: current_exact_active_control_ui_registry_record + token_type: control_plane_user + token_issuer: firemud-account-service + token_audience: control-ui + 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_billing_purpose_reauthentication_explicit_exact_tuple_consent_single_dispatch + implementation_status: + known_drift: + - 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 + classification: account_scoped + route_status: target_not_currently_routable + accepted_token_profiles: [control-ui] + issued_token_state: current_exact_active_control_ui_registry_record + token_type: control_plane_user + token_issuer: firemud-account-service + token_audience: control-ui + 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_fresh_billing_reauthentication_explicit_unchanged_consent_authorization_version_fence_no_command_replay + implementation_status: + known_drift: + - 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 2089f46ef3..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. | @@ -578,6 +579,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 a5df41db17..bf703eb17b 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -94,9 +94,9 @@ 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. The checkout transport, browser and their proof are carried by the isolated receiving PR #3410. This producer retains the Account payment owner and its SQL proof. 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 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. 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. +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. Retained positive-subscription qualification remains open. V1041 creates empty completion relations and guards and leaves historical `trialing`, `active`, `past_due` and `grace` subscriptions in place. Current positive lifecycle reads and reconciliation require exact first-payment and completion joins. An old positive receipt without that evidence fails closed. The explicit disposition is now refuse-upgrade through forward V1046.1: lock subscription writes, reject unresolved current positives without changing their evidence, and install deferred completion consistency for later writers. V1041 stays immutable and activation remains held. Genuine predecessor fixture evidence is available from the old c8dab91d owner via `AccountHostingSubscriptionDispatchPostgresIntegrationTest.paymentRequiredSdkCreateCannotCommitUntilProviderConfirmsFirstInvoice`; its prior-source proof does not qualify this migration. The manually composed lifecycle repository now has an explicit read-only completion-gap prerequisite, with a caller-selected one-to-five-second query timeout and fail-closed database errors. It is not registered or an activation grant. Focused definitions cover invalid transaction/budget, unresolved or indeterminate results, database failure, and preserved populated pre-V1041 schema rows across upgrade for all four positive statuses. Current local predecessor definitions are controlled schema-valid data, not a replay of the genuine historical owner. Additional physical definitions cover upgrade refusal, final-transaction completion, existing completion immutability and blocked concurrent insert/update writers; none has been executed here. Bounded Java 25 compilation of all three changed Java files against cached APIs and the three new unit methods pass with no failures or skips. This is not a clean exact-tree Gradle build; physical execution and genuine positive-row remediation remain unqualified for this change. @@ -112,7 +112,19 @@ The #3408 receiving source adds the Account-owned original-operation fence and i The additive [V1046.4 migration](../../../services/account-service/src/main/resources/db/migration/V1046.4__retain_first_invoice_expiry_before_post.sql) retains the winning invocation's exact expiry-before-confirm observation against its independently committed claim. [V1046.7](../../../services/account-service/src/main/resources/db/migration/V1046.7__settle_first_invoice_expiry_before_post.sql) binds that evidence to the atomic terminal cancellation receipt and instrument release under the [canonical Stripe recovery contract](../../architecture/microservices/account-service/stripe-integration.md#first-invoice-confirmation-and-completion). -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 HTTPS, browser and registered receiving proof are owned by #3410. The prior results above remain attributed to their original combined source. 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 #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 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 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. + +The bounded trusted-source qualification passes all 84 tests in eight unit classes with zero failures, skips or aborts: the shared authentication codec (7), Gateway header trust (29), login controller (10), mTLS client (4), Gateway receiving configuration (7), Account gRPC receiver (7), issuance workflow (15), and Account receiving configuration (5). Google Java Format 1.36.1 processed only the 18 edited Java files; protoc 4.36.2 and grpc-java 1.85.1 generated only the authentication wire's eight Java files. Java 25 compiled all 26 complete edited/generated files with annotation processing and implicit compilation disabled and an empty source path. The tests loaded changed production, generated and test classes from fresh private output. Dependency execution used cached APIs: 392 observed repository classes had matching source, 34 generated classes had matching proto inputs, and one cached jOOQ record retained an unreconstructed generating-schema provenance limit. This is bounded cached-API proof, not a clean exact-tree build or a new run of the historical receiving/browser suites. Canonical Gradle compilation and tests, aggregate formatting, enabled static analysis, documentation/link checks, physical PostgreSQL/Redis receiving and changed-source OTP replay, and fresh-image/runtime qualification remain unrun for this change. Shared Account credential-abuse enforcement and production activation remain held. ### Canonical public Account facade receiving diff --git a/dev-tools/validation/check-authz-route-matrix.py b/dev-tools/validation/check-authz-route-matrix.py index 15d4b61a9d..23e54d2e2b 100644 --- a/dev-tools/validation/check-authz-route-matrix.py +++ b/dev-tools/validation/check-authz-route-matrix.py @@ -133,6 +133,20 @@ ("account-service", "POST /auth/pending-deletion/recovery/challenge"), ("account-service", "POST /auth/pending-deletion/recovery"), } +FIRST_INVOICE_ROUTES = ( + "GET /billing/hosting/subscriptions/{subscriptionId}/first-invoice", + ( + "POST /billing/hosting/subscriptions/{subscriptionId}/first-invoice/" + "reauthenticate" + ), + "POST /billing/hosting/subscriptions/{subscriptionId}/first-invoice/confirm", + "POST /billing/hosting/subscriptions/{subscriptionId}/first-invoice/renew", +) +FIRST_INVOICE_REQUIRED_LIVE_CHECKS = { + "issuer_generation", + "account_generation", + "current_subscription_owner", +} REQUIRED_FIELD_PATTERN = re.compile(r"^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$") ROUTE_STATUS_VALUES = { "current_openapi_operator_surface", @@ -5456,6 +5470,46 @@ def resolve_unique_route( return matches[0] +def validate_first_invoice_routes( + routes: list[Any], + errors: list[str], + live_checks_cache: LiveChecksCache | None = None, + cardinality_errors: set[str] | None = None, +) -> None: + for route_name in FIRST_INVOICE_ROUTES: + route = resolve_unique_route( + routes, + "account-service", + route_name, + errors, + cardinality_errors, + ) + if route is None: + 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") + checks = route_live_checks(route, label, errors, live_checks_cache) + 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( route: dict[str, Any], key: str, label: str, errors: list[str] ) -> Any: @@ -6217,6 +6271,12 @@ def validate_matrix_document(path: Path) -> tuple[list[str], set[str]]: validate_membership_policy(document, errors) validate_elevation_bootstrap(document, routes, errors, cardinality_errors) validate_entitlement_contract(document, routes, errors, cardinality_errors) + validate_first_invoice_routes( + routes, + errors, + live_checks_cache, + cardinality_errors, + ) validate_ws_game_routes(routes, errors, live_checks_cache, cardinality_errors) validate_connect_token_revoke_generation_applicability( diff --git a/dev-tools/validation/test_check_authz_route_matrix.py b/dev-tools/validation/test_check_authz_route_matrix.py index bdbe08f3f8..23a59032fd 100644 --- a/dev-tools/validation/test_check_authz_route_matrix.py +++ b/dev-tools/validation/test_check_authz_route_matrix.py @@ -15,6 +15,20 @@ ROOT = Path(__file__).resolve().parents[2] SCRIPT = ROOT / "dev-tools/validation/check-authz-route-matrix.py" MATRIX = ROOT / "design/architecture/system-architecture-authz-route-matrix.yaml" +EXPECTED_FIRST_INVOICE_LIVE_CHECKS = { + "issuer_generation", + "account_generation", + "current_subscription_owner", +} +EXPECTED_FIRST_INVOICE_ROUTES = ( + "GET /billing/hosting/subscriptions/{subscriptionId}/first-invoice", + ( + "POST /billing/hosting/subscriptions/{subscriptionId}/first-invoice/" + "reauthenticate" + ), + "POST /billing/hosting/subscriptions/{subscriptionId}/first-invoice/confirm", + "POST /billing/hosting/subscriptions/{subscriptionId}/first-invoice/renew", +) def load_validator(): @@ -139,6 +153,94 @@ def setUpClass(cls): def test_current_matrix_passes(self): self.assertEqual([], self.validator.validate(MATRIX)) + def test_first_invoice_routes_require_current_owner_and_generations(self): + self.assertEqual(EXPECTED_FIRST_INVOICE_ROUTES, self.validator.FIRST_INVOICE_ROUTES) + self.assertEqual( + EXPECTED_FIRST_INVOICE_LIVE_CHECKS, + self.validator.FIRST_INVOICE_REQUIRED_LIVE_CHECKS, + ) + 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")) + route = route_for(document, "account-service", route_name) + self.assertEqual("target_not_currently_routable", route["route_status"]) + self.assertTrue( + ( + 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: + 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")) + route = route_for(document, "account-service", route_name) + route["required_live_checks"].remove(required_check) + route["required_live_checks"].append( + "binding_ownership" + if required_check == "current_subscription_owner" + else "explicit_per_subscription_binding" + ) + + errors = validate_document(self.validator, document) + + self.assertTrue( + any( + 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): + document = self.validator.yaml.safe_load( + MATRIX.read_text(encoding="utf-8") + ) + route = route_for(document, "account-service", route_name) + route["route_status"] = "current_openapi_operator_surface" + + self.assertIn( + f"account-service {route_name} must remain target_not_currently_routable", + validate_document(self.validator, document), + ) + def test_moderation_root_contract_declares_receiving_redemption_and_selector(self): document = self.validator.yaml.safe_load(MATRIX.read_text(encoding="utf-8")) contract = document["moderation_policy_intent_authorization"] diff --git a/protos/account/v1/control_ui_authentication.proto b/protos/account/v1/control_ui_authentication.proto new file mode 100644 index 0000000000..10757a2497 --- /dev/null +++ b/protos/account/v1/control_ui_authentication.proto @@ -0,0 +1,51 @@ +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; +} + +enum AccountControlUiCredentialTransportClass { + ACCOUNT_CONTROL_UI_CREDENTIAL_TRANSPORT_CLASS_UNSPECIFIED = 0; + ACCOUNT_CONTROL_UI_CREDENTIAL_TRANSPORT_CLASS_HTTP = 1; +} + +// 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; + // Gateway-derived source, accepted only from the authenticated Gateway workload. + repeated string canonical_client_address = 7; + repeated AccountControlUiCredentialTransportClass transport_class = 8; +} + +// 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 317e0c6613..7c5425101c 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -101,6 +101,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"))) } @@ -132,6 +136,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) @@ -167,6 +187,11 @@ 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") + // SCG Redis auto-configuration has a separate switch and must also stay outside Account. + systemProperty("spring.cloud.gateway.server.webflux.redis.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")) { @@ -185,6 +210,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..80029483e5 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountCheckoutReceivingProperties.java @@ -0,0 +1,49 @@ +package net.firedevops.firemud.accountservice.config; + +import java.io.IOException; +import java.nio.file.Files; +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"); + privateSignerRoot = requirePath(privateSignerRoot); + publicSignerRoot = requirePath(publicSignerRoot); + controlUiKeyringRoot = 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 Path requirePath(Path path) { + if (path == null || !path.isAbsolute() || !path.equals(path.normalize())) { + throw new IllegalArgumentException( + "Explicit absolute protected Account source paths required"); + } + try { + Path real = path.toRealPath(); + if (!Files.isDirectory(real)) { + throw new IllegalArgumentException( + "Protected Account source roots must be mounted directories"); + } + return real; + } catch (IOException | SecurityException unavailable) { + throw new IllegalArgumentException("Protected Account source roots must resolve physically"); + } + } +} 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 new file mode 100644 index 0000000000..c592279dc1 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceController.java @@ -0,0 +1,255 @@ +package net.firedevops.firemud.accountservice.controller; + +import com.stripe.exception.SignatureVerificationException; +import com.stripe.exception.StripeException; +import jakarta.servlet.http.HttpServletRequest; +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.service.session.AccountHostingFirstInvoicePaymentService; +import net.firedevops.firemud.accountservice.service.session.AccountRecentReauthenticationEvidence.BillingAuthorizationPurpose; +import org.springframework.http.CacheControl; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +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.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.server.ResponseStatusException; + +/** 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; + + public AccountHostingFirstInvoiceController(AccountHostingFirstInvoicePaymentService payments) { + this.payments = Objects.requireNonNull(payments); + } + + @GetMapping + public ResponseEntity read( + HttpServletRequest transport, + @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authorization, + @PathVariable UUID subscriptionId) { + return noStore(payments.describeOwner(bearer(transport, authorization), subscriptionId)); + } + + @PostMapping("/reauthenticate") + public ResponseEntity reauthenticate( + HttpServletRequest transport, + @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authorization, + @PathVariable UUID subscriptionId, + @RequestBody ReauthenticationRequest request) { + String token = bearer(transport, authorization); + if (request.billingBinding() == null) { + // 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( + new ReauthenticationResponse( + payments.reauthenticate( + token, + subscriptionId, + request.requestId(), + request.confirmationRequestId(), + binding.originalRequestId(), + binding.expectedRowVersion(), + binding.expectedAuthorizationVersion(), + binding.acceptedTupleDigest(), + binding.invoiceExpiresAt(), + binding.authorizationPurpose(), + request.email(), + request.secret()))); + } + + @PostMapping("/confirm") + public ResponseEntity confirm( + HttpServletRequest transport, + @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authorization, + @PathVariable UUID subscriptionId, + @RequestBody ConfirmationRequest request) + throws StripeException { + String token = bearer(transport, authorization); + if (!request.acceptCharge()) + throw new ResponseStatusException( + HttpStatus.BAD_REQUEST, "Explicit exact charge consent required"); + var handoff = + payments.confirm( + token, + subscriptionId, + request.requestId(), + request.expectedRowVersion(), + request.reauthenticationEvidenceId(), + request.acceptedTupleDigest()); + return noStore(new ConfirmationResponse(handoff.status(), handoff.clientSecret())); + } + + /** Fresh explicit owner consent on the unchanged original payment operation. */ + @PostMapping("/renew") + public ResponseEntity renew( + HttpServletRequest transport, + @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authorization, + @PathVariable UUID subscriptionId, + @RequestBody RenewalRequest request) + throws StripeException { + String token = bearer(transport, authorization); + if (!request.acceptCharge()) + throw new ResponseStatusException( + HttpStatus.BAD_REQUEST, "Explicit exact charge consent required"); + var handoff = + payments.renew( + token, + subscriptionId, + request.requestId(), + request.authorizationRequestId(), + request.expectedRowVersion(), + request.expectedAuthorizationVersion(), + request.reauthenticationEvidenceId(), + request.acceptedTupleDigest()); + return noStore(new ConfirmationResponse(handoff.status(), handoff.clientSecret())); + } + + /** Server-only intake adapter; not an owner browser endpoint and not registered here. */ + public AccountHostingFirstInvoicePaymentService.Completion signedCompletion( + String payload, String signature) throws SignatureVerificationException, StripeException { + return payments.completeSigned(payload, signature); + } + + @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, + org.springframework.dao.DataAccessException.class, + org.springframework.transaction.TransactionException.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) + .cacheControl(CacheControl.noStore()) + .body(new ErrorResponse("FIRST_INVOICE_PROVIDER_UNCERTAIN")); + } + + @ExceptionHandler(IllegalArgumentException.class) + public ResponseEntity invalidRequest() { + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .cacheControl(CacheControl.noStore()) + .body(new ErrorResponse("FIRST_INVOICE_INVALID_REQUEST")); + } + + @ExceptionHandler(IllegalStateException.class) + public ResponseEntity evidenceRefused() { + return ResponseEntity.status(HttpStatus.CONFLICT) + .cacheControl(CacheControl.noStore()) + .body(new ErrorResponse("FIRST_INVOICE_EVIDENCE_REFUSED")); + } + + public record ErrorResponse(String code) {} + + private static String bearer(HttpServletRequest transport, String authorization) { + if (transport == null + || !transport.isSecure() + || authorization == null + || !authorization.startsWith("Bearer ") + || authorization.length() <= 7 + || authorization.substring(7).isBlank()) { + throw new ResponseStatusException( + HttpStatus.UNAUTHORIZED, "Protected HTTPS control-ui authentication required"); + } + return authorization.substring(7); + } + + private static ResponseEntity noStore(T body) { + return ResponseEntity.ok() + .cacheControl(CacheControl.noStore()) + .header(HttpHeaders.PRAGMA, "no-cache") + .body(body); + } + + public record ReauthenticationRequest( + UUID requestId, + UUID confirmationRequestId, + BillingReauthenticationBinding billingBinding, + String email, + String secret) { + public ReauthenticationRequest( + UUID requestId, UUID confirmationRequestId, String email, String secret) { + this(requestId, confirmationRequestId, null, email, secret); + } + + @Override + public String toString() { + return "HostingBillingReauthenticationRequest[redacted]"; + } + } + + public record BillingReauthenticationBinding( + UUID originalRequestId, + long expectedRowVersion, + long expectedAuthorizationVersion, + String acceptedTupleDigest, + Instant invoiceExpiresAt, + BillingAuthorizationPurpose authorizationPurpose) {} + + public record ReauthenticationResponse(UUID evidenceId) {} + + public record ConfirmationRequest( + UUID requestId, + long expectedRowVersion, + UUID reauthenticationEvidenceId, + String acceptedTupleDigest, + boolean acceptCharge) {} + + public record ConfirmationResponse(String status, String clientSecret) { + @Override + public String toString() { + return "HostingFirstInvoiceConfirmationResponse[redacted]"; + } + } + + public record RenewalRequest( + UUID requestId, + UUID authorizationRequestId, + long expectedRowVersion, + long expectedAuthorizationVersion, + UUID reauthenticationEvidenceId, + String acceptedTupleDigest, + boolean acceptCharge) {} +} 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..9230418b08 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceWebhookController.java @@ -0,0 +1,86 @@ +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); + // Acknowledge only exact terminal owner classifications. Stripe redelivery can retry + // RECONCILING and unknown outcomes, but cannot resolve operator-owned reconciliation. + String state = completion.state(); + boolean terminal = + "COMMITTED".equals(state) + || "IGNORED".equals(state) + || "OPERATOR_RECONCILIATION_REQUIRED".equals(state); + return ResponseEntity.status(terminal ? 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/repository/AccountHostingFirstInvoicePaymentRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingFirstInvoicePaymentRepository.java index 2cea17367f..b3b1478ca3 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 @@ -284,15 +284,36 @@ public UUID confirmationRequestId(UUID subscriptionId) { return row == null ? null : row.get("request_id", UUID.class); } - public UUID openingRequestId(AccountHostingFirstInvoicePayment invoice, long rowVersion) { + /** Observational recovery identity only; never restores consent, proof or command permission. */ + public UUID preRowOriginalRequestId(UUID subscriptionId, UUID actor) { transaction(); - Record fence = operationFence(invoice.subscriptionId(), false); + var invoice = requireOwner(subscriptionId, actor); + // Existing confirmations own their scoped recovery, including historical rows without a fence. + if (confirmationRequestId(subscriptionId) != null) return null; + Record fence = operationFence(subscriptionId, true); + if (authorizationVersion(subscriptionId) != 0L + || dsl.fetchOne( + "SELECT 1 FROM subscription_first_invoice_dispatches WHERE subscription_id = ? LIMIT 1", + subscriptionId) + != null + || dsl.fetchOne( + "SELECT 1 FROM subscription_first_invoice_command_claims WHERE subscription_id = ? LIMIT 1", + subscriptionId) + != null) throw refused(); if (fence == null) return null; - if (!invoice.ownerAccountId().equals(fence.get("account_uuid", UUID.class)) + long rowVersion = ownerRowVersion(subscriptionId, actor); + UUID originalRequestId = fence.get("request_id", UUID.class); + OffsetDateTime fenceExpiry = fence.get("invoice_expires_at", OffsetDateTime.class); + AccountBillingCustomerRecord.requireUuid(originalRequestId); + if (!subscriptionId.equals(fence.get("subscription_id", UUID.class)) + || !actor.equals(fence.get("account_uuid", UUID.class)) || !invoice.digest().equals(fence.get("tuple_digest", String.class)) - || rowVersion != fence.get("expected_row_version", Long.class) - || !invoice.expiresAt().equals(instant(fence, "invoice_expires_at"))) throw refused(); - return fence.get("request_id", UUID.class); + || !Long.valueOf(rowVersion).equals(fence.get("expected_row_version", Long.class)) + || fenceExpiry == null + || !invoice.expiresAt().equals(fenceExpiry.toInstant())) throw refused(); + requireAwaitingPayment(invoice, rowVersion); + // Expired invoices may still be inspected; mutation owners independently enforce expiry. + return originalRequestId; } public long authorizationVersion(UUID subscriptionId) { @@ -831,6 +852,7 @@ 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; 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..b75c1ebbe4 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountCheckoutHttpAuthInterceptor.java @@ -0,0 +1,96 @@ +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 + | org.springframework.transaction.TransactionException + | 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 + .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..cd2970b348 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcService.java @@ -0,0 +1,97 @@ +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; + 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(), + request.sourceContext()); + } catch (IllegalArgumentException invalid) { + response.onError( + Status.INVALID_ARGUMENT + .withDescription("Invalid Account login request") + .asRuntimeException()); + return; + } + try (var credential = issuance.issueAccount(signInRequest)) { + 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 + | AccountControlUiIssuanceService.PermanentRecoveryDenialException denied) { + response.onNext(AccountControlUiAuthenticationGrpcCodec.toResponse(request, null)); + response.onCompleted(); + } catch (AccountControlUiIssuanceService.IdempotencyConflictException 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/AccountControlUiIssuanceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepository.java index c34941c4a0..6b88fd7863 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepository.java @@ -48,6 +48,43 @@ Stored findRequest(UUID requestId) { return row == null ? null : decodeStored(row); } + /** Serialize the bounded credential-replay budget without locking an Account source row. */ + void lockReplayRequest(UUID requestId) { + requireTransaction(); + dsl.fetch( + "SELECT pg_advisory_xact_lock(hashtextextended(?::text, ?))", + Objects.requireNonNull(requestId), + "control-ui-issuance-replay".hashCode()); + } + + int countReplayFailures(Stored original) { + requireTransaction(); + Record row = + dsl.fetchOne( + "SELECT count(*)::integer AS failures FROM account_control_ui_issuance_replay_failures" + + " WHERE operation_id = ? AND request_id = ?", + original.operationId, + original.requestId); + Integer failures = row == null ? null : row.get("failures", Integer.class); + if (failures == null || failures < 0 || failures > 5) throw denied(); + return failures; + } + + void recordReplayFailure(Stored original) { + requireTransaction(); + int next = countReplayFailures(original) + 1; + if (next > 5 + || dsl.execute( + "INSERT INTO account_control_ui_issuance_replay_failures" + + " (operation_id, request_id, failure_number) VALUES (?, ?, ?)", + original.operationId, + original.requestId, + next) + != 1) { + throw denied(); + } + } + Stored findToken(String tokenHash) { requireTransaction(); Record row = dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE token_hash = ?", tokenHash); 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..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 @@ -1,18 +1,21 @@ package net.firedevops.firemud.accountservice.service.session; import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; import java.time.Clock; import java.time.Instant; import java.util.Arrays; 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; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.common.EmailCanonicalization; +import net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec.SourceContext; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import org.springframework.beans.factory.annotation.Value; import org.springframework.transaction.PlatformTransactionManager; @@ -21,14 +24,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; @@ -42,11 +46,12 @@ public final class AccountControlUiIssuanceService { @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( value = "EI_EXPOSE_REP2", justification = - "Injected primary authentication and Draft fence services remain internal Account owner collaborators.") + "Injected primary authentication and Draft fence services remain internal Account owner" + + " collaborators.") public AccountControlUiIssuanceService( AccountServiceImpl primaryAuthentication, AccountControlUiIssuanceRepository operations, - AccountControlUiAuthority authority, + AccountControlUiAccountAuthority authority, DraftAuthorizationFenceRepository fences, AccountControlUiSignerOwner signers, AccountControlUiResponseCryptography cryptography, @@ -80,6 +85,7 @@ public AccountControlUiIssuanceService( public IssuedCredential issue(Request request, CapturedEnvironmentBoundary environment) { Objects.requireNonNull(request); + tenantAuthority(); return issueInternal( new Invocation( request.requestId, @@ -88,7 +94,8 @@ public IssuedCredential issue(Request request, CapturedEnvironmentBoundary envir request.callerContextId, AccountControlUiAuthority.ScopeKind.TENANT, java.util.Optional.of(request.tenantId), - java.util.Optional.of(Objects.requireNonNull(environment)))); + java.util.Optional.of(Objects.requireNonNull(environment)), + java.util.Optional.empty())); } /** Account-global sign-in: no tenant, membership, creator or terms selector is accepted. */ @@ -102,7 +109,8 @@ public IssuedCredential issueAccount(AccountSignInRequest request) { request.callerContextId, AccountControlUiAuthority.ScopeKind.ACCOUNT, java.util.Optional.empty(), - java.util.Optional.empty())); + java.util.Optional.empty(), + java.util.Optional.of(request.sourceContext))); } private IssuedCredential issueInternal(Invocation request) { @@ -117,6 +125,8 @@ private IssuedCredential issueInternal(Invocation request) { } String email = EmailCanonicalization.normalize(request.email); Map requestFields = new java.util.LinkedHashMap<>(); + // Source is transient new-attempt input. Preserve the immutable v1 credential replay MAC; + // a source change neither creates a new operation nor resets its retained failure budget. requestFields.put("schema", "account-control-ui-request/v1"); requestFields.put("requestId", request.requestId.toString()); requestFields.put("email", email); @@ -135,7 +145,16 @@ private IssuedCredential issueInternal(Invocation request) { ignored -> { var existing = operations.findRequest(request.requestId); if (existing != null) { - requireRequest(existing, request, peer.uri(), exactRequest); + requireRequestBinding(existing, request, peer.uri()); + operations.lockReplayRequest(existing.requestId); + if (operations.countReplayFailures(existing) >= 5) { + return new InitialPreparation(null, new IdempotencyConflictException()); + } + if (!matchesOriginalRequest(existing, exactRequest)) { + operations.recordReplayFailure(existing); + // A value, not a thrown exception, commits the independent failure history. + return new InitialPreparation(null, new IdempotencyConflictException()); + } return new InitialPreparation(current(existing, environment), null); } // Preserve canonical tenant -> Account owner order before OTP/advisory @@ -143,8 +162,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; @@ -155,8 +175,7 @@ private IssuedCredential issueInternal(Invocation request) { } catch (AuthenticationException denial) { // Only primary denial commits attempt accounting. No signer/issuance work // follows. - return new InitialPreparation( - null, new PrimaryDenial(denial.getCode(), denial.getMessage())); + return new InitialPreparation(null, denial); } var source = tenantSource.orElseGet( @@ -189,7 +208,7 @@ private IssuedCredential issueInternal(Invocation request) { throw denied(); } if (initial.denial != null) { - throw new AuthenticationException(initial.denial.code, initial.denial.message); + throw initial.denial; } Prepared preparation = Objects.requireNonNull(initial.prepared); var original = preparation.stored; @@ -306,33 +325,61 @@ 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); } } - private void requireRequest( - AccountControlUiIssuanceRepository.Stored stored, - Invocation request, - String caller, - byte[] exactRequest) { + private void requireRequestBinding( + AccountControlUiIssuanceRepository.Stored stored, Invocation request, String caller) { if (!stored.requestId.equals(request.requestId) || stored.scopeKind() != request.scopeKind || !stored.optionalTenantId().equals(request.tenantId) || !stored.caller.equals(caller) - || !stored.callerContextId.equals(request.callerContextId) - || !stored.requestDigest.equals( - cryptography.requestDigest(stored.requestMacKeyId, exactRequest))) { - throw new IllegalArgumentException("Control-ui issuance idempotency conflict"); + || !stored.callerContextId.equals(request.callerContextId)) { + throw new IdempotencyConflictException(); + } + } + + private boolean matchesOriginalRequest( + AccountControlUiIssuanceRepository.Stored stored, byte[] exactRequest) { + byte[] expected = stored.requestDigest.getBytes(StandardCharsets.US_ASCII); + byte[] supplied = + cryptography + .requestDigest(stored.requestMacKeyId, exactRequest) + .getBytes(StandardCharsets.US_ASCII); + try { + return MessageDigest.isEqual(expected, supplied); + } finally { + Arrays.fill(expected, (byte) 0); + Arrays.fill(supplied, (byte) 0); + } + } + + public static final class IdempotencyConflictException extends IllegalArgumentException { + public IdempotencyConflictException() { + super("Control-ui issuance idempotency conflict"); + } + } + + /** 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"); } } @@ -349,7 +396,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(); @@ -398,13 +446,17 @@ private record Invocation( UUID callerContextId, AccountControlUiAuthority.ScopeKind scopeKind, java.util.Optional tenantId, - java.util.Optional environment) { + java.util.Optional environment, + java.util.Optional sourceContext) { private Invocation { Objects.requireNonNull(scopeKind); Objects.requireNonNull(tenantId); Objects.requireNonNull(environment); + Objects.requireNonNull(sourceContext); boolean tenant = scopeKind == AccountControlUiAuthority.ScopeKind.TENANT; - if (tenant != tenantId.isPresent() || tenant != environment.isPresent()) { + if (tenant != tenantId.isPresent() + || tenant != environment.isPresent() + || tenant == sourceContext.isPresent()) { throw new IllegalArgumentException( "Explicit control-ui scope and source selection required"); } @@ -417,7 +469,11 @@ public String toString() { } public record AccountSignInRequest( - UUID requestId, String email, String secret, UUID callerContextId) { + UUID requestId, + String email, + String secret, + UUID callerContextId, + SourceContext sourceContext) { public AccountSignInRequest { if (requestId == null || requestId.equals(new UUID(0L, 0L)) @@ -428,7 +484,8 @@ public record AccountSignInRequest( || email.length() > 254 || secret == null || secret.isEmpty() - || secret.length() > 1024) { + || secret.length() > 1024 + || sourceContext == null) { throw new IllegalArgumentException("Exact bounded account-global sign-in request required"); } } @@ -439,14 +496,7 @@ public String toString() { } } - private record PrimaryDenial(String code, String message) { - private PrimaryDenial { - Objects.requireNonNull(code); - Objects.requireNonNull(message); - } - } - - private record InitialPreparation(Prepared prepared, PrimaryDenial denial) { + private record InitialPreparation(Prepared prepared, RuntimeException denial) { private InitialPreparation { if ((prepared == null) == (denial == null)) { throw new IllegalArgumentException( @@ -527,6 +577,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..588065faad 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 @@ -83,10 +83,10 @@ public byte[] readActive(String tokenHash) { throw denied(); } try (var connection = connections.openPinnedConnection()) { - if (connection == null - || !connection.isOpen() - || connection.getOptions() == null - || connection.getOptions().isAutoReconnect()) { + if (connection == null || !connection.isOpen()) { + throw new RegistryUnavailableException(); + } + if (connection.getOptions() == null || connection.getOptions().isAutoReconnect()) { throw denied(); } RedisCommands commands = connection.sync(); @@ -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/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/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 ffb1c07517..0c25647882 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 @@ -72,7 +72,7 @@ public OwnerView describeOwner(String bearer, UUID subscriptionId) { invoice.expiresAt(), confirmationRequestId, confirmationRequestId == null && !canceled - ? payments.openingRequestId(invoice, rowVersion) + ? payments.preRowOriginalRequestId(subscriptionId, actor.accountId()) : null, payments.authorizationVersion(subscriptionId)); }); @@ -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. */ @@ -361,7 +381,7 @@ public record OwnerView( String state, java.time.Instant expiresAt, UUID confirmationRequestId, - UUID openingRequestId, + UUID preRowOriginalRequestId, long authorizationVersion) {} public record Completion(String state, UUID requestId) {} 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 d31958d702..974b12606e 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 @@ -35,8 +35,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; @@ -125,6 +126,33 @@ AccountRecentReauthenticationEvidence reauthenticateAndBindBilling( account -> primaryAuthentication.applyBillingPrimaryVerification(account, verification)); } + /** + * 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) { + requireRequest(request); + 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(); + }), + account -> { + throw conflict(); + }); + } + private static void requireRequest(Request request) { Objects.requireNonNull(request, "Account reauthentication request is required"); if (TransactionSynchronizationManager.isActualTransactionActive()) { diff --git a/services/account-service/src/main/resources/db/migration/V1047__control_ui_issuance_replay_failure_budget.sql b/services/account-service/src/main/resources/db/migration/V1047__control_ui_issuance_replay_failure_budget.sql new file mode 100644 index 0000000000..2eb0b1383a --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1047__control_ui_issuance_replay_failure_budget.sql @@ -0,0 +1,43 @@ +-- Independent request-local abuse accounting. No Account lock, authority, issuance, OTP, +-- credential-MAC, response or recovery deadline is changed by a failed replay. +CREATE TABLE account_control_ui_issuance_replay_failures ( + operation_id UUID NOT NULL REFERENCES account_control_ui_issuance_operations(operation_id), + request_id UUID NOT NULL, + failure_number INTEGER NOT NULL CHECK (failure_number BETWEEN 1 AND 5), + PRIMARY KEY (operation_id, failure_number) +); + +-- [jooq ignore start] +CREATE FUNCTION account_control_ui_issuance_replay_failure_sequence() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original_request UUID; + previous_failures INTEGER; +BEGIN + SELECT request_id INTO STRICT original_request + FROM account_control_ui_issuance_operations WHERE operation_id = NEW.operation_id; + IF NEW.request_id IS DISTINCT FROM original_request THEN + RAISE EXCEPTION 'Issuance replay failure requires the exact original request' + USING ERRCODE = '23514'; + END IF; + -- Same seed as Java "control-ui-issuance-replay".hashCode() in lockReplayRequest. + PERFORM pg_advisory_xact_lock(hashtextextended(NEW.request_id::TEXT, -2094251312)); + SELECT count(*) INTO previous_failures + FROM account_control_ui_issuance_replay_failures WHERE operation_id = NEW.operation_id; + IF NEW.failure_number <> previous_failures + 1 OR previous_failures >= 5 THEN + RAISE EXCEPTION 'Issuance replay failures require bounded monotonic history' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_control_ui_issuance_replay_failure_sequence + BEFORE INSERT ON account_control_ui_issuance_replay_failures + FOR EACH ROW EXECUTE FUNCTION account_control_ui_issuance_replay_failure_sequence(); +CREATE TRIGGER account_control_ui_issuance_replay_failures_immutable + BEFORE UPDATE OR DELETE ON account_control_ui_issuance_replay_failures + FOR EACH ROW EXECUTE FUNCTION account_control_ui_response_immutable_guard(); +CREATE TRIGGER account_control_ui_issuance_replay_failures_no_truncate + BEFORE TRUNCATE ON account_control_ui_issuance_replay_failures + FOR EACH STATEMENT EXECUTE FUNCTION account_control_ui_response_immutable_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index 09cc4c7e7e..1ed7b8e596 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -339,6 +339,203 @@ 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. 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 + in: header + required: true + schema: {type: string, maxLength: 4096} + requestBody: + required: true + content: + application/json: + schema: + type: object + description: 'JSON object; signature verification uses exact original raw UTF-8 bytes, at most 262144 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 + in: path + required: true + schema: {type: string, format: uuid} + get: + summary: Retrieve the exact retained first invoice for its current billing owner + operationId: getHostingFirstInvoice + 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': + description: Existing invoice and non-authorizing payment or independently committed state + content: + application/json: + schema: + type: object + required: [subscriptionId, invoiceId, paymentIntentId, paymentInstrumentId, amount, currency, tupleDigest, expectedRowVersion, state, expiresAt, confirmationRequestId, preRowOriginalRequestId, authorizationVersion] + properties: + subscriptionId: {type: string, format: uuid} + invoiceId: {type: string} + paymentIntentId: {type: string} + paymentInstrumentId: {type: string, format: uuid} + amount: {type: string, pattern: '^[1-9][0-9]*$', description: Exact integer Stripe minor units} + currency: {type: string, pattern: '^[a-z]{3}$'} + tupleDigest: {type: string, pattern: '^sha256:[0-9a-f]{64}$'} + expectedRowVersion: {type: integer, format: int64, minimum: 1} + state: {type: string, enum: [AWAITING_PAYMENT, COMMITTED, CANCELED]} + expiresAt: {type: string, format: date-time} + confirmationRequestId: {type: string, format: uuid, nullable: true} + preRowOriginalRequestId: {type: string, format: uuid, nullable: true, description: Server-verified original operation identity before a confirmation row exists. Observational only; requires fresh explicit consent and PRE_ROW_RENEWAL authentication. Null once a confirmation exists.} + 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 + in: path + required: true + schema: {type: string, format: uuid} + post: + 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. 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: + application/json: + schema: + type: object + additionalProperties: false + required: [requestId, confirmationRequestId, email, secret] + properties: + requestId: {type: string, format: uuid} + confirmationRequestId: {type: string, format: uuid} + email: {type: string, format: email} + secret: {type: string, format: password, writeOnly: true} + billingBinding: + type: object + additionalProperties: false + 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} + expectedRowVersion: {type: integer, format: int64, minimum: 1} + expectedAuthorizationVersion: {type: integer, format: int64, minimum: 0} + acceptedTupleDigest: {type: string, pattern: '^sha256:[0-9a-f]{64}$'} + invoiceExpiresAt: {type: string, format: date-time} + authorizationPurpose: {type: string, enum: [INITIAL_CONFIRMATION, PRE_ROW_RENEWAL, FOLLOWUP_RENEWAL]} + responses: + '200': + description: Retained purpose-specific ordinary reauthentication evidence + content: + application/json: + schema: + type: object + required: [evidenceId] + 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 + '503': {description: AUTH_UNAVAILABLE; Account authentication authority is temporarily unavailable} + /billing/hosting/subscriptions/{subscriptionId}/first-invoice/confirm: + parameters: + - name: subscriptionId + in: path + required: true + schema: {type: string, format: uuid} + post: + summary: Confirm explicit consent for the retained first-invoice payment + operationId: confirmHostingFirstInvoice + 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 + content: + application/json: + schema: + type: object + additionalProperties: false + required: [requestId, expectedRowVersion, reauthenticationEvidenceId, acceptedTupleDigest, acceptCharge] + properties: + requestId: {type: string, format: uuid} + expectedRowVersion: {type: integer, format: int64, minimum: 1} + reauthenticationEvidenceId: {type: string, format: uuid} + acceptedTupleDigest: {type: string, pattern: '^sha256:[0-9a-f]{64}$'} + acceptCharge: {type: boolean, enum: [true]} + responses: + '200': + description: No-store provider status; browser success is not Account fulfillment + content: + application/json: + schema: + type: object + required: [status] + properties: + status: {type: string, enum: [requires_action, processing, succeeded, requires_confirmation, requires_payment_method, AUTHORIZED_NOT_CONFIRMED]} + clientSecret: {type: string, nullable: true, description: Present only for current owner requires_action handoff; never persisted or logged} + '400': {description: Missing explicit charge consent} + '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 + in: path + required: true + schema: {type: string, format: uuid} + post: + summary: Renew authorization for the same first-invoice payment operation + operationId: renewHostingFirstInvoiceAuthorization + x-runtime-status: isolated_only_default_off + description: Fresh primary reauthentication and explicit unchanged consent renew authorization on the original operation. Use expectedAuthorizationVersion zero for PRE_ROW_RENEWAL before a confirmation exists. A prior durable command claim is never resent. + requestBody: + required: true + content: + application/json: + schema: + type: object + additionalProperties: false + required: [requestId, authorizationRequestId, expectedAuthorizationVersion, expectedRowVersion, reauthenticationEvidenceId, acceptedTupleDigest, acceptCharge] + properties: + requestId: {type: string, format: uuid} + authorizationRequestId: {type: string, format: uuid} + expectedAuthorizationVersion: {type: integer, format: int64, minimum: 0} + expectedRowVersion: {type: integer, format: int64, minimum: 1} + reauthenticationEvidenceId: {type: string, format: uuid} + acceptedTupleDigest: {type: string, pattern: '^sha256:[0-9a-f]{64}$'} + acceptCharge: {type: boolean, enum: [true]} + responses: + '200': + description: No-store provider status; browser success is not Account fulfillment + content: + application/json: + schema: + type: object + required: [status] + properties: + status: {type: string, enum: [requires_action, processing, succeeded, requires_confirmation, requires_payment_method, AUTHORIZED_NOT_CONFIRMED]} + clientSecret: {type: string, nullable: true, description: Present only for current owner requires_action handoff; never persisted or logged} + '400': {description: Missing explicit charge consent} + '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 @@ -360,7 +557,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/AccountRuntimeEntitlementNoWriteIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountRuntimeEntitlementNoWriteIntegrationTest.java index 2e71e3b8ac..f5d00ed59b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountRuntimeEntitlementNoWriteIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountRuntimeEntitlementNoWriteIntegrationTest.java @@ -54,7 +54,14 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter; +import org.springframework.cloud.gateway.support.ConfigurationService; import org.springframework.context.ApplicationContext; +import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.core.ReactiveRedisTemplate; +import org.springframework.data.redis.core.ReactiveStringRedisTemplate; import org.springframework.grpc.server.GrpcServerFactory; import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; import org.springframework.mail.javamail.JavaMailSender; @@ -150,6 +157,20 @@ static void configure(DynamicPropertyRegistry registry) throws Exception { @BeforeEach void assertActualDefaultRegistration() { + assertThat(context.getBeansOfType(ConfigurationService.class)).isEmpty(); + assertThat(context.getBeansOfType(RedisRateLimiter.class)).isEmpty(); + var redisConnectionFactory = context.getBean(LettuceConnectionFactory.class); + assertThat(mockingDetails(redisConnectionFactory).isMock()).isFalse(); + assertThat(context.getBean(RedisConnectionFactory.class)).isSameAs(redisConnectionFactory); + assertThat(context.getBean(ReactiveRedisConnectionFactory.class)) + .isSameAs(redisConnectionFactory); + var reactiveRedisTemplate = + context.getBean("reactiveRedisTemplate", ReactiveRedisTemplate.class); + var reactiveStringRedisTemplate = context.getBean(ReactiveStringRedisTemplate.class); + assertThat(mockingDetails(reactiveRedisTemplate).isMock()).isFalse(); + assertThat(mockingDetails(reactiveStringRedisTemplate).isMock()).isFalse(); + assertThat(reactiveRedisTemplate.getConnectionFactory()).isSameAs(redisConnectionFactory); + assertThat(reactiveStringRedisTemplate.getConnectionFactory()).isSameAs(redisConnectionFactory); assertThat(listener.isRunning()).isTrue(); assertThat(listener.getPort()).isPositive(); assertThat(listener.getFactory()).isSameAs(context.getBean(GrpcServerFactory.class)); 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 c7dacc3318..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 @@ -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,60 @@ class AccountHostingSubscriptionDispatchPostgresIntegrationTest { private static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @Test + void unconsentedSignedSuccessRetainsOperatorConflictOnlyForExactInvoice() 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(); + 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 + .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/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java index 96bdcdea26..979d2af404 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 @@ -325,6 +325,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); @@ -1115,6 +1124,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..09965f7169 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountCheckoutRegisteredReceivingPostgresIntegrationTest.java @@ -0,0 +1,746 @@ +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.time.Instant; +import java.time.OffsetDateTime; +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.springcloudgateway.config.GatewayHeaderTrustProperties; +import net.firedevops.firemud.springcloudgateway.config.GatewayTcpProxyListenerProperties; +import net.firedevops.firemud.springcloudgateway.filter.HeaderTrustFilter; +import net.firedevops.firemud.springcloudgateway.filter.TcpProxyTrustPolicy; +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.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; +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; +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.core.publisher.Flux; +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; + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void registeredChainAuthenticatesRealOwnerAndCommitsOnlyExactSignedProviderSuccess( + boolean preRowRenewal) 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, + billingReauthentication( + tuple, confirmation, confirmation, "INITIAL_CONFIRMATION", account.getEmail())); + 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); + 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", authorizationPath, bearer, authorization); + assertThat(handoff.statusCode()).isEqualTo(200); + assertThat(JSON.readTree(handoff.body()).path("status").asText()) + .isEqualTo("requires_action"); + 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()) + .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)); + // 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(); + assertThat( + JSON.readTree(receiving.request("GET", path, bearer, null).body()) + .path("state") + .asText()) + .isEqualTo("COMMITTED"); + assertThat(receiving.rawWebhook(success.payload(), success.signature()).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(); + 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"))); + } + } + } + + 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; + private Server grpc; + private AnnotationConfigApplicationContext gateway; + private DisposableServer gatewayHttps; + private HttpClient browser; + private URI origin; + private ReactiveStringRedisTemplate rateLimitRedis; + private RedisScript> rateLimitScript; + + 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); + 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( + RedisRateLimiter.REDIS_SCRIPT_NAME, RedisScript.class, () -> rateLimitScript); + var headerTrust = new GatewayHeaderTrustProperties(); + gateway.registerBean( + HeaderTrustFilter.class, + () -> + new HeaderTrustFilter( + headerTrust, + new TcpProxyTrustPolicy( + new GatewayTcpProxyListenerProperties(), + headerTrust, + 8080, + java.time.Clock.systemUTC(), + java.util.Set.of("test")))); + gateway.register( + GatewayWebFlux.class, + net.firedevops.firemud.springcloudgateway.config.AccountCheckoutReceivingConfiguration + .class); + // 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()); + 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; + } + } + + @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)); + 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/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java index d2d23bdc9c..8e0f570f12 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java @@ -7,6 +7,9 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; +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 io.lettuce.core.ClientOptions; @@ -14,6 +17,7 @@ import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.api.sync.RedisCommands; import java.nio.charset.StandardCharsets; +import java.time.Clock; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneOffset; @@ -22,10 +26,16 @@ import java.util.Objects; import java.util.Optional; import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl.ControlUiPrimaryIdentity; import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; @@ -97,6 +107,183 @@ void originalPreparedCandidateCommittedAndLostResponseReadBackExactOwnerBytes() assertThat(c.dsl.fetchCount(DSL.table("account_control_ui_response_envelopes"))).isEqualTo(1); } + @Test + void replayDenialsPersistBoundedHistoryWithoutChangingRetainedIssuanceAccountOrOtp() { + Context c = contextAt("1043"); + Fixture f = new Fixture(c); + var original = f.prepare(300_000L, AccountControlUiOwnerSourcesFixture.CALLER); + c.tx( + () -> + c.dsl.execute( + "INSERT INTO account_email_login_challenge" + + " (account_id, code_hash, expires_at, resend_available_at, created_at, updated_at)" + + " SELECT id, 'test-only-original-otp-hash', CURRENT_TIMESTAMP + INTERVAL '5 minutes'," + + " CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP FROM accounts WHERE account_uuid = ?", + f.actor)); + var accountBefore = + Objects.requireNonNull( + c.dsl.fetchOne("SELECT * FROM accounts WHERE account_uuid = ?", f.actor)) + .intoMap(); + var otpBefore = + Objects.requireNonNull(c.dsl.fetchOne("SELECT * FROM account_email_login_challenge")) + .intoMap(); + migrateToLatest(c); + var primary = mock(AccountServiceImpl.class); + var cryptography = mock(AccountControlUiResponseCryptography.class); + when(cryptography.requestDigest(anyString(), any(byte[].class))).thenReturn("a".repeat(64)); + var service = replayService(c, primary, cryptography); + var request = + new AccountControlUiIssuanceService.Request( + original.requestId, + "owner@example.test", + "wrong-secret", + original.tenantId, + original.callerContextId); + try (var peer = AccountControlUiOwnerSourcesFixture.withPeer(original.caller)) { + for (int failure = 1; failure <= 5; failure++) { + assertThatThrownBy(() -> service.issue(request, mock(CapturedEnvironmentBoundary.class))) + .isInstanceOf(AccountControlUiIssuanceService.IdempotencyConflictException.class); + // A fresh transaction/repository observes the denial's committed history. + assertThat( + c.tx( + () -> + new AccountControlUiIssuanceRepository(c.dsl) + .countReplayFailures(original))) + .isEqualTo(failure); + } + // Even a now-correct secret cannot reach its MAC verifier after budget exhaustion. + when(cryptography.requestDigest(anyString(), any(byte[].class))) + .thenReturn(original.requestDigest); + assertThatThrownBy(() -> service.issue(request, mock(CapturedEnvironmentBoundary.class))) + .isInstanceOf(AccountControlUiIssuanceService.IdempotencyConflictException.class); + } + verify(cryptography, times(5)).requestDigest(anyString(), any(byte[].class)); + verifyNoInteractions(primary); + assertThat( + Objects.requireNonNull( + c.dsl.fetchOne("SELECT * FROM accounts WHERE account_uuid = ?", f.actor)) + .intoMap()) + .isEqualTo(accountBefore); + assertThat( + Objects.requireNonNull(c.dsl.fetchOne("SELECT * FROM account_email_login_challenge")) + .intoMap()) + .isEqualTo(otpBefore); + assertOriginal(original, c.tx(() -> c.operations.findRequest(original.requestId))); + var independent = + c.tx( + () -> + c.operations.prepare( + UUID.randomUUID(), + original.caller, + UUID.randomUUID(), + "test-mac1", + "c".repeat(64), + f.primary, + f.authority, + f.signer, + Instant.now().truncatedTo(java.time.temporal.ChronoUnit.SECONDS), + 300_000L)); + assertThat(c.tx(() -> c.operations.countReplayFailures(independent))).isZero(); + + assertThatThrownBy( + () -> + c.tx( + () -> + c.dsl.execute( + "INSERT INTO account_control_ui_issuance_replay_failures VALUES (?, ?, 1)", + independent.operationId, + original.requestId))) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("exact original request"); + assertThatThrownBy( + () -> + c.tx( + () -> + c.dsl.execute( + "INSERT INTO account_control_ui_issuance_replay_failures VALUES (?, ?, 6)", + original.operationId, + original.requestId))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + c.tx( + () -> + c.dsl.execute( + "UPDATE account_control_ui_issuance_replay_failures SET failure_number = 1"))) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("immutable"); + assertThatThrownBy( + () -> + c.tx( + () -> c.dsl.execute("DELETE FROM account_control_ui_issuance_replay_failures"))) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("immutable"); + assertThatThrownBy( + () -> c.tx(() -> c.dsl.execute("TRUNCATE account_control_ui_issuance_replay_failures"))) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("immutable"); + } + + @Test + void concurrentReplayGuessesShareOneFiveFailureBudget() throws Exception { + Context c = context(); + Fixture f = new Fixture(c); + var original = f.prepare(300_000L, AccountControlUiOwnerSourcesFixture.CALLER); + var primary = mock(AccountServiceImpl.class); + var cryptography = mock(AccountControlUiResponseCryptography.class); + when(cryptography.requestDigest(anyString(), any(byte[].class))).thenReturn("a".repeat(64)); + var service = replayService(c, primary, cryptography); + var request = + new AccountControlUiIssuanceService.Request( + original.requestId, + "owner@example.test", + "wrong-secret", + original.tenantId, + original.callerContextId); + var start = new CountDownLatch(1); + try (var workers = Executors.newFixedThreadPool(8)) { + var attempts = new java.util.ArrayList>(); + for (int index = 0; index < 8; index++) { + attempts.add( + workers.submit( + () -> { + try (var peer = AccountControlUiOwnerSourcesFixture.withPeer(original.caller)) { + if (!start.await(10, TimeUnit.SECONDS)) + throw new AssertionError("Replay start timed out"); + assertThatThrownBy( + () -> service.issue(request, mock(CapturedEnvironmentBoundary.class))) + .isInstanceOf( + AccountControlUiIssuanceService.IdempotencyConflictException.class); + } + return null; + })); + } + start.countDown(); + for (var attempt : attempts) attempt.get(15, TimeUnit.SECONDS); + } + assertThat(c.tx(() -> c.operations.countReplayFailures(original))).isEqualTo(5); + verify(cryptography, times(5)).requestDigest(anyString(), any(byte[].class)); + verifyNoInteractions(primary); + assertOriginal(original, c.tx(() -> c.operations.findRequest(original.requestId))); + } + + private static AccountControlUiIssuanceService replayService( + Context c, AccountServiceImpl primary, AccountControlUiResponseCryptography cryptography) { + return new AccountControlUiIssuanceService( + primary, + c.operations, + mock(AccountControlUiAuthority.class), + mock(DraftAuthorizationFenceRepository.class), + mock(AccountControlUiSignerOwner.class), + cryptography, + mock(AccountControlUiCoordination.class), + mock(AccountControlUiActorService.class), + Objects.requireNonNull(c.transaction.getTransactionManager()), + Clock.systemUTC(), + 300_000L, + AccountControlUiOwnerSourcesFixture.CALLER); + } + @Test void explicitlyConfiguredZeroMarginIsPresentOnNewOwnerRows() { Context c = context(); @@ -333,6 +520,9 @@ private static void assertOriginal( assertThat(observed.operationId).isEqualTo(original.operationId); assertThat(observed.requestId).isEqualTo(original.requestId); assertThat(observed.jti).isEqualTo(original.jti); + assertThat(observed.accountId).isEqualTo(original.accountId); + assertThat(observed.tenantId).isEqualTo(original.tenantId); + assertThat(observed.scopeKind).isEqualTo(original.scopeKind); assertThat(observed.claims).isEqualTo(original.claims); assertThat(observed.sources).isEqualTo(original.sources); assertThat(observed.bundle).isEqualTo(original.bundle); @@ -463,11 +653,16 @@ AccountControlUiIssuanceRepository.Stored prepare() { } AccountControlUiIssuanceRepository.Stored prepare(long sessionSafetyMarginMillis) { + return prepare(sessionSafetyMarginMillis, "spiffe://test-only/control-ui"); + } + + AccountControlUiIssuanceRepository.Stored prepare( + long sessionSafetyMarginMillis, String caller) { return c.tx( () -> c.operations.prepare( request, - "spiffe://test-only/control-ui", + caller, UUID.randomUUID(), "test-mac1", "c".repeat(64), diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java index 23dc02b9f1..c2f094c037 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java @@ -57,6 +57,7 @@ import net.firedevops.firemud.accountservice.service.impl.StartSessionOperatorAuthorizationGrpcService; import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.OwnerKeySource; import net.firedevops.firemud.accountservice.testsupport.AccountStartSessionReservationProofPki; +import net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec.SourceContext; import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; @@ -795,7 +796,8 @@ private static void assertCertifiedAccountSignIn( assertThat( f.dsl .fetchSingle( - "SELECT count(*) AS count FROM account_platform_restriction_current_projections WHERE account_uuid = ?", + "SELECT count(*) AS count FROM account_platform_restriction_current_projections" + + " WHERE account_uuid = ?", accountId) .get("count", Long.class)) .isEqualTo(2L); @@ -807,7 +809,11 @@ private static void assertCertifiedAccountSignIn( int beforeEnvelopes = f.dsl.fetchCount(DSL.table("account_control_ui_response_envelopes")); var passwordRequest = new AccountControlUiIssuanceService.AccountSignInRequest( - UUID.randomUUID(), account.getEmail(), password, UUID.randomUUID()); + UUID.randomUUID(), + account.getEmail(), + password, + UUID.randomUUID(), + new SourceContext("192.0.2.10")); String passwordCompact; try (var peer = AccountControlUiOwnerSourcesFixture.withPeer( @@ -903,7 +909,11 @@ private static void assertCertifiedAccountSignIn( f.installGlobalOtp(account, otp); var otpRequest = new AccountControlUiIssuanceService.AccountSignInRequest( - UUID.randomUUID(), account.getEmail(), otp, UUID.randomUUID()); + UUID.randomUUID(), + account.getEmail(), + otp, + UUID.randomUUID(), + new SourceContext("192.0.2.10")); byte[] originalCompact; Instant expiry, recoveryExpiry; try (var peer = @@ -920,10 +930,18 @@ private static void assertCertifiedAccountSignIn( try (var peer = AccountControlUiOwnerSourcesFixture.withPeer( AccountControlUiOwnerSourcesFixture.CALLER); - var retry = issuance.issueAccount(otpRequest)) { + var retry = + issuance.issueAccount( + new AccountControlUiIssuanceService.AccountSignInRequest( + otpRequest.requestId(), + otpRequest.email(), + otpRequest.secret(), + otpRequest.callerContextId(), + new SourceContext("198.51.100.20")))) { assertThat(retry.compactBytes()).isEqualTo(originalCompact); assertThat(retry.expiresAt()).isEqualTo(expiry); assertThat(retry.recoveryExpiresAt()).isEqualTo(recoveryExpiry); + assertThat(f.tx(() -> operations.countReplayFailures(otpOperation))).isZero(); assertThatThrownBy( () -> issuance.issueAccount( @@ -931,7 +949,8 @@ private static void assertCertifiedAccountSignIn( otpRequest.requestId(), account.getEmail(), "changed-secret", - otpRequest.callerContextId()))) + otpRequest.callerContextId(), + new SourceContext("192.0.2.10")))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Control-ui issuance idempotency conflict"); assertThatThrownBy( @@ -941,14 +960,19 @@ private static void assertCertifiedAccountSignIn( otpRequest.requestId(), "changed@example.test", otp, - otpRequest.callerContextId()))) + otpRequest.callerContextId(), + new SourceContext("192.0.2.10")))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Control-ui issuance idempotency conflict"); assertThatThrownBy( () -> issuance.issueAccount( new AccountControlUiIssuanceService.AccountSignInRequest( - otpRequest.requestId(), account.getEmail(), otp, UUID.randomUUID()))) + otpRequest.requestId(), + account.getEmail(), + otp, + UUID.randomUUID(), + new SourceContext("192.0.2.10")))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Control-ui issuance idempotency conflict"); assertThatThrownBy( @@ -963,6 +987,40 @@ private static void assertCertifiedAccountSignIn( environment)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Control-ui issuance idempotency conflict"); + // Only the two credential-bearing mismatches above count. Foreign context and scope + // conflicts cannot consume the original request's budget or its already-consumed OTP. + assertThat(f.tx(() -> operations.countReplayFailures(otpOperation))).isEqualTo(2); + for (int failure = 3; failure <= 4; failure++) { + assertThatThrownBy( + () -> + issuance.issueAccount( + new AccountControlUiIssuanceService.AccountSignInRequest( + otpRequest.requestId(), + account.getEmail(), + "wrong-replay-secret", + otpRequest.callerContextId(), + new SourceContext("192.0.2.10")))) + .isInstanceOf(AccountControlUiIssuanceService.IdempotencyConflictException.class); + } + try (var afterFailures = issuance.issueAccount(otpRequest)) { + assertThat(afterFailures.compactBytes()).isEqualTo(originalCompact); + assertThat(afterFailures.expiresAt()).isEqualTo(expiry); + assertThat(afterFailures.recoveryExpiresAt()).isEqualTo(recoveryExpiry); + } + assertThat(f.tx(() -> operations.countReplayFailures(otpOperation))).isEqualTo(4); + assertThatThrownBy( + () -> + issuance.issueAccount( + new AccountControlUiIssuanceService.AccountSignInRequest( + otpRequest.requestId(), + account.getEmail(), + "fifth-wrong-secret", + otpRequest.callerContextId(), + new SourceContext("192.0.2.10")))) + .isInstanceOf(AccountControlUiIssuanceService.IdempotencyConflictException.class); + assertThatThrownBy(() -> issuance.issueAccount(otpRequest)) + .isInstanceOf(AccountControlUiIssuanceService.IdempotencyConflictException.class); + assertThat(f.tx(() -> operations.countReplayFailures(otpOperation))).isEqualTo(5); } assertThat(f.challenges.findByAccountId(account.getId())).isEmpty(); var retryOperation = f.tx(() -> operations.findRequest(otpRequest.requestId())); @@ -1055,11 +1113,12 @@ private static List freshEnrollmentPolicyEvidence( fixture .dsl .fetch( - "SELECT category, revision::text AS revision, publication_id::text AS publication_id," - + " policy_id::text AS policy_id, closure_id::text AS closure_id, policy_rule," - + " closure_rule, source_identity, source_root, publication_digest," - + " encode(publication_bytes, 'hex') AS publication_bytes_hex" - + " FROM account_fresh_enrollment_policy_publications ORDER BY category, revision") + "SELECT category, revision::text AS revision, publication_id::text AS" + + " publication_id, policy_id::text AS policy_id, closure_id::text AS" + + " closure_id, policy_rule, closure_rule, source_identity, source_root," + + " publication_digest, encode(publication_bytes, 'hex') AS" + + " publication_bytes_hex FROM account_fresh_enrollment_policy_publications" + + " ORDER BY category, revision") .stream() .map(record -> Arrays.toString(record.intoArray())) .toList(); @@ -1067,8 +1126,8 @@ private static List freshEnrollmentPolicyEvidence( fixture .dsl .fetch( - "SELECT category, publication_id::text AS publication_id, revision::text AS revision" - + " FROM account_fresh_enrollment_policy_current ORDER BY category") + "SELECT category, publication_id::text AS publication_id, revision::text AS" + + " revision FROM account_fresh_enrollment_policy_current ORDER BY category") .stream() .map(record -> Arrays.toString(record.intoArray())) .toList(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiIssuancePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiIssuancePostgresIntegrationTest.java index 57d5842106..5ed7418de1 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiIssuancePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiIssuancePostgresIntegrationTest.java @@ -12,6 +12,7 @@ import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionMutationRequest.SourceKind; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.repository.AccountPlatformRestrictionOperationRepository; +import net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec.SourceContext; import net.firedevops.firemud.test.TestContainerImages; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -69,7 +70,11 @@ void unavailableCurrentRestrictionRollsBackActualOtpAndRetainsSameChallengeAcros var original = fixture.installGlobalOtp(account, OTP); var request = new AccountControlUiIssuanceService.AccountSignInRequest( - UUID.randomUUID(), account.getEmail(), OTP, UUID.randomUUID()); + UUID.randomUUID(), + account.getEmail(), + OTP, + UUID.randomUUID(), + new SourceContext("192.0.2.10")); try (var ignored = AccountControlUiOwnerSourcesFixture.withPeer(AccountControlUiOwnerSourcesFixture.CALLER)) { @@ -147,8 +152,9 @@ void exactBirthPredecessorsCannotAuthorizePublicRestrictionCommitOrCurrentAbsenc assertThat( Objects.requireNonNull( fixture.dsl.fetchOne( - "SELECT count(*) AS result_count FROM account_platform_restriction_current_projections " - + "WHERE account_uuid = ?", + "SELECT count(*) AS result_count FROM" + + " account_platform_restriction_current_projections WHERE account_uuid" + + " = ?", account.getAccountUuid())) .get("result_count", Long.class)) .isZero(); @@ -185,7 +191,8 @@ private static void assertNoMembership( assertThat( Objects.requireNonNull( fixture.dsl.fetchOne( - "SELECT count(*) AS result_count FROM account_tenant_membership WHERE account_id = ?", + "SELECT count(*) AS result_count FROM account_tenant_membership WHERE" + + " account_id = ?", account.getId())) .get("result_count", Long.class)) .isZero(); 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 new file mode 100644 index 0000000000..c20b71171a --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingFirstInvoiceHttpsCompositionPostgresIntegrationTest.java @@ -0,0 +1,1571 @@ +package net.firedevops.firemud.accountservice.service.session; + +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; +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.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; +import net.firedevops.firemud.accountservice.repository.StripeEventInboxRepository; +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.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; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; +import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; +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 tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Actual HTTPS/MVC to genuine Account control-ui/current primary authentication and PostgreSQL. + * Test signer/policy/custody and Stripe SDK transport are controlled. No live charge, registration + * or installed custody is established. This definition requires physical Docker execution. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AccountHostingFirstInvoiceHttpsCompositionPostgresIntegrationTest { + private static final String PASSWORD = "test-only-first-invoice-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("first-invoice-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", + "first-invoice-primary", + "6379"); + + @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 { + try (var owners = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary)) { + var issued = owners.issueCertifiedAccount(PASSWORD); + var hosting = + CanonicalHostingSubscriptionTestFixture.createAwaitingPayment( + Objects.requireNonNull(issued.sources().manager.getDataSource()), issued.account()); + var reauthentication = + new AccountRecentReauthenticationService( + issued.sources().primary, + issued.sources().accounts, + new AccountAuthorityGenerationRepository(hosting.dsl()), + new AccountRecentReauthenticationRepository(hosting.dsl()), + new AccountRecentReauthenticationPolicyRepository(hosting.dsl()), + issued.sources().manager, + hosting.clock(), + new AccountControlUiResponseCryptography( + new AccountControlUiKeyring(temporary.resolve("custody")), hosting.clock())); + var payments = + new AccountHostingFirstInvoicePaymentService( + issued.actors(), + reauthentication, + hosting.firstInvoiceRepository(), + new StripeEventInboxRepository(hosting.dsl()), + hosting.firstInvoiceProvider(), + hosting.webhookVerifier(), + hosting.service(), + issued.sources().manager); + var renewalGate = new OwnerEntryGate("/first-invoice/renew"); + try (var https = + new HttpsReceiver( + temporary, new AccountHostingFirstInvoiceController(payments), renewalGate); + var requestExecutor = new TestRequestExecutor(); + var releaseRenewalGate = renewalGate) { + String path = + "/billing/hosting/subscriptions/" + + hosting.creation().subscriptionId() + + "/first-invoice"; + var unauthenticated = https.request("GET", path, null, null); + assertThat(unauthenticated.statusCode()).isEqualTo(401); + assertThat(unauthenticated.body()).doesNotContain("secret_", PASSWORD); + var owner = https.request("GET", path, issued.compact(), null); + assertThat(owner.statusCode()).isEqualTo(200); + assertThat(owner.headers().firstValue("cache-control")).contains("no-store"); + JsonNode tuple = JSON.readTree(owner.body()); + assertThat(tuple.path("state").asText()).isEqualTo("AWAITING_PAYMENT"); + assertThat(tuple.path("amount").asText()).isEqualTo("2400"); + assertThat(tuple.path("currency").asText()).isEqualTo("usd"); + assertThat(tuple.path("confirmationRequestId").isNull()).isTrue(); + assertNoReceipt(hosting); + + UUID confirmation = UUID.randomUUID(); + var unboundProof = + https.request( + "POST", + path + "/reauthenticate", + issued.compact(), + Map.of( + "requestId", + UUID.randomUUID(), + "confirmationRequestId", + confirmation, + "email", + issued.account().getEmail(), + "secret", + PASSWORD)); + assertThat(unboundProof.statusCode()).isEqualTo(409); + assertThat(count(hosting, "SELECT count(*) FROM account_recent_reauthentication_evidence")) + .isZero(); + assertThat( + count(hosting, "SELECT count(*) FROM subscription_first_invoice_operation_fences")) + .isZero(); + var proof = + https.request( + "POST", + path + "/reauthenticate", + issued.compact(), + billingReauthenticationRequest( + tuple, + UUID.randomUUID(), + confirmation, + confirmation, + 0L, + "INITIAL_CONFIRMATION", + issued.account().getEmail())); + assertThat(proof.statusCode()).isEqualTo(200); + UUID evidence = UUID.fromString(JSON.readTree(proof.body()).path("evidenceId").asText()); + assertThat( + hosting + .dsl() + .fetchSingle( + "SELECT purpose FROM account_recent_reauthentication_evidence WHERE evidence_id = ?", + evidence) + .get(0, String.class)) + .isEqualTo(AccountRecentReauthenticationPolicy.BILLING_PURPOSE); + UUID competingAuthorization = UUID.randomUUID(); + var competingProof = + https.request( + "POST", + path + "/reauthenticate", + issued.compact(), + billingReauthenticationRequest( + tuple, + UUID.randomUUID(), + competingAuthorization, + confirmation, + 0L, + "PRE_ROW_RENEWAL", + issued.account().getEmail())); + assertThat(competingProof.statusCode()).isEqualTo(200); + UUID competingEvidence = + UUID.fromString(JSON.readTree(competingProof.body()).path("evidenceId").asText()); + Map consent = + Map.of( + "requestId", + confirmation, + "expectedRowVersion", + tuple.path("expectedRowVersion").asLong(), + "reauthenticationEvidenceId", + evidence, + "acceptedTupleDigest", + tuple.path("tupleDigest").asText(), + "acceptCharge", + true); + Map stalePreRowRenewal = + Map.of( + "requestId", + confirmation, + "authorizationRequestId", + competingAuthorization, + "expectedRowVersion", + tuple.path("expectedRowVersion").asLong(), + "expectedAuthorizationVersion", + 0L, + "reauthenticationEvidenceId", + competingEvidence, + "acceptedTupleDigest", + tuple.path("tupleDigest").asText(), + "acceptCharge", + true); + var delayedPreRowRenewal = + asyncRequest( + https, + "POST", + path + "/renew", + issued.compact(), + stalePreRowRenewal, + null, + requestExecutor); + assertThat(renewalGate.arrived.await(30, TimeUnit.SECONDS)).isTrue(); + hosting.firstInvoiceConfirmationStatus("requires_action"); + var openingEvidenceBefore = + hosting + .dsl() + .fetchSingle( + "SELECT encode(request_payload, 'hex') AS request_payload_hex, request_digest, " + + "billing_context_digest, xmin::text AS row_xmin " + + "FROM account_recent_reauthentication_evidence WHERE evidence_id = ?", + evidence); + hosting + .dsl() + .execute( + "CREATE FUNCTION reject_first_invoice_authorization() RETURNS TRIGGER LANGUAGE plpgsql AS $$ " + + "BEGIN RAISE EXCEPTION 'controlled first-invoice authorization rollback' USING ERRCODE='23514'; END; $$"); + hosting + .dsl() + .execute( + "CREATE TRIGGER reject_first_invoice_authorization BEFORE INSERT ON " + + "subscription_first_invoice_authorizations FOR EACH ROW " + + "EXECUTE FUNCTION reject_first_invoice_authorization()"); + try { + assertThat( + https.request("POST", path + "/confirm", issued.compact(), consent).statusCode()) + .isEqualTo(500); + assertThat(consumptionCount(hosting, evidence)).isZero(); + assertThat( + count(hosting, "SELECT count(*) FROM subscription_first_invoice_confirmations")) + .isZero(); + assertThat(count(hosting, "SELECT count(*) FROM subscription_first_invoice_dispatches")) + .isZero(); + assertThat( + count(hosting, "SELECT count(*) FROM subscription_first_invoice_authorizations")) + .isZero(); + assertThat( + count( + hosting, "SELECT count(*) FROM subscription_first_invoice_operation_fences")) + .isOne(); + assertNoReceipt(hosting); + assertThat( + hosting + .dsl() + .fetchSingle( + "SELECT encode(request_payload, 'hex') AS request_payload_hex, request_digest, " + + "billing_context_digest, xmin::text AS row_xmin " + + "FROM account_recent_reauthentication_evidence WHERE evidence_id = ?", + evidence)) + .isEqualTo(openingEvidenceBefore); + } finally { + hosting + .dsl() + .execute( + "DROP TRIGGER reject_first_invoice_authorization ON subscription_first_invoice_authorizations"); + hosting.dsl().execute("DROP FUNCTION reject_first_invoice_authorization()"); + } + hosting.loseNextFirstInvoiceConfirmationResponse(); + var uncertain = https.request("POST", path + "/confirm", issued.compact(), consent); + assertThat(uncertain.statusCode()).isEqualTo(502); + assertThat(uncertain.body()).contains("FIRST_INVOICE_PROVIDER_UNCERTAIN"); + assertThat(hosting.firstInvoiceConfirmations()).isEqualTo(1); + assertThat(count(hosting, "SELECT count(*) FROM subscription_first_invoice_command_claims")) + .isOne(); + var retryStart = new CountDownLatch(1); + var exactRetryOne = + asyncRequest( + https, + "POST", + path + "/confirm", + issued.compact(), + consent, + retryStart, + requestExecutor); + var exactRetryTwo = + asyncRequest( + https, + "POST", + path + "/confirm", + issued.compact(), + consent, + retryStart, + requestExecutor); + retryStart.countDown(); + var handoff = exactRetryOne.get(60, TimeUnit.SECONDS); + var duplicateHandoff = exactRetryTwo.get(60, TimeUnit.SECONDS); + assertThat(handoff.statusCode()).isEqualTo(200); + assertThat(duplicateHandoff.statusCode()).isEqualTo(200); + assertThat(handoff.headers().firstValue("cache-control")).contains("no-store"); + assertThat(JSON.readTree(handoff.body()).path("status").asText()) + .isEqualTo("requires_action"); + assertThat(JSON.readTree(duplicateHandoff.body()).path("status").asText()) + .isEqualTo("requires_action"); + assertThat(JSON.readTree(handoff.body()).path("clientSecret").asText()) + .startsWith(hosting.firstInvoice().paymentIntentId() + "_secret_"); + assertThat(hosting.firstInvoiceConfirmations()).isEqualTo(1); + assertThat( + hosting + .dsl() + .fetchSingle( + "SELECT provider_idempotency_id FROM subscription_first_invoice_confirmations " + + "WHERE request_id = ?", + confirmation) + .get("provider_idempotency_id", UUID.class) + .toString()) + .isEqualTo(hosting.lastFirstInvoiceConfirmationIdempotencyKey()); + assertNoReceipt(hosting); + releaseRenewalGate.releaseNow(); + assertThat(delayedPreRowRenewal.get(60, TimeUnit.SECONDS).statusCode()).isEqualTo(409); + assertThat(consumptionCount(hosting, competingEvidence)).isZero(); + assertThat(consumptionCount(hosting, evidence)).isOne(); + UUID authorization = UUID.randomUUID(); + var renewedProof = + https.request( + "POST", + path + "/reauthenticate", + issued.compact(), + billingReauthenticationRequest( + tuple, + UUID.randomUUID(), + authorization, + confirmation, + 1L, + "FOLLOWUP_RENEWAL", + issued.account().getEmail())); + assertThat(renewedProof.statusCode()).isEqualTo(200); + Map renewal = new java.util.HashMap<>(consent); + renewal.put("authorizationRequestId", authorization); + renewal.put("expectedAuthorizationVersion", 1); + renewal.put( + "reauthenticationEvidenceId", + JSON.readTree(renewedProof.body()).path("evidenceId").asText()); + var changed = new java.util.HashMap<>(renewal); + changed.put("acceptedTupleDigest", "sha256:" + "c".repeat(64)); + assertThat(https.request("POST", path + "/renew", issued.compact(), changed).statusCode()) + .isEqualTo(409); + var renewed = https.request("POST", path + "/renew", issued.compact(), renewal); + assertThat(renewed.statusCode()).isEqualTo(200); + assertThat(JSON.readTree(renewed.body()).path("status").asText()) + .isEqualTo("requires_action"); + assertThat(renewed.headers().firstValue("cache-control")).contains("no-store"); + assertThat(https.request("POST", path + "/renew", issued.compact(), renewal).statusCode()) + .isEqualTo(200); + assertThat(hosting.firstInvoiceConfirmations()).isEqualTo(1); + assertThat( + hosting + .dsl() + .fetchSingle("SELECT count(*) FROM subscription_first_invoice_command_claims") + .get(0, Long.class)) + .isOne(); + assertThat( + hosting + .dsl() + .fetchSingle("SELECT count(*) FROM subscription_first_invoice_authorizations") + .get(0, Long.class)) + .isEqualTo(2); + // A newer explicit authorization invalidates older disclosure/command permissions. + assertThat(https.request("POST", path + "/confirm", issued.compact(), consent).statusCode()) + .isEqualTo(409); + assertThat( + JSON.readTree(https.request("GET", path, issued.compact(), null).body()) + .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"); + assertThat( + JSON.readTree(https.request("GET", path, issued.compact(), null).body()) + .path("state") + .asText()) + .isEqualTo("AWAITING_PAYMENT"); + assertNoReceipt(hosting); + String signedPayload = hosting.signedSuccessPayload(); + String signedHeader = hosting.signedSuccessHeader(); + long auditBefore = + hosting + .dsl() + .fetchSingle("SELECT count(*) FROM account_audit_outbox") + .get(0, Long.class); + hosting + .dsl() + .execute( + "CREATE FUNCTION reject_first_invoice_billing() RETURNS TRIGGER LANGUAGE plpgsql AS $$ " + + "BEGIN RAISE EXCEPTION 'controlled first-invoice billing rollback' USING ERRCODE='23514'; END; $$"); + hosting + .dsl() + .execute( + "CREATE TRIGGER reject_first_invoice_billing BEFORE INSERT ON account_tenant_entitlement_outbox_events " + + "FOR EACH ROW EXECUTE FUNCTION reject_first_invoice_billing()"); + try { + assertThatThrownBy(() -> payments.completeSigned(signedPayload, signedHeader)) + .hasStackTraceContaining("controlled first-invoice billing rollback"); + assertNoReceipt(hosting); + assertThat( + hosting + .dsl() + .fetchSingle("SELECT count(*) FROM subscription_first_invoice_completions") + .get(0, Long.class)) + .isZero(); + assertThat( + hosting + .dsl() + .fetchSingle("SELECT count(*) FROM account_audit_outbox") + .get(0, Long.class)) + .isEqualTo(auditBefore); + assertThat( + hosting + .dsl() + .fetchSingle("SELECT count(*) FROM stripe_event_inbox") + .get(0, Long.class)) + .isOne(); + assertThat( + hosting + .dsl() + .fetchSingle( + "SELECT count(*) FROM subscription_first_invoice_success_evidence") + .get(0, Long.class)) + .isOne(); + } finally { + hosting + .dsl() + .execute( + "DROP TRIGGER reject_first_invoice_billing ON account_tenant_entitlement_outbox_events"); + hosting.dsl().execute("DROP FUNCTION reject_first_invoice_billing()"); + } + var immutableIntake = + hosting + .dsl() + .fetchSingle( + "SELECT raw_payload, payload_sha256, xmin::text AS retained_xmin FROM stripe_event_inbox"); + hosting.clock().advance(Duration.ofSeconds(12)); + assertThat(payments.completeSigned(signedPayload, signedHeader).state()) + .isEqualTo("COMMITTED"); + assertThat( + hosting + .dsl() + .fetchSingle( + "SELECT raw_payload, payload_sha256, xmin::text AS retained_xmin FROM stripe_event_inbox")) + .isEqualTo(immutableIntake); + assertThat(hosting.firstInvoiceConfirmations()).isEqualTo(1); + var complete = https.request("GET", path, issued.compact(), null); + assertThat(JSON.readTree(complete.body()).path("state").asText()).isEqualTo("COMMITTED"); + assertThat(complete.body()).doesNotContain("clientSecret", "secret_", PASSWORD); + var atomic = + hosting + .dsl() + .fetchSingle( + "SELECT c.committed_transaction_id AS completion_tx, r.committed_transaction_id AS receipt_tx " + + "FROM subscription_first_invoice_completions c JOIN subscription_lifecycle_receipts r " + + "ON r.request_id=c.lifecycle_request_id WHERE c.subscription_id=?", + hosting.creation().subscriptionId()); + assertThat(atomic.get("completion_tx", Long.class)) + .isEqualTo(atomic.get("receipt_tx", Long.class)); + } + } + } + + @Test + void delayedOriginalConfirmationLosesToExplicitPreRowRenewalWithoutConsumingItsProof() + throws Exception { + try (var owners = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary)) { + var issued = owners.issueCertifiedAccount(PASSWORD); + var hosting = + CanonicalHostingSubscriptionTestFixture.createAwaitingPayment( + Objects.requireNonNull(issued.sources().manager.getDataSource()), issued.account()); + var reauthentication = + new AccountRecentReauthenticationService( + issued.sources().primary, + issued.sources().accounts, + new AccountAuthorityGenerationRepository(hosting.dsl()), + new AccountRecentReauthenticationRepository(hosting.dsl()), + new AccountRecentReauthenticationPolicyRepository(hosting.dsl()), + issued.sources().manager, + hosting.clock(), + new AccountControlUiResponseCryptography( + new AccountControlUiKeyring(temporary.resolve("custody")), hosting.clock())); + var payments = + new AccountHostingFirstInvoicePaymentService( + issued.actors(), + reauthentication, + hosting.firstInvoiceRepository(), + new StripeEventInboxRepository(hosting.dsl()), + hosting.firstInvoiceProvider(), + hosting.webhookVerifier(), + hosting.service(), + issued.sources().manager); + var gate = new OwnerEntryGate("/first-invoice/confirm"); + var renewalGate = new OwnerEntryGate("/first-invoice/renew", 2, false); + try (var https = + new HttpsReceiver( + temporary, + new AccountHostingFirstInvoiceController(payments), + gate, + renewalGate); + var requestExecutor = new TestRequestExecutor(); + var releaseConfirmationGate = gate; + var releaseRenewalGate = renewalGate) { + String path = + "/billing/hosting/subscriptions/" + + hosting.creation().subscriptionId() + + "/first-invoice"; + JsonNode tuple = JSON.readTree(https.request("GET", path, issued.compact(), null).body()); + UUID originalRequestId = UUID.randomUUID(); + UUID openingProofRequestId = UUID.randomUUID(); + var openingRequest = + billingReauthenticationRequest( + tuple, + openingProofRequestId, + originalRequestId, + originalRequestId, + 0L, + "INITIAL_CONFIRMATION", + issued.account().getEmail()); + hosting + .dsl() + .execute( + """ + CREATE FUNCTION fixture_refuse_opening_fence() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN + RAISE EXCEPTION 'controlled first-invoice fence rollback' USING ERRCODE = '23514'; + END; + $$ + """); + hosting + .dsl() + .execute( + "CREATE TRIGGER fixture_refuse_opening_fence BEFORE INSERT" + + " ON subscription_first_invoice_operation_fences FOR EACH ROW" + + " EXECUTE FUNCTION fixture_refuse_opening_fence()"); + try { + assertThat( + https + .request("POST", path + "/reauthenticate", issued.compact(), openingRequest) + .statusCode()) + .isGreaterThanOrEqualTo(400); + assertThat( + hosting + .dsl() + .fetchSingle( + "SELECT count(*) FROM account_recent_reauthentication_evidence WHERE request_id = ?", + openingProofRequestId) + .get(0, Long.class)) + .isZero(); + assertThat( + count( + hosting, "SELECT count(*) FROM subscription_first_invoice_operation_fences")) + .isZero(); + } finally { + hosting + .dsl() + .execute( + "DROP TRIGGER fixture_refuse_opening_fence ON subscription_first_invoice_operation_fences"); + hosting.dsl().execute("DROP FUNCTION fixture_refuse_opening_fence()"); + } + var openingProof = + https.request("POST", path + "/reauthenticate", issued.compact(), openingRequest); + assertThat(openingProof.statusCode()).isEqualTo(200); + UUID openingEvidence = + UUID.fromString(JSON.readTree(openingProof.body()).path("evidenceId").asText()); + Map originalConsent = + Map.of( + "requestId", + originalRequestId, + "expectedRowVersion", + tuple.path("expectedRowVersion").asLong(), + "reauthenticationEvidenceId", + openingEvidence, + "acceptedTupleDigest", + tuple.path("tupleDigest").asText(), + "acceptCharge", + true); + hosting.firstInvoiceConfirmationStatus("requires_action"); + var delayedOriginal = + asyncRequest( + https, + "POST", + path + "/confirm", + issued.compact(), + originalConsent, + null, + requestExecutor); + assertThat(gate.arrived.await(30, TimeUnit.SECONDS)).isTrue(); + + JsonNode whileDelayed = + JSON.readTree(https.request("GET", path, issued.compact(), null).body()); + assertThat(whileDelayed.path("confirmationRequestId").isNull()).isTrue(); + assertThat(whileDelayed.path("authorizationVersion").asLong()).isZero(); + UUID recoveredOriginalRequestId = + UUID.fromString(whileDelayed.path("preRowOriginalRequestId").asText()); + assertThat(recoveredOriginalRequestId).isEqualTo(originalRequestId); + assertThat(whileDelayed.has("reauthenticationEvidenceId")).isFalse(); + assertThat(whileDelayed.has("clientSecret")).isFalse(); + assertThat(count(hosting, "SELECT count(*) FROM subscription_first_invoice_confirmations")) + .isZero(); + assertThat(count(hosting, "SELECT count(*) FROM subscription_first_invoice_authorizations")) + .isZero(); + assertThat(consumptionCount(hosting, openingEvidence)).isZero(); + assertNoReceipt(hosting); + + UUID winningAuthorization = UUID.randomUUID(); + var winningProof = + https.request( + "POST", + path + "/reauthenticate", + issued.compact(), + billingReauthenticationRequest( + tuple, + UUID.randomUUID(), + winningAuthorization, + recoveredOriginalRequestId, + 0L, + "PRE_ROW_RENEWAL", + issued.account().getEmail())); + assertThat(winningProof.statusCode()).isEqualTo(200); + UUID winningEvidence = + UUID.fromString(JSON.readTree(winningProof.body()).path("evidenceId").asText()); + UUID competingAuthorization = UUID.randomUUID(); + var competingProof = + https.request( + "POST", + path + "/reauthenticate", + issued.compact(), + billingReauthenticationRequest( + tuple, + UUID.randomUUID(), + competingAuthorization, + originalRequestId, + 0L, + "PRE_ROW_RENEWAL", + issued.account().getEmail())); + assertThat(competingProof.statusCode()).isEqualTo(200); + UUID competingEvidence = + UUID.fromString(JSON.readTree(competingProof.body()).path("evidenceId").asText()); + Map renewal = + Map.of( + "requestId", + recoveredOriginalRequestId, + "authorizationRequestId", + winningAuthorization, + "expectedRowVersion", + tuple.path("expectedRowVersion").asLong(), + "expectedAuthorizationVersion", + 0L, + "reauthenticationEvidenceId", + winningEvidence, + "acceptedTupleDigest", + tuple.path("tupleDigest").asText(), + "acceptCharge", + true); + var changedRenewal = new java.util.HashMap<>(renewal); + changedRenewal.put("acceptedTupleDigest", "sha256:" + "c".repeat(64)); + assertThat( + https + .request("POST", path + "/renew", issued.compact(), changedRenewal) + .statusCode()) + .isEqualTo(409); + assertThat(consumptionCount(hosting, winningEvidence)).isZero(); + assertThat(consumptionCount(hosting, openingEvidence)).isZero(); + assertThat(count(hosting, "SELECT count(*) FROM subscription_first_invoice_confirmations")) + .isZero(); + + Map competingRenewal = + Map.of( + "requestId", + originalRequestId, + "authorizationRequestId", + competingAuthorization, + "expectedRowVersion", + tuple.path("expectedRowVersion").asLong(), + "expectedAuthorizationVersion", + 0L, + "reauthenticationEvidenceId", + competingEvidence, + "acceptedTupleDigest", + tuple.path("tupleDigest").asText(), + "acceptCharge", + true); + var renewalStart = new CountDownLatch(1); + renewalGate.arm(); + var firstRenewal = + asyncRequest( + https, + "POST", + path + "/renew", + issued.compact(), + renewal, + renewalStart, + requestExecutor); + var secondRenewal = + asyncRequest( + https, + "POST", + path + "/renew", + issued.compact(), + competingRenewal, + renewalStart, + requestExecutor); + renewalStart.countDown(); + assertThat(renewalGate.arrived.await(30, TimeUnit.SECONDS)).isTrue(); + releaseRenewalGate.releaseNow(); + var firstRenewalResponse = firstRenewal.get(60, TimeUnit.SECONDS); + var secondRenewalResponse = secondRenewal.get(60, TimeUnit.SECONDS); + boolean firstRenewalWon = firstRenewalResponse.statusCode() == 200; + assertThat(firstRenewalResponse.statusCode()).isIn(200, 409); + assertThat(secondRenewalResponse.statusCode()).isEqualTo(firstRenewalWon ? 409 : 200); + var renewalWinner = firstRenewalWon ? firstRenewalResponse : secondRenewalResponse; + Map winningRenewal = firstRenewalWon ? renewal : competingRenewal; + Map losingRenewal = firstRenewalWon ? competingRenewal : renewal; + UUID winnerAuthorizationId = + firstRenewalWon ? winningAuthorization : competingAuthorization; + UUID winnerEvidenceId = firstRenewalWon ? winningEvidence : competingEvidence; + UUID losingEvidenceId = firstRenewalWon ? competingEvidence : winningEvidence; + assertThat(renewalWinner.statusCode()).isEqualTo(200); + JsonNode afterRenewal = + JSON.readTree(https.request("GET", path, issued.compact(), null).body()); + assertThat(afterRenewal.path("confirmationRequestId").asText()) + .isEqualTo(recoveredOriginalRequestId.toString()); + assertThat(afterRenewal.path("preRowOriginalRequestId").isNull()).isTrue(); + assertThat(JSON.readTree(renewalWinner.body()).path("status").asText()) + .isEqualTo("requires_action"); + assertThat(hosting.firstInvoiceConfirmations()).isEqualTo(1); + assertThat(count(hosting, "SELECT count(*) FROM subscription_first_invoice_authorizations")) + .isOne(); + assertThat(count(hosting, "SELECT count(*) FROM subscription_first_invoice_command_claims")) + .isOne(); + assertThat( + hosting + .dsl() + .fetchSingle( + "SELECT request_id, authorization_request_id, reauthentication_evidence_id FROM " + + "subscription_first_invoice_authorizations") + .get("request_id", UUID.class)) + .isEqualTo(originalRequestId); + assertThat( + hosting + .dsl() + .fetchSingle( + "SELECT authorization_request_id FROM " + + "subscription_first_invoice_authorizations") + .get("authorization_request_id", UUID.class)) + .isEqualTo(winnerAuthorizationId); + assertThat( + hosting + .dsl() + .fetchSingle( + "SELECT reauthentication_evidence_id FROM " + + "subscription_first_invoice_authorizations") + .get("reauthentication_evidence_id", UUID.class)) + .isEqualTo(winnerEvidenceId); + var evidenceBefore = + hosting + .dsl() + .fetchSingle( + "SELECT encode(request_payload, 'hex') AS request_payload_hex, request_digest, " + + "billing_context_digest, xmin::text AS row_xmin " + + "FROM account_recent_reauthentication_evidence WHERE evidence_id = ?", + openingEvidence); + var originalFence = + hosting + .dsl() + .fetchSingle( + "SELECT request_id, reauthentication_evidence_id, binding_digest " + + "FROM subscription_first_invoice_operation_fences"); + assertThat(originalFence.get("request_id", UUID.class)).isEqualTo(originalRequestId); + assertThat(originalFence.get("reauthentication_evidence_id", UUID.class)) + .isEqualTo(openingEvidence); + assertThat(originalFence.get("binding_digest", String.class)) + .isEqualTo(evidenceBefore.get("billing_context_digest", String.class)); + assertThat(consumptionCount(hosting, winnerEvidenceId)).isOne(); + assertThat(consumptionCount(hosting, openingEvidence)).isZero(); + assertThat(hosting.firstInvoiceConfirmations()).isEqualTo(1); + assertThat( + hosting + .dsl() + .fetchSingle( + "SELECT provider_idempotency_id FROM subscription_first_invoice_confirmations " + + "WHERE request_id = ?", + originalRequestId) + .get("provider_idempotency_id", UUID.class) + .toString()) + .isEqualTo(hosting.lastFirstInvoiceConfirmationIdempotencyKey()); + + assertThat( + https + .request("POST", path + "/renew", issued.compact(), losingRenewal) + .statusCode()) + .isEqualTo(409); + assertThat(consumptionCount(hosting, losingEvidenceId)).isZero(); + + assertThat( + https + .request("POST", path + "/renew", issued.compact(), winningRenewal) + .statusCode()) + .isEqualTo(200); + assertThat(hosting.firstInvoiceConfirmations()).isEqualTo(1); + assertThat(count(hosting, "SELECT count(*) FROM subscription_first_invoice_authorizations")) + .isOne(); + + releaseConfirmationGate.releaseNow(); + assertThat(delayedOriginal.get(60, TimeUnit.SECONDS).statusCode()).isEqualTo(409); + assertThat(consumptionCount(hosting, openingEvidence)).isZero(); + assertThat(consumptionCount(hosting, winnerEvidenceId)).isOne(); + assertThat( + hosting + .dsl() + .fetchSingle( + "SELECT encode(request_payload, 'hex') AS request_payload_hex, request_digest, " + + "billing_context_digest, xmin::text AS row_xmin " + + "FROM account_recent_reauthentication_evidence WHERE evidence_id = ?", + openingEvidence)) + .isEqualTo(evidenceBefore); + JsonNode after = JSON.readTree(https.request("GET", path, issued.compact(), null).body()); + assertThat(after.path("confirmationRequestId").asText()) + .isEqualTo(originalRequestId.toString()); + assertThat(after.path("authorizationVersion").asLong()).isEqualTo(1L); + assertThat(hosting.firstInvoiceConfirmations()).isEqualTo(1); + var latestAuthorization = + hosting + .dsl() + .fetchSingle( + "SELECT request_id, authorization_request_id, authorization_version " + + "FROM subscription_first_invoice_authorizations"); + assertThat(latestAuthorization.get("request_id", UUID.class)).isEqualTo(originalRequestId); + assertThat(latestAuthorization.get("authorization_request_id", UUID.class)) + .isEqualTo(winnerAuthorizationId); + assertThat(latestAuthorization.get("authorization_version", Long.class)).isEqualTo(1L); + + // The provider still requires action under the latest retained authorization. The next + // fresh proof is bound to that current version, then allowed to expire before renewal. + UUID expiredAuthorization = UUID.randomUUID(); + var expiredProof = + https.request( + "POST", + path + "/reauthenticate", + issued.compact(), + billingReauthenticationRequest( + tuple, + UUID.randomUUID(), + expiredAuthorization, + originalRequestId, + 1L, + "FOLLOWUP_RENEWAL", + issued.account().getEmail())); + assertThat(expiredProof.statusCode()).isEqualTo(200); + UUID expiredEvidence = + UUID.fromString(JSON.readTree(expiredProof.body()).path("evidenceId").asText()); + var expiredEvidenceBefore = + hosting + .dsl() + .fetchSingle( + "SELECT encode(request_payload, 'hex') AS request_payload_hex, request_digest, " + + "billing_context_digest, xmin::text AS row_xmin " + + "FROM account_recent_reauthentication_evidence WHERE evidence_id = ?", + expiredEvidence); + hosting.clock().advance(Duration.ofMinutes(6)); + Map expiredRenewal = + Map.of( + "requestId", + originalRequestId, + "authorizationRequestId", + expiredAuthorization, + "expectedRowVersion", + tuple.path("expectedRowVersion").asLong(), + "expectedAuthorizationVersion", + 1L, + "reauthenticationEvidenceId", + expiredEvidence, + "acceptedTupleDigest", + tuple.path("tupleDigest").asText(), + "acceptCharge", + true); + assertThat( + https + .request("POST", path + "/renew", issued.compact(), expiredRenewal) + .statusCode()) + .isEqualTo(409); + assertThat(consumptionCount(hosting, expiredEvidence)).isZero(); + assertThat(count(hosting, "SELECT count(*) FROM subscription_first_invoice_authorizations")) + .isOne(); + assertThat( + hosting + .dsl() + .fetchSingle( + "SELECT encode(request_payload, 'hex') AS request_payload_hex, request_digest, " + + "billing_context_digest, xmin::text AS row_xmin " + + "FROM account_recent_reauthentication_evidence WHERE evidence_id = ?", + expiredEvidence)) + .isEqualTo(expiredEvidenceBefore); + assertNoReceipt(hosting); + } + } + } + + 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 + .dsl() + .fetchSingle( + "SELECT count(*) FROM account_recent_reauthentication_consumptions WHERE evidence_id = ?", + evidenceId) + .get(0, Long.class); + } + + private static long count(CanonicalHostingSubscriptionTestFixture.Fixture hosting, String sql) { + return hosting.dsl().fetchSingle(sql).get(0, Long.class); + } + + private static CompletableFuture> asyncRequest( + HttpsReceiver https, + String method, + String path, + String bearer, + Object body, + CountDownLatch start, + TestRequestExecutor requestExecutor) { + return CompletableFuture.supplyAsync( + () -> { + try { + if (start != null && !start.await(30, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent HTTP request barrier did not release"); + } + return https.request(method, path, bearer, body); + } catch (Exception failure) { + throw new java.util.concurrent.CompletionException(failure); + } + }, + requestExecutor.executor()); + } + + private static void assertNoReceipt(CanonicalHostingSubscriptionTestFixture.Fixture hosting) { + assertThat( + hosting + .dsl() + .fetchSingle("SELECT count(*) FROM subscription_lifecycle_receipts") + .get(0, Long.class)) + .isZero(); + assertThat(hosting.intents().findCurrentByTenant(hosting.tenantId()).orElseThrow().status()) + .isEqualTo("provisioning"); + } + + private static Map billingReauthenticationRequest( + JsonNode tuple, + UUID requestId, + UUID authorizationRequestId, + UUID originalRequestId, + long expectedAuthorizationVersion, + String authorizationPurpose, + String email) { + return Map.of( + "requestId", + requestId, + "confirmationRequestId", + authorizationRequestId, + "billingBinding", + Map.of( + "originalRequestId", + originalRequestId, + "expectedRowVersion", + tuple.path("expectedRowVersion").asLong(), + "expectedAuthorizationVersion", + expectedAuthorizationVersion, + "acceptedTupleDigest", + tuple.path("tupleDigest").asText(), + "invoiceExpiresAt", + tuple.path("expiresAt").asText(), + "authorizationPurpose", + authorizationPurpose), + "email", + email, + "secret", + PASSWORD); + } + + /** Explicit test-only mount for the deliberately unregistered production owner. */ + private static final class HttpsReceiver implements AutoCloseable { + private final Tomcat tomcat; + private final GenericWebApplicationContext web; + private final HttpClient client; + private final URI origin; + + private HttpsReceiver(Path directory, AccountHostingFirstInvoiceController controller) + throws Exception { + this(directory, controller, new OwnerEntryGate[0]); + } + + private HttpsReceiver( + Path directory, AccountHostingFirstInvoiceController controller, OwnerEntryGate... gates) + throws Exception { + Path tls = Files.createDirectory(directory.resolve("https")); + var pki = + LoopbackMtlsTestPki.create( + tls, + "checkout-test-ca", + new LoopbackMtlsTestPki.IdentitySpec( + "checkout", "spiffe://test-only/account-checkout", true)); + var identity = pki.identity("checkout"); + var material = pki.clientProperties(tls, identity); + tomcat = new Tomcat(); + tomcat.setBaseDir(Files.createDirectory(directory.resolve("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(material.getCertChain()); + certificate.setCertificateKeyFile(material.getPrivateKey()); + certificate.setCertificateChainFile(material.getCaCert()); + ssl.addCertificate(certificate); + protocol.addSslHostConfig(ssl); + var context = + tomcat.addContext("", Files.createDirectory(directory.resolve("web-root")).toString()); + web = new GenericWebApplicationContext(); + web.setServletContext(context.getServletContext()); + org.springframework.context.annotation.AnnotationConfigUtils + .registerAnnotationConfigProcessors(web); + web.registerBean(AccountHostingFirstInvoiceController.class, () -> controller); + web.registerBean(ExplicitOwnerMvc.class, () -> new ExplicitOwnerMvc(gates)); + web.refresh(); + Tomcat.addServlet(context, "checkout", new DispatcherServlet(web)); + context.addServletMappingDecoded("/", "checkout"); + tomcat.start(); + origin = URI.create("https://localhost:" + connector.getLocalPort()); + SSLContext trust = SSLContext.getInstance("TLS"); + trust.init(null, pki.trustManagerFactory().getTrustManagers(), null); + client = + HttpClient.newBuilder().sslContext(trust).connectTimeout(Duration.ofSeconds(3)).build(); + } + + private HttpResponse request(String method, String path, String bearer, Object body) + throws Exception { + var request = HttpRequest.newBuilder(origin.resolve(path)).timeout(Duration.ofSeconds(90)); + 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 client.send(request.build(), HttpResponse.BodyHandlers.ofString()); + } + + @Override + public void close() throws Exception { + client.close(); + tomcat.stop(); + tomcat.destroy(); + web.close(); + } + } + + @Configuration(proxyBeanMethods = false) + static class ExplicitOwnerMvc extends WebMvcConfigurationSupport { + private final OwnerEntryGate[] gates; + + ExplicitOwnerMvc(OwnerEntryGate... gates) { + this.gates = gates; + } + + @Override + protected void addInterceptors(InterceptorRegistry registry) { + if (gates.length == 0) return; + registry.addInterceptor( + new HandlerInterceptor() { + @Override + public boolean preHandle( + jakarta.servlet.http.HttpServletRequest request, + jakarta.servlet.http.HttpServletResponse response, + Object handler) + throws Exception { + if ("POST".equals(request.getMethod())) { + for (OwnerEntryGate gate : gates) { + if (gate.armed && request.getRequestURI().endsWith(gate.endpointSuffix)) { + gate.arrived.countDown(); + if (!gate.release.await(60, TimeUnit.SECONDS)) { + throw new IllegalStateException("Test owner-entry gate did not release"); + } + break; + } + } + } + return true; + } + }); + } + + @Override + protected RequestMappingHandlerMapping createRequestMappingHandlerMapping() { + return new RequestMappingHandlerMapping() { + @Override + protected boolean isHandler(Class beanType) { + return beanType == AccountHostingFirstInvoiceController.class; + } + }; + } + } + + private static final class OwnerEntryGate implements AutoCloseable { + private final String endpointSuffix; + private final CountDownLatch arrived; + private final CountDownLatch release = new CountDownLatch(1); + private volatile boolean armed; + + private OwnerEntryGate(String endpointSuffix) { + this(endpointSuffix, 1, true); + } + + private OwnerEntryGate(String endpointSuffix, int arrivals) { + this(endpointSuffix, arrivals, true); + } + + private OwnerEntryGate(String endpointSuffix, int arrivals, boolean armed) { + this.endpointSuffix = endpointSuffix; + this.arrived = new CountDownLatch(arrivals); + this.armed = armed; + } + + private void arm() { + armed = true; + } + + private void releaseNow() { + release.countDown(); + } + + @Override + public void close() { + releaseNow(); + } + } + + private static final class TestRequestExecutor implements AutoCloseable { + private final ExecutorService executor = Executors.newFixedThreadPool(4); + + private ExecutorService executor() { + return executor; + } + + @Override + public void close() { + executor.shutdown(); + try { + if (!executor.awaitTermination(10, TimeUnit.SECONDS)) executor.shutdownNow(); + } catch (InterruptedException interrupted) { + executor.shutdownNow(); + Thread.currentThread().interrupt(); + } + } + } +} 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/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 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..0efeaac54d --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountCheckoutReceivingConfigurationTest.java @@ -0,0 +1,168 @@ +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.Files; +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 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( + "spring.profiles.active=" + profile, + "firemud.account.checkout-receiving.enabled=true") + .run( + ctx -> { + assertThat(ctx).hasNotFailed(); + assertThat(ctx).doesNotHaveBean(AccountControlUiAuthenticationGrpcService.class); + }); + environment.setActiveProfiles(profile, "isolated-checkout-receiving"); + assertThatThrownBy(() -> config.accountCheckoutReceivingProperties(environment)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Checkout receiving is restricted to isolated inputs"); + } + } + + @Test + void isolatedModeWithoutDeliveredInputsRefusesStartup() { + context + .withPropertyValues( + "spring.profiles.active=isolated-checkout-receiving", + "firemud.account.checkout-receiving.enabled=true") + .run(ctx -> assertThat(ctx).hasFailed()); + } + + @Test + void physicalCustodyRootsMustResolveAndRemainDisjoint() throws Exception { + Path privateRoot = Files.createDirectory(keys.resolve("private")); + Path publicRoot = Files.createDirectory(keys.resolve("public")); + Path custody = Files.createDirectory(keys.resolve("custody")); + assertThat( + new AccountCheckoutReceivingProperties("test", privateRoot, publicRoot, custody, 0) + .controlUiKeyringRoot()) + .isEqualTo(custody.toRealPath()); + for (Path signer : java.util.List.of(privateRoot, publicRoot)) { + Path child = Files.createDirectory(signer.resolve("child")); + for (Path overlap : java.util.List.of(signer, child, keys)) { + assertThatThrownBy( + () -> + new AccountCheckoutReceivingProperties( + "test", privateRoot, publicRoot, overlap, 0)) + .isInstanceOf(IllegalArgumentException.class); + } + Path alias = Files.createSymbolicLink(keys.resolve(signer.getFileName() + "-alias"), signer); + assertThatThrownBy( + () -> + new AccountCheckoutReceivingProperties("test", privateRoot, publicRoot, alias, 0)) + .isInstanceOf(IllegalArgumentException.class); + // A signer alias into custody must also fail, including the ancestor direction. + Path custodyChild = Files.createDirectory(custody.resolve(signer.getFileName())); + Path signerAlias = + Files.createSymbolicLink(keys.resolve(signer.getFileName() + "-custody"), custodyChild); + assertThatThrownBy( + () -> + new AccountCheckoutReceivingProperties( + "test", + signer == privateRoot ? signerAlias : privateRoot, + signer == publicRoot ? signerAlias : publicRoot, + custody, + 0)) + .isInstanceOf(IllegalArgumentException.class); + } + Path missing = keys.resolve("missing"); + Path dangling = Files.createSymbolicLink(keys.resolve("dangling"), missing); + for (Path invalid : + java.util.List.of( + missing, + dangling, + custody.resolve("../custody"), + Path.of("relative"), + Files.createFile(keys.resolve("file")))) { + assertThatThrownBy( + () -> + new AccountCheckoutReceivingProperties( + "test", privateRoot, publicRoot, invalid, 0)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> new AccountCheckoutReceivingProperties("test", invalid, publicRoot, custody, 0)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountCheckoutReceivingProperties("test", privateRoot, invalid, custody, 0)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @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 new file mode 100644 index 0000000000..3d48628df4 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceControllerTest.java @@ -0,0 +1,307 @@ +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.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; +import java.util.UUID; +import java.util.stream.Stream; +import net.firedevops.firemud.accountservice.service.session.AccountHostingFirstInvoicePaymentService; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +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.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.server.ResponseStatusException; +import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; + +class AccountHostingFirstInvoiceControllerTest { + @Test + void ownerStatusSerializesTheObservationalOriginalReferenceWithNoStore() throws Exception { + var service = mock(AccountHostingFirstInvoicePaymentService.class); + UUID subscription = UUID.randomUUID(); + UUID original = UUID.randomUUID(); + when(service.describeOwner("controlled-bearer", subscription)) + .thenReturn( + new AccountHostingFirstInvoicePaymentService.OwnerView( + subscription, + "in_exact", + "pi_exact", + UUID.randomUUID(), + "2400", + "usd", + "sha256:" + "a".repeat(64), + 3, + "AWAITING_PAYMENT", + java.time.Instant.parse("2099-01-01T00:00:00Z"), + null, + original, + 0)); + registeredController(service) + .perform( + org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get( + "/billing/hosting/subscriptions/" + subscription + "/first-invoice") + .secure(true) + .header("Authorization", "Bearer controlled-bearer")) + .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( + "$.preRowOriginalRequestId") + .value(original.toString())) + .andExpect( + org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath( + "$.confirmationRequestId") + .value(org.hamcrest.Matchers.nullValue())) + .andExpect( + org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath( + "$.authorizationVersion") + .value(0)) + .andExpect( + org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath( + "$.reauthenticationEvidenceId") + .doesNotExist()) + .andExpect( + org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath( + "$.clientSecret") + .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 = + 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); + var controller = new AccountHostingFirstInvoiceController(service); + var transport = mock(HttpServletRequest.class); + assertThatThrownBy(() -> controller.read(transport, "Bearer controlled", UUID.randomUUID())) + .isInstanceOf(ResponseStatusException.class); + when(transport.isSecure()).thenReturn(true); + assertThatThrownBy(() -> controller.read(transport, null, UUID.randomUUID())) + .isInstanceOf(ResponseStatusException.class); + assertThatThrownBy(() -> controller.read(transport, "Bearer ", UUID.randomUUID())) + .isInstanceOf(ResponseStatusException.class); + verifyNoInteractions(service); + } + + @ParameterizedTest + @MethodSource("ownerFailures") + void exactControllerExceptionMappingPreservesStatusAndNoStore( + RuntimeException failure, int expectedStatus, String expectedCode) throws Exception { + var service = mock(AccountHostingFirstInvoicePaymentService.class); + UUID subscription = UUID.randomUUID(); + when(service.describeOwner("controlled-bearer", subscription)).thenThrow(failure); + var mvc = registeredController(service); + + mvc.perform( + org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get( + "/billing/hosting/subscriptions/" + subscription + "/first-invoice") + .secure(true) + .header("Authorization", "Bearer controlled-bearer")) + .andExpect( + org.springframework.test.web.servlet.result.MockMvcResultMatchers.status() + .is(expectedStatus)) + .andExpect( + org.springframework.test.web.servlet.result.MockMvcResultMatchers.header() + .string("Cache-Control", "no-store")) + .andExpect( + org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath("$.code") + .value(expectedCode)); + } + + 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"), + 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( + new IllegalArgumentException("private request detail"), + 400, + "FIRST_INVOICE_INVALID_REQUEST"), + Arguments.of( + new IllegalStateException("private evidence detail"), + 409, + "FIRST_INVOICE_EVIDENCE_REFUSED")); + } + + @Test + void typedSourceUnavailableUsesTheExistingOwningAvailabilityHandler() throws Exception { + var service = mock(AccountHostingFirstInvoicePaymentService.class); + UUID subscription = UUID.randomUUID(); + when(service.describeOwner("controlled-bearer", subscription)) + .thenThrow(new AccountAsymmetricJwtVerifier.VerificationUnavailableException()); + var mvc = registeredController(service); + + mvc.perform( + org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get( + "/billing/hosting/subscriptions/" + subscription + "/first-invoice") + .secure(true) + .header("Authorization", "Bearer controlled-bearer")) + .andExpect( + org.springframework.test.web.servlet.result.MockMvcResultMatchers.status() + .isServiceUnavailable()) + .andExpect( + org.springframework.test.web.servlet.result.MockMvcResultMatchers.header() + .string("Cache-Control", "no-store")) + .andExpect( + org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath("$.code") + .value("AUTH_UNAVAILABLE")); + } + + private static org.springframework.test.web.servlet.MockMvc registeredController( + AccountHostingFirstInvoicePaymentService service) { + // Register only this prepared controller in the test; production activation remains held. + return MockMvcBuilders.standaloneSetup(new AccountHostingFirstInvoiceController(service)) + .setCustomHandlerMapping( + () -> + new RequestMappingHandlerMapping() { + @Override + protected boolean isHandler(Class beanType) { + return AccountHostingFirstInvoiceController.class.equals(beanType); + } + }) + .build(); + } + + @Test + void passwordAndClientSecretNeverAppearInRequestOrResponseDiagnosticStrings() { + assertThat( + new AccountHostingFirstInvoiceController.ReauthenticationRequest( + UUID.randomUUID(), UUID.randomUUID(), "owner@example.test", "controlled-secret") + .toString()) + .doesNotContain("controlled-secret", "owner@example.test"); + assertThat( + new AccountHostingFirstInvoiceController.ConfirmationResponse( + "requires_action", "pi_exact_secret_controlled") + .toString()) + .doesNotContain("secret_controlled"); + } + + @Test + void exactChargeConsentIsRequiredBeforeProviderWork() { + var service = mock(AccountHostingFirstInvoicePaymentService.class); + var controller = new AccountHostingFirstInvoiceController(service); + var transport = mock(HttpServletRequest.class); + when(transport.isSecure()).thenReturn(true); + var request = + new AccountHostingFirstInvoiceController.ConfirmationRequest( + UUID.randomUUID(), 3, UUID.randomUUID(), "sha256:" + "a".repeat(64), false); + assertThatThrownBy( + () -> controller.confirm(transport, "Bearer controlled", UUID.randomUUID(), request)) + .isInstanceOf(ResponseStatusException.class); + verifyNoInteractions(service); + } + + @Test + void renewedConsentAlsoRequiresSecureCurrentOwnerAndExplicitChargeApproval() { + var service = mock(AccountHostingFirstInvoicePaymentService.class); + var controller = new AccountHostingFirstInvoiceController(service); + var transport = mock(HttpServletRequest.class); + var request = + new AccountHostingFirstInvoiceController.RenewalRequest( + UUID.randomUUID(), + UUID.randomUUID(), + 3, + 1, + UUID.randomUUID(), + "sha256:" + "a".repeat(64), + false); + assertThatThrownBy( + () -> controller.renew(transport, "Bearer controlled", UUID.randomUUID(), request)) + .isInstanceOf(ResponseStatusException.class); + when(transport.isSecure()).thenReturn(true); + assertThatThrownBy( + () -> controller.renew(transport, "Bearer controlled", UUID.randomUUID(), request)) + .isInstanceOf(ResponseStatusException.class); + verifyNoInteractions(service); + } +} 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..afaba2ed7a --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountHostingFirstInvoiceWebhookControllerTest.java @@ -0,0 +1,114 @@ +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 exactUnrelatedEventClassificationIsAcknowledgedWithoutCache() throws Exception { + var payments = mock(AccountHostingFirstInvoicePaymentService.class); + var completion = new AccountHostingFirstInvoicePaymentService.Completion("IGNORED", null); + when(payments.completeSigned("{}", "t=1,v1=controlled")).thenReturn(completion); + + var response = + new AccountHostingFirstInvoiceWebhookController(payments) + .receive(request("{}".getBytes(StandardCharsets.UTF_8))); + + assertThat(response.getStatusCode().value()).isEqualTo(200); + assertThat(response.getBody()).isEqualTo(completion); + assertThat(response.getHeaders().getCacheControl()).isEqualTo("no-store"); + assertThat(response.getHeaders().getFirst("Pragma")).isEqualTo("no-cache"); + verify(payments).completeSigned("{}", "t=1,v1=controlled"); + } + + @Test + void exactLateConflictClassificationIsAcknowledgedForOperatorReconciliation() throws Exception { + var payments = mock(AccountHostingFirstInvoicePaymentService.class); + UUID requestId = UUID.randomUUID(); + var completion = + new AccountHostingFirstInvoicePaymentService.Completion( + "OPERATOR_RECONCILIATION_REQUIRED", requestId); + when(payments.completeSigned("{}", "t=1,v1=controlled")).thenReturn(completion); + + var response = + new AccountHostingFirstInvoiceWebhookController(payments) + .receive(request("{}".getBytes(StandardCharsets.UTF_8))); + + assertThat(response.getStatusCode().value()).isEqualTo(200); + assertThat(response.getBody()).isEqualTo(completion); + assertThat(response.getHeaders().getCacheControl()).isEqualTo("no-store"); + assertThat(response.getHeaders().getFirst("Pragma")).isEqualTo("no-cache"); + verify(payments).completeSigned("{}", "t=1,v1=controlled"); + } + + @Test + void unresolvedCompletionWithoutLocalRequestIdIsNotAcknowledgedAsProcessed() throws Exception { + var payments = mock(AccountHostingFirstInvoicePaymentService.class); + when(payments.completeSigned("{}", "t=1,v1=controlled")) + .thenReturn(new AccountHostingFirstInvoicePaymentService.Completion("RECONCILING", null)); + 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/repository/AccountHostingFirstInvoicePaymentRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingFirstInvoicePaymentRepositoryTest.java index 0b0ad0b0b9..194fd4be00 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 @@ -8,7 +8,9 @@ import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; 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.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -38,6 +40,114 @@ void clearTransactions() { TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); } + @Test + void ownerReadRecoversOnlyTheExactPreRowIdentityEvenAfterExpiryWithoutMutation() { + var f = new OwnerReferenceFixture(); + assertThat(f.read()).isEqualTo(f.original); + verify(f.repository).requireOwner(f.invoice.subscriptionId(), f.invoice.ownerAccountId()); + verify(f.repository).requireAwaitingPayment(f.invoice, 3); + verify(f.dsl) + .fetchOne( + "SELECT * FROM subscription_first_invoice_operation_fences WHERE subscription_id = ? FOR UPDATE", + f.invoice.subscriptionId()); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + f.fencePresent = false; + assertThat(f.read()).isNull(); + + f.fencePresent = true; + f.confirmation = UUID.randomUUID(); + assertThat(f.read()).isNull(); + } + + @Test + void inconsistentExistingFenceCannotLookLikeAnAbsentOriginalOperation() { + for (var mismatch : + Map.of( + "subscription_id", UUID.randomUUID(), + "account_uuid", UUID.randomUUID(), + "tuple_digest", "sha256:" + "c".repeat(64), + "expected_row_version", 4L, + "invoice_expires_at", Instant.EPOCH.atOffset(java.time.ZoneOffset.UTC)) + .entrySet()) { + var f = new OwnerReferenceFixture(); + f.fields.put(mismatch.getKey(), mismatch.getValue()); + assertThatThrownBy(f::read).isInstanceOf(IllegalStateException.class); + } + var missingIdentity = new OwnerReferenceFixture(); + missingIdentity.fields.remove("request_id"); + assertThatThrownBy(missingIdentity::read).isInstanceOf(IllegalArgumentException.class); + } + + @Test + void preRowReferenceRefusesAuthorizationDispatchOrCommandWithoutAConfirmation() { + var f = new OwnerReferenceFixture(); + f.version = 1; + assertThatThrownBy(f::read).isInstanceOf(IllegalStateException.class); + f.version = 0; + f.dispatched = true; + assertThatThrownBy(f::read).isInstanceOf(IllegalStateException.class); + f.dispatched = false; + f.commandClaimed = true; + assertThatThrownBy(f::read).isInstanceOf(IllegalStateException.class); + f.fencePresent = false; + assertThatThrownBy(f::read).isInstanceOf(IllegalStateException.class); + } + + private static final class OwnerReferenceFixture { + final DSLContext dsl = mock(DSLContext.class); + final AccountHostingFirstInvoicePayment invoice = invoice("in_exact", "pi_exact", 2400, "usd"); + final UUID original = UUID.randomUUID(); + final Map fields = new HashMap<>(); + final AccountHostingFirstInvoicePaymentRepository repository; + UUID confirmation; + long version; + boolean fencePresent = true; + boolean dispatched; + boolean commandClaimed; + + OwnerReferenceFixture() { + TransactionSynchronizationManager.setActualTransactionActive(true); + repository = + spy( + new AccountHostingFirstInvoicePaymentRepository( + dsl, + mock(AccountSubscriptionIntentRepository.class), + Clock.fixed(invoice.expiresAt().plusSeconds(1), java.time.ZoneOffset.UTC))); + doReturn(invoice) + .when(repository) + .requireOwner(invoice.subscriptionId(), invoice.ownerAccountId()); + doReturn(3L) + .when(repository) + .ownerRowVersion(invoice.subscriptionId(), invoice.ownerAccountId()); + doAnswer(call -> confirmation) + .when(repository) + .confirmationRequestId(invoice.subscriptionId()); + doAnswer(call -> version).when(repository).authorizationVersion(invoice.subscriptionId()); + doNothing().when(repository).requireAwaitingPayment(invoice, 3); + fields.put("subscription_id", invoice.subscriptionId()); + fields.put("request_id", original); + fields.put("account_uuid", invoice.ownerAccountId()); + fields.put("tuple_digest", invoice.digest()); + fields.put("expected_row_version", 3L); + fields.put("invoice_expires_at", invoice.expiresAt().atOffset(java.time.ZoneOffset.UTC)); + Record fence = RenewalFixture.row(fields); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + call -> { + String sql = call.getArgument(0); + if (sql.contains("operation_fences")) return fencePresent ? fence : null; + if (sql.contains("first_invoice_dispatches")) return dispatched ? fence : null; + if (sql.contains("first_invoice_command_claims")) + return commandClaimed ? fence : null; + throw new AssertionError(sql); + }); + } + + UUID read() { + return repository.preRowOriginalRequestId(invoice.subscriptionId(), invoice.ownerAccountId()); + } + } + @Test void immutableDigestBindsExistingProviderInvoiceIntentInstrumentPolicyAndExpiry() { var invoice = invoice("in_exact", "pi_exact", 2400, "usd"); 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..2a5484d396 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountCheckoutHttpAuthInterceptorTest.java @@ -0,0 +1,174 @@ +package net.firedevops.firemud.accountservice.security; + +import static org.assertj.core.api.Assertions.assertThat; +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; +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.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; + +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"); + var secureResponse = new MockHttpServletResponse(); + assertThat(interceptor.preHandle(request, secureResponse, handler)).isFalse(); + assertThat(secureResponse.getStatus()).isEqualTo(401); + } + + @ParameterizedTest + @MethodSource("unavailableAuthorities") + void unavailableAuthorityDoesNotMisreportSessionRevocation(RuntimeException failure) + 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(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( + 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( + "private database connection detail"), + new org.springframework.transaction.TransactionSystemException( + "private transaction detail"), + new org.springframework.transaction.UnexpectedRollbackException("private rollback detail")); + } + + private static RuntimeException registryFailure( + net.firedevops.firemud.accountservice.service.session + .AccountCoordinationPinnedConnectionProvider + provider) { + try { + new net.firedevops.firemud.accountservice.service.session.AccountControlUiRegistryReader( + provider) + .readActive("a".repeat(64)); + throw new AssertionError("Expected unavailable registry"); + } catch ( + net.firedevops.firemud.accountservice.service.session.AccountControlUiRegistryReader + .RegistryUnavailableException + failure) { + return failure; + } + } + + @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..702dd20fa7 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountControlUiAuthenticationGrpcServiceTest.java @@ -0,0 +1,263 @@ +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.AccountControlUiAuthLoginStatus; +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.account.auth.AccountControlUiAuthenticationGrpcCodec.SourceContext; +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); + 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(), wrongPeer)); + assertThat(wrongPeer.failureCode).isEqualTo(Status.Code.PERMISSION_DENIED); + 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); + 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"); + 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(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); + var signIn = + org.mockito.ArgumentCaptor.forClass( + AccountControlUiIssuanceService.AccountSignInRequest.class); + verify(issuer).issueAccount(signIn.capture()); + assertThat(signIn.getValue().sourceContext()).isEqualTo(request.sourceContext()); + verify(credential).close(); + verify(actors).authenticateAccount("controlled.compact.jwt"); + } + + @Test + void missingMalformedOrNonHttpSourceRefusesBeforeIssuance() { + var issuer = mock(AccountControlUiIssuanceService.class); + var actors = mock(AccountControlUiActorService.class); + var receiver = new AccountControlUiAuthenticationGrpcService(issuer, actors, "test"); + var wire = AccountControlUiAuthenticationGrpcCodec.toRequest(request("test")); + for (var invalid : + java.util.List.of( + wire.toBuilder().clearCanonicalClientAddress().build(), + wire.toBuilder().setCanonicalClientAddress(0, "untrusted-host.test").build(), + wire.toBuilder().addCanonicalClientAddress("192.0.2.11").build(), + wire.toBuilder().clearTransportClass().build(), + wire.toBuilder().setTransportClassValue(0, 99).build())) { + var result = new Result(); + gateway().run(() -> receiver.authLogin(invalid, result)); + assertThat(result.failureCode).isEqualTo(Status.Code.INVALID_ARGUMENT); + } + verifyNoInteractions(issuer, actors); + } + + @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.getStatusList()) + .containsExactly( + AccountControlUiAuthLoginStatus.ACCOUNT_CONTROL_UI_AUTH_LOGIN_STATUS_DENIED); + assertThat(denied.value.toString()).doesNotContain("not disclosed", "controlled-secret"); + 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); + 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)) + .addCanonicalClientAddress("192.0.2.10") + .addTransportClassValue(1) + .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 AccountControlUiIssuanceService.IdempotencyConflictException()); + 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); + 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); + } + + private static AccountControlUiAuthenticationGrpcCodec.Request request(String namespace) { + return new AccountControlUiAuthenticationGrpcCodec.Request( + UUID.randomUUID(), + UUID.randomUUID(), + namespace, + "owner@example.test", + "controlled-secret", + new SourceContext("192.0.2.10")); + } + + 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; + String failureDescription; + boolean completed; + + @Override + public void onNext(AuthLoginResponse value) { + this.value = value; + } + + @Override + public void onError(Throwable failure) { + Status status = Status.fromThrowable(failure); + failureCode = status.getCode(); + failureDescription = status.getDescription(); + } + + @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..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 @@ -30,6 +30,7 @@ import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec.SourceContext; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import org.jooq.DSLContext; import org.jooq.Record; @@ -144,13 +145,99 @@ 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()); + if (changed == 1 || changed == 2 || changed == 4) { + verify(fixture.operations, never()).lockReplayRequest(any()); + verify(fixture.operations, never()).recordReplayFailure(any()); + } verifyNoInteractions(fixture.registry, fixture.primary, fixture.signers); } } + @Test + 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))) + .thenAnswer( + call -> { + replayMacInput.set(call.getArgument(1, byte[].class).clone()); + return "changed-request-digest"; + }); + + try (var ignored = fixture.withPeer(ISSUER)) { + assertThatThrownBy( + () -> + fixture + .service() + .issue( + fixture.request(fixture.tenant, fixture.context, "wrong-secret"), + fixture.environment)) + .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); + order.verify(fixture.cryptography).requestDigest(anyString(), any(byte[].class)); + order.verify(fixture.operations).recordReplayFailure(original); + order.verify(fixture.transactions).commit(any()); + verify(fixture.transactions, never()).rollback(any()); + verifyNoInteractions( + fixture.primary, + fixture.authority, + fixture.fences, + fixture.signers, + fixture.registry, + fixture.actors); + verify(fixture.operations, never()).beginRecoveryFailure(any()); + } + + @Test + void exhaustedReplayBudgetDeniesBeforeCredentialMacOrAccountSourceReads() { + Fixture fixture = new Fixture(NOW.plusSeconds(30)); + var original = fixture.accountExisting(); + when(fixture.operations.countReplayFailures(original)).thenReturn(5); + + try (var ignored = fixture.withPeer(ISSUER)) { + assertThatThrownBy(() -> fixture.service().issueAccount(fixture.accountRequest())) + .isInstanceOf(AccountControlUiIssuanceService.IdempotencyConflictException.class); + } + + verify(fixture.operations).lockReplayRequest(original.requestId); + verify(fixture.operations, never()).recordReplayFailure(any()); + verify(fixture.operations, never()).beginRecoveryFailure(any()); + verifyNoInteractions( + fixture.cryptography, + fixture.primary, + fixture.authority, + fixture.fences, + fixture.signers, + fixture.registry, + fixture.actors); + } + + @Test + void unavailableReplayCustodyRollsBackWithoutCountingACredentialFailure() { + Fixture fixture = new Fixture(NOW.plusSeconds(30)); + fixture.accountExisting(); + when(fixture.cryptography.requestDigest(anyString(), any(byte[].class))) + .thenThrow(new IllegalStateException("custody unavailable")); + try (var ignored = fixture.withPeer(ISSUER)) { + assertThatThrownBy(() -> fixture.service().issueAccount(fixture.accountRequest())) + .isInstanceOf(IllegalStateException.class); + } + verify(fixture.operations, never()).recordReplayFailure(any()); + verify(fixture.transactions).rollback(any()); + verify(fixture.transactions, never()).commit(any()); + verifyNoInteractions(fixture.primary, fixture.authority, fixture.registry); + } + @Test void currentSourceUnavailabilityDeniesWithoutMarkingOriginalTerminal() { Fixture fixture = new Fixture(NOW.plusSeconds(30)); @@ -318,7 +405,14 @@ void accountGlobalIssuanceUsesAccountSourcesAndReturnsItsSingleOriginalCredentia .containsEntry("authorizationScope", "ACCOUNT") .doesNotContainKey("canonicalTenantId"); assertThat(requestFields) - .doesNotContainKeys("tenantId", "environmentId", "clusterId", "namespace"); + .doesNotContainKeys( + "tenantId", + "environmentId", + "clusterId", + "namespace", + "canonicalClientAddress", + "transportClass", + "sourceContext"); Map envelopeFields = tools.jackson.databind.json.JsonMapper.builder() .build() @@ -353,6 +447,24 @@ void accountGlobalIssuanceUsesAccountSourcesAndReturnsItsSingleOriginalCredentia verify(fixture.registry).activate(committed); } + @Test + void accountSignInRequiresSourceBeforeAnyPrimaryOrIssuanceWork() { + Fixture fixture = new Fixture(NOW); + assertThatThrownBy( + () -> + fixture + .service() + .issueAccount( + new AccountControlUiIssuanceService.AccountSignInRequest( + fixture.requestId, + "creator@example.test", + "test-only-secret", + fixture.context, + null))) + .isInstanceOf(IllegalArgumentException.class); + org.mockito.Mockito.verifyNoInteractions(fixture.primary, fixture.operations, fixture.signers); + } + @Test void accountGlobalReplayReturnsOriginalCredentialAndCrossScopeRetriesConflict() { Fixture replay = new Fixture(NOW.plusSeconds(30)); @@ -361,6 +473,7 @@ void accountGlobalReplayReturnsOriginalCredentialAndCrossScopeRetriesConflict() String tokenHash = AccountControlUiIssuanceRepository.hash(exactCredential); var original = replay.useAccountOwnerRepository(tokenHash); replay.accountRecoveryInputs(); + doAnswer(call -> 4).when(replay.operations).countReplayFailures(any()); var binding = replay.envelopeBinding(original, tokenHash); var envelope = new AccountControlUiIssuanceRepository.Envelope(new byte[] {9}, binding); doAnswer(call -> envelope).when(replay.operations).envelope(any()); @@ -371,13 +484,22 @@ void accountGlobalReplayReturnsOriginalCredentialAndCrossScopeRetriesConflict() when(actor.issuanceOperationId()).thenReturn(replay.operationId); when(replay.actors.authenticateAccount("test-only-account-original")).thenReturn(actor); + var retry = replay.accountRequest(); + var changedSourceRetry = + new AccountControlUiIssuanceService.AccountSignInRequest( + retry.requestId(), + retry.email(), + retry.secret(), + retry.callerContextId(), + new SourceContext("198.51.100.20")); try (var ignored = replay.withPeer(ISSUER)) { - try (var issued = replay.service().issueAccount(replay.accountRequest())) { + try (var issued = replay.service().issueAccount(changedSourceRetry)) { assertThat(issued.compactBytes()).containsExactly(expectedCredential); } } verify(replay.authority, org.mockito.Mockito.atLeastOnce()).captureAccount(replay.account); verify(replay.actors).authenticateAccount("test-only-account-original"); + verify(replay.operations, never()).recordReplayFailure(any()); verify(replay.primary, never()).authenticateControlUiPrimaryIdentity(anyString(), anyString()); verify(replay.signers, never()).sign(any(), any(), any()); assertThat(original.scopeKind()).isEqualTo(AccountControlUiAuthority.ScopeKind.ACCOUNT); @@ -400,10 +522,10 @@ 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(IllegalArgumentException.class); + .isInstanceOf(AccountControlUiIssuanceService.IdempotencyConflictException.class); } } verify(conflict.operations, never()).beginRecoveryFailure(any()); @@ -512,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 = @@ -562,6 +713,49 @@ 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); + 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); + } + private static final class Fixture { final UUID requestId = UUID.randomUUID(); final UUID operationId = UUID.randomUUID(); @@ -677,6 +871,7 @@ private AccountControlUiIssuanceRepository.Stored useOwnerRepository( .connection(any(org.jooq.ConnectionRunnable.class)); when(dsl.fetchOne(anyString(), any(Object[].class))).thenAnswer(call -> ownerRow); operations = Mockito.spy(new AccountControlUiIssuanceRepository(dsl)); + doAnswer(call -> 0).when(operations).countReplayFailures(any()); doAnswer(call -> stored).when(operations).findRequest(requestId); when(cryptography.requestDigest(anyString(), any(byte[].class))) .thenReturn("original-request-digest"); @@ -908,7 +1103,11 @@ AccountControlUiIssuanceService.Request request( AccountControlUiIssuanceService.AccountSignInRequest accountRequest() { return new AccountControlUiIssuanceService.AccountSignInRequest( - requestId, "creator@example.test", "test-only-secret", context); + requestId, + "creator@example.test", + "test-only-secret", + context, + new SourceContext("192.0.2.10")); } PeerScope withPeer(String uri) { 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..5bee0703b5 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,54 @@ class AccountControlUiRegistryReaderTest { private static final JsonMapper JSON = JsonMapper.builder().build(); private static final String TOKEN_HASH = "a".repeat(64); + @Test + void nullAndClosedConnectionsAreUnavailable() { + assertThatThrownBy(() -> new AccountControlUiRegistryReader(() -> null).readActive(TOKEN_HASH)) + .isInstanceOf(AccountControlUiRegistryReader.RegistryUnavailableException.class) + .hasNoCause(); + StatefulRedisConnection closed = mock(StatefulRedisConnection.class); + assertThatThrownBy( + () -> new AccountControlUiRegistryReader(() -> closed).readActive(TOKEN_HASH)) + .isInstanceOf(AccountControlUiRegistryReader.RegistryUnavailableException.class) + .hasNoCause(); + verify(closed).close(); + verify(closed, org.mockito.Mockito.never()).sync(); + } + + @Test + void invalidOptionsReconnectAndWrongAclRemainRefusals() { + StatefulRedisConnection connection = mock(StatefulRedisConnection.class); + when(connection.isOpen()).thenReturn(true); + var reader = new AccountControlUiRegistryReader(() -> connection); + assertRefused(reader); + when(connection.getOptions()).thenReturn(ClientOptions.builder().autoReconnect(true).build()); + assertRefused(reader); + when(connection.getOptions()).thenReturn(ClientOptions.builder().autoReconnect(false).build()); + RedisCommands commands = mock(RedisCommands.class); + when(connection.sync()).thenReturn(commands); + when(commands.aclWhoami()).thenReturn("wrong_acl"); + assertRefused(reader); + verify(commands, org.mockito.Mockito.never()).get(any(byte[].class)); + } + + private static void assertRefused(AccountControlUiRegistryReader reader) { + assertThatThrownBy(() -> reader.readActive(TOKEN_HASH)) + .isInstanceOf(IllegalStateException.class) + .isNotInstanceOf(AccountControlUiRegistryReader.RegistryUnavailableException.class); + } + + @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(); @@ -98,7 +146,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/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..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"); @@ -575,6 +598,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/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 5e9526d09f..da4c028bcb 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 @@ -60,6 +60,35 @@ void clearAmbient() { TransactionSynchronizationManager.clearSynchronization(); } + @Test + void authenticatedOwnerReadExposesOnlyTheVerifiedOriginalReferenceWithoutRestoringProof() { + var invoice = signedCandidate().invoice(); + var original = UUID.randomUUID(); + var actor = mock(AccountControlUiActorService.AccountAuthenticatedActor.class); + when(actor.accountId()).thenReturn(invoice.ownerAccountId()); + when(actors.withCurrentAccount(eq("bearer"), any())) + .thenAnswer( + call -> { + java.util.function.Function< + AccountControlUiActorService.AccountAuthenticatedActor, Object> + action = call.getArgument(1); + return action.apply(actor); + }); + when(payments.requireOwner(invoice.subscriptionId(), invoice.ownerAccountId())) + .thenReturn(invoice); + when(payments.ownerRowVersion(invoice.subscriptionId(), invoice.ownerAccountId())) + .thenReturn(3L); + when(payments.preRowOriginalRequestId(invoice.subscriptionId(), invoice.ownerAccountId())) + .thenReturn(original); + var view = service.describeOwner("bearer", invoice.subscriptionId()); + assertThat(view.preRowOriginalRequestId()).isEqualTo(original); + assertThat(view.confirmationRequestId()).isNull(); + assertThat(view.authorizationVersion()).isZero(); + assertThat(view.expectedRowVersion()).isEqualTo(3); + assertThat(view.tupleDigest()).isEqualTo(invoice.digest()); + verifyNoInteractions(reauthentication, provider, lifecycle, inbox, verifier); + } + @Test void delayedSignedSuccessAfterAuthorizationExpiryOrAuthorityAdvanceIsReadOnlyAndAtomicallyReadBack() @@ -155,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")) @@ -165,6 +195,39 @@ void unrelatedSignedEventIsRetainedWithoutDispatchOrLifecycleWork() throws Excep verifyNoInteractions(provider, lifecycle, actors, reauthentication); } + @Test + 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)); + + verify(inbox).retainOrReplay(event); + 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); + } + @Test void verifiedUnconsentedPaymentBeforeCancellationReturnsOperatorWithoutProviderWork() throws Exception { 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..9aad17ba59 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 @@ -19,6 +19,7 @@ import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Settlement; import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; +import net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec.SourceContext; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding; @@ -43,6 +44,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 +280,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)) { @@ -464,12 +466,30 @@ record IssuedCreator( CapturedEnvironmentBoundary environment, AccountControlUiOwnerSourcesFixture sources) {} + /** Returns the fixture's authenticated Account Coordination Redis URI. */ + 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); + } + /** Same-package reuse of genuine certified ACCOUNT issuance, separate from tenant creation. */ IssuedAccount issueCertifiedAccount(String password) { var account = f.createCertifiedGlobalAccount(password); var request = new AccountControlUiIssuanceService.AccountSignInRequest( - UUID.randomUUID(), account.getEmail(), password, UUID.randomUUID()); + UUID.randomUUID(), + account.getEmail(), + password, + UUID.randomUUID(), + new SourceContext("192.0.2.10")); String compact; try (var peer = AccountControlUiOwnerSourcesFixture.withPeer( 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..23501074bc 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" }) @@ -86,7 +88,7 @@ public ClientResources lettuceClientResources(MeterRegistry registry) { havingValue = "true", matchIfMissing = true) @ConditionalOnMissingBean(RedisConnectionFactory.class) - public RedisConnectionFactory redisConnectionFactory(ClientResources resources) { + public LettuceConnectionFactory redisConnectionFactory(ClientResources resources) { RedisStandaloneConfiguration standalone = redisStandaloneConfiguration(); LettuceClientConfiguration clientConfiguration = lettuceClientConfiguration(resources); return new LettuceConnectionFactory(standalone, clientConfiguration); 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..8f6d0216b9 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,124 @@ 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.data.redis.autoconfigure.DataRedisReactiveAutoConfiguration; +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.ReactiveRedisConnectionFactory; +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.ReactiveRedisTemplate; +import org.springframework.data.redis.core.ReactiveStringRedisTemplate; +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, + DataRedisReactiveAutoConfiguration.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); + assertSame(factory, context.getBean(ReactiveRedisConnectionFactory.class)); + assertSame( + factory, + context + .getBean("reactiveRedisTemplate", ReactiveRedisTemplate.class) + .getConnectionFactory()); + assertSame( + factory, + context + .getBean("reactiveStringRedisTemplate", ReactiveStringRedisTemplate.class) + .getConnectionFactory()); + 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(); 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..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 @@ -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(); } @@ -75,7 +95,7 @@ private ManagedChannelBuilder createPlaintextBuilder(String resolved, int def 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 new file mode 100644 index 0000000000..9ca3432fb3 --- /dev/null +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/grpc/GrpcChannelFactoryNoRetryTest.java @@ -0,0 +1,123 @@ +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.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); + 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..8c607c8c90 --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/auth/AccountControlUiAuthenticationGrpcCodec.java @@ -0,0 +1,295 @@ +package net.firedevops.firemud.common.account.auth; + +import java.net.InetAddress; +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.AccountControlUiCredentialTransportClass; +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_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; + 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, + SourceContext sourceContext) { + public Request { + requireUuid(requestId); + requireUuid(callerContextId); + requireNamespace(callerNamespace); + requireEmail(email); + requireSecret(secret); + if (sourceContext == null) throw invalid(); + } + + @Override + public String toString() { + return "AccountControlUiLoginRequest[redacted]"; + } + } + + /** Transient Gateway-attested HTTP source. Construction validates shape, not provenance. */ + public record SourceContext(String canonicalClientAddress) { + public SourceContext { + if (canonicalClientAddress == null + || canonicalClientAddress.length() > 64 + || !canonicalClientAddress.matches("[0-9a-f:.]+")) throw invalid(); + try { + // Literal-only parsing never performs DNS. Match the Gateway's normalized JDK spelling. + if (!InetAddress.ofLiteral(canonicalClientAddress) + .getHostAddress() + .equals(canonicalClientAddress)) throw invalid(); + } catch (IllegalArgumentException malformed) { + throw invalid(); + } + } + + @Override + public String toString() { + return "AccountControlUiCredentialSource[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()) + .addCanonicalClientAddress(request.sourceContext().canonicalClientAddress()) + .addTransportClass( + AccountControlUiCredentialTransportClass + .ACCOUNT_CONTROL_UI_CREDENTIAL_TRANSPORT_CLASS_HTTP) + .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(); + if (oneInt(wire.getTransportClassValueList()) + != AccountControlUiCredentialTransportClass + .ACCOUNT_CONTROL_UI_CREDENTIAL_TRANSPORT_CLASS_HTTP_VALUE) throw invalid(); + return new Request( + uuid(one(wire.getRequestIdList())), + uuid(one(wire.getCallerContextIdList())), + one(wire.getTargetNamespaceList()), + one(wire.getEmailList()), + one(wire.getSecretList()), + new SourceContext(one(wire.getCanonicalClientAddressList()))); + } + + /** 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 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 + || value.chars().anyMatch(Character::isWhitespace) + || value.chars().anyMatch(Character::isISOControl)) throw invalid(); + } + + private static void requireSecret(String value) { + 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) { + 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..0b5d5a2f13 --- /dev/null +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/account/auth/AccountControlUiAuthenticationGrpcCodecTest.java @@ -0,0 +1,197 @@ +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 net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec.SourceContext; +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); + assertThat(parsed.sourceContext().canonicalClientAddress()).isEqualTo("192.0.2.10"); + assertThat(parsed.sourceContext().toString()).doesNotContain("192.0.2.10"); + } + + @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, + new SourceContext("192.0.2.10")); + + 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(); + 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 rejectsAbsentDuplicateMalformedAndWrongTransportSourceBeforeAuthentication() { + var wire = AccountControlUiAuthenticationGrpcCodec.toRequest(request()); + assertRejected(wire.toBuilder().clearCanonicalClientAddress().build()); + assertRejected(wire.toBuilder().addCanonicalClientAddress("192.0.2.11").build()); + assertRejected(wire.toBuilder().clearTransportClass().build()); + assertRejected(wire.toBuilder().addTransportClassValue(1).build()); + assertRejected(wire.toBuilder().setTransportClassValue(0, 0).build()); + assertRejected(wire.toBuilder().setTransportClassValue(0, 99).build()); + for (String address : + java.util.List.of( + "", + "localhost", + "192.0.2.010", + "192.0.2.256", + "127.1", + " 192.0.2.10", + "192.0.2.10:443", + "2001:DB8:0:0:0:0:0:1", + "2001:db8::1", + "[::1]", + "fe80:0:0:0:0:0:0:1%eth0", + "::ffff:192.0.2.10", + "a".repeat(65))) { + assertRejected(wire.toBuilder().setCanonicalClientAddress(0, address).build()); + } + assertThatThrownBy(() -> new SourceContext(null)).isInstanceOf(IllegalArgumentException.class); + assertThat( + AccountControlUiAuthenticationGrpcCodec.parseRequest( + wire.toBuilder().setCanonicalClientAddress(0, "2001:db8:0:0:0:0:0:1").build()) + .sourceContext() + .canonicalClientAddress()) + .isEqualTo("2001:db8:0:0:0:0:0:1"); + } + + @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, new SourceContext("192.0.2.10")); + } + + 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/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java index a5f4e7e47a..12576c1005 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java @@ -37,6 +37,7 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.context.annotation.Import; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.core.RedisOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.SessionCallback; @@ -72,8 +73,8 @@ class GameSessionLoginIntegrationTest { @MockitoBean private SharedSettingsAuthorityReader sharedSettingsAuthorityReader; - @MockitoBean - private org.springframework.data.redis.connection.RedisConnectionFactory redisConnectionFactory; + // Preserve both Redis factory interfaces used by Boot health auto-configuration. + @MockitoBean private LettuceConnectionFactory redisConnectionFactory; @MockitoBean private RedisTemplate redisTemplate; diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index c6499a3147..cd8c63b697 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -66,7 +66,7 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.context.annotation.Import; -import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.core.RedisOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.SessionCallback; @@ -157,7 +157,8 @@ static void registerProperties(DynamicPropertyRegistry registry) { @MockitoBean private ScreenBufferService screenBufferService; - @MockitoBean private RedisConnectionFactory redisConnectionFactory; + // Preserve both Redis factory interfaces used by Boot health auto-configuration. + @MockitoBean private LettuceConnectionFactory redisConnectionFactory; @MockitoBean private RedisTemplate redisTemplate; diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/RedisHealthMockitoBeanConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/RedisHealthMockitoBeanConfigurationTest.java new file mode 100644 index 0000000000..b6db4151f6 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/RedisHealthMockitoBeanConfigurationTest.java @@ -0,0 +1,58 @@ +package net.firedevops.firemud.gamesession.config; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.lettuce.core.resource.ClientResources; +import io.micrometer.core.instrument.MeterRegistry; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import net.firedevops.firemud.common.config.DatabaseAutoConfiguration; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.data.redis.autoconfigure.health.DataRedisReactiveHealthContributorAutoConfiguration; +import org.springframework.boot.health.contributor.ReactiveHealthContributor; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +@SpringJUnitConfig(RedisHealthMockitoBeanConfigurationTest.Config.class) +@TestPropertySource(properties = "firemud.database.enabled=false") +class RedisHealthMockitoBeanConfigurationTest { + @MockitoBean private ClientResources clientResources; + + // An imperative-only replacement loses the reactive interface after conditions are evaluated. + @MockitoBean private LettuceConnectionFactory redisConnectionFactory; + + @Autowired private ApplicationContext context; + + @Test + void mockedFactoryRetainsBothInterfacesAndReactiveHealthContributor() { + assertThat(context.getBeansOfType(RedisConnectionFactory.class)) + .containsOnlyKeys("redisConnectionFactory") + .containsValue(redisConnectionFactory); + assertThat(context.getBeansOfType(ReactiveRedisConnectionFactory.class)) + .containsOnlyKeys("redisConnectionFactory"); + assertThat(context.getBean(ReactiveRedisConnectionFactory.class)) + .isSameAs(redisConnectionFactory); + assertThat(context.getBean("redisHealthContributor")) + .isInstanceOf(ReactiveHealthContributor.class); + } + + @Configuration(proxyBeanMethods = false) + @ImportAutoConfiguration({ + DatabaseAutoConfiguration.class, + DataRedisReactiveHealthContributorAutoConfiguration.class + }) + static class Config { + @Bean + MeterRegistry meterRegistry() { + return new SimpleMeterRegistry(); + } + } +} 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..2b7fb3b7dd --- /dev/null +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/client/AccountCheckoutHttpClient.java @@ -0,0 +1,324 @@ +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; +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 { + 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 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); + + 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)) { + return Mono.just(ForwardedResponse.unauthorized()); + } + if (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( + method, + accountPath, + response.statusCode(), + response.headers().asHttpHeaders(), + response.bodyToMono(byte[].class))) + .timeout(totalTimeout) + .onErrorResume(ignored -> Mono.just(ForwardedResponse.gatewayError())); + } + + private Mono readResponse( + HttpMethod method, + String path, + HttpStatusCode status, + HttpHeaders headers, + Mono responseBody) { + if (!status.is2xxSuccessful()) { + HttpStatusCode safeStatus = + 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 + .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() + || 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 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); + } + + 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 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]); + } + + 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..10a8be0dfd --- /dev/null +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/client/AccountControlUiAuthenticationClient.java @@ -0,0 +1,145 @@ +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.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; +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; + + 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 { + initOnce( + "Account authentication client is closed", "Account authentication stub is unavailable"); + } + + /** 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); + AuthLoginResponse wireResponse; + try { + 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(); + } + 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"); + } catch (IllegalStateException unavailable) { + throw new AuthenticationUnavailableException(); + } + try { + return AccountControlUiAuthenticationGrpcCodec.requireResponse(request, wireResponse); + } 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)); + } + + 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"); + } + } + + /** 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/config/AccountCheckoutReceivingConfiguration.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfiguration.java new file mode 100644 index 0000000000..627e2d4a49 --- /dev/null +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfiguration.java @@ -0,0 +1,200 @@ +package net.firedevops.firemud.springcloudgateway.config; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +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.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; +import org.springframework.web.server.WebFilter; +import org.springframework.web.server.WebFilterChain; +import org.springframework.web.util.pattern.PathPattern; +import org.springframework.web.util.pattern.PathPatternParser; +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, + @Qualifier(RedisRateLimiter.REDIS_SCRIPT_NAME) RedisScript> script, + AccountCheckoutReceivingProperties properties) { + Objects.requireNonNull(redisTemplate, "Gateway Redis rate limiting must be available"); + GatewayRateLimiterConfig.DefaultRequestRateLimiterArguments arguments = + GatewayRateLimiterConfig.defaultRequestRateLimiterArguments(gatewayProperties); + var rateLimiter = + new AccountCheckoutReceivingRateLimiter( + redisTemplate, script, arguments, properties.getRateLimitDecisionTimeoutMs()); + 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 PathPattern LOGIN_PATH = + PathPatternParser.defaultInstance.parse("/api/account/auth/login"); + private static final PathPattern WEBHOOK_PATH = + PathPatternParser.defaultInstance.parse("/api/account/billing/hosting/webhook"); + private static final String FIRST_INVOICE = + "/api/account/billing/hosting/subscriptions/{subscriptionId}/first-invoice"; + private static final PathPattern FIRST_INVOICE_PATH = + PathPatternParser.defaultInstance.parse(FIRST_INVOICE); + private static final List FIRST_INVOICE_ACTIONS = + List.of("reauthenticate", "confirm", "renew").stream() + .map(action -> PathPatternParser.defaultInstance.parse(FIRST_INVOICE + "/" + action)) + .toList(); + 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) { + // PathPattern uses the same decoded, matrix-parameter-free segments as WebFlux routing. + var path = exchange.getRequest().getPath().pathWithinApplication(); + var method = exchange.getRequest().getMethod(); + if (org.springframework.http.HttpMethod.POST.equals(method)) { + return LOGIN_PATH.matches(path) + || WEBHOOK_PATH.matches(path) + || FIRST_INVOICE_ACTIONS.stream().anyMatch(pattern -> pattern.matches(path)); + } + return (org.springframework.http.HttpMethod.GET.equals(method) + || org.springframework.http.HttpMethod.HEAD.equals(method)) + && FIRST_INVOICE_PATH.matches(path); + } + + 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)))); + } + + @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..ac9a7be6a9 --- /dev/null +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingProperties.java @@ -0,0 +1,81 @@ +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; + private int rateLimitDecisionTimeoutMs = 2_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 + || rateLimitDecisionTimeoutMs < 1 + || rateLimitDecisionTimeoutMs > 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/AccountCheckoutReceivingRateLimiter.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingRateLimiter.java new file mode 100644 index 0000000000..01e1b38ac8 --- /dev/null +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingRateLimiter.java @@ -0,0 +1,86 @@ +package net.firedevops.firemud.springcloudgateway.config; + +import java.time.Duration; +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; + private final Duration decisionTimeout; + + AccountCheckoutReceivingRateLimiter( + ReactiveStringRedisTemplate redisTemplate, + RedisScript> script, + GatewayRateLimiterConfig.DefaultRequestRateLimiterArguments configuration, + int decisionTimeoutMs) { + if (decisionTimeoutMs < 1 || decisionTimeoutMs > 30_000) { + throw new IllegalArgumentException("Bounded positive rate-limit decision timeout required"); + } + this.decisionTimeout = Duration.ofMillis(decisionTimeoutMs); + 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) + .timeout(decisionTimeout); + } + + 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/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..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 @@ -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,65 @@ 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(); + } + 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) { + 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..f79b4747a7 --- /dev/null +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/controller/AccountCheckoutGatewayController.java @@ -0,0 +1,365 @@ +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; +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 net.firedevops.firemud.springcloudgateway.filter.VerifiedHttpClientOrigin; +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 Duration REQUEST_BODY_TIMEOUT = Duration.ofSeconds(5); + 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"))); + } + VerifiedHttpClientOrigin origin = VerifiedHttpClientOrigin.from(exchange); + if (origin == null) { + return Mono.just(jsonResponse(HttpStatus.SERVICE_UNAVAILABLE, 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(), + origin.sourceContext()); + } 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.AuthenticationInvalidRequestException + .class, + invalid -> + Mono.just(jsonResponse(HttpStatus.BAD_REQUEST, 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")))) + .onErrorResume( + RequestBodyTimeoutException.class, + timedOut -> Mono.just(jsonResponse(HttpStatus.REQUEST_TIMEOUT, 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")))) + .onErrorResume( + RequestBodyTimeoutException.class, + timedOut -> Mono.just(jsonResponse(HttpStatus.REQUEST_TIMEOUT, 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")))) + .onErrorResume( + RequestBodyTimeoutException.class, + timedOut -> Mono.just(jsonResponse(HttpStatus.REQUEST_TIMEOUT, 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) + .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()]; + 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/java/net/firedevops/firemud/springcloudgateway/filter/HeaderTrustFilter.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/HeaderTrustFilter.java index 4a0d2b9135..80bee3afca 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/HeaderTrustFilter.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/HeaderTrustFilter.java @@ -60,6 +60,7 @@ public HeaderTrustFilter( @Override public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { + VerifiedHttpClientOrigin.clear(exchange); PathContainer path = exchange.getRequest().getPath().pathWithinApplication(); boolean isGameplayRoute = GameplayRouteClassifier.classify(path).gameplayRoute(); boolean isSessionRoute = isGameplayRoute || GameplayRouteClassifier.sessionApiRoute(path); @@ -87,6 +88,10 @@ public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { return exchange.getResponse().setComplete(); } + if (!dedicatedTcpProxyListener && !isGameplayRoute) { + VerifiedHttpClientOrigin.retain(exchange, canonicalClientIp); + } + String incomingProxyConnectionId = trustedTcpProxy ? exchange.getRequest().getHeaders().getFirst(HDR_PROXY_CONNECTION_ID) diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/VerifiedHttpClientOrigin.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/VerifiedHttpClientOrigin.java new file mode 100644 index 0000000000..42371d1ca7 --- /dev/null +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/VerifiedHttpClientOrigin.java @@ -0,0 +1,43 @@ +package net.firedevops.firemud.springcloudgateway.filter; + +import net.firedevops.firemud.common.account.auth.AccountControlUiAuthenticationGrpcCodec.SourceContext; +import org.springframework.web.server.ServerWebExchange; + +/** Process-private HTTP source proof produced by the Gateway header-trust filter. */ +public final class VerifiedHttpClientOrigin { + private static final String ATTRIBUTE = VerifiedHttpClientOrigin.class.getName(); + private final SourceContext sourceContext; + + private VerifiedHttpClientOrigin(SourceContext sourceContext) { + this.sourceContext = sourceContext; + } + + static void clear(ServerWebExchange exchange) { + exchange.getAttributes().remove(ATTRIBUTE); + } + + static void retain(ServerWebExchange exchange, String canonicalAddress) { + try { + exchange + .getAttributes() + .put(ATTRIBUTE, new VerifiedHttpClientOrigin(new SourceContext(canonicalAddress))); + } catch (IllegalArgumentException invalidSource) { + // Unresolved or noncanonical source is unavailable to credential receivers, never a fallback. + clear(exchange); + } + } + + public static VerifiedHttpClientOrigin from(ServerWebExchange exchange) { + Object value = exchange.getAttributes().get(ATTRIBUTE); + return value instanceof VerifiedHttpClientOrigin origin ? origin : null; + } + + public SourceContext sourceContext() { + return sourceContext; + } + + @Override + public String toString() { + return "VerifiedHttpClientOrigin[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..6ab3436a33 100644 --- a/services/spring-cloud-gateway/src/main/resources/openapi.yaml +++ b/services/spring-cloud-gateway/src/main/resources/openapi.yaml @@ -38,6 +38,232 @@ 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 + 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} + 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} + '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} + '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 + in: path + required: true + 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: + '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} + '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 + in: path + required: true + 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. Account validates the typed billingBinding against the retained invoice and authorization attempt. + requestBody: + required: true + content: + application/json: + schema: + type: object + additionalProperties: false + required: [requestId, confirmationRequestId, email, secret, billingBinding] + properties: + requestId: {type: string, format: uuid} + confirmationRequestId: {type: string, format: uuid} + email: {type: string, format: email} + secret: {type: string, format: password, writeOnly: true} + 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. + required: [originalRequestId, expectedRowVersion, expectedAuthorizationVersion, acceptedTupleDigest, invoiceExpiresAt, authorizationPurpose] + properties: + originalRequestId: {type: string, format: uuid} + expectedRowVersion: {type: integer, format: int64, minimum: 1} + expectedAuthorizationVersion: {type: integer, format: int64, minimum: 0} + acceptedTupleDigest: {type: string, pattern: '^sha256:[0-9a-f]{64}$'} + invoiceExpiresAt: {type: string, format: date-time} + authorizationPurpose: {type: string, enum: [INITIAL_CONFIRMATION, PRE_ROW_RENEWAL, FOLLOWUP_RENEWAL]} + 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} + '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} + '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 + in: path + required: true + 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. + requestBody: + required: true + content: + application/json: + schema: + type: object + additionalProperties: false + required: [requestId, expectedRowVersion, reauthenticationEvidenceId, acceptedTupleDigest, acceptCharge] + properties: + requestId: {type: string, format: uuid} + expectedRowVersion: {type: integer, format: int64, minimum: 1} + reauthenticationEvidenceId: {type: string, format: uuid} + acceptedTupleDigest: {type: string, pattern: '^sha256:[0-9a-f]{64}$'} + acceptCharge: {type: boolean, enum: [true]} + 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} + '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} + '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 + in: path + required: true + 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. + requestBody: + required: true + content: + application/json: + schema: + type: object + additionalProperties: false + required: [requestId, authorizationRequestId, expectedAuthorizationVersion, expectedRowVersion, reauthenticationEvidenceId, acceptedTupleDigest, acceptCharge] + properties: + requestId: {type: string, format: uuid} + authorizationRequestId: {type: string, format: uuid} + expectedAuthorizationVersion: {type: integer, format: int64, minimum: 0} + expectedRowVersion: {type: integer, format: int64, minimum: 1} + reauthenticationEvidenceId: {type: string, format: uuid} + acceptedTupleDigest: {type: string, pattern: '^sha256:[0-9a-f]{64}$'} + acceptCharge: {type: boolean, enum: [true]} + 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} + '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} + '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 + 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. + parameters: + - name: Stripe-Signature + in: header + required: true + schema: {type: string, maxLength: 4096} + requestBody: + required: true + description: >- + Exact raw UTF-8 JSON provider event authenticated by Stripe-Signature. + The raw request body must not exceed 262144 bytes (256 KiB), enforced + before forwarding. This is a byte limit, not a JSON character limit. + Forward the original bytes unchanged without parsing or reserialization, + automatic retries, or redirects. + x-max-body-bytes: 262144 + content: + application/json: + schema: + type: object + additionalProperties: true + responses: + '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} + '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 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..c69eb259a9 --- /dev/null +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/client/AccountCheckoutHttpClientTlsTest.java @@ -0,0 +1,516 @@ +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 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; +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 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(); + 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); + } + + @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")); + 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..6f1d5d0b5a --- /dev/null +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/client/AccountControlUiAuthenticationClientMtlsTest.java @@ -0,0 +1,334 @@ +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.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; +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.CountDownLatch; +import java.util.concurrent.Executors; +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.account.auth.AccountControlUiAuthenticationGrpcCodec.SourceContext; +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 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(); + 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()); + } + + @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, + AtomicReference peer) + throws Exception { + return startServer(serverIdentityAlias, observed, peer, (Status.Code) null); + } + + private AtomicInteger startServer( + String serverIdentityAlias, + AtomicReference observed, + 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 { + 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 + 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 (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) + .withDescription("controlled upstream detail") + .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 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); + 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, + new SourceContext("192.0.2.10")); + } +} 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..49a04ab100 --- /dev/null +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfigurationTest.java @@ -0,0 +1,315 @@ +package net.firedevops.firemud.springcloudgateway.config; + +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; +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 net.firedevops.firemud.springcloudgateway.filter.HeaderTrustFilter; +import net.firedevops.firemud.springcloudgateway.filter.TcpProxyTrustPolicy; +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.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; +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(); + for (int invalid : new int[] {0, -1, 30_001}) { + properties.setRateLimitDecisionTimeoutMs(invalid); + assertThat(catchThrowable(properties::validateEnabledConfiguration)) + .isInstanceOf(IllegalStateException.class); + } + for (int valid : new int[] {1, 30_000}) { + properties.setRateLimitDecisionTimeoutMs(valid); + 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 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("https://localhost/api/account/auth/login") + .sslInfo(mock(SslInfo.class)) + .remoteAddress(new java.net.InetSocketAddress("192.0.2.10", 443)) + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .body(body); + + var headerProperties = new GatewayHeaderTrustProperties(); + var trust = + new HeaderTrustFilter( + headerProperties, + new TcpProxyTrustPolicy( + new GatewayTcpProxyListenerProperties(), + headerProperties, + 8080, + java.time.Clock.systemUTC(), + java.util.Set.of("test"))); + var responseHolder = new AtomicReference>(); + trust + .filter( + MockServerWebExchange.from(request), + exchange -> controller.login(exchange).doOnNext(responseHolder::set).then()) + .block(); + var response = responseHolder.get(); + + 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<>(); + 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 AccountCheckoutReceivingProperties receivingProperties() { + var properties = new AccountCheckoutReceivingProperties(); + properties.setEnabled(true); + properties.setWorkloadNamespace("checkout-test"); + return properties; + } + + 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/AccountCheckoutReceivingRateLimiterTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingRateLimiterTest.java new file mode 100644 index 0000000000..f47e70aefc --- /dev/null +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingRateLimiterTest.java @@ -0,0 +1,333 @@ +package net.firedevops.firemud.springcloudgateway.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; +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.time.Duration; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.Stream; +import net.firedevops.firemud.springcloudgateway.controller.AccountCheckoutGatewayController; +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.cloud.gateway.filter.ratelimit.RateLimiter; +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.http.ResponseEntity; +import org.springframework.mock.env.MockEnvironment; +import org.springframework.mock.http.server.reactive.MockServerHttpRequest; +import org.springframework.mock.web.server.MockServerWebExchange; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.web.server.WebFilter; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; +import reactor.test.publisher.TestPublisher; + +class AccountCheckoutReceivingRateLimiterTest { + @Test + void neverCompletingRedisDecisionTimesOutAndCancelsWithoutForwarding() { + var redis = mock(ReactiveStringRedisTemplate.class); + var script = tokenBucketScript(); + var cancelled = new AtomicBoolean(); + when(redis.execute(eq(script), anyList(), anyList())) + .thenReturn(Flux.>never().doOnCancel(() -> cancelled.set(true))); + var exchange = + MockServerWebExchange.from( + MockServerHttpRequest.post("https://localhost/api/account/auth/login") + .header("X-Client-IP", "192.0.2.123")); + var forwarded = new AtomicBoolean(); + StepVerifier.withVirtualTime( + () -> + configuredFilter(redis, script) + .filter( + exchange, + ignored -> { + forwarded.set(true); + return Mono.empty(); + })) + .thenAwait(Duration.ofMillis(1_999)) + .then( + () -> { + assertThat(cancelled).isFalse(); + assertThat(exchange.getResponse().getStatusCode()).isNull(); + }) + .thenAwait(Duration.ofMillis(1)) + .verifyComplete(); + assertThat(cancelled).isTrue(); + assertThat(forwarded).isFalse(); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); + assertThat(exchange.getResponse().getHeaders().getCacheControl()).contains("no-store"); + } + + @Test + void lateAllowAfterTimeoutCannotForward() { + var redis = mock(ReactiveStringRedisTemplate.class); + var script = tokenBucketScript(); + var publisher = + TestPublisher.>createNoncompliant(TestPublisher.Violation.DEFER_CANCELLATION); + when(redis.execute(eq(script), anyList(), anyList())).thenReturn(publisher.flux()); + var exchange = + MockServerWebExchange.from( + MockServerHttpRequest.post("https://localhost/api/account/auth/login") + .header("X-Client-IP", "192.0.2.123")); + var forwarded = new AtomicBoolean(); + StepVerifier.withVirtualTime( + () -> + configuredFilter(redis, script) + .filter( + exchange, + ignored -> { + forwarded.set(true); + return Mono.empty(); + })) + .thenAwait(Duration.ofSeconds(2)) + .verifyComplete(); + publisher.assertCancelled(); + publisher.emit(List.of(1L, 38L)); + assertThat(forwarded).isFalse(); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); + } + + @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.HEAD, 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); + } + + @ParameterizedTest + @MethodSource("handlerBoundRequests") + void handlerEquivalentPathsAndImplicitHeadCannotSkipTheLimiter( + HttpMethod method, String path, int decision) { + var controller = mock(AccountCheckoutGatewayController.class); + when(controller.login(any())).thenReturn(Mono.just(ResponseEntity.ok(new byte[0]))); + when(controller.getFirstInvoice(anyString(), any())) + .thenReturn(Mono.just(ResponseEntity.ok(new byte[0]))); + RateLimiter limiter = mock(RateLimiter.class); + when(limiter.isAllowed("account-checkout-receiving", "test-client")) + .thenReturn( + decision < 0 + ? Mono.error(new IllegalStateException("Redis unavailable")) + : Mono.just(new RateLimiter.Response(decision > 0, Map.of()))); + var client = + WebTestClient.bindToController(controller) + .webFilter( + AccountCheckoutReceivingConfiguration.receivingRateLimitWebFilter( + limiter, ignored -> Mono.just("test-client"))) + .build(); + + client + .method(method) + .uri(URI.create("https://localhost" + path)) + .exchange() + .expectStatus() + .isEqualTo(decision < 0 ? 503 : decision == 0 ? 429 : 200); + + verify(limiter).isAllowed("account-checkout-receiving", "test-client"); + if (decision > 0) { + if (method == HttpMethod.POST) verify(controller).login(any()); + else verify(controller).getFirstInvoice(anyString(), any()); + } else { + verify(controller, never()).login(any()); + verify(controller, never()).getFirstInvoice(anyString(), any()); + } + } + + static Stream handlerBoundRequests() { + String invoice = + "/api/account/billing/hosting/subscriptions/927fb6a8-3975-4cba-8145-c2a8f4a9b0d1/first-invoice"; + return Stream.of(-1, 0, 1) + .flatMap( + decision -> + Stream.of( + Arguments.of(HttpMethod.POST, "/api/account/auth/%6cogin", decision), + Arguments.of(HttpMethod.POST, "/api/account/auth/login;x=1", decision), + Arguments.of(HttpMethod.GET, invoice + ";x=1", decision), + Arguments.of(HttpMethod.HEAD, invoice, decision), + Arguments.of( + HttpMethod.HEAD, + invoice.replace("first-invoice", "%66irst-invoice"), + decision))); + } + + 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, + new AccountCheckoutReceivingProperties()); + } + + @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/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..21fc50d757 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,103 @@ 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 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(); + 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..5d24807308 --- /dev/null +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/controller/AccountCheckoutGatewayControllerTest.java @@ -0,0 +1,461 @@ +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 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; +import net.firedevops.firemud.springcloudgateway.client.AccountCheckoutHttpClient; +import net.firedevops.firemud.springcloudgateway.client.AccountControlUiAuthenticationClient; +import net.firedevops.firemud.springcloudgateway.config.AccountCheckoutReceivingProperties; +import net.firedevops.firemud.springcloudgateway.config.GatewayHeaderTrustProperties; +import net.firedevops.firemud.springcloudgateway.config.GatewayTcpProxyListenerProperties; +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; +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 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"); + 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().sourceContext().canonicalClientAddress()) + .isEqualTo("192.0.2.10"); + assertThat(requestCaptor.getValue().toString()).doesNotContain(SECRET); + verifyNoCheckoutCalls(checkoutClient); + } + + @Test + void canonicalSourceComesFromTrustFilterAndNeverFromUntrustedHeaders() { + for (boolean trustedForwarder : new boolean[] {false, true}) { + var authClient = mock(AccountControlUiAuthenticationClient.class); + var checkoutClient = mock(AccountCheckoutHttpClient.class); + var controller = + new AccountCheckoutGatewayController(authClient, checkoutClient, properties()); + when(authClient.login(any())) + .thenReturn( + new AccountControlUiAuthenticationGrpcCodec.Result( + AccountControlUiAuthenticationGrpcCodec.Outcome.DENIED, null)); + var headers = new GatewayHeaderTrustProperties(); + if (trustedForwarder) + headers.getForwardedClientIp().setTrustedProxyCidrs(java.util.List.of("192.0.2.0/24")); + var request = + MockServerHttpRequest.post("https://localhost/api/account/auth/login") + .sslInfo(mock(SslInfo.class)) + .remoteAddress(new java.net.InetSocketAddress("192.0.2.10", 443)) + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .header("X-Client-IP", "203.0.113.99") + .header("X-Forwarded-For", "198.51.100.20") + .header("X-Proxy-Client-IP", "203.0.113.98") + .body(loginJson()); + var response = + controller.login(canonicalized(MockServerWebExchange.from(request), headers)).block(); + assertThat(response).isNotNull(); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); + var captured = org.mockito.ArgumentCaptor.forClass(Request.class); + verify(authClient).login(captured.capture()); + assertThat(captured.getValue().sourceContext().canonicalClientAddress()) + .isEqualTo(trustedForwarder ? "198.51.100.20" : "192.0.2.10"); + } + } + + @Test + void absentFilterProofOrUnresolvedPeerRefusesBeforeCredentialForwarding() { + var authClient = mock(AccountControlUiAuthenticationClient.class); + var checkoutClient = mock(AccountCheckoutHttpClient.class); + var controller = new AccountCheckoutGatewayController(authClient, checkoutClient, properties()); + var request = + MockServerHttpRequest.post("https://localhost/api/account/auth/login") + .sslInfo(mock(SslInfo.class)) + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .header("X-Client-IP", "192.0.2.10") + .header("X-Forwarded-For", "192.0.2.10") + .body(loginJson()); + for (ServerWebExchange exchange : + java.util.List.of( + MockServerWebExchange.from(request), + canonicalized( + MockServerWebExchange.from(request), new GatewayHeaderTrustProperties()))) { + var response = controller.login(exchange).block(); + assertThat(response).isNotNull(); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); + assertThat(response.getHeaders().getCacheControl()).contains("no-store"); + } + verify(authClient, never()).login(any()); + 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 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 = + 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 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); + 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\" \t\n} \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"); + 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"), + 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()); + } + + @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 ServerWebExchange secureExchange(String path, String body) { + var request = + MockServerHttpRequest.method(HttpMethod.POST, URI.create("https://localhost" + path)) + .sslInfo(mock(SslInfo.class)) + .remoteAddress(new java.net.InetSocketAddress("192.0.2.10", 443)) + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .body(body); + return canonicalized(MockServerWebExchange.from(request), new GatewayHeaderTrustProperties()); + } + + private static ServerWebExchange canonicalized( + ServerWebExchange exchange, GatewayHeaderTrustProperties properties) { + var filter = + new HeaderTrustFilter( + properties, + new TcpProxyTrustPolicy( + new GatewayTcpProxyListenerProperties(), + properties, + 8080, + java.time.Clock.systemUTC(), + java.util.Set.of("test"))); + var result = new java.util.concurrent.atomic.AtomicReference(); + filter + .filter( + exchange, + canonical -> { + result.set(canonical); + return Mono.empty(); + }) + .block(); + return result.get(); + } + + private static void verifyNoCheckoutCalls(AccountCheckoutHttpClient checkoutClient) { + verify(checkoutClient, never()).forward(any(), any(), any(), any()); + } +} diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/HeaderTrustFilterTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/HeaderTrustFilterTest.java index 198499fe11..01094e74bd 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/HeaderTrustFilterTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/HeaderTrustFilterTest.java @@ -48,6 +48,28 @@ void stripsSpoofedClientIpHeader() { .isEqualTo("1.2.3.4"); } + @Test + void retainsPrivateHttpOriginIndependentlyOfMutableHeadersAndRedactsIt() { + var request = + MockServerHttpRequest.post("/api/account/auth/login") + .remoteAddress(new InetSocketAddress("192.0.2.10", 443)) + .header("X-Client-IP", "198.51.100.20") + .build(); + var original = MockServerWebExchange.from(request); + assertThat(VerifiedHttpClientOrigin.from(original)).isNull(); + var canonical = filterThroughChain(legacyFilter(new GatewayHeaderTrustProperties()), original); + var changed = + canonical + .mutate() + .request( + builder -> builder.headers(headers -> headers.set("X-Client-IP", "203.0.113.1"))) + .build(); + var origin = VerifiedHttpClientOrigin.from(changed); + assertThat(origin).isNotNull(); + assertThat(origin.sourceContext().canonicalClientAddress()).isEqualTo("192.0.2.10"); + assertThat(origin.toString()).doesNotContain("192.0.2.10"); + } + @Test void stripsSpoofedRoutingBundleFromPublicGameplayIngress() { HeaderTrustFilter filter = legacyFilter(new GatewayHeaderTrustProperties());