diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 5f0272e0bc..e2b50698be 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -56,7 +56,7 @@ permissions: contents: read concurrency: - group: runtime-images-${{ github.workflow }}-${{ (github.event_name == 'pull_request' || github.event_name == 'repository_dispatch') && format('pr-{0}', github.event_name == 'pull_request' && github.event.pull_request.number || github.event.client_payload.pr_number) || github.event_name == 'workflow_run' && format('branch-{0}', github.event.workflow_run.head_branch) || github.ref }}-${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'metadata' || 'required' }} + group: runtime-images-${{ github.workflow }}-${{ (github.event_name == 'pull_request' && format('pr-{0}-base-{1}-head-{2}-merge-{3}', github.event.pull_request.number, github.event.pull_request.base.sha, github.event.pull_request.head.sha, github.sha)) || (github.event_name == 'repository_dispatch' && github.event.client_payload.pr_number != '' && github.event.client_payload.base_sha != '' && github.event.client_payload.head_sha != '' && github.event.client_payload.merge_sha != '' && format('pr-{0}-base-{1}-head-{2}-merge-{3}', github.event.client_payload.pr_number, github.event.client_payload.base_sha, github.event.client_payload.head_sha, github.event.client_payload.merge_sha)) || (github.event_name == 'repository_dispatch' && format('repository-dispatch-run-{0}', github.run_id)) || (github.event_name == 'workflow_run' && format('branch-{0}', github.event.workflow_run.head_branch)) || github.ref }}-${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'metadata' || 'required' }} cancel-in-progress: true jobs: diff --git a/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md b/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md index 3e398afaee..82c176f5b1 100644 --- a/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md +++ b/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md @@ -99,14 +99,20 @@ For the tenant-scoped `tenantAdmin` branch of `firemud.game-session.start-sessio #### Redeemed StartSession Projection Read -After Game Session has redeemed the original human StartSession reference and allocated its owner attempt and fence, Account may serve `ReadRedeemedOperationProjection` to the exact same-namespace `game-design-service` peer only to read the immutable template-selected source/descriptor for the same original tenant, template, and `controlPlaneRequestId`. The request is bound to the exact canonical pre-authorization tuple, Account-returned authorization-reference fingerprint, original reservation owner/fence, and actual Game Session `ownerAttemptId`/`ownerFence`; Account independently revalidates the original actor and `control-ui` token `jti`, current Account source and reference expiry, and the stored original reservation and redeemed Game Session attempt/fence before returning that projection. No forwarded JWT or opaque reference is sent on this read, and neither workload identity, fingerprint, nor authority-bundle integrity alone establishes authority. The read is credential-free and read-only: it does not renew or extend a reservation/reference, issue or redeem a credential, mutate source state, select a different template or policy, create another owner attempt, commit the owner mutation, or bootstrap/activate a runtime. Exact retries repeat the same binding and return the same operation projection without policy reselection; changed, stale, or ambiguous bindings fail closed. This read is not a commit-spanning CAS proof; owner commit and runtime activation remain separately fenced by their owners. +After Game Session has redeemed the original human StartSession reference and allocated its owner attempt and fence, Account may serve `ReadRedeemedOperationProjection` to the exact same-namespace `game-design-service` peer to read the immutable template-selected source/descriptor for the same original tenant, template, and `controlPlaneRequestId`. The request is bound to the exact canonical pre-authorization tuple, Account-returned authorization-reference fingerprint, original reservation owner/fence, and actual Game Session `ownerAttemptId`/`ownerFence`; Account independently revalidates the original actor and `control-ui` token `jti`, current Account source and reference expiry, and the stored original reservation and redeemed Game Session attempt/fence before returning that projection. -The separately bounded original Game Session read/pin continuation is governed by the [Game Session owner contract](../microservices/game-session-service/api-contracts.md#restricted-original-claim-evidence-continuation); it is not a broader template-selection or mutation permission. +The same RPC may serve the exact configured same-namespace `game-session-service` identity only for the separately bounded original read/pin continuation under the [Game Session owner contract](../microservices/game-session-service/api-contracts.md#restricted-original-claim-evidence-continuation). That continuation must use the unchanged complete original tuple, Account-returned fingerprint, reservation owner and claim fence, and actual owner attempt and fence, while the same stored `PENDING` claim, attempt, and fence remain unexpired. Account independently revalidates the original actor and `control-ui` token `jti`, current Account source and reference expiry, original reservation, and redeemed Game Session attempt/fence for the read. The owner may only read or replay the existing immutable association and its selection pin; this caller cannot select or pin a different template or descriptor. No other Game Session caller is allowed by this mapping. + +No forwarded JWT or opaque reference is sent on either read, and neither workload identity, fingerprint, nor authority-bundle integrity alone establishes authority. Both reads are credential-free and read-only: they do not renew or extend a reservation/reference, issue or redeem a credential, mutate source state, create another owner attempt, commit the owner mutation, or bootstrap/activate a runtime. Exact retries repeat the same binding and return the same operation projection without reselection; changed, stale, or ambiguous bindings fail closed. Neither read is a commit-spanning CAS proof; owner commit and runtime activation remain separately fenced by their owners. + +The Game Session caller mapping remains limited to that original read/pin continuation; it is not a broader template-selection or mutation permission. `authorityTuple` is copied without scalarization or field renaming from the complete canonical shape in the [JWT and token contracts](../system-architecture-jwt-and-token-contracts.md#canonical-authority-tuple). `membershipVersion` is the independently applicable Account membership-version map, including `{}` when no membership applies. `HumanAuthorityEvidence/v1` carries the Account-derived actor account, `control-ui` token `jti`, role, assurance only when applicable to that role, account generation, and applicable tenant or target-tenant generation. `AutomationAuthorityEvidence/v1` carries the exact authenticated workload, automation-policy identity/version, and applicable tenant generation. The tagged `issuanceEvidence` arm must agree with Account-derived `issuanceKind`; the inapplicable arm and inapplicable authority-scope identifiers are omitted rather than serialized as `null`, empty objects, or sentinels. `sourceEvidenceId` identifies the one Account authority snapshot and its linearization evidence, while `sourceEvidenceVersion` is the corresponding Account-issued source version; together they are the canonical source fence for the bundle and are carried unchanged with the existing `{bundleVersion, sourceVersion, sourceFence, linearization}` reference. Account derives every authority, generation, membership, freshness, and branch-decision member from that one atomic snapshot and stores the source pair with the issuance record. During redemption, Account exact-compares `sourceEvidenceId`, `sourceEvidenceVersion`, the bundle reference, and every snapshot-bound field against the stored issuance record and the current applicable authority evidence; a missing, changed, or mixed-version value rejects redemption. Consumers reject missing, extra, contradictory, separately sourced, stale, expired, wrongly tagged, or non-canonical bundle fields and must redeem the original reference with Account; a copied bundle never becomes a second authority. For every forwarded owner-mutation family, ADR 0048's canonical complete `postAuthorizationExecutionTuple` is the required post-authorization identity. It explicitly contains ADR 0048's stable `controlPlaneRequestId` for orchestration, reservation, lookup, and correlation across forwarding, `mutationDigest`, `issuanceKind`, Account-returned `authorizationReferenceFingerprint`, exact authenticated workload and actor/policy binding, exact typed `scope`, normalized `actionFamily`, `actionFamilySchemaId`, `actionFamilySchemaVersion`, typed `target`, immutable typed `targetOwner`, typed `expectedVersion`, typed `mutation`, typed `auditReason`, the exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, the exact canonical `authorityEvidenceBundle/v1` defined above (whose issuance identity carries the tagged `actionFamilyRequestIdentity` for domain action/idempotency), and every schema-bound typed presence/absence value. `targetOwner` is distinct from `target`, immutable after reservation, and is never inferred from current routing or owner state. Reservation and pre-authorization Account issuance/recovery compare `preAuthorizationReservationTuple`; post-authorization tuple completion, owner idempotency, terminal/no-commit proof, result lookup, conflict handling, and any later fresh owner attempt carries and compares its own exact tuple; no participant may omit a required identity because it is unavailable locally. +For human StartSession, Account returns the complete original canonical post-authorization tuple in its authenticated ISSUE, RECOVER, and REDEEM replies, deriving it from its retained original issuance and authority capture independently of the caller. Logging and Admin compares and preserves those exact bytes through completion, recovery, and handoff. Game Session compares its incoming tuple with the independently returned Account tuple at redemption, retains that owner evidence, and compares it again at launch. This comparison includes all four authority-bundle reference fields: `bundleVersion`, `sourceVersion`, `sourceFence`, and `linearization`; `sourceFence` is distinct from `issuanceFence`. Schema and bundle-version integrity alone do not establish owner binding. The returned evidence grants no separate authority and does not replace exact workload/namespace, reference, claim, attempt/fence, currentness, or expiry checks. Existing issued bundle/reference and encrypted recovery-envelope bytes remain unchanged. Retained scalar projections lacking the complete Account tuple remain historical evidence only and fail closed for current execution; no inferred backfill upgrades them. + Within `authorityEvidenceBundle/v1`, `actionFamilyRequestIdentity` is the canonical tagged representation of the applicable domain action/idempotency identity: it contains exactly one `requestIdentityKind` and its corresponding `requestId`. At typed request and durable-record boundaries, that kind selects the corresponding named action-family field rather than creating a generic substitute. For non-moderation mutations, the tag carries `controlPlaneRequestId`, which is the canonical logical request name across HTTP, Java/domain contracts, ADRs, and audit records; the current automation issuance branch is non-moderation-only and therefore uses that arm. Moderation policy intent and owner enforcement use their dedicated `policyIntentRequestId` and `ownerEnforcementRequestId` identities. For those moderation flows, `controlPlaneRequestId` remains the stable ADR 0048 orchestration/reservation/lookup identity and correlation across forwarding, but is correlation-only for domain idempotency and is not an alias or substitute for either dedicated identity. Neither identity authorizes the domain mutation: authorization comes from the Account-issued reference and the owner-side validation and fencing rules. Protobuf contracts may use the language-standard wire spelling `control_plane_request_id`, which maps directly to that same identifier and does not introduce a second identity. For moderation, the linked records have two distinct lookup roles. The ADR 0048 orchestration/reservation/reconciliation record is located solely by the stable `controlPlaneRequestId`; its phase-appropriate tuple is then exact-compared against the stored record. After issuance, Account's domain-issuance idempotency record and the selected domain owner's mutation/result record are located by the tagged dedicated action-family identity (`policyIntentRequestId` for policy intent or `ownerEnforcementRequestId` for owner enforcement) and then validated against the complete tuple and digest. The owner never uses `controlPlaneRequestId` as its domain idempotency lookup. The same `controlPlaneRequestId` with a changed orchestration tuple conflicts with the ADR 0048 record; a different `controlPlaneRequestId` normally names a distinct orchestration attempt, but for moderation it may carry the same dedicated domain ID, which must still deduplicate or conflict according to the Account/domain record and complete domain tuple. The same tagged dedicated action-family identity with a changed domain tuple conflicts with that domain record. A correlation-only ID change cannot alias or create a second domain mutation, and neither identity grants authority. diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 34b6721b1f..fe7306cdbf 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -163,6 +163,8 @@ The handler returns `PERMISSION_DENIED` for a caller that is not the exact verif StartSession response recovery preserves the raw `firemud/account-response-envelope/aad/v1` grammar and authenticates the canonical authority-evidence bytes directly; no digest replaces those bytes. The authority bundle is bounded at 128 KiB, the complete canonical binding and exact response plaintext at 144 KiB each, and the AES-GCM envelope by that plaintext maximum plus its bounded header and tag. Repository and PostgreSQL storage allow at most 160 KiB. Forward migration [V126.3](../../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql) replaces only the envelope-size guard and leaves retained ciphertext and the existing immutable/erasure rules intact. +The human StartSession ISSUE/RECOVER replies additionally carry `original_account_post_authorization_tuple` at tag 7; REDEEM carries it at tag 6. The service derives these canonical bytes from the original retained issuance/capture and maps them independently of caller tuple copies, under the [operator binding contract](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md). This public response addition does not change the five-field encrypted recovery plaintext or retained ciphertext. The additional tuple is bounded at 256 KiB; the existing authority-bundle and envelope limits remain separate. These source APIs remain default inactive; this carrier change does not register an executable ingress. + `IssueHumanOperatorAuthorizationReferenceRequest` contains the forwarded `control-ui` evidence, target owner service, typed target scope, action family, action-family schema identifier/version, the applicable mutation identity, correlation-only `controlPlaneRequestId`, and canonical digest. Its branch selector is `action_category_or_absence`: published moderation schemas must validate a closed `action_category` before branch selection, while published non-moderation schemas must explicitly omit `action_category` and select `non_moderation`; omission cannot downgrade a moderation family. For moderation action families, the typed request carries exactly one dedicated identity: `policyIntentRequestId` with the local policy-intent digest, or `ownerEnforcementRequestId` with the owner-enforcement digest. Neither dedicated identity may be omitted, replaced, or aliased by `controlPlaneRequestId`; the separate appeal-submission identity is not carried by operator issuance. For non-moderation families, the typed mutation identity remains `controlPlaneRequestId` with `mutationDigest/v1`. The typed scope is branch-specific: `non_moderation` and `tenant_restriction` require `tenant_scope`, while `platform_access_ban` requires explicit `target_account_id` and has no tenant scope or membership fields. Actor identity is not a request field: Account derives it from the validated token forwarded by the exact Logging & Admin mTLS workload. Account chooses a short expiry, stores a keyed hash for lookup, and retains the original high-entropy opaque reference only in protected encrypted authority storage or a bounded encrypted response envelope for the reference lifetime plus the documented retry and read-only recovery window. The exact authenticated internal response contains `operatorAuthorizationReference`, Account-calculated `authorizationReferenceFingerprint`, `expiresAt`, the immutable `authorityEvidenceBundle/v1`, and `authenticatedLoggingWorkloadIdentity`, which is copied from the verified same-namespace Logging/Admin TLS peer after successful issue or recovery; Logging checks the returned identity against the action target namespace before accepting the response. Account never exposes that evidence through an external route, logs, audit text, or client-visible response. `IssueAutomationOperatorAuthorizationReferenceRequest` contains no workload identity field: Account derives `workloadIdentity` from the authenticated mTLS transport peer and rejects any serialized or caller-supplied substitute. It contains `automation_policy_id`, `automation_policy_version`, target owner service, typed target scope, action family, action-family schema identifier/version, `controlPlaneRequestId`, and canonical `mutationDigest`, with no account, end-user token, or human identity. The target request is `non_moderation`-only: published schema pairs must select the branch with `action_category` absent, moderation schema pairs are rejected before issuance, and no concrete schema pairs are published while the route remains target-not-routable. For the supported tenant-scoped branch, Account binds the exact `tenant_generation`; global-role or `privileged_control` authority is rejected rather than inferred. The exact authenticated internal response has the same opaque reference, fingerprint, expiry, and immutable authority-evidence shape; its stored binding includes the authenticated workload and policy evidence plus the applicable generation predicate. `controlPlaneRequestId` and `mutationDigest/v1` cannot be reused for moderation; any future moderation automation contract must declare dedicated request identity, digest, and idempotency semantics with `controlPlaneRequestId` correlation-only. @@ -174,6 +176,8 @@ An exact retry of either typed issuance RPC with the same applicable mutation id `authorizationReferenceFingerprint` is Account's versioned, keyed, non-reversible identity of the exact opaque reference: `arfp/v1//`, using the [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#bounded-owner-delegation) domain-separated framing of `keyId`, `referenceKind`, and the exact reference bytes. Account alone owns the HMAC keys, rotation, and calculation. Logging & Admin stores and forwards the Account-returned fingerprint unchanged and may retain it in durable intent; it never accepts a caller-supplied fingerprint or derives one. The owner transports that forwarded value unchanged in `RedeemOperatorAuthorizationRequest`, receives a fresh Account recomputation during redemption, and compares the two before treating redemption as successful or authorizing the mutation. The fingerprint is not a substitute for the full authority-bound tuple or `mutationDigest`. +For StartSession issuance and recovery, Account validates the producer observation and exact active-claim bindings under the [Logging claim-evidence contract](../logging-admin-service/api-contracts.md#startsession-reservation-claim-evidence). Account independently requires its local clock to remain strictly before `claimExpiresAt`; it does not require the producer's `observedAt` to be at or before Account's local time. The independent Account authority and source gates still apply. + The immutable `authorityEvidenceBundle/v1` is exactly the canonical tagged bundle defined by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#bounded-owner-delegation). It carries the complete canonical `authorityTuple` without scalarization, the independent applicable `membershipVersion` map, positive `issuanceFence`, Account projection provenance/freshness, issuance-operation identity, and exactly one human or automation issuance-evidence arm. It is internal authority evidence only: it contains no raw JWT, opaque reference, HMAC key, or payment credential and is returned only to the exact authenticated workload that is authorized for issuance or redemption. Neither Logging & Admin nor an owner defines a variant, serializes an inapplicable arm as `null`, or reconstructs authority evidence from assertions or later reads. `RedeemOperatorAuthorizationRequest` has three distinct data-provenance classes. Pre-authorization identity is exactly [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md)'s stored `preAuthorizationReservationTuple/v1`; Account and callers do not define a local variant. Request and transport evidence adds the exact opaque `operatorAuthorizationReference`, the applicable mutation identity (`controlPlaneRequestId` for non-moderation or the dedicated `policyIntentRequestId`/`ownerEnforcementRequestId` for moderation), the Account-returned `authorizationReferenceFingerprint` forwarded byte-for-byte through Logging & Admin and the owner, and the authenticated immediate owner/redeemer mTLS identity. The moderation `controlPlaneRequestId` is correlation-only and never substitutes for the dedicated identity. The owner also recomputes the typed operation and every schema-declared presence/absence value so Account can compare those values with the stored pre-authorization tuple. The opaque reference and fingerprint are never decoded, regenerated, or substituted by Logging & Admin or the owner. Account first authenticates the immediate mTLS identity as an allowed owner/redeemer workload; after that authentication succeeds, it validates the syntax and presence of the applicable mutation identity, correlation-only `controlPlaneRequestId` when carried, and `reservationClaimFence` before looking up the opaque reference, then compares the caller with the issuance record's stored redeemer/workload binding before disclosing or comparing tuple and evidence. That authenticated identity and the fingerprint are redemption evidence, not fields retroactively added to the pre-authorization tuple. Account-derived `issuanceKind`, `authorityTuple`, `membershipVersion`, `issuanceFence`, and `authorityEvidenceBundle/v1` are post-authorization enrichment compared only from Account's durable issuance record. Applicable `tenant_generation`, `target_tenant_generation`, and `privileged_control` evidence remain inside the authority or policy binding and are never inferred from role text. @@ -185,7 +189,9 @@ Error precedence is canonical: (1) Account authenticates the exact immediate mTL The broader action-family RPC and schema set remains accepted target state and is not fully present in the current Account proto or implementation. StartSession Account ISSUE/RECOVER/REDEEM and the read-only original redeemed-operation projection are present at source level; source-level Logging & Admin durable handoff and Game Session claim/redemption/prepared-action slices are tracked in the [StartSession action-schema implementation status](../game-session-service/start-session-action-schema.md#implementation-status). Account's receiving adapter and owner service are composed only by the explicit `firemud.account.start-session-operator-authorization` configuration, disabled by default; enabling requires existing owner collaborators, explicit bounded timings, a workload namespace, an owner-supplied fingerprint-key source, and a distinct operator response-envelope mount. The Hosted Validation run `38113324723` at `f6d34031221a3337e7a958ac4b085554460668c9` is historical bounded owner-workflow fixture proof. Current exact-head Account fixture results and limits are recorded in the [AA-1.3 tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-operation-and-signer-source-preparation); this does not establish overall CI success, deployed mTLS, full-service boot, production key custody, or activation. The production hosted-terms environment producer plus pinned trusted-provider/key-custody composition remain absent. The Game Design prepared selector/current-Account-projection consumer and full physical cross-service smoke remain unproved. Logging & Admin remains the external operator ingress and durable intent/audit coordinator, Account remains the authorization authority and owner of original-reference retention, and the domain service remains the mutation owner. -For the redeemed StartSession projection, `ReadRedeemedOperationProjection` accepts the exact canonical pre-authorization tuple bytes, Account-issued authorization-reference fingerprint, original reservation owner and claim fence, and actual Game Session owner-attempt ID and fence. Account authenticates the exact same-namespace Game Design workload over mTLS before parsing or lookup. Its read-only result returns the original request ID, tuple, digest, fingerprint, reservation and owner-attempt bindings, recorded redeemer workload identity, reference expiry and redemption time, issuance operation and fence, bundle reference, and unchanged authority-evidence bundle; it returns neither the forwarded `control-ui` token nor the opaque authorization reference. The normative applicability and authority boundary are owned by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#redeemed-startsession-projection-read). +For the redeemed StartSession projection, `ReadRedeemedOperationProjection` accepts the exact canonical pre-authorization tuple bytes, Account-issued authorization-reference fingerprint, original reservation owner and claim fence, and actual Game Session owner-attempt ID and fence. Account authenticates either the exact configured same-namespace Game Design workload or the exact original Game Session redeemer over mTLS before parsing or lookup, and compares the request with the stored original redeemer and owner attempt. Its read-only result returns the original request ID, tuple, digest, fingerprint, reservation and owner-attempt bindings, recorded redeemer workload identity, reference expiry and redemption time, issuance operation and fence, bundle reference, and unchanged authority-evidence bundle; it returns neither the forwarded `control-ui` token nor the opaque authorization reference. The normative original-operation restriction remains owned by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#redeemed-startsession-projection-read). + +The current Account source also prepares `AcquireStartSessionWorldParticipation` and `ReadHistoricalStartSessionWorldParticipation` as same-namespace World workload methods. Acquisition first reads the actual current Game Session attempt, then retains its exact response and unchanged lease expiry with the complete original tuple, owner attempt and fence, and World preparation identity while Account revalidates its current source and reference around the local transaction. The capture reference is retained independently of the issuance fence. The no-user-context historical read accepts the complete unchanged original post-authorization tuple and resolves the retained Account participation ID/fence plus immutable Game Session association, so World need not already know Account's random participation coordinates. It exact-matches the retained tuple and complete source-child vector, and remains an immutable read after lease expiry or terminal settlement; it does not recompute currentness, renew authorization, admit execution, settle participation, or mint World terminal state. Missing or changed tuple bytes and incomplete or changed source evidence fail closed. These methods are unregistered and default-inactive; they do not establish World execution admission, renew authorization, or replace World terminal authority. The related source boundary and its proof status are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#account-world-participation-source-preparation); the World receiving contract remains owned by [Game Session API Contracts](../game-session-service/api-contracts.md#restricted-original-claim-evidence-continuation) and [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md). ## REST APIs diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 863c23bf9a..fa969a4388 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -26,6 +26,8 @@ V126.3 raises only the encrypted StartSession response-envelope size guard after The StartSession owner preserves request IDs already accepted by the generic response-envelope identifier field. For other canonical NFC request IDs, its envelope binding uses lowercase hexadecimal SHA-256 of the exact UTF-8 request ID; the SHA-256 digest of the complete canonical tuple remains a separate binding field. This Account-local encoding leaves the generic envelope format and cryptography unchanged. +The newer Account source cut adds a retained immutable source capture and World-participation records with original Game Session attempt evidence and terminal-settlement storage in V158–V160. These tables preserve the Account-side tuple and source bindings needed for a bounded World receiving flow; they do not register the Account methods, activate a World execution owner, or provide continuous Game Session admission protection. The World terminal value and read client are integrity and internal-transport sources, not World terminal authority. The exact method boundary and current proof status are recorded in [Account API Contracts](./api-contracts.md#operator-authorization-references) and the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-world-participation-source-preparation). + The passive signer repository can abandon only the exact current unprepared generation with its owner-recorded generation result and trust fence. An immutable abort receipt and desired-state CAS preserve both durable and published active fences, retain the original operation/result, and permit an exact retry after repository restart. A subsequent generation advances past the retained operation high-water mark; it does not reuse the aborted generation. Prepared promotion or changed evidence remains rejected. This storage operation is not wired to a cancellation coordinator or runtime activation path. Promotion storage retains the existing non-secret canonical readiness-proof preimage alongside its digest. The database hashes those exact bytes and binds the parsed proof to the locked generation, publication, inventory plan and complete verified probe receipts; altered, incomplete or mismatched evidence is rejected. PostgreSQL execution of these transition and tamper cases is required in the scoped CI proof; local compilation or skipped integration tests alone do not establish those database guarantees. @@ -48,7 +50,7 @@ Account also performs a bounded sweep of public connect-scope evidence after its The current public registration path creates only a global Account row and a platform-scoped audit outbox record; it does not create a tenant membership or profile, and a legacy caller-supplied `tenantId` does not establish tenant authority. Explicit `JoinPublicProductionMembership` is the only public-production membership writer. It first commits a policy-independent `PENDING` intent containing the global request ID, verified caller binding, exact retained connect-scope evidence, and a version-1 intent digest. Only after authoritative entitlement evaluation succeeds does a separate Account transaction bind `allowPublicJoin`, the positive `entitlementVersion`, and the version-1 policy digest; that transaction revalidates the exact policy at the membership commit gate and atomically commits any membership transition, tenant-scoped audit outbox event, and terminal operation outcome. If entitlement authority is unavailable, the row remains `PENDING` with a typed last-attempt failure and availability but null policy values and null policy digest; an exact request retry may reconcile it after authority recovers. For a retained `PENDING` operation, an expired or malformed scope now fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. Definitive pre-policy failures retain the intent digest and a durable terminal outcome rather than fabricating policy evidence. A definitive mismatch between the freshly evaluated policy digest and an already-bound digest fails terminally as `IDEMPOTENCY_CONFLICT`, retaining the original request digest, policy version, and policy result without membership or transition audit/outbox mutation; this applies both on a retry and at the immediate commit-gate reread. Unavailable or unsafe authority and uncertain commit outcomes remain `PENDING`. A post-transaction readback applies the terminal retry checks when a terminal row is present; otherwise Account returns retryable `AUTH_UNAVAILABLE` and the caller must retry the same request ID. No background PENDING-operation reconciler is claimed; recovery/reconciliation after an unknown database commit outcome remains open. An exact retry of a terminal JOIN replays its stored result only after the retained scope is still unexpired and current target/entitlement authority is available and matches the stored policy digest; expiry, unavailable authority, or changed policy fails closed without rewriting the terminal operation or membership. `ACTIVE` membership is idempotent, while only missing or inactive membership transitions to `ACTIVE`. PostgreSQL repository proof covers independent intent insertion and atomic policy-binding/membership/outbox/outcome persistence, while the service unit proof covers the separate transaction commit/rollback boundary; all PostgreSQL cases are skipped locally without Docker, so no live PostgreSQL execution is claimed. No direct text-client end-to-end proof is claimed. Legacy Account migrations still assign tenant defaults/backfills and retain prior memberships as unverified, non-admitting evidence. This remains a retained-data deployment blocker: before any affected deployment, Account must record either a verified no-data boundary or an explicit retained-row disposition/mapping, including exact readback and admission-isolation evidence. No recovery is implied for already-applied irreversible migrations, and this status does not choose a tenant-identity migration design. -Account has source-only persistence for individual Creator Party identity, hosted-terms acceptance/environment-binding evidence, and (from V98) disclosure handoffs with immutable captured source evidence. The V98 database guards constrain handoff identity, result transitions, and source-evidence insertion; no Account writer, external observer, authenticated legal publication verifier, dispatch RPC, consumer, registry/runtime binding, creator UI, or Game Design evidence binding is active. Reserve, claim, and publication paths that require hosted-terms disclosure checks remain unavailable; unrelated source-fence paths are unaffected. The acceptance/currentness authority remains target-only under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md), and local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner workflow is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled. +Account has source-only persistence for individual Creator Party identity, hosted-terms acceptance/environment-binding evidence, and (from V98) disclosure handoffs with immutable captured source evidence. The V98 database guards constrain handoff identity, result transitions, and source-evidence insertion. A passive Account source-fence seam now excludes unsettled World participation from applicable source mutation/abort settlement and hosted-terms disclosure preparation/dispatch admission; `HostedTermsDisclosureHandoff` and its repository use the existing V98 journal. The unregistered historical World-participation reader resolves retained participation coordinates from the complete unchanged original tuple, verifies the retained capture and source-child vector, and can read after lease expiry or immutable terminal settlement; it uses existing rows and introduces no migration or table. It does not establish currentness, renew or admit authorization, or classify an Account expiry or failed response as World `ABORTED`; only the World owner can produce that terminal outcome with its original commit/fence evidence. The handoff retains opaque authority evidence as supplied and does not authenticate it. No verifier, dispatcher, transport, registry/runtime binding, creator UI, or Game Design evidence binding is registered. Reserve, claim, and publication paths that require the hosted-terms workflow remain unavailable. The acceptance/currentness authority remains target-only under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md), with changed-terms continuity under [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md); local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner workflow is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled. The live `GetTenantMembershipForRuntime` producer emits `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`; `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent from the proto and producer. Current consumers still rely on only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and do not enforce the complete atomic-freshness contract or consume the emitted lifecycle/generation fields. Account-first bootstrap and credential-bearing gameplay `Authenticate` authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current connect-token issuance and character discovery require membership after applicable target and entitlement checks; on an eligible public-production target only absent membership may return non-actionable `JOIN_REQUIRED`, while existing membership with `gameplayAdmissionAllowed=false` is denied as `CONNECT_TOKEN_REJECTED`. Current text `PLAY` can still return non-actionable `JOIN_REQUIRED` for missing or present non-admitting membership before fresh entitlement and public-target-policy ordering is established; this remains the AA-2.1 / Unit 1B ordering gap. These flows do not create or restore membership. The Account-owned public-production `JOIN` writer is implemented locally with a v1 policy-bound digest and atomic membership, operation-outcome, and audit-outbox evidence. Its HTTP exposure remains blocked by the Gateway route guard; Game Session text `JOIN`/`Join & Play` dispatch remains with #2898, while durable recovery after an unknown database commit and Logging receipt receiver/readback remain with #2848. Exact-final-head PostgreSQL runtime proof remains unavailable locally without Docker; no live PostgreSQL runtime proof or direct text-client end-to-end proof is claimed. See [Account API Contracts](./api-contracts.md) for the public and internal API boundary and [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the canonical direct-text scope and JOIN contract. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The entitlement producer returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field) when a tenant has zero or multiple subscription rows; only one explicit row is projected through current status mapping. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and canonical snapshot fields/freshness remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof covers only that cardinality guard and retry boundary. `CommitTenantCapacityAdmission` has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index 6b20fe6bbe..39101efd31 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -6,7 +6,7 @@ This document defines the Logging & Admin Service REST and gRPC surfaces, authen `logging_admin.v1.StartSessionReservationEvidenceService/ReadCurrentClaimEvidence` is a read-only internal Account handoff for [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md)'s current pre-authorization reservation. It requires the exact certificate-derived `account-service` peer in the configured workload namespace and rejects caller JWT context before reading the reservation. It is not an external operator route, authorization-reference issuance, claim renewal, ownership transfer, or commit-spanning CAS proof. -The request binds the canonical non-nil `controlPlaneRequestId`, exact bounded canonical UTF-8 `preAuthorizationReservationTuple/v1`, original reservation owner/fence, current claim owner/fence, and an explicit `ISSUE` or `RECOVER` purpose. `ISSUE` accepts only an exact, unexpired, active `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` claim for the original owner or a fresh claim recovered from `RESERVED`. `RECOVER` accepts an exact, unexpired, active `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` or `ACCOUNT_AUTHORIZATION/AUTHORIZED` claim under a distinct recovery owner and later fence; recovery from `AUTHORIZED` is lookup-only. The response echoes the exact tuple, mutation digest, both owner/fence pairs, purpose, claim expiry, and observation time. Missing, changed, expired, or unavailable evidence fails closed; unknown fields and malformed or non-canonical input are rejected. Account validates all returned bindings and freshness before using this snapshot as an issuance or recovery precondition; it must still establish its own current authority and durable operation boundary. +The request binds the canonical non-nil `controlPlaneRequestId`, exact bounded canonical UTF-8 `preAuthorizationReservationTuple/v1`, original reservation owner/fence, current claim owner/fence, and an explicit `ISSUE` or `RECOVER` purpose. `ISSUE` accepts only an exact, unexpired, active `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` claim for the original owner or a fresh claim recovered from `RESERVED`. `RECOVER` accepts an exact, unexpired, active `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` or `ACCOUNT_AUTHORIZATION/AUTHORIZED` claim under a distinct recovery owner and later fence; recovery from `AUTHORIZED` is lookup-only. The response echoes the exact tuple, mutation digest, both owner/fence pairs, purpose, claim expiry, and observation time. Missing, changed, expired, or unavailable evidence fails closed; unknown fields and malformed or non-canonical input are rejected. `observedAt` is producer-side ordering evidence: it must be positive and earlier than `claimExpiresAt`, but may be later than Account's local clock. Account independently requires its local `now < claimExpiresAt`, validates every returned binding, and establishes its own current authority and durable operation boundary. This clock-skew rule grants no numerical allowance, maximum age, or expiry extension. Implementation status: the claim-evidence receiver and Account read client exist with focused proof. The source-level Logging coordinator and typed Account client now have a Spring composition, but it is available only through the disabled-by-default configuration described in [Configuration](./configuration.md#conditional-startsession-coordinator-composition). This does not register an external operator ingress or establish that an operator command can execute. @@ -113,6 +113,8 @@ The implementation gap is fail-closed: the HTTP controller and Gateway route are The source-level `StartSessionAuthorizationCoordinator` now offers separate `issueHumanAndDispatch` and `recoverAndDispatch` methods that compose its existing authorization/recovery flow with `GameSessionClient`. They call the owner once only when that invocation wins the durable `OWNER_EXECUTION_PENDING` transition; exact/in-progress and recovery-unavailable results do not dispatch, and ambiguous owner outcomes propagate without automatic retry or rearming. The existing `issueHuman` and `recover` methods remain prepare-only. The typed `GameSessionClient` call sends the transient post-authorization tuple/reference and validates Game Session's secret-free durable attempt/progress echo; it requires readable file-backed workload mTLS and pins both request and response to the exact same-namespace Game Session SPIFFE URI derived from the tuple. Ping and stop keep their existing client behavior. These methods are not wired to a routable Logging & Admin StartSession ingress. Mocked tests do not establish physical mTLS, production ingress, prepared launch selection, or instance activation. +The Account client accepts the new StartSession response only after comparing its complete returned owner tuple with the exact reservation and response evidence. The coordinator retains and hands off the Account-returned tuple bytes through the existing completion/recovery path, under [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md). Missing or substituted owner evidence fails closed before durable completion or owner dispatch; this does not activate a routable ingress. + **Target ADR 0047/0048 owner-forwarding path:** [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md) owns the Logging & Admin ingress and Account-reference issuance boundary; [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md) owns the phase-qualified execution, redemption, and reconciliation contract. Supported executable operator mutations use Account's canonical [`IssueHumanOperatorAuthorizationReference`](../account-service/api-contracts.md#operator-authorization-references) issuance RPC after Logging & Admin authenticates the current `control-ui` actor and records durable intent. Logging & Admin forwards the opaque bounded reference and unchanged request/generation binding; the authoritative receiving owner recomputes the canonical digest and is the only service that calls Account's `RedeemOperatorAuthorization` RPC. Unattended automation uses Account's `IssueAutomationOperatorAuthorizationReference` with `exact_mtls_workload_plus_versioned_automation_policy`, bound to the exact Logging and Admin workload mTLS identity and current `automation_policy_id`/`automation_policy_version`; the currently supported automation branch is tenant-scoped only and carries the exact target `tenant_generation` through issuance, forwarding, redemption, and owner commit. It carries no human identity, end-user token, or `privileged_control` authority. For each owner contract, predicate evidence comes exclusively from Account's redemption response; any copy forwarded by Logging & Admin is unchanged audit/context evidence, not authority. The local `/moderation/actions` policy-input/audit mutation is a separate receiving-service path: after its gate exists, Logging & Admin redeems its one Account reference exactly once for local persistence and never forwards or reuses that reference. Any future moderation owner-enforcement command uses a separately issued command-bound reference redeemed exactly once by the receiving owner. The moderation route is currently gated/unavailable; it hard fails closed without dispatch or persistence and performs no target fixed-category policy/audit persistence or forwarding. `EvaluateModerationPolicy` is a live read and carries no mutation authorization reference. For non-moderation action families, the request identity is the exact `controlPlaneRequestId` plus digest pair. Moderation and appeal transports instead use dedicated `policyIntentRequestId`, `ownerEnforcementRequestId`, and stable appeal-submission request identities end-to-end; `controlPlaneRequestId` remains a separate correlation-only field and must not carry, replace, alias, or serve as any of those mutation identities. The dedicated identities are never shared or reused. Logging & Admin never becomes a second authorization authority. Current feature-flag and tick forwarding paths, plus internal admission control-plane implementations, are not evidence that this ADR 0048 target contract is complete. For every forwarded owner mutation, excluding the separate local `/moderation/actions` policy-input/audit path, the authoritative owner calls Account's `RedeemOperatorAuthorization` with the separately issued opaque reference and its independently derived request binding. Authorization predicates and generation authority come exclusively from that Account response. Any predicate, generation, checkpoint, or assurance copies forwarded by Logging & Admin are unchanged audit/context evidence only; the owner must not authorize or mutate from those copies, and they are excluded from the canonical `mutationDigest/v1`, which covers the normalized action request rather than ingress assertions. The local moderation route is gated/unavailable; it hard fails closed without dispatch or persistence and does not persist target fixed-category policy/audit evidence, redeem, forward, or enforce. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 76e233e5b5..849feb09ad 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -173,3 +173,18 @@ Entry format: - Expected pattern: classify connection-refused fixture failures separately from product assertions; capture live container events, PostgreSQL logs and endpoint state before fixture cleanup, and qualify the exact suites before crediting physical proof. Retained Docker events are bounded and destroyed containers lose inspect/log evidence; an exit code of 137 after an explicit cleanup kill does not establish OOM or external cleanup. - Current status: the three affected suites passed all 13 cases in the composed #3125 run and fresh exact-parent #3120 CI (all 105 PostgreSQL cases passed). The subsequent #3155 local Account gate also failed before assertions in 24 of 218 integration cases across eight suites, leaving PostgreSQL proof partial and Redis initialization unproved. The local connection-refused cause remains unknown; retain time-correlated container and endpoint evidence without weakening fixtures or changing the environment speculatively. - Reconsideration trigger: revisit after the affected cases execute physically against the final parent and the endpoint failure is explained or shown to be transient; retain until the cause and proof limits are recorded. + +- `2026-10-13`: Local PostgreSQL readiness does not prove mapped endpoint availability + - Context: During the otherwise-required Account correction gate on 2026-10-12 UTC, two participation repository cases refused the mapped `localhost:57828` endpoint before Flyway. + - Observation: The bounded container/event/server capture tied that port to its PostgreSQL 18 container: final TCP readiness and Testcontainers startup confirmation preceded the case failures, while the recorded kill followed suite completion. This rules out a simple pre-readiness attempt for that capture but does not identify the refused-connection cause or cleanup initiator. + - Expected pattern: Preserve correlated port, readiness, case and teardown evidence during required gates. Do not infer a source defect, early cleanup or OOM from a generic refusal, add speculative wait/configuration changes, or start a diagnostics-only rerun. Report passing subsets and missing full proof separately; matching current-candidate CI remains a qualification path when local endpoints are unavailable. + +- `2026-10-13`: Controller route provenance selects its receiving command + - Context: Gameplay opened the remaining #3155 owner-tuple obligation on #3183 through `decide route open`, then attempted the documented `records route decide` and `records route resolve` receiving operations. + - Observation: The newly opened route retained `legacy_controller` provenance, so both native receiving commands rejected it. The canonical `decide route accepted-fixed` path successfully recorded verified successor proof; a separate native source resolution retained the actual child SHA and frozen review counts. + - Expected pattern: Use the command family selected by the recorded route provenance. The README distinguishes route origins; controller help should also identify that choice before an operator attempts a mutation; opening a new route does not imply native source-record provenance. + +- `2026-10-13`: A completed Hosted checkpoint can still expose a recapture warning + - Context: The #3155 second Hosted request reported a predecessor terminal-capture warning after the earlier Hosted run had already been captured and finalized. + - Observation: `HostedCaptureError` reported unmarked content after a finding comment's final `cr-comment:v1` marker. The warning retained a diagnostic and did not prevent the new request from being posted; the exact content or actor responsible remains unverified. + - Expected pattern: Preserve the completed checkpoint and frozen counts, distinguish a recapture warning from a failed new provider request, and report the diagnostic to controller maintenance. Do not invent replacement findings or spend another review to repair historical capture metadata. 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 3c1df1bcef..b775a6a3fb 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -10,6 +10,24 @@ This is a non-normative implementation tracker for player access and session. Ca The existing scalar-only Entity `CreateCharacter` RPC now returns `FAILED_PRECONDITION` before allocation for valid requests in shared and isolated scopes; the focused service test also confirms the malformed zero-account case remains `INVALID_ARGUMENT`. This is denial-only implementation and unit proof. The canonical Account producer, authenticated owner proof, exact catalog/admission-pointer evidence, Game Session and World protections, and Entity durable terminal composition remain missing, so character creation is unavailable under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Entity owner-protection contract](../../architecture/microservices/entity-management-service/api-contracts.md#character-creation-owner-protection). +### Account World participation source preparation + +The current Account source adds an immutable full source capture for the original StartSession operation, Account-owned World participation acquisition and historical-read services, exact current Game Session attempt evidence, and local terminal-settlement storage. The receiving methods remain unregistered and default-inactive. Acquisition reads the actual original Game Session attempt before its Account transaction, then preserves the complete original tuple, attempt/fence, exact response, and unchanged lease expiry beside the separate World participation identity while revalidating and locking the current Account source and reference. The capture reference remains independent of the issuance fence. The historical read is credential-free and returns retained evidence; terminal settlement requires an exact World-owned result. These sources add no credential issuance, redemption, renewal, runtime admission, or new authority. + +Migration intake maps donor V128 source capture to receiving V158, donor V129 World participation to V159, and donor V131 actual-original-Game-Session-attempt evidence to V160. Published [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql) separately replaces the legacy bundle-source/issuance-fence equality with the canonical positive-BIGINT source-fence check; capture and issuance fences remain independent. Prior receiving migrations through V157 and the protected V1–V40, V40.1, V53, and V73 remain unchanged. This source cut does not include the World runtime owner or the continuous Game Session admission protection tracked by V133/V134. The shared World terminal value and client/codec remain internal integrity and transport sources, not genuine World terminal authority. At original child tip `38c5a26e21d73282f75183d7c58f2746f9c9e391`, the authorized Account/Common checks, jOOQ generation, integration-source compilation, and Checkstyle gate passed. The Account/Common test results report 1,224 unit/test cases with zero failures and four skipped, plus 193 integration cases with zero failures and 190 skipped. All 20 focused PostgreSQL-backed cases were skipped: authorization repository (8), source capture (1), World participation repository (1), original-attempt evidence (3), owner composition (1), and disclosure handoff (6). No physical PostgreSQL or Redis execution, current real-key custody, runtime activation, or playable closure is claimed. Account-local contract and storage consequences are recorded in [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references) and [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status); this tracker records implementation and proof status only. The normative original-operation read constraints remain in [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#redeemed-startsession-projection-read). + +At reconciled local candidate head `94aece5bbe4ca1aa537dcb6367921f99e439423e`, `FIREMUD_LOCK_GRADLE_WAIT=1 bash dev-tools/validation/run-locked-gradle.sh :account-service:check linkCheck lintMarkdown -PfullCheck` passed in 2m 38s. Fresh Account XML reports 1,255 unit cases with zero failures, zero errors, and four skipped, plus 205 integration cases with zero failures, zero errors, and 202 skipped. All 20 focused PostgreSQL-backed cases were skipped. This exact-head local check does not establish physical PostgreSQL or Redis execution, current real-key custody, runtime activation, or playable completion. + +At local current-parent source `c7a61401f2220f70d567b7709397b967daf5e991`, the Account/Common Security full gate failed in 11m39s after 1,278 unit cases passed (four skips) and 222 physical integration cases ran with zero skips: 214 passed, while eight `AccountFirstJoinAuthorityStorageIntegrationTest` cases refused `localhost:55056` before Flyway migration (`SQLState 08001`). Captured PostgreSQL TCP readiness preceded Testcontainers startup and all failures preceded normal cleanup; no source fixture mistake or OOM was demonstrated, and the host-endpoint cause remains unknown. This does not claim a passing full Account gate; the replacement exact-head CI and subsequent current-parent proof are recorded in the next paragraph. + +Published commit `0a84bfa2800c6f33f3d85023c786a9fdd80ff0ba` passed [exact-head validation run 38276405663](https://github.com/benhook1013/FireMUD/actions/runs/38276405663): all 1,278 unit cases had zero failures or errors (four skipped), and all 222 physical integration cases passed with zero failures, errors, or skips, including the eight FirstJoin storage cases previously refused locally. The local current-parent carry at `932f2e1334a9ffa31fdf3be177a0fdbcd588a0e5` then passed the locked Account check and focused `AccountGameplayDelegationRedisIntegrationTest`, along with formatting and documentation checks, in 2m56s: 1,280 unit cases had zero failures or errors (four skipped), and five targeted physical integration cases had zero failures, errors, or skips. This carry changed only three inherited Account paths, preserving the child-owned source and SQL history. These results prove the listed exact-head CI scope and focused current-parent composition; they do not establish an unfiltered 222-case physical integration run on the new head or runtime activation. + +At correction source `0f049f5bf5d45b2b9663385eec53efff8f1bf757`, local unit checks passed 1,289 Account cases (four skips), 437 Common Core cases and 159 Common Security cases without failures or errors. Ten selected physical PostgreSQL/Redis cases passed without failures, errors or skips: seven [disclosure-handoff cases](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java), two [participation repository cases](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java), and one [Account original-authorization/acquisition/settlement composition case](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationPostgresIntegrationTest.java). The new repository case commits real Account evidence, discards the acquisition response, waits for the retained original lease to expire, verifies current lookup refusal and recovers the immutable participation coordinates from the unchanged original tuple; the upstream Game Session observation is stipulated. This was a filtered physical run. The subsequent full local Account gate ran 224 physical cases with zero skips: 220 passed and four `AccountControlUiOwnerWorkflowPostgresIntegrationTest` cases failed before Flyway because `localhost:57418` refused connections (`SQLState 08001`). The endpoint cause remains unknown; the full gate did not pass. Static-only closeout then passed without rerunning the physical suite. These results do not establish a genuine World terminal, failed-acquisition settlement, deployed owner custody, runtime registration or admission. + +This preparation is owned by the existing `AA-1.3` row, which already tracks the original StartSession operator authorization/reference and original-ACK sources. Its implementation anchors include [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql), [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql), [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql), [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java), [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java), and [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java). + +The passive Account source-fence seam leaves Draft source mutation and abort pending while a matching World participation is unsettled, and blocks hosted-terms disclosure preparation and new dispatch authorization for that source until settlement. The immutable `HostedTermsDisclosureHandoff` value and repository use the existing V98 journal; their opaque evidence bytes are not authenticated by the passive value. No verifier, dispatcher, or transport is registered. The six physical PostgreSQL disclosure-handoff storage cases are specifically attributed to published commit `0a84bfa2800c6f33f3d85023c786a9fdd80ff0ba` and [exact-head validation run 38276405663](https://github.com/benhook1013/FireMUD/actions/runs/38276405663); they also ran within the failed local full check at `c7a61401f2220f70d567b7709397b967daf5e991`. The separate local carry at `932f2e1334a9ffa31fdf3be177a0fdbcd588a0e5` covered five targeted physical integration cases and does not include those six handoff cases. These results prove bounded storage and transaction behavior only. No focused executable proof establishes a genuine authenticated World terminal, failed-acquisition settlement, or composed runtime registration/admission. Hosted-terms authority remains defined by [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). + ### Initial private gameplay LOGIN issuance source intake This preparation is owned by `AA-2.1` in [Capability Status](#capability-status). @@ -118,7 +136,7 @@ These links add decision provenance only; they do not upgrade player-access or s | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [RuntimeAccountIdentityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [RuntimeAccountIdentityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The focused unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped because Docker is unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. Authentication results and JWT subjects remain unchanged; profile/export profile identity fields and tenant IDs remain numeric and full portable export is not implemented. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. `RuntimeAccountIdentityGrpcService` implements the authenticated Account-owner UUID/provenance read; its 31 focused unit cases, integration-source compilation, and formatting/documentation checks do not prove PostgreSQL execution or a live mTLS handshake, and do not enable UUID authentication or gameplay admission. Lifecycle-state retention remains tracked under AA-1.3. | | `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountTenantAuthorityEventRepository` appends the canonical tenant authority event during demo entitlement provisioning; `AccountMembershipAuthorityEventProducer` emits the first-JOIN membership event with its billing cutoff taken from that current tenant authority event, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. On fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance does not yet validate that grant. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | -| `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. | +| `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. No focused executable proof: a genuine authenticated World terminal, failed-acquisition settlement, or composed runtime registration/admission. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | | `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current text `PLAY` checks membership and entitlement before persisted actor selection, but fresh connect-token issuance does not validate the applicable non-public realm grant; final Account admission and complete private/playtest grant and entitlement authority remain open under [Game Session admission](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary). Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. The initial private gameplay LOGIN source remains unregistered; runtime registration and caller authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). | diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 9f11f1686f..96af956069 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -525,6 +525,24 @@ if "&& 'metadata' || 'required'" not in concurrency_group: dispatch_condition = runtime_jobs["dispatch-pr-base-refreshes"].get("if", "") if "github.event_name == 'workflow_run'" not in dispatch_condition: raise SystemExit("runtime refresh dispatch is not isolated from pull-request metadata events") + +# Distinct verified PR tuples must not evict one another; pull_request and +# typed refresh runs for the same tuple must share a group. A dispatch missing +# any tuple field gets a unique run namespace. +pull_request_selector = "format('pr-{0}-base-{1}-head-{2}-merge-{3}', github.event.pull_request.number, github.event.pull_request.base.sha, github.event.pull_request.head.sha, github.sha)" +if pull_request_selector not in concurrency_group: + raise SystemExit("pull_request runtime concurrency must use its exact PR, base, head, and test-merge identity") +dispatch_fields = ("pr_number", "base_sha", "head_sha", "merge_sha") +for field in dispatch_fields: + if f"github.event.client_payload.{field} != ''" not in concurrency_group: + raise SystemExit(f"typed refresh runtime concurrency must require its {field} identity") +dispatch_selector = "format('pr-{0}-base-{1}-head-{2}-merge-{3}', github.event.client_payload.pr_number, github.event.client_payload.base_sha, github.event.client_payload.head_sha, github.event.client_payload.merge_sha)" +if dispatch_selector not in concurrency_group: + raise SystemExit("typed refresh runtime concurrency must use its full payload tuple") +if "format('repository-dispatch-run-{0}', github.run_id)" not in concurrency_group: + raise SystemExit("incomplete typed refresh identity must receive a unique run namespace") +if "github.sha" in concurrency_group.split("github.event_name == 'repository_dispatch'", 1)[-1].split("github.event_name == 'workflow_run'", 1)[0]: + raise SystemExit("repository_dispatch concurrency must not use the default-branch github.sha") PY run_image_meta_exact_parent_fixture() { diff --git a/protos/account/v1/start_session_operator_authorization.proto b/protos/account/v1/start_session_operator_authorization.proto index 7f781d5515..e3271740b4 100644 --- a/protos/account/v1/start_session_operator_authorization.proto +++ b/protos/account/v1/start_session_operator_authorization.proto @@ -60,6 +60,8 @@ message IssueHumanOperatorAuthorizationReferenceResponse { AuthorityEvidenceBundleReference bundle_reference = 5; // Exact Logging/Admin SPIFFE identity verified from the authenticated request TLS peer. string authenticated_logging_workload_identity = 6; + // Account-derived canonical original postAuthorizationExecutionTuple/v1 bytes. + bytes original_account_post_authorization_tuple = 7; } message RecoverOperatorAuthorizationReferenceResponse { @@ -70,6 +72,8 @@ message RecoverOperatorAuthorizationReferenceResponse { AuthorityEvidenceBundleReference bundle_reference = 5; // Exact Logging/Admin SPIFFE identity verified from the authenticated request TLS peer. string authenticated_logging_workload_identity = 6; + // Exact original tuple re-derived from Account's retained issuance record and capture. + bytes original_account_post_authorization_tuple = 7; } message RedeemOperatorAuthorizationResponse { @@ -78,6 +82,8 @@ message RedeemOperatorAuthorizationResponse { string issuance_operation_id = 3; uint64 issuance_fence = 4; bool replay = 5; + // Exact original tuple re-derived from Account's durable issuance record. + bytes original_account_post_authorization_tuple = 6; } // Read-only projection of the exact original operation after its owner redemption. diff --git a/protos/account/v1/start_session_world_participation_acquisition.proto b/protos/account/v1/start_session_world_participation_acquisition.proto new file mode 100644 index 0000000000..183e915188 --- /dev/null +++ b/protos/account/v1/start_session_world_participation_acquisition.proto @@ -0,0 +1,40 @@ +syntax = "proto3"; + +package account.v1; + +import "game-session/v1/original_start_session_current_attempt_read.proto"; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone and unregistered. This acquires Account-owned World source protection for one +// original human StartSession and does not establish World execution admission. +service AccountStartSessionWorldParticipationAcquisitionService { + rpc AcquireStartSessionWorldParticipation( + AcquireStartSessionWorldParticipationRequest) + returns (AcquireStartSessionWorldParticipationResponse); +} + +message AcquireStartSessionWorldParticipationRequest { + int32 schema_version = 1; + // Fresh correlation UUID; independent of all retained mutation and authority identities. + string acquisition_request_id = 2; + string target_namespace = 3; + bytes original_post_authorization_tuple = 4; + string game_session_owner_mutation_id = 5; + string game_session_owner_attempt_id = 6; + int64 game_session_owner_fence = 7; + string canonical_game_instance_id = 8; + // Exact bounded World preparation JSON and its digest; these are not caller authority claims. + string preparation_input_json = 9; + string preparation_input_digest = 10; +} + +message AcquireStartSessionWorldParticipationResponse { + // The complete exact request is echoed, including the independent acquisition correlation. + AcquireStartSessionWorldParticipationRequest request = 1; + string account_world_participation_id = 2; + int64 account_world_participation_fence = 3; + // Complete retained first original-attempt response, using the existing Game Session codec. + game_session.v1.ReadOriginalStartSessionCurrentAttemptResponse original_attempt_evidence = 4; +} diff --git a/protos/account/v1/start_session_world_participation_read.proto b/protos/account/v1/start_session_world_participation_read.proto new file mode 100644 index 0000000000..9af63d3dc6 --- /dev/null +++ b/protos/account/v1/start_session_world_participation_read.proto @@ -0,0 +1,35 @@ +syntax = "proto3"; + +package account.v1; +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone and unregistered. This exact historical read resolves retained participation +// coordinates from the unchanged original tuple; it neither admits execution nor renews Account +// authority. World must separately authenticate its original Game Session operation. +service AccountStartSessionWorldParticipationHistoricalReadService { + rpc ReadHistoricalStartSessionWorldParticipation( + ReadHistoricalStartSessionWorldParticipationRequest) + returns (ReadHistoricalStartSessionWorldParticipationResponse); +} + +message ReadHistoricalStartSessionWorldParticipationRequest { + int32 schema_version = 1; + string read_request_id = 2; + string target_namespace = 3; + reserved 4, 5; + bytes original_post_authorization_tuple = 6; +} + +message ReadHistoricalStartSessionWorldParticipationResponse { + ReadHistoricalStartSessionWorldParticipationRequest request = 1; + reserved 2; + string game_session_owner_attempt_id = 3; + int64 game_session_owner_fence = 4; + string canonical_game_instance_id = 5; + // Byte-for-byte retained World preparation JSON, not fresh admission or currentness evidence. + string preparation_input_json = 6; + string preparation_input_digest = 7; + string account_world_participation_id = 8; + int64 account_world_participation_fence = 9; +} diff --git a/protos/world-management/v1/world_management_service.proto b/protos/world-management/v1/world_management_service.proto index 8c0edb0683..23d8c2c11c 100644 --- a/protos/world-management/v1/world_management_service.proto +++ b/protos/world-management/v1/world_management_service.proto @@ -45,6 +45,33 @@ service WorldAuthoredSourceIntakeService { returns (ReadAuthoredWorldSourceIntakeByIdResponse); } +// Explicitly unwired Account-authenticated read of one original StartSession World terminal. +service WorldStartSessionExecutionTerminalReadService { + rpc ReadWorldStartSessionExecutionTerminal( + ReadWorldStartSessionExecutionTerminalRequest) + returns (ReadWorldStartSessionExecutionTerminalResponse); +} + +message ReadWorldStartSessionExecutionTerminalRequest { + // Fresh correlation identity for this read, distinct from all retained operation identities. + string read_request_id = 1; + string target_namespace = 2; + bytes original_post_authorization_tuple = 3; + string account_world_participation_id = 4; + int64 account_world_participation_fence = 5; + string game_session_owner_attempt_id = 6; + int64 game_session_owner_fence = 7; + string canonical_game_instance_id = 8; + // Exact original preparation input; World never reparses or normalizes it during recovery. + string preparation_input_json = 9; +} + +message ReadWorldStartSessionExecutionTerminalResponse { + string read_request_id = 1; + // The only result is the existing closed WorldStartSessionExecutionTerminal carrier. + bytes canonical_terminal_bytes = 2; +} + message IntakeAuthoredWorldSourceRequest { int32 schema_version = 1; string target_namespace = 2; diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index 166c116f20..39063a3e35 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -82,6 +82,7 @@ dependencies { testImplementation(libs.grpc.inprocess) testImplementation(project(":logging-admin-service")) testImplementation(testFixtures(project(":account-service"))) + testImplementation(testFixtures(project(":common-platform-core"))) testCompileOnly(libs.spotbugs.annotations) add("integrationTestCompileOnly", libs.spotbugs.annotations) integrationTestImplementation(testFixtures(project(":account-service"))) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java index f8b9c063fd..c7c95d475c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java @@ -267,6 +267,7 @@ public void requireDisclosurePreparation(List exactSources) { } requireNoPendingPublication(sources); requireNoPendingGameLogicIntake(sources); + requireNoPendingWorldParticipation(sources); for (UUID operationId : affectedOperations(sources)) { Record row = readOperation(operationId); if (row == null) { @@ -301,6 +302,16 @@ public void lockDisclosureSources(List exactSources) { lockSources(sources); } + /** Narrow dispatch exclusion, including ambiguity recovery, without rerunning preparation. */ + public void requireWorldParticipationDisclosureAdmission(List exactSources) { + List sources = + List.copyOf(Objects.requireNonNull(exactSources, "exact disclosure sources")).stream() + .sorted(Comparator.comparing(SourceEvidence::key)) + .toList(); + lockDisclosureSources(sources); + requireNoPendingWorldParticipation(sources); + } + private void requireNoAuthorizedDisclosure(List sources) { for (SourceEvidence source : sources) { if (source.kind() == SourceKind.HOSTED_TERMS @@ -369,6 +380,28 @@ private void requireNoPendingGameLogicIntake(List sources) { } } + private boolean hasPendingWorldParticipation(List sources) { + for (SourceEvidence source : sources) { + if (!dsl.fetch( + "SELECT 1 FROM account_start_session_world_participation_sources s " + + "JOIN account_start_session_world_participations p " + + "ON p.participation_id = s.participation_id " + + "WHERE s.source_key = ? " + + "AND NOT account_start_session_world_participation_is_settled(p.participation_id)", + source.key()) + .isEmpty()) { + return true; + } + } + return false; + } + + private void requireNoPendingWorldParticipation(List sources) { + if (hasPendingWorldParticipation(sources)) { + throw new IllegalStateException("Original StartSession World participation remains pending"); + } + } + private boolean hasPendingPublication(List sources) { for (SourceEvidence source : sources) { if (!dsl.fetch( @@ -820,7 +853,9 @@ private List affectedOperations(List sources) { * between affected operations. */ private boolean allAffectedSettled(List sources) { - if (hasPendingPublication(sources) || hasPendingGameLogicIntake(sources)) { + if (hasPendingPublication(sources) + || hasPendingGameLogicIntake(sources) + || hasPendingWorldParticipation(sources)) { return false; } for (UUID operation : affectedOperations(sources)) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java index 82796d30ea..ff072c2bf7 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java @@ -163,7 +163,6 @@ private void validateResponse( || response.getClaimFence() != currentClaimFence || response.getPurpose() != toWirePurpose(purpose) || response.getObservedAtEpochMillis() <= 0L - || response.getObservedAtEpochMillis() > localNowEpochMillis || response.getClaimExpiresAtEpochMillis() <= response.getObservedAtEpochMillis() || response.getClaimExpiresAtEpochMillis() <= localNowEpochMillis) { throw new IllegalStateException( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfiguration.java index 8b6a275528..7f2acfff18 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfiguration.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfiguration.java @@ -13,8 +13,10 @@ import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.OwnerKeySource; import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography; import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeKeyring; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionAuthorityCaptureRepository; import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.jooq.DSLContext; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -40,6 +42,13 @@ public class AccountStartSessionOperatorAuthorizationConfiguration { static final String OPERATOR_RESPONSE_CRYPTOGRAPHY_BEAN = "startSessionOperatorResponseEnvelopeCryptography"; + /** Keeps capture storage inside this disabled-by-default feature boundary. */ + @Bean + public AccountStartSessionAuthorityCaptureRepository + accountStartSessionAuthorityCaptureRepository(DSLContext accountDsl) { + return new AccountStartSessionAuthorityCaptureRepository(accountDsl); + } + /** Creates Account's explicit active/retained HMAC calculator from an owner-supplied source. */ @Bean public AccountOperatorAuthorizationFingerprintKeyring @@ -85,6 +94,7 @@ public class AccountStartSessionOperatorAuthorizationConfiguration { accountStartSessionOperatorAuthorizationService( AccountControlUiActorService actors, AccountControlUiIssuanceRepository issuanceOperations, + AccountStartSessionAuthorityCaptureRepository captureRepository, StartSessionReservationEvidenceClient reservationEvidence, AccountStartSessionOperatorAuthorizationRepository repository, AccountOperatorAuthorizationFingerprintKeyring fingerprintKeys, @@ -105,6 +115,7 @@ public class AccountStartSessionOperatorAuthorizationConfiguration { return new AccountStartSessionOperatorAuthorizationService( actors, issuanceOperations, + captureRepository, reservationEvidence, repository, fingerprintKeys, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoff.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoff.java new file mode 100644 index 0000000000..bb8c728000 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoff.java @@ -0,0 +1,275 @@ +package net.firedevops.firemud.accountservice.hostedterms; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; + +/** + * Exact, immutable Account evidence prepared before an elective terms deadline is disclosed. This + * value is not an authorization decision: its opaque authority bytes must come from a future + * trusted Account verifier, and this class does not authenticate them. + */ +public record HostedTermsDisclosureHandoff( + UUID handoffId, + UUID requestId, + Kind kind, + String sourceKey, + String predecessorDigest, + String candidateDigest, + Instant effectiveAt, + List sources, + byte[] authenticatedAuthorityEvidence) { + public static final String SCHEMA = "account-hosted-terms-disclosure-handoff/v1"; + private static final int MAX_SOURCES = 128; + private static final int MAX_EVIDENCE_BYTES = 1_048_576; + + public enum Kind { + CATALOG, + ENVIRONMENT_BINDING + } + + public HostedTermsDisclosureHandoff { + HostedTermsEncoding.requireUuid(handoffId, "disclosure handoff"); + HostedTermsEncoding.requireUuid(requestId, "disclosure request"); + Objects.requireNonNull(kind, "disclosure handoff kind"); + String exactSourceKey = HostedTermsEncoding.requireText(sourceKey, 512); + sourceKey = exactSourceKey; + if (exactSourceKey.getBytes(StandardCharsets.UTF_8).length > 512) { + throw new IllegalArgumentException( + "Disclosure source key exceeds the Account lock-key bound"); + } + HostedTermsEncoding.requireDigest(predecessorDigest); + HostedTermsEncoding.requireDigest(candidateDigest); + Objects.requireNonNull(effectiveAt, "disclosed effective instant"); + if (effectiveAt.getNano() % 1_000 != 0) { + throw new IllegalArgumentException( + "Effective instant must preserve PostgreSQL microsecond precision"); + } + List exactSources = + Objects.requireNonNull(sources, "complete exact source vector").stream() + .map(Objects::requireNonNull) + .sorted(Comparator.comparing(SourceEvidence::key)) + .toList(); + if (exactSources.isEmpty() + || exactSources.size() > MAX_SOURCES + || exactSources.stream().map(SourceEvidence::key).distinct().count() != exactSources.size() + || exactSources.stream().noneMatch(source -> source.key().equals(exactSourceKey))) { + throw new IllegalArgumentException( + "Distinct complete sorted source evidence including the changed source is required"); + } + SourceEvidence changedSource = + exactSources.stream() + .filter(source -> source.key().equals(exactSourceKey)) + .findFirst() + .orElseThrow(); + if (changedSource.kind() != SourceKind.HOSTED_TERMS) { + throw new IllegalArgumentException("Disclosure source must be Account hosted terms evidence"); + } + if (kind == Kind.CATALOG) { + DraftAuthorizationFenceBinding.canonicalUuid(changedSource.scopeId()); + if (!sourceKey.equals("HOSTED_TERMS:" + changedSource.scopeId())) { + throw new IllegalArgumentException( + "Catalog disclosure source key must bind its exact scope"); + } + } else if (!changedSource.scopeId().startsWith("environment-boundary/")) { + throw new IllegalArgumentException( + "Environment-binding disclosure source must name its exact boundary"); + } + sources = List.copyOf(exactSources); + authenticatedAuthorityEvidence = + requireEvidence(authenticatedAuthorityEvidence, "authenticated authority evidence"); + } + + @Override + public List sources() { + return List.copyOf(sources); + } + + @Override + public byte[] authenticatedAuthorityEvidence() { + return authenticatedAuthorityEvidence.clone(); + } + + @Override + public boolean equals(Object other) { + return other instanceof HostedTermsDisclosureHandoff that + && Arrays.equals(canonicalBytes(), that.canonicalBytes()); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes()); + } + + /** Closed length-framed bytes; the caller-provided evidence is retained exactly, not trusted. */ + public byte[] canonicalBytes() { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(output, SCHEMA); + DraftAuthorizationFenceBinding.frame(output, handoffId.toString()); + DraftAuthorizationFenceBinding.frame(output, requestId.toString()); + DraftAuthorizationFenceBinding.frame(output, kind.name()); + DraftAuthorizationFenceBinding.frame(output, sourceKey); + DraftAuthorizationFenceBinding.frame(output, predecessorDigest); + DraftAuthorizationFenceBinding.frame(output, candidateDigest); + DraftAuthorizationFenceBinding.frame(output, effectiveAt.toString()); + DraftAuthorizationFenceBinding.frame(output, Integer.toString(sources.size())); + for (SourceEvidence source : sources) { + DraftAuthorizationFenceBinding.frame(output, source.canonicalBytes()); + } + DraftAuthorizationFenceBinding.frame(output, authenticatedAuthorityEvidence); + return output.toByteArray(); + } + + /** Decodes only this exact immutable frame; it does not authenticate the authority bytes. */ + public static HostedTermsDisclosureHandoff fromStored(byte[] stored) { + DraftAuthorizationFenceBinding.FrameReader reader = + new DraftAuthorizationFenceBinding.FrameReader(stored); + reader.expect(SCHEMA); + UUID handoffId = canonicalUuid(reader.text()); + UUID requestId = canonicalUuid(reader.text()); + Kind kind = Kind.valueOf(reader.text()); + String sourceKey = reader.text(); + String predecessorDigest = reader.text(); + String candidateDigest = reader.text(); + String effectiveAtText = reader.text(); + String countText = reader.text(); + DraftAuthorizationFenceBinding.decimal(countText, false); + int count; + try { + count = Integer.parseInt(countText); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException("Stored source count is out of range", invalid); + } + if (count > MAX_SOURCES || count > reader.remaining() / Integer.BYTES) { + throw new IllegalArgumentException("Stored source vector is incomplete or too large"); + } + java.util.ArrayList sources = new java.util.ArrayList<>(); + for (int index = 0; index < count; index++) { + sources.add(SourceEvidence.fromStored(reader.bytes())); + } + byte[] authorityEvidence = reader.bytes(); + reader.requireEnd(); + final Instant effectiveAt; + try { + effectiveAt = Instant.parse(effectiveAtText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException("Stored effective instant is invalid", invalid); + } + HostedTermsDisclosureHandoff handoff = + new HostedTermsDisclosureHandoff( + handoffId, + requestId, + kind, + sourceKey, + predecessorDigest, + candidateDigest, + effectiveAt, + sources, + authorityEvidence); + if (!Arrays.equals(stored, handoff.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical stored disclosure handoff"); + } + return handoff; + } + + /** Exact authenticated owner result. The opaque evidence must be verified before construction. */ + public record DisclosureResult( + UUID handoffId, + UUID requestId, + String bindingDigest, + Outcome outcome, + byte[] authenticatedEvidence) { + private static final String RESULT_SCHEMA = "account-hosted-terms-disclosure-result/v1"; + + public DisclosureResult { + HostedTermsEncoding.requireUuid(handoffId, "disclosure handoff"); + HostedTermsEncoding.requireUuid(requestId, "disclosure request"); + HostedTermsEncoding.requireDigest(bindingDigest); + Objects.requireNonNull(outcome, "authenticated disclosure outcome"); + authenticatedEvidence = + requireEvidence(authenticatedEvidence, "authenticated result evidence"); + } + + @Override + public byte[] authenticatedEvidence() { + return authenticatedEvidence.clone(); + } + + @Override + public boolean equals(Object other) { + return other instanceof DisclosureResult that + && Arrays.equals(canonicalBytes(), that.canonicalBytes()); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes()); + } + + public byte[] canonicalBytes() { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(output, RESULT_SCHEMA); + DraftAuthorizationFenceBinding.frame(output, handoffId.toString()); + DraftAuthorizationFenceBinding.frame(output, requestId.toString()); + DraftAuthorizationFenceBinding.frame(output, bindingDigest); + DraftAuthorizationFenceBinding.frame(output, outcome.name()); + DraftAuthorizationFenceBinding.frame( + output, HostedTermsEncoding.digest(authenticatedEvidence)); + DraftAuthorizationFenceBinding.frame(output, authenticatedEvidence); + return output.toByteArray(); + } + + public static DisclosureResult fromStored(byte[] stored) { + DraftAuthorizationFenceBinding.FrameReader reader = + new DraftAuthorizationFenceBinding.FrameReader(stored); + reader.expect(RESULT_SCHEMA); + DisclosureResult result = + new DisclosureResult( + canonicalUuid(reader.text()), + canonicalUuid(reader.text()), + reader.text(), + Outcome.valueOf(reader.text()), + readEvidence(reader)); + reader.requireEnd(); + if (!Arrays.equals(stored, result.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical stored disclosure result"); + } + return result; + } + + private static byte[] readEvidence(DraftAuthorizationFenceBinding.FrameReader reader) { + String digest = reader.text(); + byte[] evidence = reader.bytes(); + if (!HostedTermsEncoding.digest(evidence).equals(digest)) { + throw new IllegalArgumentException("Stored disclosure result evidence digest conflicts"); + } + return evidence; + } + } + + public enum Outcome { + DISCLOSED, + DEFINITIVELY_NOT_DISCLOSED + } + + private static UUID canonicalUuid(String value) { + DraftAuthorizationFenceBinding.canonicalUuid(value); + return UUID.fromString(value); + } + + private static byte[] requireEvidence(byte[] evidence, String description) { + byte[] exact = HostedTermsEncoding.requireBytes(evidence); + if (exact.length > MAX_EVIDENCE_BYTES) { + throw new IllegalArgumentException(description + " exceeds the durable evidence bound"); + } + return exact; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffRepository.java new file mode 100644 index 0000000000..128615894f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffRepository.java @@ -0,0 +1,423 @@ +package net.firedevops.firemud.accountservice.hostedterms; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsDisclosureHandoff.DisclosureResult; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsDisclosureHandoff.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Immutable Account-owned disclosure intent and exact owner-result journal. It performs no + * authentication and no RPC; only a future trusted Account verifier/dispatcher may supply the + * opaque authority and result bytes. Every write and source-fence check is one writable owner + * READ_COMMITTED transaction, which must finish before external dispatch. + */ +public final class HostedTermsDisclosureHandoffRepository { + private static final String HANDOFFS = "account_hosted_terms_disclosure_handoffs"; + private static final String SOURCES = "account_hosted_terms_disclosure_sources"; + private final DSLContext dsl; + private final DraftAuthorizationFenceRepository fenceRepository; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected owner persistence collaborators are retained privately and never exposed.") + public HostedTermsDisclosureHandoffRepository( + DSLContext dsl, DraftAuthorizationFenceRepository fenceRepository) { + this.dsl = Objects.requireNonNull(dsl); + this.fenceRepository = Objects.requireNonNull(fenceRepository); + } + + public enum Status { + PREPARED, + DISPATCH_AUTHORIZED, + AMBIGUOUS, + DISCLOSED, + DEFINITIVELY_NOT_DISCLOSED + } + + public record Snapshot( + HostedTermsDisclosureHandoff handoff, + Status status, + int dispatchAttempts, + Optional result, + OffsetDateTime createdAt, + OffsetDateTime resultRecordedAt) { + public Snapshot { + Objects.requireNonNull(handoff); + Objects.requireNonNull(status); + if (dispatchAttempts < 0) { + throw new IllegalArgumentException("Nonnegative dispatch attempt count required"); + } + result = Objects.requireNonNull(result); + Objects.requireNonNull(createdAt); + if (status == Status.DISCLOSED || status == Status.DEFINITIVELY_NOT_DISCLOSED) { + if (result.isEmpty() || resultRecordedAt == null) { + throw new IllegalArgumentException("Terminal status requires exact durable result"); + } + } else if (result.isPresent() || resultRecordedAt != null) { + throw new IllegalArgumentException("Nonterminal status cannot carry a result"); + } + } + } + + /** True only when this transaction durably authorized a new exact dispatch attempt. */ + public record DispatchPermit(Snapshot snapshot, boolean newlyAuthorized) { + public DispatchPermit { + Objects.requireNonNull(snapshot); + } + } + + /** + * Prepare the immutable exact source handoff. Existing exact identities are idempotent; a new + * identity first locks all sorted source keys, refuses unsettled original operations without + * modifying them, and writes the journal before those locks are released. + */ + public Snapshot prepare(HostedTermsDisclosureHandoff handoff) { + requireWriteTransaction(); + Objects.requireNonNull(handoff); + byte[] exactBinding = handoff.canonicalBytes(); + fenceRepository.lockDisclosureSources(handoff.sources()); + Record existing = findByIdentity(handoff.handoffId(), handoff.requestId()); + if (existing != null) { + return exactSnapshot(existing, handoff, exactBinding); + } + + fenceRepository.requireDisclosurePreparation(handoff.sources()); + dsl.execute( + "INSERT INTO " + + HANDOFFS + + " (handoff_id, request_id, kind, source_key, predecessor_digest, candidate_digest, " + + "effective_at, binding, binding_digest, status) " + + "VALUES (?, ?, ?, ?, ?, ?, ?::timestamptz, ?, ?, 'PREPARED') " + + "ON CONFLICT DO NOTHING", + handoff.handoffId(), + handoff.requestId(), + handoff.kind().name(), + handoff.sourceKey(), + handoff.predecessorDigest(), + handoff.candidateDigest(), + java.time.OffsetDateTime.ofInstant(handoff.effectiveAt(), java.time.ZoneOffset.UTC), + exactBinding, + HostedTermsEncoding.digest(exactBinding)); + + Record row = findByIdentity(handoff.handoffId(), handoff.requestId()); + if (row == null) { + throw new IllegalStateException("Disclosure handoff durable readback is unavailable"); + } + Snapshot current = snapshot(row); + requireExactHandoffColumns(row, handoff, exactBinding); + if (current.status() == Status.PREPARED && current.dispatchAttempts() == 0) { + for (SourceEvidence source : handoff.sources()) { + byte[] evidence = source.canonicalBytes(); + dsl.execute( + "INSERT INTO " + + SOURCES + + " (handoff_id, source_key, source_evidence, source_evidence_digest) " + + "VALUES (?, ?, ?, ?) ON CONFLICT DO NOTHING", + handoff.handoffId(), + source.key(), + evidence, + HostedTermsEncoding.digest(evidence)); + } + row = findByIdentity(handoff.handoffId(), handoff.requestId()); + if (row == null) { + throw new IllegalStateException("Disclosure handoff disappeared during source readback"); + } + } + return exactSnapshot(row, handoff, exactBinding); + } + + /** + * Durably authorizes one dispatch before the caller leaves the transaction. A pre-existing + * DISPATCH_AUTHORIZED row is recovered by readback, not by guessing that a previous RPC failed. + * An exact retry after explicit ambiguity may reauthorize the same stable request identity; the + * external receiver must deduplicate it. Sorted source locks precede journal and operation locks; + * a prepared handoff rechecks original settlement before its first dispatch authorization. + */ + public DispatchPermit authorizeDispatch(HostedTermsDisclosureHandoff handoff) { + requireWriteTransaction(); + Objects.requireNonNull(handoff); + fenceRepository.lockDisclosureSources(handoff.sources()); + Record row = requireExactRow(handoff); + Status status = Status.valueOf(row.get("status", String.class)); + boolean newlyAuthorized = false; + if (status == Status.PREPARED || status == Status.AMBIGUOUS) { + fenceRepository.requireWorldParticipationDisclosureAdmission(handoff.sources()); + if (status == Status.PREPARED) { + fenceRepository.requireDisclosurePreparation(handoff.sources()); + } + int updated = + dsl.execute( + "UPDATE " + + HANDOFFS + + " SET status = 'DISPATCH_AUTHORIZED', dispatch_attempts = dispatch_attempts + 1 " + + "WHERE handoff_id = ? AND status = ?", + handoff.handoffId(), + status.name()); + if (updated != 1) { + throw new IllegalStateException("Disclosure dispatch authorization did not advance once"); + } + newlyAuthorized = true; + } + row = requireExactRow(handoff); + return new DispatchPermit(snapshot(row), newlyAuthorized); + } + + /** Records uncertainty only; absence, timeout, or an empty readback is never no-disclosure. */ + public Snapshot recordAmbiguous(HostedTermsDisclosureHandoff handoff) { + requireWriteTransaction(); + Objects.requireNonNull(handoff); + fenceRepository.lockDisclosureSources(handoff.sources()); + Record row = requireExactRow(handoff); + Status status = Status.valueOf(row.get("status", String.class)); + if (status == Status.DISPATCH_AUTHORIZED) { + int updated = + dsl.execute( + "UPDATE " + + HANDOFFS + + " SET status = 'AMBIGUOUS' WHERE handoff_id = ? AND status = 'DISPATCH_AUTHORIZED'", + handoff.handoffId()); + if (updated != 1) { + throw new IllegalStateException("Ambiguous disclosure outcome did not persist once"); + } + row = requireExactRow(handoff); + } else if (status != Status.AMBIGUOUS) { + throw new IllegalStateException("Only an authorized unresolved dispatch can be ambiguous"); + } + return snapshot(row); + } + + /** + * Stores immutable exact owner evidence after its authenticated verifier proves either outcome. + * The repository itself cannot authenticate the supplied evidence, and never infers a negative + * result from timeout, process restart, or a missing owner row. + */ + public Snapshot recordResult(HostedTermsDisclosureHandoff handoff, DisclosureResult result) { + requireWriteTransaction(); + Objects.requireNonNull(handoff); + Objects.requireNonNull(result); + fenceRepository.lockDisclosureSources(handoff.sources()); + Record row = requireExactRow(handoff); + byte[] resultBytes = result.canonicalBytes(); + String resultDigest = HostedTermsEncoding.digest(resultBytes); + requireResultBinding(handoff, result); + Status status = Status.valueOf(row.get("status", String.class)); + if (status == Status.DISCLOSED || status == Status.DEFINITIVELY_NOT_DISCLOSED) { + if (!Arrays.equals(resultBytes, row.get("result_payload", byte[].class))) { + throw new IllegalArgumentException("Changed terminal disclosure result evidence"); + } + return snapshot(row); + } + if (status != Status.DISPATCH_AUTHORIZED && status != Status.AMBIGUOUS) { + throw new IllegalStateException( + "A disclosure result requires durable dispatch authorization"); + } + Status terminal = + result.outcome() == Outcome.DISCLOSED + ? Status.DISCLOSED + : Status.DEFINITIVELY_NOT_DISCLOSED; + int updated = + dsl.execute( + "UPDATE " + + HANDOFFS + + " SET status = ?, result_outcome = ?, result_payload = ?, result_digest = ?, " + + "result_recorded_at = CURRENT_TIMESTAMP WHERE handoff_id = ? " + + "AND status IN ('DISPATCH_AUTHORIZED', 'AMBIGUOUS')", + terminal.name(), + result.outcome().name(), + resultBytes, + resultDigest, + handoff.handoffId()); + if (updated != 1) { + Record prior = requireExactRow(handoff); + if (Status.valueOf(prior.get("status", String.class)) != terminal + || !Arrays.equals(resultBytes, prior.get("result_payload", byte[].class))) { + throw new IllegalStateException( + "Disclosure result did not persist as exact terminal readback"); + } + return snapshot(prior); + } + return snapshot(requireExactRow(handoff)); + } + + public Optional read(UUID handoffId) { + requireTransaction(); + HostedTermsEncoding.requireUuid(handoffId, "disclosure handoff"); + Record row = dsl.fetchOne("SELECT * FROM " + HANDOFFS + " WHERE handoff_id = ?", handoffId); + if (row == null) { + return Optional.empty(); + } + Snapshot snapshot = snapshot(row); + requireExactSourceRows(snapshot.handoff()); + return Optional.of(snapshot); + } + + private Record requireExactRow(HostedTermsDisclosureHandoff handoff) { + Record row = findByIdentity(handoff.handoffId(), handoff.requestId()); + if (row == null) { + throw new IllegalStateException("Exact disclosure handoff is unavailable"); + } + exactSnapshot(row, handoff, handoff.canonicalBytes()); + return row; + } + + private Record findByIdentity(UUID handoffId, UUID requestId) { + List rows = + dsl.fetch( + "SELECT * FROM " + HANDOFFS + " WHERE handoff_id = ? OR request_id = ? FOR UPDATE", + handoffId, + requestId); + if (rows.size() > 1) { + throw new IllegalStateException("Disclosure handoff and request identities conflict"); + } + return rows.isEmpty() ? null : rows.getFirst(); + } + + private Snapshot exactSnapshot( + Record row, HostedTermsDisclosureHandoff expected, byte[] expectedBinding) { + Snapshot snapshot = snapshot(row); + requireExactHandoffColumns(row, expected, expectedBinding); + requireExactSourceRows(expected); + return snapshot; + } + + private void requireExactHandoffColumns( + Record row, HostedTermsDisclosureHandoff expected, byte[] expectedBinding) { + if (!Arrays.equals(expectedBinding, row.get("binding", byte[].class)) + || !expected.handoffId().equals(row.get("handoff_id", UUID.class)) + || !expected.requestId().equals(row.get("request_id", UUID.class)) + || !expected.kind().name().equals(row.get("kind", String.class)) + || !expected.sourceKey().equals(row.get("source_key", String.class)) + || !expected.predecessorDigest().equals(row.get("predecessor_digest", String.class)) + || !expected.candidateDigest().equals(row.get("candidate_digest", String.class)) + || !expected.effectiveAt().equals(row.get("effective_at", OffsetDateTime.class).toInstant()) + || !HostedTermsEncoding.digest(expectedBinding) + .equals(row.get("binding_digest", String.class))) { + throw new IllegalArgumentException( + "Disclosure handoff identity conflicts with prior evidence"); + } + } + + private Snapshot snapshot(Record row) { + byte[] bindingBytes = row.get("binding", byte[].class); + String bindingDigest = HostedTermsEncoding.digest(bindingBytes); + if (!bindingDigest.equals(row.get("binding_digest", String.class))) { + throw new IllegalStateException( + "Disclosure handoff binding digest conflicts with exact bytes"); + } + HostedTermsDisclosureHandoff handoff = HostedTermsDisclosureHandoff.fromStored(bindingBytes); + if (!handoff.handoffId().equals(row.get("handoff_id", UUID.class)) + || !handoff.requestId().equals(row.get("request_id", UUID.class)) + || !handoff.kind().name().equals(row.get("kind", String.class)) + || !handoff.sourceKey().equals(row.get("source_key", String.class)) + || !handoff.predecessorDigest().equals(row.get("predecessor_digest", String.class)) + || !handoff.candidateDigest().equals(row.get("candidate_digest", String.class)) + || !handoff + .effectiveAt() + .equals(row.get("effective_at", OffsetDateTime.class).toInstant())) { + throw new IllegalStateException("Disclosure handoff columns conflict with exact binding"); + } + Status status = Status.valueOf(row.get("status", String.class)); + String resultOutcome = row.get("result_outcome", String.class); + byte[] resultPayload = row.get("result_payload", byte[].class); + String resultDigest = row.get("result_digest", String.class); + OffsetDateTime resultRecordedAt = row.get("result_recorded_at", OffsetDateTime.class); + Optional result = Optional.empty(); + if (resultPayload != null) { + if (resultDigest == null + || !HostedTermsEncoding.digest(resultPayload).equals(resultDigest) + || resultOutcome == null) { + throw new IllegalStateException("Disclosure result digest or outcome is incomplete"); + } + DisclosureResult decoded = DisclosureResult.fromStored(resultPayload); + requireResultBinding(handoff, decoded); + if (!decoded.outcome().name().equals(resultOutcome)) { + throw new IllegalStateException("Disclosure result outcome differs from exact evidence"); + } + if ((status == Status.DISCLOSED && decoded.outcome() != Outcome.DISCLOSED) + || (status == Status.DEFINITIVELY_NOT_DISCLOSED + && decoded.outcome() != Outcome.DEFINITIVELY_NOT_DISCLOSED)) { + throw new IllegalStateException("Terminal disclosure status differs from exact result"); + } + result = Optional.of(decoded); + } else if (resultOutcome != null || resultDigest != null || resultRecordedAt != null) { + throw new IllegalStateException("Partial disclosure result columns are not permitted"); + } + return new Snapshot( + handoff, + status, + row.get("dispatch_attempts", Integer.class), + result, + row.get("created_at", OffsetDateTime.class), + resultRecordedAt); + } + + private void requireExactSourceRows(HostedTermsDisclosureHandoff handoff) { + List rows = + dsl + .fetch( + "SELECT source_key, source_evidence, source_evidence_digest FROM " + + SOURCES + + " WHERE handoff_id = ?", + handoff.handoffId()) + .stream() + .sorted(Comparator.comparing(row -> row.get("source_key", String.class))) + .toList(); + if (rows.size() != handoff.sources().size()) { + throw new IllegalStateException("Disclosure handoff source participation is incomplete"); + } + for (int index = 0; index < rows.size(); index++) { + SourceEvidence expected = handoff.sources().get(index); + Record row = rows.get(index); + byte[] evidence = row.get("source_evidence", byte[].class); + if (!expected.key().equals(row.get("source_key", String.class)) + || !Arrays.equals(expected.canonicalBytes(), evidence) + || !HostedTermsEncoding.digest(evidence) + .equals(row.get("source_evidence_digest", String.class))) { + throw new IllegalStateException("Disclosure handoff source evidence differs from binding"); + } + } + } + + private void requireResultBinding(HostedTermsDisclosureHandoff handoff, DisclosureResult result) { + if (!handoff.handoffId().equals(result.handoffId()) + || !handoff.requestId().equals(result.requestId()) + || !HostedTermsEncoding.digest(handoff.canonicalBytes()).equals(result.bindingDigest())) { + throw new IllegalArgumentException("Disclosure result is not bound to the exact handoff"); + } + } + + private void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Caller Account transaction required"); + } + } + + private void requireWriteTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable caller Account transaction required"); + } + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Transaction-bound writable READ_COMMITTED connection required"); + } + }); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepository.java index 674a21f5a8..b01fde8330 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepository.java @@ -12,6 +12,7 @@ import java.util.Optional; import java.util.UUID; import java.util.regex.Pattern; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle.BundleReference; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import org.jooq.DSLContext; @@ -289,8 +290,6 @@ private static void validateDurableRecord(IssuanceRecord issuance) { || !issuance.issuanceWorkloadUri().endsWith("/sa/logging-admin-service") || issuance.reservationClaimFence() <= 0L || issuance.issuanceFence() <= 0L - || !Long.toString(issuance.issuanceFence()) - .equals(issuance.bundleReference().sourceFence()) || !issuance.referenceExpiresAt().isAfter(issuance.issuedAt()) || issuance.referenceExpiresAt().isAfter(issuance.issuedAt().plus(MAX_REFERENCE_LIFETIME)) || !issuance.responseEnvelopeExpiresAt().isAfter(issuance.referenceExpiresAt()) @@ -299,6 +298,13 @@ private static void validateDurableRecord(IssuanceRecord issuance) { .isAfter(issuance.referenceExpiresAt().plus(MAX_RESPONSE_RECOVERY_WINDOW))) { throw unavailable(); } + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(issuance.authorityEvidenceBundle()); + bundle.requireReferenceBinding(issuance.bundleReference()); + if (!Long.toString(issuance.issuanceFence()).equals(bundle.issuanceFence()) + || !issuance.bundleReference().sourceVersion().equals(bundle.sourceEvidenceVersion())) { + throw unavailable(); + } if (issuance.status() == Status.REDEEMED && (!ownerWorkloadUri(issuance.issuanceWorkloadUri(), issuance.preAuthorizationTuple()) .equals(issuance.redemptionRedeemerWorkloadUri()) @@ -336,9 +342,17 @@ private static void validateCandidate(IssuanceCandidate candidate) { requirePositive(candidate.reservationClaimFence(), "reservationClaimFence"); requireNonNilUuid(candidate.issuanceOperationId(), "issuanceOperationId"); requirePositive(candidate.issuanceFence(), "issuanceFence"); - requireBundleReference(candidate.bundleReference(), candidate.issuanceFence()); + requireBundleReference(candidate.bundleReference()); requireBytes( candidate.authorityEvidenceBundle(), MAX_AUTHORITY_BUNDLE_BYTES, "authority bundle"); + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(candidate.authorityEvidenceBundle()); + bundle.requireReferenceBinding(candidate.bundleReference()); + if (!Long.toString(candidate.issuanceFence()).equals(bundle.issuanceFence()) + || !candidate.bundleReference().sourceVersion().equals(bundle.sourceEvidenceVersion())) { + throw new IllegalArgumentException( + "bundle reference or Account issuance fence differs from the candidate"); + } requireFingerprint(candidate.authorizationReferenceFingerprint()); requireBytes( candidate.encryptedResponseEnvelope(), @@ -433,12 +447,8 @@ private static BundleReference bundleReference(Record row) { row.get("bundle_linearization", String.class)); } - private static void requireBundleReference(BundleReference reference, long issuanceFence) { + private static void requireBundleReference(BundleReference reference) { Objects.requireNonNull(reference, "original authority bundle reference is required"); - if (!Long.toString(issuanceFence).equals(reference.sourceFence())) { - throw new IllegalArgumentException( - "original bundle source fence must equal the Account issuance fence"); - } } private static void requireSameRedemptionBinding( @@ -772,7 +782,8 @@ public record IssuanceRecord( throw unavailable(); } Objects.requireNonNull(status, "status is required"); - requireBundleReference(bundleReference, issuanceFence); + if (issuanceFence <= 0L) throw unavailable(); + requireBundleReference(bundleReference); if (status == Status.ISSUED && (redemptionRedeemerWorkloadUri != null || redemptionOwnerAttemptId != null diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java new file mode 100644 index 0000000000..66cdfcceec --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java @@ -0,0 +1,577 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionCurrentAttemptResponse; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** + * Immutable storage for the exact observation of the original live Game Session StartSession + * attempt that is attached to an existing Account World participation. + * + *

This repository does not authenticate Game Session, continuously establish owner authority, + * issue or renew an Account reference, or authorize World admission. The attached response is a + * point-in-time observation. Callers must obtain it from the exact same-namespace Game Session read + * and independently perform the current Account authority checks required by the owning service + * path. + * + *

All operations require the caller's writable READ COMMITTED Account transaction. Current + * retention and lookup lock the exact immutable participation before checking settlement and the + * original lease against the Account database clock. Historical readback is lookup-only and may + * return expired evidence; it cannot be used as current admission evidence. + */ +@Repository +public class AccountStartSessionWorldOriginalAttemptEvidenceRepository { + private static final String EVIDENCE = "account_start_session_world_original_attempt_evidence"; + private static final String PARTICIPATIONS = "account_start_session_world_participations"; + private static final String SOURCES = "account_start_session_world_participation_sources"; + private static final String SETTLEMENTS = "account_start_session_world_participation_settlements"; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Set EVIDENCE_COLUMNS = + Set.of( + "participation_id", + "target_namespace", + "game_session_owner_attempt_id", + "game_session_owner_mutation_id", + "game_session_owner_fence", + "original_lease_expires_at", + "original_response_bytes", + "original_response_digest"); + private static final Set SOURCE_COLUMNS = + Set.of("participation_id", "source_key", "source_evidence"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Preserve the injected DSLContext precondition; this transactional Spring repository must remain proxyable, owns no resources, and declares no finalizer.") + public AccountStartSessionWorldOriginalAttemptEvidenceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + } + + /** + * Appends the first complete observation for an existing unsettled participation, or reads back + * its immutable winner for an exact semantic retry. + * + *

A new transport correlation UUID is allowed on retry. The original tuple, target namespace, + * owner attempt, owner mutation UUID, owner fence, original expiry, and exact Account projection + * must remain unchanged. The first encoded complete response and its digest are retained. + */ + @Transactional(propagation = Propagation.MANDATORY) + public StoredEvidence retainCurrentExact(StoredParticipation participation, Result observation) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(participation, "exact Account World participation is required"); + Objects.requireNonNull(observation, "exact current Game Session observation is required"); + + byte[] responseBytes = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(observation).toByteArray(); + Result decoded = decodeResponse(observation.request(), responseBytes, participation); + + StoredParticipation locked = lockExactParent(participation); + requirePending(locked.participationId()); + requireLeaseCurrent(decoded.originalLeaseExpiresAt()); + + dsl.execute( + "INSERT INTO " + + EVIDENCE + + " (participation_id, target_namespace, game_session_owner_attempt_id, " + + "game_session_owner_mutation_id, game_session_owner_fence, original_lease_expires_at, " + + "original_response_bytes, original_response_digest) " + + "VALUES (?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?) " + + "ON CONFLICT (participation_id) DO NOTHING", + locked.participationId(), + decoded.request().targetNamespace(), + decoded.request().expectedOwnerAttemptId(), + decoded.request().expectedOwnerMutationId(), + decoded.request().expectedOwnerFence(), + OffsetDateTime.ofInstant(decoded.originalLeaseExpiresAt(), java.time.ZoneOffset.UTC), + responseBytes, + digestPrefixed(responseBytes)); + + Record row = selectEvidence(locked.participationId(), false); + if (row == null) throw unavailable(); + StoredEvidence stored = decodeStoredEvidence(row, locked); + requireSameSemanticObservation(decoded, stored.result()); + // Recheck after row-lock waits and readback work. The migration's INSERT guard independently + // checks the database clock after its parent lock as well. + requireLeaseCurrent(stored.originalLeaseExpiresAt()); + return stored; + } + + /** + * Lookup-only current read. It locks the exact pending Account participation and rechecks the + * retained original lease against the database clock after the lock wait. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findCurrentExact( + StoredParticipation participation, Request expectedRequest) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(participation, "exact Account World participation is required"); + Objects.requireNonNull(expectedRequest, "exact current-attempt request is required"); + StoredParticipation locked = lockExactParent(participation); + requirePending(locked.participationId()); + Record row = selectEvidence(locked.participationId(), false); + if (row == null) return Optional.empty(); + StoredEvidence stored = decodeStoredEvidence(row, locked); + requireSameSemanticRequest(expectedRequest, stored.result().request()); + requireLeaseCurrent(stored.originalLeaseExpiresAt()); + return Optional.of(stored); + } + + /** + * Exact historical readback for recovery. It neither locks for admission nor checks current + * expiry or settlement; the returned observation remains historical evidence only. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findHistoricalExact( + StoredParticipation participation, Request expectedRequest) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(participation, "exact Account World participation is required"); + Objects.requireNonNull(expectedRequest, "exact historical current-attempt request is required"); + StoredParticipation historical = readExactParent(participation, false); + if (historical == null) return Optional.empty(); + Record row = selectEvidence(historical.participationId(), false); + if (row == null) return Optional.empty(); + StoredEvidence stored = decodeStoredEvidence(row, historical); + requireSameSemanticRequest(expectedRequest, stored.result().request()); + return Optional.of(stored); + } + + private StoredParticipation lockExactParent(StoredParticipation expected) { + StoredParticipation stored = readExactParent(expected, true); + if (stored == null) throw unavailable(); + return stored; + } + + private StoredParticipation readExactParent(StoredParticipation expected, boolean forUpdate) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + + PARTICIPATIONS + + " WHERE participation_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + expected.participationId()); + if (row == null) return null; + StoredParticipation actual = + AccountStartSessionWorldParticipationRepository.decodeParticipation(row, List.of()); + requireSameParent(expected, actual); + requireSameParentSources(expected); + return actual; + } + + private void requireSameParentSources(StoredParticipation expected) { + var rows = + dsl.fetch( + "SELECT * FROM " + SOURCES + " WHERE participation_id = ? ORDER BY source_key", + expected.participationId()); + List actual = new ArrayList<>(rows.size()); + for (Record row : rows) { + requireColumns(row, SOURCE_COLUMNS, "participation source"); + if (!expected.participationId().equals(requiredUuid(row, "participation_id"))) { + throw unavailable(); + } + actual.add( + new SourceRow(requiredString(row, "source_key"), requiredBytes(row, "source_evidence"))); + } + actual.sort(Comparator.comparing(SourceRow::key)); + List expectedSources = + expected.sources().stream().sorted(Comparator.comparing(SourceEvidence::key)).toList(); + if (actual.size() != expectedSources.size()) throw conflict(); + for (int index = 0; index < actual.size(); index++) { + SourceRow left = actual.get(index); + SourceEvidence right = expectedSources.get(index); + if (!left.key().equals(right.key()) + || !Arrays.equals(left.canonicalBytes(), right.canonicalBytes())) { + throw conflict(); + } + } + } + + private static void requireSameParent(StoredParticipation expected, StoredParticipation actual) { + if (!expected.participationId().equals(actual.participationId()) + || expected.participationFence() != actual.participationFence() + || !expected.controlPlaneRequestId().equals(actual.controlPlaneRequestId()) + || !Arrays.equals( + expected.originalPostAuthorizationTuple(), actual.originalPostAuthorizationTuple()) + || !expected.targetNamespace().equals(actual.targetNamespace()) + || !expected.canonicalTenantId().equals(actual.canonicalTenantId()) + || !expected.canonicalGameInstanceId().equals(actual.canonicalGameInstanceId()) + || !expected.gameSessionOwnerAttemptId().equals(actual.gameSessionOwnerAttemptId()) + || expected.gameSessionOwnerFence() != actual.gameSessionOwnerFence() + || !expected.preparationInputJson().equals(actual.preparationInputJson()) + || !expected.preparationInputDigest().equals(actual.preparationInputDigest()) + || expected.producerXid() != actual.producerXid() + || !expected.createdAt().equals(actual.createdAt())) { + throw conflict(); + } + } + + private void requirePending(UUID participationId) { + if (dsl.fetchOne( + "SELECT participation_id FROM " + SETTLEMENTS + " WHERE participation_id = ?", + participationId) + != null) { + throw unavailable(); + } + } + + private Record selectEvidence(UUID participationId, boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + EVIDENCE + + " WHERE participation_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + participationId); + } + + private StoredEvidence decodeStoredEvidence(Record row, StoredParticipation parent) { + try { + requireColumns(row, EVIDENCE_COLUMNS, "original attempt evidence"); + UUID participationId = requiredUuid(row, "participation_id"); + String namespace = requiredString(row, "target_namespace"); + UUID ownerAttempt = requiredUuid(row, "game_session_owner_attempt_id"); + UUID ownerMutation = requiredUuid(row, "game_session_owner_mutation_id"); + long ownerFence = positive(requiredLong(row, "game_session_owner_fence")); + OffsetDateTime expiry = requiredTimestamp(row, "original_lease_expires_at"); + byte[] responseBytes = requiredBytes(row, "original_response_bytes"); + String responseDigest = requiredString(row, "original_response_digest"); + if (!parent.participationId().equals(participationId) + || !parent.targetNamespace().equals(namespace) + || !parent.gameSessionOwnerAttemptId().equals(ownerAttempt) + || parent.gameSessionOwnerFence() != ownerFence + || !SHA256.matcher(responseDigest).matches() + || !responseDigest.equals(digestPrefixed(responseBytes))) { + throw unavailable(); + } + + Result result = decodeResponseFromStoredBytes(responseBytes, parent); + if (!ownerMutation.equals(result.request().expectedOwnerMutationId()) + || !ownerAttempt.equals(result.request().expectedOwnerAttemptId()) + || ownerFence != result.request().expectedOwnerFence() + || !namespace.equals(result.request().targetNamespace()) + || !expiry.toInstant().equals(result.originalLeaseExpiresAt())) { + throw unavailable(); + } + return new StoredEvidence( + participationId, + ownerMutation, + expiry.toInstant(), + responseBytes, + responseDigest, + result); + } catch (RuntimeException malformed) { + if (malformed instanceof IllegalStateException state + && ("Exact original StartSession attempt evidence unavailable".equals(state.getMessage()) + || "Original StartSession attempt evidence conflicts with its immutable binding" + .equals(state.getMessage()))) { + throw state; + } + throw unavailable(); + } + } + + private static Result decodeResponse( + Request expectedRequest, byte[] responseBytes, StoredParticipation parent) { + return validateResponse(expectedRequest, responseBytes, parent); + } + + static Result validateResponse( + Request expectedRequest, byte[] responseBytes, StoredParticipation parent) { + Objects.requireNonNull(expectedRequest, "exact current-attempt request is required"); + Objects.requireNonNull(responseBytes, "complete current-attempt response bytes are required"); + if (responseBytes.length == 0 + || responseBytes.length + > OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.MAX_RESPONSE_BYTES) { + throw conflict(); + } + try { + ReadOriginalStartSessionCurrentAttemptResponse response = + ReadOriginalStartSessionCurrentAttemptResponse.parseFrom(responseBytes); + Result result = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + expectedRequest, response); + if (!Arrays.equals( + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(result).toByteArray(), + responseBytes)) { + throw conflict(); + } + requireObservationBinding(parent, result); + return result; + } catch (IOException | RuntimeException malformed) { + if (malformed instanceof IllegalStateException state + && "Original StartSession attempt evidence conflicts with its immutable binding" + .equals(state.getMessage())) { + throw state; + } + throw conflict(); + } + } + + private static Result decodeResponseFromStoredBytes( + byte[] responseBytes, StoredParticipation parent) { + if (responseBytes.length == 0 + || responseBytes.length + > OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.MAX_RESPONSE_BYTES) { + throw unavailable(); + } + try { + ReadOriginalStartSessionCurrentAttemptResponse response = + ReadOriginalStartSessionCurrentAttemptResponse.parseFrom(responseBytes); + if (!response.hasRequest()) throw unavailable(); + Request echoedRequest = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromRequest(response.getRequest()); + Result result = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse(echoedRequest, response); + if (!Arrays.equals( + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(result).toByteArray(), + responseBytes)) { + throw unavailable(); + } + requireObservationBinding(parent, result); + return result; + } catch (IOException | RuntimeException malformed) { + if (malformed instanceof IllegalStateException state + && "Exact original StartSession attempt evidence unavailable" + .equals(state.getMessage())) { + throw state; + } + throw unavailable(); + } + } + + private static void requireObservationBinding(StoredParticipation parent, Result result) { + Request request = result.request(); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(parent.originalPostAuthorizationTuple()); + if (!"StartSession".equals(tuple.preAuthorizationTuple().actionFamily()) + || !"game-session-service".equals(tuple.preAuthorizationTuple().targetOwner()) + || !parent.controlPlaneRequestId().equals(tuple.controlPlaneRequestId()) + || !parent.targetNamespace().equals(request.targetNamespace()) + || !parent + .targetNamespace() + .equals(tuple.preAuthorizationTuple().action().scope().targetNamespace()) + || !Arrays.equals( + parent.originalPostAuthorizationTuple(), request.canonicalPostAuthorizationTuple()) + || !parent.gameSessionOwnerAttemptId().equals(request.expectedOwnerAttemptId()) + || parent.gameSessionOwnerFence() != request.expectedOwnerFence() + || !accountProjectionMatches(tuple, result.accountRedemptionProjection()) + || result.originalLeaseExpiresAt().getNano() % 1_000 != 0) { + throw conflict(); + } + } + + static void requireSameSemanticObservation(Result expected, Result actual) { + requireSameSemanticRequest(expected.request(), actual.request()); + if (!expected.phaseState().equals(actual.phaseState()) + || !expected.originalLeaseExpiresAt().equals(actual.originalLeaseExpiresAt()) + || !Arrays.equals( + expected.accountRedemptionProjection(), actual.accountRedemptionProjection())) { + throw conflict(); + } + } + + static void requireSameSemanticRequest(Request expected, Request actual) { + if (!expected.targetNamespace().equals(actual.targetNamespace()) + || !Arrays.equals( + expected.canonicalPostAuthorizationTuple(), actual.canonicalPostAuthorizationTuple()) + || !expected.expectedOwnerAttemptId().equals(actual.expectedOwnerAttemptId()) + || !expected.expectedOwnerMutationId().equals(actual.expectedOwnerMutationId()) + || expected.expectedOwnerFence() != actual.expectedOwnerFence()) { + throw conflict(); + } + } + + private static boolean accountProjectionMatches( + StartSessionPostAuthorizationExecutionTuple tuple, byte[] projectionBytes) { + try { + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + long issuanceFence = Long.parseLong(tuple.issuanceFence()); + if (issuanceFence <= 0L) return false; + byte[] expected = + Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString( + Map.of( + "projectionSchemaId", + "accountStartSessionRedemptionProjection", + "projectionSchemaVersion", + "1", + "authorizationReferenceFingerprint", + tuple.authorizationReferenceFingerprint(), + "authorityEvidenceBundle", + bundle.jsonValue(), + "issuanceOperationId", + bundle.issuanceOperationId().toString(), + "issuanceFence", + issuanceFence))); + return Arrays.equals(expected, projectionBytes); + } catch (IOException | RuntimeException malformed) { + return false; + } + } + + private void requireLeaseCurrent(Instant expiry) { + Record row = dsl.fetchOne("SELECT clock_timestamp()"); + if (row == null) throw unavailable(); + OffsetDateTime now = Objects.requireNonNull(row.get(0, OffsetDateTime.class)); + if (!expiry.isAfter(now.toInstant())) throw unavailable(); + } + + private void requireWritableReadCommittedTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); + } + Integer declaredIsolation = + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (declaredIsolation != null && declaredIsolation != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); + } + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); + } + }); + } + + private static void requireColumns(Record row, Set expected, String label) { + Set actual = + Arrays.stream(row.fields()) + .map(field -> field.getName()) + .collect(java.util.stream.Collectors.toSet()); + if (!actual.equals(expected)) throw unavailable(); + } + + private static UUID requiredUuid(Record row, String column) { + UUID value = Objects.requireNonNull(row.get(column, UUID.class), column + " is required"); + if (NIL_UUID.equals(value)) throw unavailable(); + return value; + } + + private static String requiredString(Record row, String column) { + String value = Objects.requireNonNull(row.get(column, String.class), column + " is required"); + if (value.isBlank()) throw unavailable(); + return value; + } + + private static byte[] requiredBytes(Record row, String column) { + byte[] value = Objects.requireNonNull(row.get(column, byte[].class), column + " is required"); + return value.clone(); + } + + private static long requiredLong(Record row, String column) { + return Objects.requireNonNull(row.get(column, Long.class), column + " is required"); + } + + private static OffsetDateTime requiredTimestamp(Record row, String column) { + return Objects.requireNonNull(row.get(column, OffsetDateTime.class), column + " is required"); + } + + private static long positive(long value) { + if (value <= 0L) throw unavailable(); + return value; + } + + private static String digestPrefixed(byte[] bytes) { + return "sha256:" + digestHex(bytes); + } + + private static String digestHex(byte[] bytes) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static IllegalStateException conflict() { + return new IllegalStateException( + "Original StartSession attempt evidence conflicts with its immutable binding"); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Exact original StartSession attempt evidence unavailable"); + } + + private record SourceRow(String key, byte[] canonicalBytes) { + private SourceRow { + canonicalBytes = canonicalBytes.clone(); + } + + @Override + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + } + + public record StoredEvidence( + UUID participationId, + UUID gameSessionOwnerMutationId, + Instant originalLeaseExpiresAt, + byte[] originalResponseBytes, + String originalResponseDigest, + Result result) { + public StoredEvidence { + Objects.requireNonNull(participationId); + Objects.requireNonNull(gameSessionOwnerMutationId); + Objects.requireNonNull(originalLeaseExpiresAt); + originalResponseBytes = Objects.requireNonNull(originalResponseBytes).clone(); + Objects.requireNonNull(originalResponseDigest); + Objects.requireNonNull(result); + if (!SHA256.matcher(originalResponseDigest).matches() + || !originalResponseDigest.equals(digestPrefixed(originalResponseBytes))) { + throw new IllegalArgumentException( + "Stored original response digest differs from its bytes"); + } + } + + @Override + public byte[] originalResponseBytes() { + return originalResponseBytes.clone(); + } + + @Override + public String toString() { + return "StoredEvidence[participationId=" + + participationId + + ", ownerMutationId=" + + gameSessionOwnerMutationId + + ", responseBytes=, projection=]"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java new file mode 100644 index 0000000000..925ae6a8d7 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java @@ -0,0 +1,1101 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Comparator; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionAuthorityCapture; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Immutable Account storage for the distinct World StartSession receiving participation. + * + *

This repository is not a transport authenticator, authority issuer, currentness proof, or + * execution-admission decision. Acquisition callers must authenticate the same-namespace World peer + * before parsing, and must establish the original actor/JTI, live Account source, original redeemed + * Game Session attempt/fence, and exact retained capture inside the existing {@code + * withCurrentCommitted} source-protection callback before calling this repository. Remote + * environment observations belong outside SQL. Terminal callers must separately authenticate the + * original World operation before passing its typed terminal here. + * + *

All operations require the caller's writable READ COMMITTED Account transaction. In + * particular, an exact create retry is not admitted by the database's insert-only expiry trigger: + * the caller must re-establish currentness before retrying. Historical reads and terminal + * settlement intentionally do not renew or recheck reference expiry. + */ +@Repository +public class AccountStartSessionWorldParticipationRepository { + private static final String PARTICIPATIONS = "account_start_session_world_participations"; + private static final String SOURCES = "account_start_session_world_participation_sources"; + private static final String SETTLEMENTS = "account_start_session_world_participation_settlements"; + private static final String CAPTURES = "account_start_session_authority_captures"; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern PREPARATION_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern CAPTURED_AT = + Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{3}Z"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .build(); + private static final Set PARTICIPATION_COLUMNS = + Set.of( + "participation_id", + "participation_fence", + "control_plane_request_id", + "original_post_authorization_tuple", + "target_namespace", + "canonical_tenant_id", + "canonical_game_instance_id", + "game_session_owner_attempt_id", + "game_session_owner_fence", + "preparation_input_json", + "preparation_input_digest", + "producer_xid", + "created_at"); + private static final Set SOURCE_COLUMNS = + Set.of("participation_id", "source_key", "source_evidence"); + private static final Set SETTLEMENT_COLUMNS = + Set.of( + "participation_id", + "outcome", + "world_execution_fence", + "terminal_bytes", + "terminal_digest", + "settled_at"); + private static final Set CAPTURE_COLUMNS = + Set.of( + "control_plane_request_id", + "account_uuid", + "tenant_uuid", + "target_owner", + "logging_workload_uri", + "reservation_owner_id", + "reservation_claim_fence", + "pre_authorization_tuple", + "mutation_digest", + "control_ui_operation_id", + "control_ui_token_jti", + "control_ui_token_hash", + "control_ui_signer_receipt_sha256", + "issuance_fence", + "issuance_fence_source_version", + "captured_at", + "snapshot_sha256", + "canonical_snapshot_bytes", + "source_version", + "source_fence", + "linearization", + "canonical_sha256", + "canonical_capture_bytes", + "created_at"); + private static final Set CAPTURE_SNAPSHOT_FIELDS = + Set.of( + "schema", + "controlPlaneRequestId", + "preAuthorizationTuple", + "mutationDigest", + "accountId", + "tenantId", + "targetOwner", + "loggingWorkloadUri", + "reservationOwnerId", + "reservationClaimFence", + "controlUiOperationId", + "controlUiTokenJti", + "controlUiTokenHash", + "controlUiSignerReceipt", + "controlUiSignerReceiptSha256", + "sourceVectorEvidence", + "sourceVector", + "outboxCheckpoints", + "authorityTuple", + "membershipVersion", + "accountIdentitySource", + "issuanceFence", + "issuanceFenceSourceVersion"); + private static final Set CAPTURE_REFERENCE_FIELDS = + Set.of("schema", "controlPlaneRequestId", "capturedAt", "bundleReference", "snapshotSha256"); + private static final Set BUNDLE_REFERENCE_FIELDS = + Set.of("bundleVersion", "sourceVersion", "sourceFence", "linearization"); + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Preserve the injected DSLContext precondition; this transactional Spring repository must remain proxyable, owns no resources, and declares no finalizer.") + public AccountStartSessionWorldParticipationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + } + + /** + * Inserts the exact participation and every child from the already retained source capture, or + * returns the immutable winner for an exact request retry. + * + *

Call only after the service has revalidated currentness, original redemption, and the exact + * capture inside {@code withCurrentCommitted}. The reference expiry check in V129 runs on an + * attempted insert; it cannot establish admission for a duplicate lookup. + */ + @Transactional(propagation = Propagation.MANDATORY) + public StoredParticipation createOrReadExact(Candidate candidate) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(candidate, "exact participation candidate is required"); + List expectedSources = + sourceVector(candidate.capture().snapshotBytes(), candidate.controlPlaneRequestId()); + requireCaptureMatches( + candidate.capture(), + candidate.originalTuple(), + selectCapture(candidate.controlPlaneRequestId(), true)); + + UUID proposedId = UUID.randomUUID(); + int inserted = + dsl.execute( + "INSERT INTO " + + PARTICIPATIONS + + " (participation_id, control_plane_request_id, original_post_authorization_tuple, " + + "target_namespace, canonical_tenant_id, canonical_game_instance_id, " + + "game_session_owner_attempt_id, game_session_owner_fence, preparation_input_json, " + + "preparation_input_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (control_plane_request_id) DO NOTHING", + proposedId, + candidate.controlPlaneRequestId(), + candidate.originalPostAuthorizationTuple(), + candidate.targetNamespace(), + candidate.canonicalTenantId(), + candidate.canonicalGameInstanceId(), + candidate.gameSessionOwnerAttemptId(), + candidate.gameSessionOwnerFence(), + candidate.preparationInputJson(), + candidate.preparationInputDigest()); + + if (inserted == 1) { + for (SourceEvidence source : expectedSources) { + dsl.execute( + "INSERT INTO " + + SOURCES + + " (participation_id, source_key, source_evidence) VALUES (?, ?, ?)", + proposedId, + source.key(), + source.canonicalBytes()); + } + } + + Record row = selectByRequestId(candidate.controlPlaneRequestId(), true); + if (row == null) throw unavailable(); + StoredParticipation stored = decodeParticipation(row, readSources(candidateId(row))); + requireSameCandidate(candidate, stored); + requireExactSources(expectedSources, stored.sources()); + if (inserted == 1 && !proposedId.equals(stored.participationId())) throw unavailable(); + if (readSettlement(stored.participationId()) != null) throw unavailable(); + return stored; + } + + /** + * Lookup-only read used after the caller independently establishes current Account authority. + * + *

This method never creates a capture or participation, never authenticates the peer, and + * refuses a settled participation. The currentness proof and capture lock belong to the + * surrounding service callback. + */ + @Transactional(propagation = Propagation.MANDATORY) + public java.util.Optional findCurrentExact(Candidate expected) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(expected, "exact current participation binding is required"); + List expectedSources = + sourceVector(expected.capture().snapshotBytes(), expected.controlPlaneRequestId()); + requireCaptureMatches( + expected.capture(), + expected.originalTuple(), + selectCapture(expected.controlPlaneRequestId(), false)); + Record row = selectByRequestId(expected.controlPlaneRequestId(), false); + if (row == null) return java.util.Optional.empty(); + StoredParticipation stored = decodeParticipation(row, readSources(candidateId(row))); + requireSameCandidate(expected, stored); + requireExactSources(expectedSources, stored.sources()); + if (readSettlement(stored.participationId()) != null) throw unavailable(); + return java.util.Optional.of(stored); + } + + /** + * Exact historical lookup for recovery only; it proves no fresh admission or expiry extension. + */ + @Transactional(propagation = Propagation.MANDATORY) + public java.util.Optional findHistoricalExact( + UUID participationId, long participationFence) { + requireWritableReadCommittedTransaction(); + requireNonnil(participationId, "participationId"); + requirePositive(participationFence, "participationFence"); + Record row = selectById(participationId, false); + if (row == null) return java.util.Optional.empty(); + StoredParticipation parent = decodeParticipation(row, List.of()); + if (parent.participationFence() != participationFence) throw unavailable(); + Record capture = selectCapture(parent.controlPlaneRequestId(), false); + List capturedSources = decodeHistoricalCapture(capture, parent); + List children = readSources(participationId); + requireExactSources(capturedSources, children); + return java.util.Optional.of(withSources(parent, children)); + } + + /** + * Resolves the retained World participation for the exact original StartSession tuple. + * + *

The canonical tuple's stable request identity is only a unique historical lookup key. The + * complete tuple is compared with the retained parent, and the historical Account capture and + * every source child are verified before its participation identity and fence are returned. This + * supplies coordinates only; callers must independently establish fresh Account currentness + * before using the result. + */ + @Transactional(propagation = Propagation.MANDATORY) + public java.util.Optional findHistoricalForOriginalTuple( + byte[] originalPostAuthorizationTuple) { + requireWritableReadCommittedTransaction(); + if (originalPostAuthorizationTuple == null || originalPostAuthorizationTuple.length == 0) { + throw unavailable(); + } + + StartSessionPostAuthorizationExecutionTuple expectedTuple; + try { + expectedTuple = + StartSessionPostAuthorizationExecutionTuple.decode(originalPostAuthorizationTuple); + } catch (RuntimeException malformed) { + throw unavailable(); + } + if (!Arrays.equals(originalPostAuthorizationTuple, expectedTuple.canonicalBytes())) { + throw unavailable(); + } + + String requestId = expectedTuple.controlPlaneRequestId(); + Record row = selectByRequestId(requestId, false); + if (row == null) return java.util.Optional.empty(); + + StoredParticipation parent = decodeParticipation(row, List.of()); + if (!MessageDigest.isEqual( + originalPostAuthorizationTuple, parent.originalPostAuthorizationTuple())) { + throw unavailable(); + } + List capturedSources = + decodeHistoricalCapture(selectCapture(requestId, false), parent); + List children = readSources(parent.participationId()); + requireExactSources(capturedSources, children); + return java.util.Optional.of(withSources(parent, children)); + } + + /** + * Lookup-only post-commit readback of an immutable terminal receipt for exact historical + * participation identity. + * + *

A missing participation or receipt returns empty. This does not admit a new operation, renew + * reference expiry, or require a current actor; it validates the retained historical parent, + * capture, complete source vector, and terminal binding only. It never inserts. + */ + @Transactional(propagation = Propagation.MANDATORY) + public java.util.Optional findSettlementExact( + UUID participationId, long participationFence) { + requireWritableReadCommittedTransaction(); + java.util.Optional participation = + findHistoricalExact(participationId, participationFence); + if (participation.isEmpty()) return java.util.Optional.empty(); + Record row = readSettlement(participationId); + if (row == null) return java.util.Optional.empty(); + return java.util.Optional.of(decodeSettlement(row, participation.orElseThrow())); + } + + /** + * Appends or reads back the exact typed terminal for an existing participation. + * + *

The caller authenticates the original World operation before invoking this method. This + * storage boundary accepts no raw outcome or fence and does not require a current actor or an + * unexpired reference; it only binds immutable historical identity and terminal bytes. + */ + @Transactional(propagation = Propagation.MANDATORY) + public StoredSettlement settleExact(WorldStartSessionExecutionTerminal terminal) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(terminal, "authenticated typed World terminal is required"); + StoredParticipation participation = + findHistoricalExact( + terminal.accountWorldParticipationId(), terminal.accountWorldParticipationFence()) + .orElseThrow(AccountStartSessionWorldParticipationRepository::unavailable); + requireTerminalMatches(participation, terminal); + + byte[] terminalBytes = terminal.canonicalBytes(); + dsl.execute( + "INSERT INTO " + + SETTLEMENTS + + " (participation_id, outcome, world_execution_fence, terminal_bytes, terminal_digest) " + + "VALUES (?, ?, ?, ?, ?) ON CONFLICT (participation_id) DO NOTHING", + participation.participationId(), + terminal.outcome().name(), + terminal.worldExecutionFence(), + terminalBytes, + terminal.digest()); + + Record row = readSettlement(participation.participationId()); + if (row == null) throw unavailable(); + StoredSettlement stored = decodeSettlement(row, participation); + requireSameTerminal(stored, terminal); + return stored; + } + + private Record selectByRequestId(String requestId, boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + PARTICIPATIONS + + " WHERE control_plane_request_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + requestId); + } + + private Record selectById(UUID id, boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + PARTICIPATIONS + + " WHERE participation_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + id); + } + + private Record selectCapture(String requestId, boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + CAPTURES + + " WHERE control_plane_request_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + requestId); + } + + private List readSources(UUID participationId) { + var rows = + dsl.fetch("SELECT * FROM " + SOURCES + " WHERE participation_id = ?", participationId); + List sources = new ArrayList<>(rows.size()); + for (Record row : rows) { + requireColumns(row, SOURCE_COLUMNS, "participation source"); + UUID storedId = typedUuid(row, "participation_id"); + String key = requiredString(row, "source_key"); + byte[] bytes = requiredBytes(row, "source_evidence"); + if (!participationId.equals(storedId)) throw unavailable(); + SourceEvidence source = decodeSource(key, bytes); + sources.add(source); + } + sources.sort(Comparator.comparing(SourceEvidence::key)); + if (sources.stream().map(SourceEvidence::key).distinct().count() != sources.size()) { + throw unavailable(); + } + return List.copyOf(sources); + } + + static StoredParticipation decodeParticipation(Record row, List sources) { + try { + requireColumns(row, PARTICIPATION_COLUMNS, "participation"); + UUID id = typedUuid(row, "participation_id"); + long fence = positive(number(row, "participation_fence"), "participation_fence"); + String requestId = requiredString(row, "control_plane_request_id"); + byte[] tupleBytes = requiredBytes(row, "original_post_authorization_tuple"); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(tupleBytes); + String namespace = requiredString(row, "target_namespace"); + UUID tenant = typedUuid(row, "canonical_tenant_id"); + UUID instance = typedUuid(row, "canonical_game_instance_id"); + UUID ownerAttempt = typedUuid(row, "game_session_owner_attempt_id"); + long ownerFence = + positive(number(row, "game_session_owner_fence"), "game_session_owner_fence"); + String preparationJson = requiredString(row, "preparation_input_json"); + String preparationDigest = requiredString(row, "preparation_input_digest"); + long producerXid = positive(number(row, "producer_xid"), "producer_xid"); + OffsetDateTime createdAt = + Objects.requireNonNull(row.get("created_at", OffsetDateTime.class)); + if (id.equals(NIL_UUID) + || !requestId.equals(tuple.controlPlaneRequestId()) + || !namespace.equals(tuple.preAuthorizationTuple().action().scope().targetNamespace()) + || !tenant.equals(tuple.preAuthorizationTuple().action().scope().tenantId()) + || !"game-session-service".equals(tuple.preAuthorizationTuple().targetOwner()) + || !PREPARATION_DIGEST.matcher(preparationDigest).matches() + || !preparationDigest.equals( + digestPrefixed(preparationJson.getBytes(StandardCharsets.UTF_8)))) { + throw unavailable(); + } + return new StoredParticipation( + id, + fence, + requestId, + tupleBytes, + namespace, + tenant, + instance, + ownerAttempt, + ownerFence, + preparationJson, + preparationDigest, + producerXid, + createdAt, + sources); + } catch (RuntimeException malformed) { + if (malformed instanceof IllegalStateException state + && "Exact StartSession World participation evidence unavailable" + .equals(state.getMessage())) { + throw state; + } + throw unavailable(); + } + } + + private static StoredParticipation withSources( + StoredParticipation parent, List sources) { + return new StoredParticipation( + parent.participationId(), + parent.participationFence(), + parent.controlPlaneRequestId(), + parent.originalPostAuthorizationTuple(), + parent.targetNamespace(), + parent.canonicalTenantId(), + parent.canonicalGameInstanceId(), + parent.gameSessionOwnerAttemptId(), + parent.gameSessionOwnerFence(), + parent.preparationInputJson(), + parent.preparationInputDigest(), + parent.producerXid(), + parent.createdAt(), + sources); + } + + private static List sourceVector(byte[] snapshotBytes, String requestId) { + Map snapshot = parseCanonicalObject(snapshotBytes, "Account capture snapshot"); + if (!CAPTURE_SNAPSHOT_FIELDS.equals(snapshot.keySet()) + || !"account-start-session-authority-snapshot/v1".equals(snapshot.get("schema")) + || !requestId.equals(snapshot.get("controlPlaneRequestId"))) { + throw unavailable(); + } + Object value = snapshot.get("sourceVector"); + if (!(value instanceof List encoded) || encoded.isEmpty()) throw unavailable(); + List sources = new ArrayList<>(encoded.size()); + Set keys = new HashSet<>(); + String previousKey = null; + for (Object element : encoded) { + if (!(element instanceof String base64)) throw unavailable(); + byte[] bytes = strictBase64(base64); + SourceEvidence source = SourceEvidence.fromStored(bytes); + if (bytes.length == 0 + || bytes.length > 131_072 + || !keys.add(source.key()) + || (previousKey != null && previousKey.compareTo(source.key()) >= 0)) { + throw unavailable(); + } + previousKey = source.key(); + sources.add(source); + } + return List.copyOf(sources); + } + + private static SourceEvidence decodeSource(String key, byte[] bytes) { + try { + SourceEvidence source = SourceEvidence.fromStored(bytes); + if (!key.equals(source.key()) || bytes.length > 131_072) throw unavailable(); + return source; + } catch (RuntimeException malformed) { + throw unavailable(); + } + } + + private static void requireCaptureMatches( + AccountStartSessionAuthorityCapture capture, + StartSessionPostAuthorizationExecutionTuple tuple, + Record retainedRow) { + Objects.requireNonNull(capture, "exact retained Account capture is required"); + Objects.requireNonNull(tuple, "exact original StartSession tuple is required"); + if (!capture.controlPlaneRequestId().equals(tuple.controlPlaneRequestId())) throw conflict(); + if (retainedRow == null) throw unavailable(); + Map snapshot = + parseCanonicalObject(capture.snapshotBytes(), "Account capture snapshot"); + if (!CAPTURE_SNAPSHOT_FIELDS.equals(snapshot.keySet()) + || !"account-start-session-authority-snapshot/v1".equals(snapshot.get("schema")) + || !tuple.controlPlaneRequestId().equals(snapshot.get("controlPlaneRequestId")) + || !Base64.getEncoder() + .encodeToString( + tuple.preAuthorizationTuple().canonicalJson().getBytes(StandardCharsets.UTF_8)) + .equals(snapshot.get("preAuthorizationTuple")) + || !tuple.mutationDigest().equals(snapshot.get("mutationDigest")) + || !tuple + .preAuthorizationTuple() + .actor() + .accountId() + .toString() + .equals(snapshot.get("accountId")) + || !tuple + .preAuthorizationTuple() + .action() + .scope() + .tenantId() + .toString() + .equals(snapshot.get("tenantId")) + || !"game-session-service".equals(snapshot.get("targetOwner")) + || !tuple.authenticatedWorkloadIdentity().equals(snapshot.get("loggingWorkloadUri")) + || !tuple.reservationOwnerId().toString().equals(snapshot.get("reservationOwnerId")) + || !Long.toString(tuple.reservationClaimFence()) + .equals(snapshot.get("reservationClaimFence")) + || !tuple.issuanceFence().equals(snapshot.get("issuanceFence")) + || !capture.bundleReference().equals(tuple.bundleReference())) { + throw conflict(); + } + sourceVector(capture.snapshotBytes(), tuple.controlPlaneRequestId()); + requireCaptureRow(retainedRow, capture, tuple, snapshot); + } + + private static void requireCaptureRow( + Record row, + AccountStartSessionAuthorityCapture capture, + StartSessionPostAuthorizationExecutionTuple tuple, + Map snapshot) { + requireColumns(row, CAPTURE_COLUMNS, "Account capture"); + requireCaptureColumnsMatchSnapshot(row, snapshot); + OffsetDateTime capturedAt = requiredTimestamp(row, "captured_at"); + if (!tuple.controlPlaneRequestId().equals(requiredString(row, "control_plane_request_id")) + || !Instant.parse(capture.capturedAt()).equals(capturedAt.toInstant()) + || !capture.controlPlaneRequestId().equals(requiredString(row, "control_plane_request_id")) + || capture.sourceVersion() != number(row, "source_version") + || capture.sourceFence() != number(row, "source_fence") + || !capture.linearization().equals(requiredString(row, "linearization")) + || !capture.snapshotSha256().equals(requiredString(row, "snapshot_sha256")) + || !Arrays.equals(capture.snapshotBytes(), requiredBytes(row, "canonical_snapshot_bytes")) + || !capture.canonicalSha256().equals(requiredString(row, "canonical_sha256")) + || !Arrays.equals( + capture.canonicalBytes(), requiredBytes(row, "canonical_capture_bytes"))) { + throw unavailable(); + } + } + + private static void requireCaptureColumnsMatchSnapshot(Record row, Map snapshot) { + if (!Objects.equals(requiredUuidString(row, "account_uuid"), snapshot.get("accountId")) + || !Objects.equals(requiredUuidString(row, "tenant_uuid"), snapshot.get("tenantId")) + || !Objects.equals(requiredString(row, "target_owner"), snapshot.get("targetOwner")) + || !Objects.equals( + requiredString(row, "logging_workload_uri"), snapshot.get("loggingWorkloadUri")) + || !Objects.equals( + requiredUuidString(row, "reservation_owner_id"), snapshot.get("reservationOwnerId")) + || !Objects.equals( + Long.toString(number(row, "reservation_claim_fence")), + snapshot.get("reservationClaimFence")) + || !Arrays.equals( + requiredBytes(row, "pre_authorization_tuple"), + strictBase64(string(snapshot.get("preAuthorizationTuple")))) + || !Objects.equals(requiredString(row, "mutation_digest"), snapshot.get("mutationDigest")) + || !Objects.equals( + requiredUuidString(row, "control_ui_operation_id"), + snapshot.get("controlUiOperationId")) + || !Objects.equals( + requiredUuidString(row, "control_ui_token_jti"), snapshot.get("controlUiTokenJti")) + || !Objects.equals( + requiredString(row, "control_ui_token_hash"), snapshot.get("controlUiTokenHash")) + || !Objects.equals( + requiredString(row, "control_ui_signer_receipt_sha256"), + snapshot.get("controlUiSignerReceiptSha256")) + || !Objects.equals( + Long.toString(number(row, "issuance_fence")), snapshot.get("issuanceFence")) + || !Objects.equals( + Long.toString(number(row, "issuance_fence_source_version")), + snapshot.get("issuanceFenceSourceVersion"))) { + throw unavailable(); + } + byte[] receipt = strictBase64(string(snapshot.get("controlUiSignerReceipt"))); + if (!digestHex(receipt).equals(snapshot.get("controlUiSignerReceiptSha256"))) + throw unavailable(); + } + + private static List decodeHistoricalCapture( + Record row, StoredParticipation parent) { + requireColumns(row, CAPTURE_COLUMNS, "Account capture"); + byte[] snapshotBytes = requiredBytes(row, "canonical_snapshot_bytes"); + byte[] canonicalCaptureBytes = requiredBytes(row, "canonical_capture_bytes"); + if (!digestHex(snapshotBytes).equals(requiredString(row, "snapshot_sha256")) + || !digestHex(canonicalCaptureBytes).equals(requiredString(row, "canonical_sha256"))) { + throw unavailable(); + } + Map snapshot = parseCanonicalObject(snapshotBytes, "Account capture snapshot"); + Map reference = + parseCanonicalObject(canonicalCaptureBytes, "Account capture reference"); + if (!CAPTURE_SNAPSHOT_FIELDS.equals(snapshot.keySet()) + || !CAPTURE_REFERENCE_FIELDS.equals(reference.keySet()) + || !"account-start-session-authority-snapshot/v1".equals(snapshot.get("schema")) + || !"account-start-session-authority-capture/v1".equals(reference.get("schema")) + || !parent.controlPlaneRequestId().equals(requiredString(row, "control_plane_request_id")) + || !parent.controlPlaneRequestId().equals(snapshot.get("controlPlaneRequestId")) + || !parent.controlPlaneRequestId().equals(reference.get("controlPlaneRequestId")) + || !requiredString(row, "snapshot_sha256").equals(reference.get("snapshotSha256")) + || !CAPTURED_AT.matcher(string(reference.get("capturedAt"))).matches() + || !Instant.parse(string(reference.get("capturedAt"))) + .equals(requiredTimestamp(row, "captured_at").toInstant()) + || !referenceMatchesCaptureRow(reference, row)) { + throw unavailable(); + } + requireCaptureColumnsMatchSnapshot(row, snapshot); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(parent.originalPostAuthorizationTuple()); + if (!Base64.getEncoder() + .encodeToString( + tuple.preAuthorizationTuple().canonicalJson().getBytes(StandardCharsets.UTF_8)) + .equals(snapshot.get("preAuthorizationTuple")) + || !tuple.mutationDigest().equals(snapshot.get("mutationDigest")) + || !tuple + .preAuthorizationTuple() + .actor() + .accountId() + .toString() + .equals(snapshot.get("accountId")) + || !parent.canonicalTenantId().toString().equals(snapshot.get("tenantId")) + || !tuple.authenticatedWorkloadIdentity().equals(snapshot.get("loggingWorkloadUri")) + || !tuple.reservationOwnerId().toString().equals(snapshot.get("reservationOwnerId")) + || !Long.toString(tuple.reservationClaimFence()) + .equals(snapshot.get("reservationClaimFence")) + || !tuple.issuanceFence().equals(snapshot.get("issuanceFence")) + || !tuple.preAuthorizationTuple().targetOwner().equals(snapshot.get("targetOwner")) + || !referenceMatchesTuple(reference, tuple) + || !parent + .targetNamespace() + .equals(tuple.preAuthorizationTuple().action().scope().targetNamespace()) + || !parent + .canonicalTenantId() + .equals(tuple.preAuthorizationTuple().action().scope().tenantId())) { + throw unavailable(); + } + return sourceVector(snapshotBytes, parent.controlPlaneRequestId()); + } + + private static boolean referenceMatchesCaptureRow(Map reference, Record row) { + Object bundleValue = reference.get("bundleReference"); + if (!(bundleValue instanceof Map bundle) + || !BUNDLE_REFERENCE_FIELDS.equals(bundle.keySet())) return false; + return StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION.equals(bundle.get("bundleVersion")) + && Long.toString(number(row, "source_version")).equals(bundle.get("sourceVersion")) + && Long.toString(number(row, "source_fence")).equals(bundle.get("sourceFence")) + && requiredString(row, "linearization").equals(bundle.get("linearization")); + } + + private static boolean referenceMatchesTuple( + Map reference, StartSessionPostAuthorizationExecutionTuple tuple) { + Object bundleValue = reference.get("bundleReference"); + if (!(bundleValue instanceof Map bundle)) return false; + var expected = tuple.bundleReference(); + return expected.bundleVersion().equals(bundle.get("bundleVersion")) + && expected.sourceVersion().equals(bundle.get("sourceVersion")) + && expected.sourceFence().equals(bundle.get("sourceFence")) + && expected.linearization().equals(bundle.get("linearization")); + } + + static void requireSameCandidate(Candidate candidate, StoredParticipation stored) { + if (!candidate.controlPlaneRequestId().equals(stored.controlPlaneRequestId()) + || !Arrays.equals( + candidate.originalPostAuthorizationTuple(), stored.originalPostAuthorizationTuple()) + || !candidate.targetNamespace().equals(stored.targetNamespace()) + || !candidate.canonicalTenantId().equals(stored.canonicalTenantId()) + || !candidate.canonicalGameInstanceId().equals(stored.canonicalGameInstanceId()) + || !candidate.gameSessionOwnerAttemptId().equals(stored.gameSessionOwnerAttemptId()) + || candidate.gameSessionOwnerFence() != stored.gameSessionOwnerFence() + || !candidate.preparationInputJson().equals(stored.preparationInputJson()) + || !candidate.preparationInputDigest().equals(stored.preparationInputDigest())) { + throw conflict(); + } + } + + static void requireExactSources(List expected, List actual) { + if (expected == null + || actual == null + || expected.isEmpty() + || expected.size() != actual.size()) { + throw unavailable(); + } + List expectedSorted = + expected.stream().sorted(Comparator.comparing(SourceEvidence::key)).toList(); + List actualSorted = + actual.stream().sorted(Comparator.comparing(SourceEvidence::key)).toList(); + Set expectedKeys = new HashSet<>(); + for (int index = 0; index < expectedSorted.size(); index++) { + SourceEvidence left = expectedSorted.get(index); + SourceEvidence right = actualSorted.get(index); + if (!expectedKeys.add(left.key()) + || !left.key().equals(right.key()) + || !Arrays.equals(left.canonicalBytes(), right.canonicalBytes())) { + throw unavailable(); + } + } + } + + static void requireTerminalMatches( + StoredParticipation participation, WorldStartSessionExecutionTerminal terminal) { + if (!participation.participationId().equals(terminal.accountWorldParticipationId()) + || participation.participationFence() != terminal.accountWorldParticipationFence() + || !Arrays.equals( + participation.originalPostAuthorizationTuple(), + terminal.originalPostAuthorizationTuple()) + || !participation.gameSessionOwnerAttemptId().equals(terminal.gameSessionOwnerAttemptId()) + || participation.gameSessionOwnerFence() != terminal.gameSessionOwnerFence() + || !participation.targetNamespace().equals(terminal.targetNamespace()) + || !participation.canonicalTenantId().equals(terminal.canonicalTenantId()) + || !participation.controlPlaneRequestId().equals(terminal.controlPlaneRequestId()) + || !participation.canonicalGameInstanceId().equals(terminal.canonicalGameInstanceId()) + || !participation.preparationInputDigest().equals(terminal.preparationInputDigest()) + || !participation.preparationInputJson().equals(terminal.preparationInputJson())) { + throw conflict(); + } + } + + private Record readSettlement(UUID participationId) { + return dsl.fetchOne( + "SELECT * FROM " + SETTLEMENTS + " WHERE participation_id = ?", participationId); + } + + private static StoredSettlement decodeSettlement(Record row, StoredParticipation participation) { + try { + requireColumns(row, SETTLEMENT_COLUMNS, "participation settlement"); + UUID id = typedUuid(row, "participation_id"); + String outcomeValue = requiredString(row, "outcome"); + WorldStartSessionExecutionTerminal.Outcome outcome = + WorldStartSessionExecutionTerminal.Outcome.valueOf(outcomeValue); + long worldFence = positive(number(row, "world_execution_fence"), "world_execution_fence"); + byte[] terminalBytes = requiredBytes(row, "terminal_bytes"); + String terminalDigest = requiredString(row, "terminal_digest"); + OffsetDateTime settledAt = requiredTimestamp(row, "settled_at"); + if (!id.equals(participation.participationId()) + || !PREPARATION_DIGEST.matcher(terminalDigest).matches() + || !terminalDigest.equals(digestPrefixed(terminalBytes))) { + throw unavailable(); + } + WorldStartSessionExecutionTerminal terminal = + WorldStartSessionExecutionTerminal.fromStored(terminalBytes); + requireTerminalMatches(participation, terminal); + if (terminal.outcome() != outcome || terminal.worldExecutionFence() != worldFence) { + throw unavailable(); + } + return new StoredSettlement( + id, outcome, worldFence, terminalBytes, terminalDigest, settledAt); + } catch (RuntimeException malformed) { + throw unavailable(); + } + } + + private static void requireSameTerminal( + StoredSettlement stored, WorldStartSessionExecutionTerminal terminal) { + if (stored.outcome() != terminal.outcome() + || stored.worldExecutionFence() != terminal.worldExecutionFence() + || !stored.terminalDigest().equals(terminal.digest()) + || !Arrays.equals(stored.terminalBytes(), terminal.canonicalBytes())) { + throw conflict(); + } + } + + private static Map parseCanonicalObject(byte[] bytes, String field) { + try { + String json = strictUtf8(bytes); + if (!Arrays.equals(Rfc8785CanonicalJson.canonicalizeUtf8(json), bytes)) throw unavailable(); + Object decoded = JSON.readValue(json, Object.class); + if (!(decoded instanceof Map raw)) throw unavailable(); + Map result = new LinkedHashMap<>(); + for (Map.Entry entry : raw.entrySet()) { + if (!(entry.getKey() instanceof String key)) throw unavailable(); + result.put(key, entry.getValue()); + } + return Map.copyOf(result); + } catch (RuntimeException | java.io.IOException malformed) { + throw unavailable(); + } + } + + private static byte[] strictBase64(String value) { + try { + byte[] decoded = Base64.getDecoder().decode(value); + if (!Base64.getEncoder().encodeToString(decoded).equals(value)) throw unavailable(); + return decoded; + } catch (IllegalArgumentException malformed) { + throw unavailable(); + } + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException malformed) { + throw unavailable(); + } + } + + private static void requireColumns(Record row, Set expected, String kind) { + if (row == null) throw unavailable(); + Set actual = new HashSet<>(); + Arrays.stream(row.fields()).forEach(field -> actual.add(field.getName())); + if (!actual.equals(expected)) throw unavailable(); + } + + private static UUID candidateId(Record row) { + return typedUuid(row, "participation_id"); + } + + private static UUID typedUuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + if (value == null || value.equals(NIL_UUID)) throw unavailable(); + return value; + } + + private static String requiredUuidString(Record row, String field) { + return typedUuid(row, field).toString(); + } + + private static String requiredString(Record row, String field) { + String value = row.get(field, String.class); + if (value == null) throw unavailable(); + return value; + } + + private static byte[] requiredBytes(Record row, String field) { + byte[] value = row.get(field, byte[].class); + if (value == null) throw unavailable(); + return value.clone(); + } + + private static OffsetDateTime requiredTimestamp(Record row, String field) { + OffsetDateTime value = row.get(field, OffsetDateTime.class); + if (value == null) throw unavailable(); + return value; + } + + private static long number(Record row, String field) { + Long value = row.get(field, Long.class); + if (value == null) throw unavailable(); + return value; + } + + private static long positive(long value, String field) { + if (value <= 0L) throw unavailable(); + return value; + } + + private static void requirePositive(long value, String field) { + if (value <= 0L) throw new IllegalArgumentException(field + " must be positive"); + } + + private static void requireNonnil(UUID value, String field) { + if (value == null || value.equals(NIL_UUID)) + throw new IllegalArgumentException(field + " must be nonnil"); + } + + private static String string(Object value) { + if (!(value instanceof String text)) throw unavailable(); + return text; + } + + private static String digestPrefixed(byte[] bytes) { + return "sha256:" + digestHex(bytes); + } + + private static String digestHex(byte[] bytes) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private void requireWritableReadCommittedTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); + } + Integer declaredIsolation = + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (declaredIsolation != null && declaredIsolation != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); + } + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); + } + }); + } + + private static IllegalStateException conflict() { + return new IllegalStateException( + "StartSession World participation conflicts with its immutable binding"); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Exact StartSession World participation evidence unavailable"); + } + + public record Candidate( + StartSessionPostAuthorizationExecutionTuple originalTuple, + AccountStartSessionAuthorityCapture capture, + UUID canonicalGameInstanceId, + UUID gameSessionOwnerAttemptId, + long gameSessionOwnerFence, + String preparationInputJson, + String preparationInputDigest) { + public Candidate { + Objects.requireNonNull(originalTuple, "typed original StartSession tuple is required"); + Objects.requireNonNull(capture, "exact retained Account capture is required"); + requireNonnil(canonicalGameInstanceId, "canonicalGameInstanceId"); + requireNonnil(gameSessionOwnerAttemptId, "gameSessionOwnerAttemptId"); + requirePositive(gameSessionOwnerFence, "gameSessionOwnerFence"); + Objects.requireNonNull(preparationInputJson, "exact preparation input JSON is required"); + Objects.requireNonNull(preparationInputDigest, "preparation input digest is required"); + if (!"StartSession".equals(originalTuple.preAuthorizationTuple().actionFamily()) + || !"game-session-service".equals(originalTuple.preAuthorizationTuple().targetOwner()) + || !capture.controlPlaneRequestId().equals(originalTuple.controlPlaneRequestId()) + || preparationInputJson.isBlank() + || !StandardCharsets.UTF_8.newEncoder().canEncode(preparationInputJson) + || preparationInputJson.getBytes(StandardCharsets.UTF_8).length + > WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES + || !PREPARATION_DIGEST.matcher(preparationInputDigest).matches() + || !digestPrefixed(preparationInputJson.getBytes(StandardCharsets.UTF_8)) + .equals(preparationInputDigest)) { + throw new IllegalArgumentException( + "StartSession World participation candidate is malformed"); + } + sourceVector(capture.snapshotBytes(), originalTuple.controlPlaneRequestId()); + } + + public byte[] originalPostAuthorizationTuple() { + return originalTuple.canonicalBytes(); + } + + public String controlPlaneRequestId() { + return originalTuple.controlPlaneRequestId(); + } + + public String targetNamespace() { + return originalTuple.preAuthorizationTuple().action().scope().targetNamespace(); + } + + public UUID canonicalTenantId() { + return originalTuple.preAuthorizationTuple().action().scope().tenantId(); + } + + @Override + public String toString() { + return "Candidate[requestId=" + controlPlaneRequestId() + ", preparationInput=]"; + } + } + + public record StoredParticipation( + UUID participationId, + long participationFence, + String controlPlaneRequestId, + byte[] originalPostAuthorizationTuple, + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalGameInstanceId, + UUID gameSessionOwnerAttemptId, + long gameSessionOwnerFence, + String preparationInputJson, + String preparationInputDigest, + long producerXid, + OffsetDateTime createdAt, + List sources) { + public StoredParticipation { + requireNonnil(participationId, "participationId"); + requirePositive(participationFence, "participationFence"); + Objects.requireNonNull(controlPlaneRequestId); + originalPostAuthorizationTuple = originalPostAuthorizationTuple.clone(); + requireNonnil(canonicalTenantId, "canonicalTenantId"); + requireNonnil(canonicalGameInstanceId, "canonicalGameInstanceId"); + requireNonnil(gameSessionOwnerAttemptId, "gameSessionOwnerAttemptId"); + requirePositive(gameSessionOwnerFence, "gameSessionOwnerFence"); + requirePositive(producerXid, "producerXid"); + Objects.requireNonNull(preparationInputJson); + Objects.requireNonNull(preparationInputDigest); + Objects.requireNonNull(createdAt); + sources = List.copyOf(sources); + } + + @Override + public byte[] originalPostAuthorizationTuple() { + return originalPostAuthorizationTuple.clone(); + } + + @Override + public String toString() { + return "StoredParticipation[id=" + + participationId + + ", fence=" + + participationFence + + ", requestId=" + + controlPlaneRequestId + + ", sources=" + + sources.size() + + "]"; + } + + public List sourceVector() { + return sources; + } + } + + public record StoredSettlement( + UUID participationId, + WorldStartSessionExecutionTerminal.Outcome outcome, + long worldExecutionFence, + byte[] terminalBytes, + String terminalDigest, + OffsetDateTime settledAt) { + public StoredSettlement { + requireNonnil(participationId, "participationId"); + Objects.requireNonNull(outcome); + requirePositive(worldExecutionFence, "worldExecutionFence"); + terminalBytes = terminalBytes.clone(); + Objects.requireNonNull(terminalDigest); + Objects.requireNonNull(settledAt); + } + + @Override + public byte[] terminalBytes() { + return terminalBytes.clone(); + } + + @Override + public String toString() { + return "StoredSettlement[id=" + + participationId + + ", outcome=" + + outcome + + ", fence=" + + worldExecutionFence + + "]"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcService.java index 278e50a59a..b1361a8722 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcService.java @@ -25,7 +25,6 @@ import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationRequest; import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationResponse; import net.firedevops.firemud.account.v1.StartSessionOperatorAuthorizationServiceGrpc; -import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.RedemptionResult; import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.KeyUnavailableException; import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography.CryptographyUnavailableException; import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography.ResponseRecoveryExpiredException; @@ -37,7 +36,10 @@ import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RecoverRequest; import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RedeemRequest; import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RedeemedOperationProjection; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RedemptionResult; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import net.firedevops.firemud.common.security.SessionContext; import org.jooq.exception.DataAccessException; @@ -60,6 +62,8 @@ public final class StartSessionOperatorAuthorizationGrpcService private static final int MAX_CONTROL_UI_JWT_BYTES = 16 * 1024; private static final int MAX_AUTHORIZATION_REFERENCE_BYTES = 128; private static final int MAX_AUTHORITY_EVIDENCE_BUNDLE_BYTES = 128 * 1024; + private static final int MAX_POST_AUTHORIZATION_TUPLE_BYTES = + StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES; private static final int MAX_FINGERPRINT_BYTES = 137; private static final UUID NIL_UUID = new UUID(0L, 0L); private static final String AUTHORIZATION_REFERENCE = "[A-Za-z0-9_-]{43}"; @@ -169,11 +173,11 @@ public void redeemOperatorAuthorization( public void readRedeemedOperationProjection( ReadRedeemedOperationProjectionRequest request, StreamObserver responseObserver) { - if (!isAllowedPeer("game-design-service")) { + if (!isAllowedPeer("game-design-service") && !isAllowedPeer("game-session-service")) { fail( responseObserver, Status.PERMISSION_DENIED, - "Verified same-namespace Game Design workload identity is required"); + "Verified same-namespace Game Design or Game Session workload identity is required"); return; } @@ -383,7 +387,7 @@ private static void rejectUnknownFields(boolean requestHasNoUnknownFields) { private static IssueHumanOperatorAuthorizationReferenceResponse toIssueResponse( AuthorizationResponse response, String authenticatedLoggingWorkloadIdentity) { - requireResponse(response); + requireResponse(response, authenticatedLoggingWorkloadIdentity); return IssueHumanOperatorAuthorizationReferenceResponse.newBuilder() .setOperatorAuthorizationReference(response.operatorAuthorizationReference()) .setAuthorizationReferenceFingerprint(response.authorizationReferenceFingerprint()) @@ -391,12 +395,14 @@ private static IssueHumanOperatorAuthorizationReferenceResponse toIssueResponse( .setAuthorityEvidenceBundle(ByteString.copyFrom(response.authorityEvidenceBundle())) .setBundleReference(toWireBundleReference(response.bundleReference())) .setAuthenticatedLoggingWorkloadIdentity(authenticatedLoggingWorkloadIdentity) + .setOriginalAccountPostAuthorizationTuple( + ByteString.copyFrom(response.originalAccountPostAuthorizationTuple())) .build(); } private static RecoverOperatorAuthorizationReferenceResponse toRecoverResponse( AuthorizationResponse response, String authenticatedLoggingWorkloadIdentity) { - requireResponse(response); + requireResponse(response, authenticatedLoggingWorkloadIdentity); return RecoverOperatorAuthorizationReferenceResponse.newBuilder() .setOperatorAuthorizationReference(response.operatorAuthorizationReference()) .setAuthorizationReferenceFingerprint(response.authorizationReferenceFingerprint()) @@ -404,10 +410,13 @@ private static RecoverOperatorAuthorizationReferenceResponse toRecoverResponse( .setAuthorityEvidenceBundle(ByteString.copyFrom(response.authorityEvidenceBundle())) .setBundleReference(toWireBundleReference(response.bundleReference())) .setAuthenticatedLoggingWorkloadIdentity(authenticatedLoggingWorkloadIdentity) + .setOriginalAccountPostAuthorizationTuple( + ByteString.copyFrom(response.originalAccountPostAuthorizationTuple())) .build(); } - private static void requireResponse(AuthorizationResponse response) { + private static void requireResponse( + AuthorizationResponse response, String authenticatedLoggingWorkloadIdentity) { if (response == null || response.operatorAuthorizationReference() == null || response.operatorAuthorizationReference().getBytes(StandardCharsets.UTF_8).length @@ -424,10 +433,35 @@ private static void requireResponse(AuthorizationResponse response) { || response.authorityEvidenceBundle() == null || response.authorityEvidenceBundle().length == 0 || response.authorityEvidenceBundle().length > MAX_AUTHORITY_EVIDENCE_BUNDLE_BYTES - || response.bundleReference() == null) { + || response.bundleReference() == null + || response.originalAccountPostAuthorizationTuple() == null + || response.originalAccountPostAuthorizationTuple().length == 0 + || response.originalAccountPostAuthorizationTuple().length + > MAX_POST_AUTHORIZATION_TUPLE_BYTES) { throw new IllegalStateException( "Account produced an invalid StartSession authorization result"); } + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode( + response.originalAccountPostAuthorizationTuple()); + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(response.authorityEvidenceBundle()); + bundle.requireTupleBinding(tuple.preAuthorizationTuple()); + bundle.requireReferenceBinding(tuple.bundleReference()); + var tupleReference = tuple.bundleReference(); + BundleReference responseReference = response.bundleReference(); + if (!tuple + .authorizationReferenceFingerprint() + .equals(response.authorizationReferenceFingerprint()) + || !Arrays.equals(tuple.authorityEvidenceBundleBytes(), bundle.canonicalBytes()) + || !tupleReference.bundleVersion().equals(responseReference.bundleVersion()) + || !tupleReference.sourceVersion().equals(responseReference.sourceVersion()) + || !tupleReference.sourceFence().equals(responseReference.sourceFence()) + || !tupleReference.linearization().equals(responseReference.linearization()) + || !tuple.authenticatedWorkloadIdentity().equals(authenticatedLoggingWorkloadIdentity)) { + throw new IllegalStateException( + "Account authorization result differs from its original owner tuple"); + } } private static AuthorityEvidenceBundleReference toWireBundleReference(BundleReference reference) { @@ -453,15 +487,34 @@ private static RedeemOperatorAuthorizationResponse toRedeemResponse(RedemptionRe || result.authorityEvidenceBundle().length > MAX_AUTHORITY_EVIDENCE_BUNDLE_BYTES || result.issuanceOperationId() == null || NIL_UUID.equals(result.issuanceOperationId()) - || result.issuanceFence() <= 0L) { + || result.issuanceFence() <= 0L + || result.originalAccountPostAuthorizationTuple() == null + || result.originalAccountPostAuthorizationTuple().length == 0 + || result.originalAccountPostAuthorizationTuple().length + > MAX_POST_AUTHORIZATION_TUPLE_BYTES) { throw new IllegalStateException("Account produced an invalid StartSession redemption result"); } + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode( + result.originalAccountPostAuthorizationTuple()); + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(result.authorityEvidenceBundle()); + if (!tuple + .authorizationReferenceFingerprint() + .equals(result.authorizationReferenceFingerprint()) + || !Arrays.equals(tuple.authorityEvidenceBundleBytes(), bundle.canonicalBytes()) + || !Long.toString(result.issuanceFence()).equals(bundle.issuanceFence()) + || !result.issuanceOperationId().equals(bundle.issuanceOperationId())) { + throw new IllegalStateException("Account redemption differs from its original owner tuple"); + } return RedeemOperatorAuthorizationResponse.newBuilder() .setAuthorizationReferenceFingerprint(result.authorizationReferenceFingerprint()) .setAuthorityEvidenceBundle(ByteString.copyFrom(result.authorityEvidenceBundle())) .setIssuanceOperationId(result.issuanceOperationId().toString()) .setIssuanceFence(result.issuanceFence()) .setReplay(result.replay()) + .setOriginalAccountPostAuthorizationTuple( + ByteString.copyFrom(result.originalAccountPostAuthorizationTuple())) .build(); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapture.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapture.java new file mode 100644 index 0000000000..55037841b9 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapture.java @@ -0,0 +1,316 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.Arrays; +import java.util.Objects; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle.BundleReference; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Immutable full Account source capture retained before StartSession private cryptography. */ +public final class AccountStartSessionAuthorityCapture { + public static final String SCHEMA = "account-start-session-authority-capture/v1"; + public static final int MAX_CAPTURE_BYTES = 256 * 1024; + public static final int MAX_SNAPSHOT_BYTES = 240 * 1024; + + private static final Pattern POSITIVE_U64 = Pattern.compile("[1-9][0-9]{0,19}"); + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final DateTimeFormatter CAPTURED_AT_FORMAT = + DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final String controlPlaneRequestId; + private final long sourceVersion; + private final long sourceFence; + private final String linearization; + private final String capturedAt; + private final byte[] snapshotBytes; + private final String snapshotSha256; + private final byte[] canonicalBytes; + private final String canonicalSha256; + + private AccountStartSessionAuthorityCapture( + String controlPlaneRequestId, + long sourceVersion, + long sourceFence, + String linearization, + String capturedAt, + byte[] snapshotBytes, + String snapshotSha256, + byte[] canonicalBytes, + String canonicalSha256) { + this.controlPlaneRequestId = + StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId( + controlPlaneRequestId); + this.sourceVersion = positive(sourceVersion, "capture sourceVersion"); + this.sourceFence = positive(sourceFence, "capture sourceFence"); + this.linearization = requireU64(linearization, "capture linearization"); + this.capturedAt = requireCapturedAt(capturedAt); + this.snapshotBytes = bounded(snapshotBytes, MAX_SNAPSHOT_BYTES, "source snapshot"); + this.snapshotSha256 = requireDigest(snapshotSha256, "source snapshot SHA-256"); + this.canonicalBytes = bounded(canonicalBytes, MAX_CAPTURE_BYTES, "capture reference"); + this.canonicalSha256 = requireDigest(canonicalSha256, "capture SHA-256"); + if (!this.snapshotSha256.equals(sha256(this.snapshotBytes)) + || !this.canonicalSha256.equals(sha256(this.canonicalBytes))) { + throw invalid("Capture bytes do not match their retained digests"); + } + requireCanonicalJson(this.snapshotBytes, "source snapshot"); + requireCanonicalJson(this.canonicalBytes, "capture reference"); + var reference = bundleReference(); + requireReferenceEnvelope( + this.canonicalBytes, + this.controlPlaneRequestId, + this.capturedAt, + reference, + this.snapshotSha256); + } + + static AccountStartSessionAuthorityCapture create( + String controlPlaneRequestId, + long sourceVersion, + long sourceFence, + String linearization, + String capturedAt, + byte[] snapshotBytes) { + String snapshotDigest = sha256(snapshotBytes); + BundleReference reference = + new BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + Long.toString(sourceVersion), + Long.toString(sourceFence), + linearization); + byte[] referenceBytes = + AccountControlUiAuthority.canonical( + java.util.Map.of( + "schema", SCHEMA, + "controlPlaneRequestId", controlPlaneRequestId, + "capturedAt", capturedAt, + "bundleReference", + java.util.Map.of( + "bundleVersion", reference.bundleVersion(), + "sourceVersion", reference.sourceVersion(), + "sourceFence", reference.sourceFence(), + "linearization", reference.linearization()), + "snapshotSha256", snapshotDigest)); + return new AccountStartSessionAuthorityCapture( + controlPlaneRequestId, + sourceVersion, + sourceFence, + linearization, + capturedAt, + snapshotBytes, + snapshotDigest, + referenceBytes, + sha256(referenceBytes)); + } + + static AccountStartSessionAuthorityCapture fromStorage( + String controlPlaneRequestId, + Long sourceVersion, + Long sourceFence, + String linearization, + String capturedAt, + byte[] snapshotBytes, + String snapshotSha256, + byte[] canonicalBytes, + String canonicalSha256) { + if (sourceVersion == null || sourceFence == null) { + throw invalid("Stored capture version or fence is absent"); + } + return new AccountStartSessionAuthorityCapture( + controlPlaneRequestId, + sourceVersion, + sourceFence, + linearization, + capturedAt, + snapshotBytes, + snapshotSha256, + canonicalBytes, + canonicalSha256); + } + + public String controlPlaneRequestId() { + return controlPlaneRequestId; + } + + public long sourceVersion() { + return sourceVersion; + } + + public long sourceFence() { + return sourceFence; + } + + public String linearization() { + return linearization; + } + + public String capturedAt() { + return capturedAt; + } + + public BundleReference bundleReference() { + return new BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + Long.toString(sourceVersion), + Long.toString(sourceFence), + linearization); + } + + public byte[] snapshotBytes() { + return snapshotBytes.clone(); + } + + public String snapshotSha256() { + return snapshotSha256; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String canonicalSha256() { + return canonicalSha256; + } + + boolean sameSnapshot(AccountStartSessionAuthorityCapture other) { + return other != null + && controlPlaneRequestId.equals(other.controlPlaneRequestId) + && MessageDigest.isEqual(snapshotBytes, other.snapshotBytes) + && snapshotSha256.equals(other.snapshotSha256); + } + + boolean sameStoredValue(AccountStartSessionAuthorityCapture other) { + return sameSnapshot(other) + && sourceVersion == other.sourceVersion + && sourceFence == other.sourceFence + && linearization.equals(other.linearization) + && capturedAt.equals(other.capturedAt) + && MessageDigest.isEqual(canonicalBytes, other.canonicalBytes) + && canonicalSha256.equals(other.canonicalSha256); + } + + private static void requireReferenceEnvelope( + byte[] bytes, + String requestId, + String capturedAt, + BundleReference reference, + String snapshotSha256) { + try { + String text = new String(bytes, StandardCharsets.UTF_8); + Object value = JSON.readValue(text, Object.class); + if (!(value instanceof java.util.Map root) + || !root.keySet() + .equals( + java.util.Set.of( + "schema", + "controlPlaneRequestId", + "capturedAt", + "bundleReference", + "snapshotSha256")) + || !SCHEMA.equals(root.get("schema")) + || !requestId.equals(root.get("controlPlaneRequestId")) + || !capturedAt.equals(root.get("capturedAt")) + || !snapshotSha256.equals(root.get("snapshotSha256")) + || !(root.get("bundleReference") instanceof java.util.Map ref) + || !ref.keySet() + .equals( + java.util.Set.of( + "bundleVersion", "sourceVersion", "sourceFence", "linearization")) + || !reference.bundleVersion().equals(ref.get("bundleVersion")) + || !reference.sourceVersion().equals(ref.get("sourceVersion")) + || !reference.sourceFence().equals(ref.get("sourceFence")) + || !reference.linearization().equals(ref.get("linearization"))) { + throw invalid("Capture reference does not bind the full source snapshot"); + } + } catch (RuntimeException malformed) { + if (malformed instanceof IllegalArgumentException expected) throw expected; + throw invalid("Capture reference is malformed"); + } + } + + private static void requireCanonicalJson(byte[] bytes, String name) { + try { + String original = new String(bytes, StandardCharsets.UTF_8); + if (!Arrays.equals(bytes, Rfc8785CanonicalJson.canonicalizeUtf8(original))) { + throw invalid(name + " is not canonical JSON"); + } + JSON.readValue(original, Object.class); + } catch (java.io.IOException | RuntimeException malformed) { + if (malformed instanceof IllegalArgumentException expected) throw expected; + throw invalid(name + " is malformed"); + } + } + + private static byte[] bounded(byte[] value, int maximum, String field) { + Objects.requireNonNull(value, field + " bytes are required"); + if (value.length == 0 || value.length > maximum) { + throw invalid(field + " bytes are absent or over the supported bound"); + } + return value.clone(); + } + + private static long positive(long value, String field) { + if (value <= 0L) throw invalid(field + " must be positive"); + return value; + } + + private static String requireU64(String value, String field) { + if (value == null + || !POSITIVE_U64.matcher(value).matches() + || new java.math.BigInteger(value) + .compareTo( + java.math.BigInteger.ONE.shiftLeft(64).subtract(java.math.BigInteger.ONE)) + > 0) { + throw invalid(field + " is malformed"); + } + return value; + } + + private static String requireDigest(String value, String field) { + if (value == null || !SHA256.matcher(value).matches()) throw invalid(field + " is malformed"); + return value; + } + + private static String requireCapturedAt(String value) { + if (value == null) throw invalid("Database capture timestamp is absent"); + try { + Instant parsed = Instant.parse(value); + String canonical = CAPTURED_AT_FORMAT.format(parsed); + if (!canonical.equals(value) || parsed.getNano() % 1_000_000 != 0) { + throw invalid("Database capture timestamp must use canonical millisecond precision"); + } + return canonical; + } catch (RuntimeException malformed) { + if (malformed instanceof IllegalArgumentException expected) throw expected; + throw invalid("Database capture timestamp is malformed"); + } + } + + private static String sha256(byte[] bytes) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java new file mode 100644 index 0000000000..7e4c5fb476 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java @@ -0,0 +1,598 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority.Snapshot; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Account-local immutable capture of the complete current ControlUI source for StartSession. + * + *

This repository has no transport or crypto responsibilities. Call it only inside the callback + * of AccountControlUiActorService.withCurrent or withCurrentCommitted, before creating or + * fingerprinting the operator reference or encrypting its response. A capture is non-authorizing: + * the actor must be current again when the issuer locks it for finalization or redemption. + */ +public final class AccountStartSessionAuthorityCaptureRepository { + private static final String TABLE = "account_start_session_authority_captures"; + private static final String SOURCE_VERSION_ALLOCATOR = + "account_start_session_capture_source_version_allocator"; + private static final String SOURCE_FENCE_ALLOCATOR = + "account_start_session_capture_source_fence_allocator"; + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern LOGGING_WORKLOAD = + Pattern.compile( + "^spiffe://firemud/ns/([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)/sa/logging-admin-service$"); + private static final JsonMapper STRICT_JSON_MAPPER = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final DSLContext dsl; + + public AccountStartSessionAuthorityCaptureRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + } + + /** + * Persists the current source snapshot before private issuance work, or returns the exact + * original capture when every source and request binding is unchanged. + */ + public AccountStartSessionAuthorityCapture prepareOrReadExact( + AccountControlUiActorService.Current current, + StartSessionPreAuthorizationReservationTuple tuple, + String loggingWorkloadUri, + UUID reservationOwnerId, + long reservationClaimFence) { + requireOwnerTransaction(); + Objects.requireNonNull(current, "current committed ControlUI actor is required"); + RequestSnapshot candidate = + requestSnapshot( + current, tuple, loggingWorkloadUri, reservationOwnerId, reservationClaimFence); + + Record prior = lockByRequestId(candidate.requestId()); + if (prior != null) { + AccountStartSessionAuthorityCapture stored = decode(prior); + requireSameRequestAndSnapshot(candidate, stored, prior); + return stored; + } + + Allocation allocation = allocate(candidate.requestId()); + AccountStartSessionAuthorityCapture proposed = + AccountStartSessionAuthorityCapture.create( + candidate.requestId(), + allocation.sourceVersion(), + allocation.sourceFence(), + allocation.linearization(), + allocation.capturedAt(), + candidate.snapshotBytes()); + int inserted = insert(candidate, proposed); + Record row = lockByRequestId(candidate.requestId()); + if (row == null) throw unavailable(); + AccountStartSessionAuthorityCapture stored = decode(row); + requireSameRequestAndSnapshot(candidate, stored, row); + if (inserted == 1 && !proposed.sameStoredValue(stored)) { + throw unavailable(); + } + return stored; + } + + /** Locks and reads an existing exact capture without allocating or inserting one. */ + public AccountStartSessionAuthorityCapture lockReadExactCurrent( + AccountControlUiActorService.Current current, + StartSessionPreAuthorizationReservationTuple tuple, + String loggingWorkloadUri, + UUID reservationOwnerId, + long reservationClaimFence) { + return lockReadExactCurrent( + current, tuple, loggingWorkloadUri, reservationOwnerId, reservationClaimFence, true); + } + + /** + * Locks and reads the original capture for the authenticated same-namespace World receiver. The + * original Logging identity is checked as retained issuance evidence; it is not the current + * caller on this receiver path. + */ + public AccountStartSessionAuthorityCapture lockReadExactCurrentFromWorldReceiving( + AccountControlUiActorService.Current current, + StartSessionPreAuthorizationReservationTuple tuple, + String loggingWorkloadUri, + UUID reservationOwnerId, + long reservationClaimFence, + String worldManagementWorkloadUri) { + requireOwnerTransaction(); + Objects.requireNonNull(current, "current committed ControlUI actor is required"); + Objects.requireNonNull(tuple, "exact typed StartSession tuple is required"); + if (!canonicalWorldWorkload( + worldManagementWorkloadUri, tuple.action().scope().targetNamespace())) { + throw unavailable(); + } + return lockReadExactCurrent( + current, tuple, loggingWorkloadUri, reservationOwnerId, reservationClaimFence, false); + } + + private AccountStartSessionAuthorityCapture lockReadExactCurrent( + AccountControlUiActorService.Current current, + StartSessionPreAuthorizationReservationTuple tuple, + String loggingWorkloadUri, + UUID reservationOwnerId, + long reservationClaimFence, + boolean requireLoggingPeer) { + requireOwnerTransaction(); + Objects.requireNonNull(current, "current committed ControlUI actor is required"); + RequestSnapshot observed = + requestSnapshot( + current, + tuple, + loggingWorkloadUri, + reservationOwnerId, + reservationClaimFence, + requireLoggingPeer); + Record row = lockByRequestId(observed.requestId()); + if (row == null) throw unavailable(); + AccountStartSessionAuthorityCapture stored = decode(row); + requireSameRequestAndSnapshot(observed, stored, row); + return stored; + } + + /** Locks the immutable original capture and requires the exact current source and tuple again. */ + public AccountStartSessionAuthorityCapture lockExactCurrent( + AccountStartSessionAuthorityCapture expected, + AccountControlUiActorService.Current current, + StartSessionPreAuthorizationReservationTuple tuple, + String loggingWorkloadUri, + UUID reservationOwnerId, + long reservationClaimFence) { + requireOwnerTransaction(); + Objects.requireNonNull(expected, "original Account source capture is required"); + Objects.requireNonNull(current, "current committed ControlUI actor is required"); + RequestSnapshot observed = + requestSnapshot( + current, tuple, loggingWorkloadUri, reservationOwnerId, reservationClaimFence); + Record row = lockByRequestId(expected.controlPlaneRequestId()); + if (row == null) throw unavailable(); + AccountStartSessionAuthorityCapture stored = decode(row); + requireSameRequestAndSnapshot(observed, stored, row); + if (!expected.sameStoredValue(stored)) throw unavailable(); + return stored; + } + + private int insert(RequestSnapshot request, AccountStartSessionAuthorityCapture capture) { + byte[] tupleBytes = request.tupleBytes(); + byte[] snapshotBytes = capture.snapshotBytes(); + byte[] captureBytes = capture.canonicalBytes(); + return dsl.execute( + "INSERT INTO " + + TABLE + + " (control_plane_request_id, account_uuid, tenant_uuid, target_owner, " + + "logging_workload_uri, reservation_owner_id, reservation_claim_fence, " + + "pre_authorization_tuple, mutation_digest, control_ui_operation_id, " + + "control_ui_token_jti, control_ui_token_hash, control_ui_signer_receipt_sha256, " + + "issuance_fence, issuance_fence_source_version, captured_at, snapshot_sha256, " + + "canonical_snapshot_bytes, source_version, source_fence, linearization, " + + "canonical_sha256, canonical_capture_bytes) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?::timestamptz, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (control_plane_request_id) DO NOTHING", + request.requestId(), + request.accountId(), + request.tenantId(), + request.targetOwner(), + request.loggingWorkloadUri(), + request.reservationOwnerId(), + request.reservationClaimFence(), + tupleBytes, + request.mutationDigest(), + request.controlUiOperationId(), + request.controlUiTokenJti(), + request.controlUiTokenHash(), + request.controlUiSignerReceiptSha256(), + request.issuanceFence(), + request.issuanceFenceSourceVersion(), + capture.capturedAt(), + capture.snapshotSha256(), + snapshotBytes, + capture.sourceVersion(), + capture.sourceFence(), + capture.linearization(), + capture.canonicalSha256(), + captureBytes); + } + + private Allocation allocate(String requestId) { + Record sourceVersion = + dsl.fetchOne( + "UPDATE " + + SOURCE_VERSION_ALLOCATOR + + " SET last_source_version = last_source_version + 1, " + + "last_control_plane_request_id = ?, " + + "last_transaction_id = pg_current_xact_id()::text " + + "WHERE allocator_id = TRUE AND last_source_version < 9223372036854775807 " + + "RETURNING last_source_version, last_control_plane_request_id, last_transaction_id", + requestId); + Record sourceFence = + dsl.fetchOne( + "UPDATE " + + SOURCE_FENCE_ALLOCATOR + + " SET last_source_fence = last_source_fence + 1, " + + "last_control_plane_request_id = ?, " + + "last_transaction_id = pg_current_xact_id()::text " + + "WHERE allocator_id = TRUE AND last_source_fence < 9223372036854775807 " + + "RETURNING last_source_fence, last_control_plane_request_id, last_transaction_id", + requestId); + Record observedAt = + dsl.fetchOne( + "SELECT to_char(date_trunc('milliseconds', clock_timestamp()) AT TIME ZONE 'UTC', " + + "'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"') AS captured_at"); + if (sourceVersion == null || sourceFence == null || observedAt == null) throw unavailable(); + String versionTransaction = sourceVersion.get("last_transaction_id", String.class); + String fenceTransaction = sourceFence.get("last_transaction_id", String.class); + if (!requestId.equals(sourceVersion.get("last_control_plane_request_id", String.class)) + || !requestId.equals(sourceFence.get("last_control_plane_request_id", String.class)) + || versionTransaction == null + || !versionTransaction.equals(fenceTransaction)) { + throw unavailable(); + } + Long version = sourceVersion.get("last_source_version", Long.class); + Long fence = sourceFence.get("last_source_fence", Long.class); + if (version == null || version <= 0L || fence == null || fence <= 0L) throw unavailable(); + String capturedAt = observedAt.get("captured_at", String.class); + if (capturedAt == null) throw unavailable(); + return new Allocation(version, fence, versionTransaction, capturedAt); + } + + private Record lockByRequestId(String requestId) { + return dsl.fetchOne( + "SELECT control_plane_request_id, account_uuid, tenant_uuid, target_owner, " + + "logging_workload_uri, reservation_owner_id, reservation_claim_fence, " + + "pre_authorization_tuple, mutation_digest, control_ui_operation_id, " + + "control_ui_token_jti, control_ui_token_hash, control_ui_signer_receipt_sha256, " + + "issuance_fence, issuance_fence_source_version, " + + "to_char(captured_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"') AS captured_at, snapshot_sha256, " + + "canonical_snapshot_bytes, source_version, source_fence, linearization, " + + "canonical_sha256, canonical_capture_bytes FROM " + + TABLE + + " WHERE control_plane_request_id = ? FOR UPDATE", + requestId); + } + + private AccountStartSessionAuthorityCapture decode(Record row) { + try { + String requestId = row.get("control_plane_request_id", String.class); + Long version = row.get("source_version", Long.class); + Long fence = row.get("source_fence", Long.class); + String linearization = row.get("linearization", String.class); + byte[] snapshot = row.get("canonical_snapshot_bytes", byte[].class); + String snapshotDigest = row.get("snapshot_sha256", String.class); + byte[] captureBytes = row.get("canonical_capture_bytes", byte[].class); + String captureDigest = row.get("canonical_sha256", String.class); + var capture = + AccountStartSessionAuthorityCapture.fromStorage( + requestId, + version, + fence, + linearization, + row.get("captured_at", String.class), + snapshot, + snapshotDigest, + captureBytes, + captureDigest); + requireStoredColumnsMatchPayload(row, capture); + return capture; + } catch (RuntimeException malformed) { + throw unavailable(); + } + } + + private static void requireStoredColumnsMatchPayload( + Record row, AccountStartSessionAuthorityCapture capture) { + Map snapshot = parseObject(capture.snapshotBytes()); + Map reference = parseObject(capture.canonicalBytes()); + Map bundleReference = (Map) reference.get("bundleReference"); + if (!capture.controlPlaneRequestId().equals(row.get("control_plane_request_id", String.class)) + || !Long.toString(capture.sourceVersion()).equals(bundleReference.get("sourceVersion")) + || !Long.toString(capture.sourceFence()).equals(bundleReference.get("sourceFence")) + || !capture.linearization().equals(bundleReference.get("linearization")) + || !capture.capturedAt().equals(reference.get("capturedAt")) + || !capture.capturedAt().equals(row.get("captured_at", String.class)) + || !capture.snapshotSha256().equals(row.get("snapshot_sha256", String.class)) + || !Objects.equals(snapshot.get("accountId"), canonicalUuid(row, "account_uuid")) + || !Objects.equals(snapshot.get("tenantId"), canonicalUuid(row, "tenant_uuid")) + || !Objects.equals(snapshot.get("targetOwner"), row.get("target_owner", String.class)) + || !Objects.equals( + snapshot.get("loggingWorkloadUri"), row.get("logging_workload_uri", String.class)) + || !Objects.equals( + snapshot.get("reservationOwnerId"), canonicalUuid(row, "reservation_owner_id")) + || !Objects.equals( + snapshot.get("reservationClaimFence"), + Long.toString(number(row, "reservation_claim_fence"))) + || !Objects.equals(snapshot.get("mutationDigest"), row.get("mutation_digest", String.class)) + || !Objects.equals( + snapshot.get("controlUiOperationId"), canonicalUuid(row, "control_ui_operation_id")) + || !Objects.equals( + snapshot.get("controlUiTokenJti"), canonicalUuid(row, "control_ui_token_jti")) + || !Objects.equals( + snapshot.get("controlUiTokenHash"), row.get("control_ui_token_hash", String.class)) + || !Objects.equals( + snapshot.get("controlUiSignerReceiptSha256"), + row.get("control_ui_signer_receipt_sha256", String.class)) + || !Objects.equals( + snapshot.get("issuanceFence"), Long.toString(number(row, "issuance_fence"))) + || !Objects.equals( + snapshot.get("issuanceFenceSourceVersion"), + Long.toString(number(row, "issuance_fence_source_version")))) { + throw unavailable(); + } + } + + private static RequestSnapshot requestSnapshot( + AccountControlUiActorService.Current current, + StartSessionPreAuthorizationReservationTuple tuple, + String loggingWorkloadUri, + UUID reservationOwnerId, + long reservationClaimFence) { + return requestSnapshot( + current, tuple, loggingWorkloadUri, reservationOwnerId, reservationClaimFence, true); + } + + private static RequestSnapshot requestSnapshot( + AccountControlUiActorService.Current current, + StartSessionPreAuthorizationReservationTuple tuple, + String loggingWorkloadUri, + UUID reservationOwnerId, + long reservationClaimFence, + boolean requireLoggingPeer) { + Objects.requireNonNull(tuple, "exact typed StartSession tuple is required"); + Objects.requireNonNull(current.stored(), "original committed ControlUI issuance is required"); + Snapshot source = + Objects.requireNonNull(current.source(), "current Account snapshot is required"); + var stored = current.stored(); + byte[] tupleBytes = tuple.canonicalJson().getBytes(StandardCharsets.UTF_8); + if (!tuple.actor().accountId().equals(stored.accountId) + || !tuple.actor().accountId().equals(source.actor()) + || !tuple.action().scope().tenantId().equals(stored.tenantId) + || !tuple.action().scope().tenantId().equals(source.tenant()) + || !"game-session-service".equals(tuple.targetOwner()) + || !"COMMITTED".equals(stored.status) + || !canonicalTuple(tupleBytes, tuple) + || !(requireLoggingPeer + ? canonicalLoggingWorkload(loggingWorkloadUri, tuple.action().scope().targetNamespace()) + : canonicalLoggingWorkloadUri( + loggingWorkloadUri, tuple.action().scope().targetNamespace())) + || reservationOwnerId == null + || reservationOwnerId.equals(new UUID(0L, 0L)) + || reservationClaimFence <= 0L + || stored.operationId == null + || stored.jti == null + || stored.tokenHash == null + || !SHA256.matcher(stored.tokenHash).matches() + || stored.signerReceipt == null + || stored.signerReceipt.length == 0 + || source.issuanceFence() <= 0L + || source.issuanceFenceSourceVersion() <= 0L + || source.evidence() == null + || source.evidence().length == 0 + || source.sources() == null + || source.sources().isEmpty() + || source.outboxCheckpoints() == null) { + throw unavailable(); + } + byte[] signerReceipt = stored.signerReceipt.clone(); + Map snapshot = new LinkedHashMap<>(); + snapshot.put("schema", "account-start-session-authority-snapshot/v1"); + snapshot.put("controlPlaneRequestId", tuple.controlPlaneRequestId()); + snapshot.put("preAuthorizationTuple", Base64.getEncoder().encodeToString(tupleBytes)); + snapshot.put("mutationDigest", tuple.mutationDigest()); + snapshot.put("accountId", stored.accountId.toString()); + snapshot.put("tenantId", stored.tenantId.toString()); + snapshot.put("targetOwner", tuple.targetOwner()); + snapshot.put("loggingWorkloadUri", loggingWorkloadUri); + snapshot.put("reservationOwnerId", reservationOwnerId.toString()); + snapshot.put("reservationClaimFence", Long.toString(reservationClaimFence)); + snapshot.put("controlUiOperationId", stored.operationId.toString()); + snapshot.put("controlUiTokenJti", stored.jti.toString()); + snapshot.put("controlUiTokenHash", stored.tokenHash); + snapshot.put("controlUiSignerReceipt", Base64.getEncoder().encodeToString(signerReceipt)); + snapshot.put("controlUiSignerReceiptSha256", sha256(signerReceipt)); + snapshot.put("sourceVectorEvidence", Base64.getEncoder().encodeToString(source.evidence())); + List sourceVector = new ArrayList<>(); + for (SourceEvidence evidence : source.sources()) { + if (evidence == null || evidence.canonicalBytes().length == 0) throw unavailable(); + sourceVector.add(Base64.getEncoder().encodeToString(evidence.canonicalBytes())); + } + snapshot.put("sourceVector", List.copyOf(sourceVector)); + snapshot.put("outboxCheckpoints", source.outboxCheckpoints()); + snapshot.put("authorityTuple", source.authorityTuple()); + snapshot.put("membershipVersion", source.membershipVersion()); + snapshot.put("accountIdentitySource", source.accountIdentitySource()); + snapshot.put("issuanceFence", Long.toString(source.issuanceFence())); + snapshot.put("issuanceFenceSourceVersion", Long.toString(source.issuanceFenceSourceVersion())); + byte[] snapshotBytes = AccountControlUiAuthority.canonical(Map.copyOf(snapshot)); + if (snapshotBytes.length > AccountStartSessionAuthorityCapture.MAX_SNAPSHOT_BYTES) { + throw unavailable(); + } + return new RequestSnapshot( + tuple.controlPlaneRequestId(), + tuple.actor().accountId(), + tuple.action().scope().tenantId(), + tuple.targetOwner(), + loggingWorkloadUri, + reservationOwnerId, + reservationClaimFence, + tupleBytes, + tuple.mutationDigest(), + stored.operationId, + stored.jti, + stored.tokenHash, + sha256(signerReceipt), + source.issuanceFence(), + source.issuanceFenceSourceVersion(), + snapshotBytes); + } + + private static void requireSameRequestAndSnapshot( + RequestSnapshot request, AccountStartSessionAuthorityCapture capture, Record storedRow) { + requireStoredColumnsMatchPayload(storedRow, capture); + Map snapshot = parseObject(capture.snapshotBytes()); + if (!request.requestId().equals(capture.controlPlaneRequestId()) + || !MessageDigest.isEqual(request.snapshotBytes(), capture.snapshotBytes()) + || !Objects.equals( + snapshot.get("preAuthorizationTuple"), + Base64.getEncoder().encodeToString(request.tupleBytes())) + || !Objects.equals( + snapshot.get("controlUiOperationId"), request.controlUiOperationId().toString()) + || !Objects.equals( + snapshot.get("controlUiTokenJti"), request.controlUiTokenJti().toString()) + || !Objects.equals(snapshot.get("controlUiTokenHash"), request.controlUiTokenHash()) + || !Objects.equals( + snapshot.get("controlUiSignerReceiptSha256"), request.controlUiSignerReceiptSha256()) + || !Objects.equals( + snapshot.get("reservationOwnerId"), request.reservationOwnerId().toString()) + || !Objects.equals( + snapshot.get("reservationClaimFence"), + Long.toString(request.reservationClaimFence()))) { + throw unavailable(); + } + } + + private static boolean canonicalTuple( + byte[] tupleBytes, StartSessionPreAuthorizationReservationTuple tuple) { + try { + String json = new String(tupleBytes, StandardCharsets.UTF_8); + var parsed = StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(json); + return MessageDigest.isEqual( + tupleBytes, parsed.canonicalJson().getBytes(StandardCharsets.UTF_8)) + && parsed.controlPlaneRequestId().equals(tuple.controlPlaneRequestId()) + && parsed.mutationDigest().equals(tuple.mutationDigest()); + } catch (RuntimeException malformed) { + return false; + } + } + + private static boolean canonicalLoggingWorkload(String uri, String targetNamespace) { + if (!canonicalLoggingWorkloadUri(uri, targetNamespace)) return false; + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + return peer != null + && uri.equals(peer.uri()) + && "logging-admin-service".equals(peer.service()) + && targetNamespace.equals(peer.namespace()); + } + + private static boolean canonicalLoggingWorkloadUri(String uri, String targetNamespace) { + if (uri == null) return false; + var match = LOGGING_WORKLOAD.matcher(uri); + return match.matches() && match.group(1).equals(targetNamespace); + } + + private static boolean canonicalWorldWorkload(String uri, String targetNamespace) { + return canonicalReceivingWorkload(uri, targetNamespace, "world-management-service"); + } + + private static boolean canonicalReceivingWorkload( + String uri, String targetNamespace, String service) { + String expectedUri = "spiffe://firemud/ns/" + targetNamespace + "/sa/" + service; + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + return !SessionContext.hasAuthenticatedCallerContext() + && expectedUri.equals(uri) + && peer != null + && uri.equals(peer.uri()) + && service.equals(peer.service()) + && targetNamespace.equals(peer.namespace()); + } + + private static Map parseObject(byte[] bytes) { + try { + Object value = + STRICT_JSON_MAPPER.readValue(new String(bytes, StandardCharsets.UTF_8), Object.class); + if (value instanceof Map map) return map; + throw unavailable(); + } catch (RuntimeException malformed) { + throw unavailable(); + } + } + + private static String canonicalUuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + return value == null ? null : value.toString(); + } + + private static long number(Record row, String field) { + Long value = row.get(field, Long.class); + if (value == null) throw unavailable(); + return value; + } + + private static String sha256(byte[] bytes) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("A writable Account owner transaction is required"); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Account StartSession source capture is unavailable"); + } + + private record Allocation( + long sourceVersion, long sourceFence, String linearization, String capturedAt) {} + + private record RequestSnapshot( + String requestId, + UUID accountId, + UUID tenantId, + String targetOwner, + String loggingWorkloadUri, + UUID reservationOwnerId, + long reservationClaimFence, + byte[] tupleBytes, + String mutationDigest, + UUID controlUiOperationId, + UUID controlUiTokenJti, + String controlUiTokenHash, + String controlUiSignerReceiptSha256, + long issuanceFence, + long issuanceFenceSourceVersion, + byte[] snapshotBytes) { + private RequestSnapshot { + tupleBytes = tupleBytes.clone(); + snapshotBytes = snapshotBytes.clone(); + } + + @Override + public byte[] tupleBytes() { + return tupleBytes.clone(); + } + + @Override + public byte[] snapshotBytes() { + return snapshotBytes.clone(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundle.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundle.java index 40f6c2becf..fafc8b2f8c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundle.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundle.java @@ -13,12 +13,13 @@ import java.util.regex.Pattern; import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority.Snapshot; -import net.firedevops.firemud.accountservice.service.session.AccountControlUiIssuanceRepository.OwnerLinearization; import net.firedevops.firemud.accountservice.service.session.AccountControlUiIssuanceRepository.Stored; -import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; -import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; /** Exact ADR 0047 Account authority evidence for the tenantAdmin StartSession branch. */ public final class AccountStartSessionOperatorAuthorityBundle { @@ -26,6 +27,36 @@ public final class AccountStartSessionOperatorAuthorityBundle { public static final String HUMAN_EVIDENCE_TYPE = StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE; private static final Pattern DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Set CAPTURE_SNAPSHOT_FIELDS = + Set.of( + "schema", + "controlPlaneRequestId", + "preAuthorizationTuple", + "mutationDigest", + "accountId", + "tenantId", + "targetOwner", + "loggingWorkloadUri", + "reservationOwnerId", + "reservationClaimFence", + "controlUiOperationId", + "controlUiTokenJti", + "controlUiTokenHash", + "controlUiSignerReceipt", + "controlUiSignerReceiptSha256", + "sourceVectorEvidence", + "sourceVector", + "outboxCheckpoints", + "authorityTuple", + "membershipVersion", + "accountIdentitySource", + "issuanceFence", + "issuanceFenceSourceVersion"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); private final StartSessionAuthorityEvidenceBundle decoded; private final byte[] canonicalBytes; @@ -38,44 +69,46 @@ private AccountStartSessionOperatorAuthorityBundle(StartSessionAuthorityEvidence } /** - * Builds the one supported human branch from Account's already-current source snapshot and the - * control-ui token row proven by {@link AccountControlUiActorService}. + * Builds the one supported human branch only from Account's already committed immutable capture + * and the original control-ui token row proven by {@link AccountControlUiActorService}. */ public static AccountStartSessionOperatorAuthorityBundle create( StartSessionPreAuthorizationReservationTuple tuple, - Snapshot source, + AccountStartSessionAuthorityCapture capture, Stored controlUiIssuance, UUID issuanceOperationId, - OwnerLinearization linearization, Instant issuedAt, Instant referenceExpiresAt) { Objects.requireNonNull(tuple, "pre-authorization tuple is required"); - Objects.requireNonNull(source, "current Account source is required"); - Objects.requireNonNull(controlUiIssuance, "current control-ui issuance is required"); + Objects.requireNonNull(capture, "durable Account authority capture is required"); + Objects.requireNonNull(controlUiIssuance, "original control-ui issuance is required"); Objects.requireNonNull(issuanceOperationId, "issuance operation identity is required"); - Objects.requireNonNull(linearization, "Account owner linearization is required"); requireTimeWindow(issuedAt, referenceExpiresAt); - if (!tuple.actor().accountId().equals(source.actor()) - || !tuple.action().scope().tenantId().equals(source.tenant()) - || !controlUiIssuance.accountId.equals(source.actor()) - || !controlUiIssuance.tenantId.equals(source.tenant())) { - throw denied("Current Account and control-ui source must exactly match the typed actor"); - } - + Map snapshot = captureSnapshot(capture); + UUID actor = canonicalUuid(snapshot.get("accountId"), "captured accountId"); + UUID tenant = canonicalUuid(snapshot.get("tenantId"), "captured tenantId"); + UUID controlUiJti = canonicalUuid(snapshot.get("controlUiTokenJti"), "captured token jti"); + Map authorityTuple = object(snapshot.get("authorityTuple"), "authorityTuple"); + Map membershipVersion = + object(snapshot.get("membershipVersion"), "membershipVersion"); Map claims = AccountControlUiIssuanceRepository.object(controlUiIssuance.claims); - requireCurrentTenantClaims(tuple, source, controlUiIssuance, claims, false); - SourceEvidence accountSource = uniqueAccountSource(source, source.actor()); - BundleReference reference = - new BundleReference( - BUNDLE_VERSION, - accountSource.sourceVersion(), - Long.toString(linearization.sourceFence()), - linearization.transactionId()); - String sourceEvidenceId = - sourceEvidenceId(source.evidence(), accountSource.sourceVersion(), reference); + requireCapturedTenantClaims( + tuple, actor, tenant, authorityTuple, membershipVersion, controlUiIssuance, claims); + if (!tuple.controlPlaneRequestId().equals(snapshot.get("controlPlaneRequestId")) + || !tuple.targetOwner().equals(snapshot.get("targetOwner")) + || !tuple.mutationDigest().equals(snapshot.get("mutationDigest")) + || !Base64.getEncoder() + .encodeToString(tuple.canonicalJson().getBytes(java.nio.charset.StandardCharsets.UTF_8)) + .equals(snapshot.get("preAuthorizationTuple")) + || !controlUiIssuance.operationId.toString().equals(snapshot.get("controlUiOperationId")) + || !controlUiIssuance.tokenHash.equals(snapshot.get("controlUiTokenHash")) + || !controlUiIssuance.jti.equals(controlUiJti)) { + throw denied("Retained Account capture differs from the original request or credential"); + } + BundleReference reference = referenceForCaptureValue(capture); Map typedScope = Map.of( "tenantId", tuple.action().scope().tenantId().toString(), @@ -84,22 +117,25 @@ public static AccountStartSessionOperatorAuthorityBundle create( Map.of( "scope", typedScope, "actionFamily", tuple.actionFamily(), - "applicableAccountId", source.actor().toString(), - "applicableTenantId", source.tenant().toString()); + "applicableAccountId", actor.toString(), + "applicableTenantId", tenant.toString()); Map projection = Map.of( - "sourceType", - "ACCOUNT", + "sourceType", "ACCOUNT", "sourceEvidenceId", - sourceEvidenceId, - "sourceEvidenceVersion", - accountSource.sourceVersion(), - "projectionStatus", - "CURRENT", - "evaluatedAt", - issuedAt.toString(), - "expiresAt", - referenceExpiresAt.toString()); + sourceEvidenceId( + Base64.getDecoder() + .decode( + string(snapshot.get("sourceVectorEvidence"), "sourceVectorEvidence")), + reference, + positiveNumber(snapshot.get("issuanceFence"), "captured issuanceFence"), + positiveNumber( + snapshot.get("issuanceFenceSourceVersion"), + "captured issuanceFenceSourceVersion")), + "sourceEvidenceVersion", reference.sourceVersion(), + "projectionStatus", "CURRENT", + "evaluatedAt", canonicalCaptureTimestamp(capture), + "expiresAt", referenceExpiresAt.toString()); Map operationIdentity = Map.of( "issuanceOperationId", issuanceOperationId.toString(), @@ -112,7 +148,7 @@ public static AccountStartSessionOperatorAuthorityBundle create( tuple.controlPlaneRequestId()), "mutationDigest", tuple.mutationDigest()); Map humanEvidence = - humanTenantEvidence(source, controlUiIssuance.jti, claims, false); + humanTenantEvidence(actor, tenant, authorityTuple, controlUiJti, claims); Map bundle = new LinkedHashMap<>(); bundle.put("bundleVersion", BUNDLE_VERSION); @@ -120,15 +156,16 @@ public static AccountStartSessionOperatorAuthorityBundle create( bundle.put("accountProjectionEvidence", projection); bundle.put("issuanceOperationIdentity", operationIdentity); bundle.put("issuanceKind", "human_operator"); - bundle.put("authorityTuple", source.authorityTuple()); - bundle.put("membershipVersion", source.membershipVersion()); - bundle.put("issuanceFence", reference.sourceFence()); + bundle.put("authorityTuple", authorityTuple); + bundle.put("membershipVersion", membershipVersion); + bundle.put( + "issuanceFence", + positiveDecimalString(snapshot.get("issuanceFence"), "captured issuanceFence")); bundle.put("issuanceEvidence", humanEvidence); - byte[] encoded = AccountControlUiAuthority.canonical(bundle); - AccountStartSessionOperatorAuthorityBundle result = decode(encoded); + AccountStartSessionOperatorAuthorityBundle result = + decode(AccountControlUiAuthority.canonical(bundle)); result.requireTupleBinding(tuple); - result.requireReferenceBinding(reference); - result.requireCurrent(source, controlUiIssuance, tuple, reference, issuedAt); + result.requireCaptureBinding(capture, tuple, reference); return result; } @@ -168,15 +205,11 @@ public void requireCurrent( Map claims = AccountControlUiIssuanceRepository.object(currentControlUiIssuance.claims); requireCurrentTenantClaims(tuple, currentSource, currentControlUiIssuance, claims, true); - SourceEvidence source = uniqueAccountSource(currentSource, currentSource.actor()); - if (!source.sourceVersion().equals(projection.get("sourceEvidenceVersion")) - || !source.sourceVersion().equals(originalReference.sourceVersion()) - || !sourceEvidenceId(currentSource.evidence(), source.sourceVersion(), originalReference) - .equals(projection.get("sourceEvidenceId")) - || !canonicalEquals(currentSource.authorityTuple(), value.get("authorityTuple")) + if (!canonicalEquals(currentSource.authorityTuple(), value.get("authorityTuple")) || !canonicalEquals(currentSource.membershipVersion(), value.get("membershipVersion"))) { throw denied(true, "Current Account source, generation, or membership changed"); } + requireCurrentSourceEvidence(currentSource, originalReference); Map expectedEvidence = humanTenantEvidence(currentSource, currentControlUiIssuance.jti, claims, true); if (!canonicalEquals(expectedEvidence, value.get("issuanceEvidence"))) { @@ -209,16 +242,9 @@ public void requireCurrentSnapshotForExactReplay( Map claims = AccountControlUiIssuanceRepository.object(currentControlUiIssuance.claims); requireCurrentTenantClaims(tuple, currentSource, currentControlUiIssuance, claims, true); - SourceEvidence accountSource = uniqueAccountSource(currentSource, currentSource.actor()); - Map projection = - object(value.get("accountProjectionEvidence"), "accountProjectionEvidence"); - if (!accountSource.sourceVersion().equals(originalReference.sourceVersion()) - || !accountSource.sourceVersion().equals(projection.get("sourceEvidenceVersion")) - || !sourceEvidenceId( - currentSource.evidence(), accountSource.sourceVersion(), originalReference) - .equals(projection.get("sourceEvidenceId")) - || !canonicalEquals(currentSource.authorityTuple(), value.get("authorityTuple")) + if (!canonicalEquals(currentSource.authorityTuple(), value.get("authorityTuple")) || !canonicalEquals(currentSource.membershipVersion(), value.get("membershipVersion")) + || !currentSourceMatchesEvidence(currentSource, originalReference) || !canonicalEquals( humanTenantEvidence(currentSource, currentControlUiIssuance.jti, claims, true), value.get("issuanceEvidence"))) { @@ -239,22 +265,47 @@ public byte[] canonicalBytes() { return canonicalBytes.clone(); } - public BundleReference referenceForSource(Snapshot source, OwnerLinearization linearization) { - SourceEvidence accountSource = uniqueAccountSource(source, source.actor()); - BundleReference reference = - new BundleReference( - BUNDLE_VERSION, - accountSource.sourceVersion(), - Long.toString(linearization.sourceFence()), - linearization.transactionId()); - requireReferenceBinding(reference); - if (!sourceEvidenceId(source.evidence(), accountSource.sourceVersion(), reference) - .equals(sourceEvidenceId())) { - throw denied("Account source reference does not identify this captured source"); - } + public BundleReference referenceForCapture(AccountStartSessionAuthorityCapture capture) { + Objects.requireNonNull(capture, "original Account source capture is required"); + BundleReference reference = referenceForCaptureValue(capture); + requireCaptureBinding(capture, null, reference); return reference; } + /** Requires the bundle and immutable source reference to identify the same stored capture. */ + public void requireCaptureBinding( + AccountStartSessionAuthorityCapture capture, + StartSessionPreAuthorizationReservationTuple tuple, + BundleReference expectedReference) { + Objects.requireNonNull(capture, "original Account source capture is required"); + Objects.requireNonNull(expectedReference, "original Account bundle reference is required"); + Map projection = + object(value.get("accountProjectionEvidence"), "accountProjectionEvidence"); + Map snapshot = captureSnapshot(capture); + String expectedEvidenceId = + sourceEvidenceId( + Base64.getDecoder() + .decode(string(snapshot.get("sourceVectorEvidence"), "sourceVectorEvidence")), + expectedReference, + positiveNumber(snapshot.get("issuanceFence"), "captured issuanceFence"), + positiveNumber( + snapshot.get("issuanceFenceSourceVersion"), "captured issuanceFenceSourceVersion")); + if (!referenceForCaptureValue(capture).equals(expectedReference) + || !expectedEvidenceId.equals(projection.get("sourceEvidenceId")) + || !Long.toString(capture.sourceVersion()).equals(projection.get("sourceEvidenceVersion")) + || !canonicalCaptureTimestamp(capture).equals(projection.get("evaluatedAt")) + || !capture.controlPlaneRequestId().equals(controlPlaneRequestId()) + || (tuple != null && !tuple.controlPlaneRequestId().equals(controlPlaneRequestId())) + || !canonicalEquals(snapshot.get("authorityTuple"), value.get("authorityTuple")) + || !canonicalEquals(snapshot.get("membershipVersion"), value.get("membershipVersion"))) { + throw denied("Authority bundle does not bind the exact retained Account capture"); + } + if (!Long.toString(positiveNumber(snapshot.get("issuanceFence"), "captured issuanceFence")) + .equals(decoded.issuanceFence())) { + throw denied("Account issuance fence differs from the retained source snapshot"); + } + } + public Map authorityTuple() { return decoded.authorityTuple(); } @@ -283,6 +334,10 @@ public String sourceEvidenceVersion() { return decoded.sourceEvidenceVersion(); } + public long issuanceFence() { + return positiveNumber(decoded.issuanceFence(), "Account issuance fence"); + } + public UUID controlUiTokenJti() { return decoded.controlUiTokenJti(); } @@ -295,10 +350,6 @@ private Instant originalReferenceExpiresAt() { return decoded.expiresAt(); } - private void requireReferenceBinding(BundleReference reference) { - decoded.requireReferenceBinding(toSharedReference(reference)); - } - static StartSessionAuthorityEvidenceBundle.BundleReference toSharedReference( BundleReference reference) { Objects.requireNonNull(reference, "original Account source reference is required"); @@ -319,6 +370,105 @@ static BundleReference fromSharedReference( reference.linearization()); } + private static BundleReference referenceForCaptureValue( + AccountStartSessionAuthorityCapture capture) { + return fromSharedReference(capture.bundleReference()); + } + + private static Map captureSnapshot(AccountStartSessionAuthorityCapture capture) { + try { + byte[] bytes = capture.snapshotBytes(); + Map snapshot = + JSON.readValue( + new String(bytes, java.nio.charset.StandardCharsets.UTF_8), new TypeReference<>() {}); + if (!CAPTURE_SNAPSHOT_FIELDS.equals(snapshot.keySet()) + || !"account-start-session-authority-snapshot/v1".equals(snapshot.get("schema")) + || !MessageDigest.isEqual(bytes, AccountControlUiAuthority.canonical(snapshot))) { + throw denied("Retained Account source snapshot is not exact canonical data"); + } + return snapshot; + } catch (RuntimeException malformed) { + throw denied("Retained Account source snapshot is malformed"); + } + } + + private static UUID canonicalUuid(Object value, String field) { + String text = string(value, field); + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text)) throw new IllegalArgumentException(); + return parsed; + } catch (RuntimeException malformed) { + throw denied(field + " must be a canonical UUID"); + } + } + + private static String positiveDecimalString(Object value, String field) { + return Long.toString(positiveNumber(value, field)); + } + + private static long positive(long value, String field) { + if (value <= 0L) throw denied(field + " must be positive"); + return value; + } + + private static void requireCapturedTenantClaims( + StartSessionPreAuthorizationReservationTuple tuple, + UUID actor, + UUID tenant, + Map authorityTuple, + Map membershipVersion, + Stored stored, + Map claims) { + if (!tuple.actor().accountId().equals(actor) + || !tuple.actor().accountId().equals(stored.accountId) + || !tuple.action().scope().tenantId().equals(tenant) + || !tuple.action().scope().tenantId().equals(stored.tenantId) + || !"COMMITTED".equals(stored.status) + || stored.jti == null + || !stored.jti.toString().equals(claims.get("jti")) + || !actor.toString().equals(claims.get("sub")) + || !actor.toString().equals(claims.get("accountId")) + || !"control-ui".equals(claims.get("aud")) + || positiveNumber(claims.get("tokenGeneration"), "tokenGeneration") != 1L + || claims.containsKey("assurance") + || claims.containsKey("globalRoles") + || !Map.of(tenant.toString(), List.of("tenantAdmin")).equals(claims.get("scopedRoles")) + || !canonicalEquals(authorityTuple, claims.get("authorityTuple")) + || !canonicalEquals(membershipVersion, claims.get("membershipVersion"))) { + throw denied("Captured tenantAdmin control-ui evidence is required"); + } + } + + private static Map humanTenantEvidence( + UUID actor, + UUID tenant, + Map authorityTuple, + UUID tokenJti, + Map claims) { + if (claims.containsKey("assurance") || claims.containsKey("globalRoles")) { + throw denied("Tenant authority must omit assurance and global-role evidence"); + } + long accountGeneration = + positiveNumber( + authorityTuple.get("accountAuthorityGeneration"), "accountAuthorityGeneration"); + Map tenantGenerations = + object(authorityTuple.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"); + if (!tenantGenerations.keySet().equals(Set.of(tenant.toString()))) { + throw denied("Exact selected tenant authority generation is required"); + } + long tenantGeneration = + positiveNumber(tenantGenerations.get(tenant.toString()), "tenantAuthorityGeneration"); + Map evidence = new LinkedHashMap<>(); + evidence.put("evidenceType", HUMAN_EVIDENCE_TYPE); + evidence.put("actorAccountId", actor.toString()); + evidence.put("controlUiTokenJti", tokenJti.toString()); + evidence.put("role", "tenantAdmin"); + evidence.put("accountGeneration", Long.toString(accountGeneration)); + evidence.put("tenantGeneration", Long.toString(tenantGeneration)); + return Map.copyOf(evidence); + } + private static void requireCurrentTenantClaims( StartSessionPreAuthorizationReservationTuple tuple, Snapshot source, @@ -371,21 +521,30 @@ private static Map humanTenantEvidence( } private static String sourceEvidenceId( - byte[] sourceEvidence, String sourceVersion, BundleReference reference) { + byte[] sourceEvidence, + BundleReference reference, + long accountIssuanceFence, + long accountIssuanceFenceSourceVersion) { Map value = Map.of( "schema", - "account-authority-source-linearization/v1", + "account-start-session-source-capture-evidence/v1", "sourceType", "ACCOUNT", "sourceEvidenceBytesBase64", Base64.getEncoder().encodeToString(sourceEvidence), "sourceVersion", - sourceVersion, + reference.sourceVersion(), "sourceFence", reference.sourceFence(), - "transactionId", - reference.linearization()); + "linearization", + reference.linearization(), + "accountIssuanceFence", + Long.toString(positive(accountIssuanceFence, "Account issuance fence")), + "accountIssuanceFenceSourceVersion", + Long.toString( + positive( + accountIssuanceFenceSourceVersion, "Account issuance fence source version"))); try { byte[] digest = MessageDigest.getInstance("SHA-256").digest(AccountControlUiAuthority.canonical(value)); @@ -395,18 +554,25 @@ private static String sourceEvidenceId( } } - private static SourceEvidence uniqueAccountSource(Snapshot source, UUID actor) { - List matches = - source.sources().stream() - .filter( - candidate -> - candidate.kind() == SourceKind.ACCOUNT - && actor.toString().equals(candidate.scopeId())) - .toList(); - if (matches.size() != 1) { - throw denied("One exact Account source version for the human actor is required"); + private void requireCurrentSourceEvidence(Snapshot source, BundleReference reference) { + if (!currentSourceMatchesEvidence(source, reference)) { + throw denied( + true, + "Current Account source evidence or issuance fence differs from the original capture"); } - return matches.getFirst(); + } + + private boolean currentSourceMatchesEvidence(Snapshot source, BundleReference reference) { + Map projection = + object(value.get("accountProjectionEvidence"), "accountProjectionEvidence"); + if (source.issuanceFence() <= 0L || source.issuanceFenceSourceVersion() <= 0L) return false; + return Long.toString(source.issuanceFence()).equals(decoded.issuanceFence()) + && sourceEvidenceId( + source.evidence(), + reference, + source.issuanceFence(), + source.issuanceFenceSourceVersion()) + .equals(projection.get("sourceEvidenceId")); } private static void requireTimeWindow(Instant issuedAt, Instant expiresAt) { @@ -420,6 +586,24 @@ private static void requireTimeWindow(Instant issuedAt, Instant expiresAt) { } } + /** + * V128 stores a fixed-width UTC millisecond timestamp, while the shared bundle contract uses the + * canonical {@link Instant#toString()} representation. Preserve the captured instant and + * precision while normalizing only that textual representation (notably, dropping .000). + */ + private static String canonicalCaptureTimestamp(AccountStartSessionAuthorityCapture capture) { + final Instant capturedAt; + try { + capturedAt = Instant.parse(capture.capturedAt()); + } catch (RuntimeException malformed) { + throw denied("Capture timestamp is malformed"); + } + if (capturedAt.getNano() % 1_000_000 != 0) { + throw denied("Capture timestamp must use exact millisecond precision"); + } + return capturedAt.toString(); + } + private static Instant instant(String value) { try { Instant parsed = Instant.parse(value); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java index a4bb79030e..2045ccbca9 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java @@ -14,6 +14,7 @@ import java.util.Optional; import java.util.Set; import java.util.UUID; +import java.util.function.Function; import java.util.regex.Pattern; import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; import net.firedevops.firemud.accountservice.client.StartSessionReservationEvidenceClient; @@ -23,18 +24,20 @@ import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.IssuanceCandidate; import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.IssuanceRecord; import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.RedemptionRequest; -import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.RedemptionResult; import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.Status; import net.firedevops.firemud.accountservice.service.session.AccountControlUiActorService.Current; -import net.firedevops.firemud.accountservice.service.session.AccountControlUiIssuanceRepository.OwnerLinearization; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiIssuanceRepository.Stored; import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationReferenceFingerprint.ReferenceKind; import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography.Binding; import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; import tools.jackson.core.StreamReadFeature; import tools.jackson.core.type.TypeReference; @@ -68,6 +71,7 @@ public final class AccountStartSessionOperatorAuthorizationService { private final AccountControlUiActorService actors; private final AccountControlUiIssuanceRepository issuanceOperations; + private final AccountStartSessionAuthorityCaptureRepository captureRepository; private final StartSessionReservationEvidenceClient reservationEvidence; private final AccountStartSessionOperatorAuthorizationRepository repository; private final AccountOperatorAuthorizationFingerprintKeyring fingerprintKeys; @@ -79,6 +83,7 @@ public final class AccountStartSessionOperatorAuthorizationService { private final String loggingPeerUri; private final String gameSessionPeerUri; private final String gameDesignPeerUri; + private final String worldManagementPeerUri; private final long referenceLifetimeMillis; private final long responseRecoveryWindowMillis; @@ -89,6 +94,7 @@ public final class AccountStartSessionOperatorAuthorizationService { public AccountStartSessionOperatorAuthorizationService( AccountControlUiActorService actors, AccountControlUiIssuanceRepository issuanceOperations, + AccountStartSessionAuthorityCaptureRepository captureRepository, StartSessionReservationEvidenceClient reservationEvidence, AccountStartSessionOperatorAuthorizationRepository repository, AccountOperatorAuthorizationFingerprintKeyring fingerprintKeys, @@ -104,6 +110,9 @@ public AccountStartSessionOperatorAuthorizationService( this.actors = Objects.requireNonNull(actors, "current Account actor service is required"); this.issuanceOperations = Objects.requireNonNull(issuanceOperations, "Account control-ui issuance owner is required"); + this.captureRepository = + Objects.requireNonNull( + captureRepository, "durable Account source capture owner is required"); this.reservationEvidence = Objects.requireNonNull(reservationEvidence, "Logging claim evidence client is required"); this.repository = Objects.requireNonNull(repository, "Account owner repository is required"); @@ -120,6 +129,7 @@ public AccountStartSessionOperatorAuthorizationService( loggingPeerUri = exactPeer(exactLoggingPeerUri, "logging-admin-service"); gameSessionPeerUri = exactPeer(exactGameSessionPeerUri, "game-session-service"); gameDesignPeerUri = sameNamespacePeer(gameSessionPeerUri, "game-design-service"); + worldManagementPeerUri = sameNamespacePeer(gameSessionPeerUri, "world-management-service"); referenceLifetimeMillis = policyMillis(referenceLifetime, "reference lifetime", 5 * 60_000L); responseRecoveryWindowMillis = policyMillis(responseRecoveryWindow, "response recovery window", 60_000L); @@ -128,7 +138,8 @@ public AccountStartSessionOperatorAuthorizationService( } /** - * ISSUE: current exact Logging peer, fresh original claim, current actor, one owner transaction. + * ISSUE: exact Logging peer and current original claim; committed capture precedes final owner + * issuance with current actor and capture revalidation. */ public AuthorizationResponse issue(IssueRequest request) { requirePeer(loggingPeerUri); @@ -151,6 +162,7 @@ public AuthorizationResponse issue(IssueRequest request) { request.reservationClaimFence(), request.claimOwnerId(), request.claimFence()); + requireFreshClaimEvidence(claim); var environment = hostedTerms.captureCurrentEnvironmentBoundary(); IssuePreparation preparation = @@ -159,12 +171,45 @@ public AuthorizationResponse issue(IssueRequest request) { tuple.action().scope().tenantId(), environment, current -> { + requireFreshClaimEvidence(claim); IssuanceRecord existing = findRecord(tuple.controlPlaneRequestId()).orElse(null); - OwnerLinearization linearization = - existing == null ? issuanceOperations.captureOwnerLinearization() : null; - return new IssuePreparation(current, existing, linearization); + if (existing != null) { + requireOriginalBinding( + existing, + tuple, + request.canonicalTupleBytes(), + request.reservationOwnerId(), + request.reservationClaimFence()); + } + AccountStartSessionAuthorityCapture capture = + existing == null + ? captureRepository.prepareOrReadExact( + current, + tuple, + loggingPeerUri, + request.reservationOwnerId(), + request.reservationClaimFence()) + : captureRepository.lockReadExactCurrent( + current, + tuple, + loggingPeerUri, + request.reservationOwnerId(), + request.reservationClaimFence()); + if (existing != null) { + var originalBundle = + AccountStartSessionOperatorAuthorityBundle.decode( + existing.authorityEvidenceBundle()); + var originalReference = + AccountStartSessionOperatorAuthorityBundle.fromSharedReference( + existing.bundleReference()); + originalBundle.requireCaptureBinding(capture, tuple, originalReference); + originalBundle.requireCurrent( + current.source(), current.stored(), tuple, originalReference, clock.instant()); + } + return new IssuePreparation(current, capture, existing); }); + requireFreshClaimEvidence(claim); if (preparation.existing() != null) { IssuanceRecord original = preparation.existing(); requireOriginalBinding( @@ -174,51 +219,80 @@ public AuthorizationResponse issue(IssueRequest request) { request.reservationOwnerId(), request.reservationClaimFence()); AuthorizationResponse response = openOriginalResponse(tuple, original); - return actors.withCurrent( - request.controlUiJwt(), - tuple.action().scope().tenantId(), - environment, - current -> { - requireSameCurrent(preparation.current(), current); - IssuanceRecord exact = - findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); - requireSameStoredIssuance(original, exact); - requireOriginalBinding( - exact, - tuple, - request.canonicalTupleBytes(), - request.reservationOwnerId(), - request.reservationClaimFence()); - AccountStartSessionOperatorAuthorityBundle.decode(exact.authorityEvidenceBundle()) - .requireCurrent( - current.source(), - current.stored(), + var finalEnvironment = hostedTerms.captureCurrentEnvironmentBoundary(); + AuthorizationResponse currentResponse = + actors.withCurrentCommitted( + tuple.actor().accountId(), + tuple.action().scope().tenantId(), + preparation.current().stored().jti, + finalEnvironment, + current -> { + requireSameCurrent(preparation.current(), current); + IssuanceRecord exact = + findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); + requireSameStoredIssuance(original, exact); + requireOriginalBinding( + exact, tuple, + request.canonicalTupleBytes(), + request.reservationOwnerId(), + request.reservationClaimFence()); + AccountStartSessionAuthorityCapture lockedCapture = + captureRepository.lockExactCurrent( + preparation.capture(), + current, + tuple, + loggingPeerUri, + request.reservationOwnerId(), + request.reservationClaimFence()); + var exactBundle = + AccountStartSessionOperatorAuthorityBundle.decode( + exact.authorityEvidenceBundle()); + var originalReference = AccountStartSessionOperatorAuthorityBundle.fromSharedReference( - original.bundleReference()), - clock.instant()); - return response; - }); + original.bundleReference()); + exactBundle.requireCaptureBinding(lockedCapture, tuple, originalReference); + exactBundle.requireCurrent( + current.source(), current.stored(), tuple, originalReference, clock.instant()); + requireFreshClaimEvidence(claim); + return response; + }); + requireFreshClaimEvidence(claim); + return currentResponse; } PreparedIssuance candidate = - prepareIssuance(preparation.current(), tuple, request, preparation.linearization()); + prepareIssuance(preparation.current().stored(), preparation.capture(), tuple, request); + var finalEnvironment = hostedTerms.captureCurrentEnvironmentBoundary(); IssueOutcome outcome = - actors.withCurrent( - request.controlUiJwt(), + actors.withCurrentCommitted( + tuple.actor().accountId(), tuple.action().scope().tenantId(), - environment, + preparation.current().stored().jti, + finalEnvironment, current -> { requireSameCurrent(preparation.current(), current); + AccountStartSessionAuthorityCapture lockedCapture = + captureRepository.lockExactCurrent( + preparation.capture(), + current, + tuple, + loggingPeerUri, + request.reservationOwnerId(), + request.reservationClaimFence()); + candidate + .bundle() + .requireCaptureBinding( + lockedCapture, tuple, candidate.bundle().referenceForCapture(lockedCapture)); candidate .bundle() .requireCurrent( current.source(), current.stored(), tuple, - AccountStartSessionOperatorAuthorityBundle.fromSharedReference( - candidate.candidate().bundleReference()), + candidate.bundle().referenceForCapture(lockedCapture), clock.instant()); + requireFreshClaimEvidence(claim); var created = repository.createOrReadExact(candidate.candidate()); requireOriginalBinding( created.issuance(), @@ -228,33 +302,64 @@ public AuthorizationResponse issue(IssueRequest request) { request.reservationClaimFence()); if (created.created()) { requireCandidateRecord(candidate.candidate(), created.issuance()); + } else { + var originalBundle = + AccountStartSessionOperatorAuthorityBundle.decode( + created.issuance().authorityEvidenceBundle()); + originalBundle.requireCaptureBinding( + lockedCapture, + tuple, + AccountStartSessionOperatorAuthorityBundle.fromSharedReference( + created.issuance().bundleReference())); } + requireFreshClaimEvidence(claim); return new IssueOutcome(created.created(), created.issuance()); }); if (outcome.created()) { - return candidate.response(); + return authorizationResponse(candidate.response(), outcome.issuance()); } - AuthorizationResponse response = openOriginalResponse(tuple, outcome.issuance()); - return actors.withCurrent( - request.controlUiJwt(), - tuple.action().scope().tenantId(), - environment, - current -> { - requireSameCurrent(preparation.current(), current); - IssuanceRecord exact = - findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); - requireSameStoredIssuance(outcome.issuance(), exact); - AccountStartSessionOperatorAuthorityBundle.decode(exact.authorityEvidenceBundle()) - .requireCurrent( - current.source(), - current.stored(), + AuthorizationResponse originalResponse = openOriginalResponse(tuple, outcome.issuance()); + var winnerEnvironment = hostedTerms.captureCurrentEnvironmentBoundary(); + AuthorizationResponse currentResponse = + actors.withCurrentCommitted( + tuple.actor().accountId(), + tuple.action().scope().tenantId(), + preparation.current().stored().jti, + winnerEnvironment, + current -> { + requireSameCurrent(preparation.current(), current); + IssuanceRecord exact = + findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); + requireSameStoredIssuance(outcome.issuance(), exact); + requireOriginalBinding( + exact, tuple, + request.canonicalTupleBytes(), + request.reservationOwnerId(), + request.reservationClaimFence()); + AccountStartSessionAuthorityCapture lockedCapture = + captureRepository.lockExactCurrent( + preparation.capture(), + current, + tuple, + loggingPeerUri, + request.reservationOwnerId(), + request.reservationClaimFence()); + var exactBundle = + AccountStartSessionOperatorAuthorityBundle.decode( + exact.authorityEvidenceBundle()); + var exactReference = AccountStartSessionOperatorAuthorityBundle.fromSharedReference( - exact.bundleReference()), - clock.instant()); - return response; - }); + exact.bundleReference()); + exactBundle.requireCaptureBinding(lockedCapture, tuple, exactReference); + exactBundle.requireCurrent( + current.source(), current.stored(), tuple, exactReference, clock.instant()); + requireFreshClaimEvidence(claim); + return originalResponse; + }); + requireFreshClaimEvidence(claim); + return currentResponse; } /** @@ -283,6 +388,7 @@ public AuthorizationResponse recover(RecoverRequest request) { request.reservationClaimFence(), request.claimOwnerId(), request.claimFence()); + requireFreshClaimEvidence(claim); IssuanceRecord observed = findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); @@ -297,7 +403,7 @@ public AuthorizationResponse recover(RecoverRequest request) { bundle.requireTupleBinding(tuple); UUID tokenJti = bundle.controlUiTokenJti(); var environment = hostedTerms.captureCurrentEnvironmentBoundary(); - Current preparation = + IssuePreparation preparation = actors.withCurrentCommitted( tuple.actor().accountId(), tuple.action().scope().tenantId(), @@ -313,35 +419,66 @@ public AuthorizationResponse recover(RecoverRequest request) { request.canonicalTupleBytes(), request.reservationOwnerId(), request.reservationClaimFence()); - return current; + AccountStartSessionAuthorityCapture capture = + captureRepository.lockReadExactCurrent( + current, + tuple, + loggingPeerUri, + request.reservationOwnerId(), + request.reservationClaimFence()); + var exactBundle = + AccountStartSessionOperatorAuthorityBundle.decode( + exact.authorityEvidenceBundle()); + var exactReference = + AccountStartSessionOperatorAuthorityBundle.fromSharedReference( + exact.bundleReference()); + exactBundle.requireCaptureBinding(capture, tuple, exactReference); + exactBundle.requireCurrent( + current.source(), current.stored(), tuple, exactReference, clock.instant()); + requireFreshClaimEvidence(claim); + return new IssuePreparation(current, capture, exact); }); AuthorizationResponse response = openOriginalResponse(tuple, observed); - return actors.withCurrentCommitted( - tuple.actor().accountId(), - tuple.action().scope().tenantId(), - tokenJti, - environment, - current -> { - requireSameCurrent(preparation, current); - IssuanceRecord exact = - findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); - requireSameStoredIssuance(observed, exact); - requireOriginalBinding( - exact, - tuple, - request.canonicalTupleBytes(), - request.reservationOwnerId(), - request.reservationClaimFence()); - AccountStartSessionOperatorAuthorityBundle.decode(exact.authorityEvidenceBundle()) - .requireCurrent( - current.source(), - current.stored(), + var finalEnvironment = hostedTerms.captureCurrentEnvironmentBoundary(); + AuthorizationResponse currentResponse = + actors.withCurrentCommitted( + tuple.actor().accountId(), + tuple.action().scope().tenantId(), + tokenJti, + finalEnvironment, + current -> { + requireSameCurrent(preparation.current(), current); + IssuanceRecord exact = + findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); + requireSameStoredIssuance(preparation.existing(), exact); + requireOriginalBinding( + exact, tuple, + request.canonicalTupleBytes(), + request.reservationOwnerId(), + request.reservationClaimFence()); + AccountStartSessionAuthorityCapture lockedCapture = + captureRepository.lockExactCurrent( + preparation.capture(), + current, + tuple, + loggingPeerUri, + request.reservationOwnerId(), + request.reservationClaimFence()); + var exactBundle = + AccountStartSessionOperatorAuthorityBundle.decode( + exact.authorityEvidenceBundle()); + var exactReference = AccountStartSessionOperatorAuthorityBundle.fromSharedReference( - exact.bundleReference()), - clock.instant()); - return response; - }); + exact.bundleReference()); + exactBundle.requireCaptureBinding(lockedCapture, tuple, exactReference); + exactBundle.requireCurrent( + current.source(), current.stored(), tuple, exactReference, clock.instant()); + requireFreshClaimEvidence(claim); + return response; + }); + requireFreshClaimEvidence(claim); + return currentResponse; } /** REDEEM: exact Game Session peer before tuple parsing or durable reference lookup. */ @@ -436,24 +573,34 @@ public RedemptionResult redeem(RedeemRequest request) { observed.bundleReference()), currentInstant); } - RedemptionResult result = - repository.redeemExact( - new RedemptionRequest( - tuple.controlPlaneRequestId(), - request.canonicalTupleBytes(), - observed.authorizationReferenceFingerprint(), - observed.reservationOwnerId(), - observed.reservationClaimFence(), - gameSessionPeerUri, - request.ownerAttemptId(), - request.ownerFence(), - observed.authorityEvidenceBundle(), - currentInstant)); + net.firedevops.firemud.accountservice.repository + .AccountStartSessionOperatorAuthorizationRepository.RedemptionResult + result = + repository.redeemExact( + new RedemptionRequest( + tuple.controlPlaneRequestId(), + request.canonicalTupleBytes(), + observed.authorizationReferenceFingerprint(), + observed.reservationOwnerId(), + observed.reservationClaimFence(), + gameSessionPeerUri, + request.ownerAttemptId(), + request.ownerFence(), + observed.authorityEvidenceBundle(), + currentInstant)); requireRedemptionProjection(result, observed); if (sameAttemptReplay != result.replay()) { throw denied("Account returned a changed one-time redemption outcome"); } - return result; + StartSessionPostAuthorizationExecutionTuple originalTuple = + postAuthorizationTuple(exact); + return new RedemptionResult( + result.authorizationReferenceFingerprint(), + result.authorityEvidenceBundle(), + result.issuanceOperationId(), + result.issuanceFence(), + result.replay(), + originalTuple.canonicalBytes()); }); } finally { Arrays.fill(referenceBytes, (byte) 0); @@ -462,12 +609,13 @@ public RedemptionResult redeem(RedeemRequest request) { /** * Returns only the immutable original projection of an already-redeemed operation to the exact - * same-namespace Game Design peer. This read neither exposes a credential nor changes owner - * state; Account independently revalidates the original committed actor and source. + * same-namespace Game Design peer or the exact original Game Session redeemer. This read neither + * exposes a credential nor changes owner state; Account independently revalidates the original + * committed actor and source. */ public RedeemedOperationProjection readRedeemedOperationProjection( ReadRedeemedOperationProjectionRequest request) { - requirePeer(gameDesignPeerUri); + requireRedeemedProjectionReadPeer(); Objects.requireNonNull(request, "redeemed operation projection request is required"); byte[] exactTupleBytes = request.canonicalPreAuthorizationTuple(); StartSessionPreAuthorizationReservationTuple tuple = decodeTuple(exactTupleBytes); @@ -524,12 +672,158 @@ public RedeemedOperationProjection readRedeemedOperationProjection( }); } + /** + * Revalidates the original human StartSession authority for a package-local World participation + * mutation and invokes the supplied Account-local mutation callback after locking its exact + * durable source capture in the same Account transaction. This is only a currentness building + * block: it does not authenticate caller-provided Game Session evidence or constitute a complete + * World participation service. A future caller must obtain genuine Game Session proof before + * invoking it. No end-user credential is accepted on this World-only path. + * + *

The canonical tuple is decoded only after authenticating the exact derived same-namespace + * World peer. All input bytes and the actual redeemed Game Session attempt/fence are compared to + * Account's original issuance and redemption; this path never issues, redeems, allocates, or + * renews authority. + */ + T withCurrentWorldReceivingParticipationCurrentness( + byte[] exactCanonicalPostAuthorizationTuple, + UUID actualGameSessionOwnerAttemptId, + long actualGameSessionOwnerFence, + Function accountMutation) { + requirePeer(worldManagementPeerUri); + if (SessionContext.hasAuthenticatedCallerContext()) { + throw denied("World participation currentness requires no authenticated end-user context"); + } + requireNoAmbientTransactionOrSynchronization(); + return withCurrentReceivingParticipationCurrentness( + exactCanonicalPostAuthorizationTuple, + actualGameSessionOwnerAttemptId, + actualGameSessionOwnerFence, + accountMutation); + } + + private T withCurrentReceivingParticipationCurrentness( + byte[] exactCanonicalPostAuthorizationTuple, + UUID actualGameSessionOwnerAttemptId, + long actualGameSessionOwnerFence, + Function accountMutation) { + + byte[] exactPostTupleBytes = copy(exactCanonicalPostAuthorizationTuple); + StartSessionPostAuthorizationExecutionTuple postTuple = + StartSessionPostAuthorizationExecutionTuple.decode(exactPostTupleBytes); + Objects.requireNonNull(accountMutation, "Account-local participation mutation is required"); + StartSessionPreAuthorizationReservationTuple tuple = postTuple.preAuthorizationTuple(); + if (!"game-session-service".equals(tuple.targetOwner())) { + throw denied("Original StartSession target owner must remain Game Session"); + } + GrpcPeerIdentity receivingPeer = GrpcPeerIdentity.current(); + if (receivingPeer == null + || !tuple.action().scope().targetNamespace().equals(receivingPeer.namespace())) { + throw denied("StartSession target namespace does not match the authenticated World peer"); + } + if (!loggingPeerUri.equals(postTuple.authenticatedWorkloadIdentity())) { + throw denied("Original StartSession Logging workload identity changed"); + } + requireNonNilUuid(actualGameSessionOwnerAttemptId, "actual Game Session owner attempt ID"); + requirePositiveFence(actualGameSessionOwnerFence, "actual Game Session owner fence"); + + byte[] exactPreTupleBytes = tuple.canonicalJson().getBytes(StandardCharsets.UTF_8); + IssuanceRecord observed = + findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); + requireOriginalBinding( + observed, + tuple, + exactPreTupleBytes, + postTuple.reservationOwnerId(), + postTuple.reservationClaimFence()); + AccountStartSessionOperatorAuthorityBundle observedBundle = + AccountStartSessionOperatorAuthorityBundle.decode(observed.authorityEvidenceBundle()); + observedBundle.requireTupleBinding(tuple); + requireReceivingPostTupleBinding(postTuple, observed, tuple); + ReadRedeemedOperationProjectionRequest redemptionRequest = + new ReadRedeemedOperationProjectionRequest( + exactPreTupleBytes, + postTuple.authorizationReferenceFingerprint(), + postTuple.reservationOwnerId(), + postTuple.reservationClaimFence(), + actualGameSessionOwnerAttemptId, + actualGameSessionOwnerFence); + requireRedeemedProjectionBinding( + observed, tuple, redemptionRequest, observedBundle, clock.instant()); + + var environment = hostedTerms.captureCurrentEnvironmentBoundary(); + return actors.withCurrentCommitted( + tuple.actor().accountId(), + tuple.action().scope().tenantId(), + observedBundle.controlUiTokenJti(), + environment, + current -> { + IssuanceRecord exact = + findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); + requireSameStoredRedemption(observed, exact); + requireOriginalBinding( + exact, + tuple, + exactPreTupleBytes, + postTuple.reservationOwnerId(), + postTuple.reservationClaimFence()); + AccountStartSessionOperatorAuthorityBundle exactBundle = + AccountStartSessionOperatorAuthorityBundle.decode(exact.authorityEvidenceBundle()); + exactBundle.requireTupleBinding(tuple); + requireReceivingPostTupleBinding(postTuple, exact, tuple); + requireRedeemedProjectionBinding( + exact, tuple, redemptionRequest, exactBundle, clock.instant()); + + AccountStartSessionAuthorityCapture lockedCapture = + captureRepository.lockReadExactCurrentFromWorldReceiving( + current, + tuple, + loggingPeerUri, + postTuple.reservationOwnerId(), + postTuple.reservationClaimFence(), + worldManagementPeerUri); + var originalReference = + AccountStartSessionOperatorAuthorityBundle.fromSharedReference( + exact.bundleReference()); + exactBundle.requireCaptureBinding(lockedCapture, tuple, originalReference); + exactBundle.requireCurrent( + current.source(), current.stored(), tuple, originalReference, clock.instant()); + return accountMutation.apply(lockedCapture); + }); + } + + private void requireReceivingPostTupleBinding( + StartSessionPostAuthorizationExecutionTuple supplied, + IssuanceRecord original, + StartSessionPreAuthorizationReservationTuple tuple) { + StartSessionPostAuthorizationExecutionTuple expected = + StartSessionPostAuthorizationExecutionTuple.createHuman( + tuple, + original.issuanceWorkloadUri(), + original.authorizationReferenceFingerprint(), + original.reservationOwnerId(), + original.reservationClaimFence(), + original.authorityEvidenceBundle(), + original.bundleReference()); + if (!MessageDigest.isEqual(expected.canonicalBytes(), supplied.canonicalBytes())) { + throw denied("World participation tuple differs from the original Account issuance"); + } + } + + private static void requireNoAmbientTransactionOrSynchronization() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw denied("World currentness must begin without an ambient Account transaction"); + } + } + private PreparedIssuance prepareIssuance( - Current current, + Stored controlUiIssuance, + AccountStartSessionAuthorityCapture capture, StartSessionPreAuthorizationReservationTuple tuple, - IssueRequest request, - OwnerLinearization linearization) { - Objects.requireNonNull(linearization, "Account owner source linearization is required"); + IssueRequest request) { + Objects.requireNonNull(controlUiIssuance, "original ControlUI issuance is required"); + Objects.requireNonNull(capture, "committed Account source capture is required"); byte[] exactTuple = request.canonicalTupleBytes(); Instant issuedAt = Instant.ofEpochMilli(clock.millis()); Instant referenceExpiresAt = addMillis(issuedAt, referenceLifetimeMillis); @@ -537,14 +831,8 @@ private PreparedIssuance prepareIssuance( UUID issuanceOperationId = UUID.randomUUID(); var bundle = AccountStartSessionOperatorAuthorityBundle.create( - tuple, - current.source(), - current.stored(), - issuanceOperationId, - linearization, - issuedAt, - referenceExpiresAt); - var bundleReference = bundle.referenceForSource(current.source(), linearization); + tuple, capture, controlUiIssuance, issuanceOperationId, issuedAt, referenceExpiresAt); + var bundleReference = bundle.referenceForCapture(capture); byte[] random = new byte[REFERENCE_RANDOM_BYTES]; secureRandom.nextBytes(random); @@ -555,8 +843,8 @@ private PreparedIssuance prepareIssuance( try { String fingerprint = fingerprintKeys.fingerprintForIssue(ReferenceKind.HUMAN_OPERATOR, referenceBytes); - AuthorizationResponse response = - new AuthorizationResponse( + StoredAuthorizationResponse response = + new StoredAuthorizationResponse( authorizationReference, fingerprint, referenceExpiresAt, @@ -570,7 +858,7 @@ private PreparedIssuance prepareIssuance( tuple, exactTuple, loggingPeerUri, - linearization.sourceFence(), + bundle.issuanceFence(), bundle), responseBytes, responseExpiresAt); @@ -583,7 +871,7 @@ private PreparedIssuance prepareIssuance( request.reservationOwnerId(), request.reservationClaimFence(), issuanceOperationId, - linearization.sourceFence(), + bundle.issuanceFence(), AccountStartSessionOperatorAuthorityBundle.toSharedReference(bundleReference), bundle.canonicalBytes(), fingerprint, @@ -619,9 +907,9 @@ private AuthorizationResponse openOriginalResponse( record.issuanceFence(), bundle), record.responseEnvelopeExpiresAt()); - AuthorizationResponse response = decodeResponse(plaintext); + StoredAuthorizationResponse response = decodeResponse(plaintext); requireResponseMatchesRecord(response, record); - return response; + return authorizationResponse(response, record); } finally { if (plaintext != null) Arrays.fill(plaintext, (byte) 0); } @@ -648,9 +936,9 @@ private Optional tryOpenOriginalResponse( record.issuanceFence(), bundle), record.responseEnvelopeExpiresAt()); - AuthorizationResponse response = decodeResponse(plaintext); + StoredAuthorizationResponse response = decodeResponse(plaintext); requireResponseMatchesRecord(response, record); - return Optional.of(response); + return Optional.of(authorizationResponse(response, record)); } catch (AccountResponseEnvelopeCryptography.ResponseRecoveryExpiredException expired) { return Optional.empty(); } finally { @@ -687,7 +975,7 @@ static String envelopeBindingRequestId(String requestId) { return java.util.HexFormat.of().formatHex(sha256(requestId.getBytes(StandardCharsets.UTF_8))); } - private static byte[] encodeResponse(AuthorizationResponse response) { + private static byte[] encodeResponse(StoredAuthorizationResponse response) { return AccountControlUiAuthority.canonical( Map.of( "operatorAuthorizationReference", response.operatorAuthorizationReference(), @@ -700,7 +988,7 @@ private static byte[] encodeResponse(AuthorizationResponse response) { "bundleReference", response.bundleReference().asJsonValue())); } - private static AuthorizationResponse decodeResponse(byte[] exactBytes) { + private static StoredAuthorizationResponse decodeResponse(byte[] exactBytes) { try { String json = new String(exactBytes, StandardCharsets.UTF_8); Map root = JSON.readValue(json, new TypeReference<>() {}); @@ -717,12 +1005,12 @@ private static AuthorizationResponse decodeResponse(byte[] exactBytes) { root.get("bundleReference")); byte[] canonical = encodeResponse( - new AuthorizationResponse( + new StoredAuthorizationResponse( reference, fingerprint, expiresAt, bundleBytes, sourceReference)); if (!MessageDigest.isEqual(canonical, exactBytes)) { throw denied("Original response envelope is not canonical"); } - return new AuthorizationResponse( + return new StoredAuthorizationResponse( reference, fingerprint, expiresAt, bundleBytes, sourceReference); } catch (IllegalStateException failure) { throw failure; @@ -731,7 +1019,8 @@ private static AuthorizationResponse decodeResponse(byte[] exactBytes) { } } - private void requireResponseMatchesRecord(AuthorizationResponse response, IssuanceRecord record) { + private void requireResponseMatchesRecord( + StoredAuthorizationResponse response, IssuanceRecord record) { var bundle = AccountStartSessionOperatorAuthorityBundle.decode(record.authorityEvidenceBundle()); if (!response @@ -746,10 +1035,7 @@ private void requireResponseMatchesRecord(AuthorizationResponse response, Issuan || !response.bundleReference().sourceVersion().equals(bundleSourceVersion(bundle)) || !AccountStartSessionOperatorAuthorityBundle.toSharedReference(response.bundleReference()) .equals(record.bundleReference()) - || !response - .bundleReference() - .sourceFence() - .equals(Long.toString(record.issuanceFence()))) { + || bundle.issuanceFence() != record.issuanceFence()) { throw denied("Original issuance response differs from the immutable Account record"); } byte[] referenceBytes = @@ -768,6 +1054,43 @@ private void requireResponseMatchesRecord(AuthorizationResponse response, Issuan } } + private AuthorizationResponse authorizationResponse( + StoredAuthorizationResponse response, IssuanceRecord record) { + requireResponseMatchesRecord(response, record); + return new AuthorizationResponse( + response.operatorAuthorizationReference(), + response.authorizationReferenceFingerprint(), + response.expiresAt(), + response.authorityEvidenceBundle(), + response.bundleReference(), + postAuthorizationTuple(record).canonicalBytes()); + } + + /** Builds the complete public owner tuple only from Account's immutable original record. */ + private static StartSessionPostAuthorizationExecutionTuple postAuthorizationTuple( + IssuanceRecord record) { + Objects.requireNonNull(record, "retained Account issuance record is required"); + StartSessionPreAuthorizationReservationTuple tuple = + decodeTuple(record.preAuthorizationTuple()); + AccountStartSessionOperatorAuthorityBundle bundle = + AccountStartSessionOperatorAuthorityBundle.decode(record.authorityEvidenceBundle()); + var reference = record.bundleReference(); + bundle.requireTupleBinding(tuple); + if (!tuple.controlPlaneRequestId().equals(record.controlPlaneRequestId()) + || !tuple.mutationDigest().equals(record.mutationDigest()) + || bundle.issuanceFence() != record.issuanceFence()) { + throw denied("Retained Account issuance binding is inconsistent"); + } + return StartSessionPostAuthorizationExecutionTuple.createHuman( + tuple, + record.issuanceWorkloadUri(), + record.authorizationReferenceFingerprint(), + record.reservationOwnerId(), + record.reservationClaimFence(), + record.authorityEvidenceBundle(), + reference); + } + private static void requireSameCurrent(Current expected, Current observed) { if (!sameCurrentSource(expected.source(), observed.source()) || !sameControlUiIssuance(expected.stored(), observed.stored())) { @@ -844,7 +1167,10 @@ private static String bundleSourceVersion(AccountStartSessionOperatorAuthorityBu } private static void requireRedemptionProjection( - RedemptionResult result, IssuanceRecord issuance) { + net.firedevops.firemud.accountservice.repository + .AccountStartSessionOperatorAuthorizationRepository.RedemptionResult + result, + IssuanceRecord issuance) { if (!issuance .authorizationReferenceFingerprint() .equals(result.authorizationReferenceFingerprint()) @@ -882,6 +1208,16 @@ private static void requireClaimEcho( } } + private void requireFreshClaimEvidence(ReadCurrentClaimEvidenceResponse evidence) { + Objects.requireNonNull(evidence, "Logging/Admin claim evidence is required"); + long observedAt = evidence.getObservedAtEpochMillis(); + long expiresAt = evidence.getClaimExpiresAtEpochMillis(); + long now = clock.millis(); + if (observedAt <= 0L || expiresAt <= observedAt || now >= expiresAt) { + throw denied("Logging/Admin StartSession claim evidence is stale or contradictory"); + } + } + private static StartSessionPreAuthorizationReservationTuple decodeTuple(byte[] exactTupleBytes) { if (exactTupleBytes == null || exactTupleBytes.length == 0) { throw new IllegalArgumentException("Canonical StartSession reservation tuple is required"); @@ -1067,6 +1403,14 @@ private static void requirePeer(String exactUri) { } } + private void requireRedeemedProjectionReadPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || (!gameDesignPeerUri.equals(peer.uri()) && !gameSessionPeerUri.equals(peer.uri()))) { + throw denied("Exact authenticated Game Design or original Game Session identity is required"); + } + } + private static String exactPeer(String value, String expectedService) { return GrpcPeerIdentity.parseUri(value) .map(GrpcPeerIdentity::uri) @@ -1123,18 +1467,16 @@ private static IllegalStateException denied(String reason) { } private record IssuePreparation( - Current current, IssuanceRecord existing, OwnerLinearization linearization) { + Current current, AccountStartSessionAuthorityCapture capture, IssuanceRecord existing) { private IssuePreparation { Objects.requireNonNull(current, "current Account actor is required"); - if ((existing == null) != (linearization != null)) { - throw denied("Issue preparation must contain either an original record or its fence"); - } + Objects.requireNonNull(capture, "durable Account source capture is required"); } } private record PreparedIssuance( AccountStartSessionOperatorAuthorityBundle bundle, - AuthorizationResponse response, + StoredAuthorizationResponse response, IssuanceCandidate candidate) { private PreparedIssuance { Objects.requireNonNull(bundle, "authority bundle is required"); @@ -1283,13 +1625,16 @@ public record AuthorizationResponse( String authorizationReferenceFingerprint, Instant expiresAt, byte[] authorityEvidenceBundle, - AccountStartSessionOperatorAuthorityBundle.BundleReference bundleReference) { + AccountStartSessionOperatorAuthorityBundle.BundleReference bundleReference, + byte[] originalAccountPostAuthorizationTuple) { public AuthorizationResponse { requireReference(operatorAuthorizationReference); requireFingerprint(authorizationReferenceFingerprint); Objects.requireNonNull(expiresAt, "reference expiry is required"); authorityEvidenceBundle = copy(authorityEvidenceBundle); Objects.requireNonNull(bundleReference, "source bundle reference is required"); + originalAccountPostAuthorizationTuple = copy(originalAccountPostAuthorizationTuple); + StartSessionPostAuthorizationExecutionTuple.decode(originalAccountPostAuthorizationTuple); } @Override @@ -1297,12 +1642,72 @@ public byte[] authorityEvidenceBundle() { return copy(authorityEvidenceBundle); } + @Override + public byte[] originalAccountPostAuthorizationTuple() { + return copy(originalAccountPostAuthorizationTuple); + } + @Override public String toString() { return "AuthorizationResponse[reference, bundle, and fingerprint redacted]"; } } + /** Private five-field plaintext used only inside the unchanged encrypted recovery envelope. */ + private record StoredAuthorizationResponse( + String operatorAuthorizationReference, + String authorizationReferenceFingerprint, + Instant expiresAt, + byte[] authorityEvidenceBundle, + AccountStartSessionOperatorAuthorityBundle.BundleReference bundleReference) { + private StoredAuthorizationResponse { + requireReference(operatorAuthorizationReference); + requireFingerprint(authorizationReferenceFingerprint); + Objects.requireNonNull(expiresAt, "reference expiry is required"); + authorityEvidenceBundle = copy(authorityEvidenceBundle); + Objects.requireNonNull(bundleReference, "source bundle reference is required"); + } + + @Override + public byte[] authorityEvidenceBundle() { + return copy(authorityEvidenceBundle); + } + } + + /** Public redemption result with the independently reconstructed original Account tuple. */ + public record RedemptionResult( + String authorizationReferenceFingerprint, + byte[] authorityEvidenceBundle, + UUID issuanceOperationId, + long issuanceFence, + boolean replay, + byte[] originalAccountPostAuthorizationTuple) { + public RedemptionResult { + authorityEvidenceBundle = copy(authorityEvidenceBundle); + originalAccountPostAuthorizationTuple = copy(originalAccountPostAuthorizationTuple); + StartSessionPostAuthorizationExecutionTuple.decode(originalAccountPostAuthorizationTuple); + } + + @Override + public byte[] authorityEvidenceBundle() { + return copy(authorityEvidenceBundle); + } + + @Override + public byte[] originalAccountPostAuthorizationTuple() { + return copy(originalAccountPostAuthorizationTuple); + } + + @Override + public String toString() { + return "RedemptionResult[issuanceOperationId=" + + issuanceOperationId + + ", replay=" + + replay + + ", authority and tuple redacted]"; + } + } + public static final class NotFoundException extends RuntimeException { public NotFoundException() { super("No original StartSession operator authorization exists"); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionGrpcService.java new file mode 100644 index 0000000000..06bdfd6ef9 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionGrpcService.java @@ -0,0 +1,374 @@ +package net.firedevops.firemud.accountservice.service.session; + +import com.google.protobuf.Message; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.SQLException; +import java.util.Arrays; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.account.v1.AccountStartSessionWorldParticipationAcquisitionServiceGrpc; +import net.firedevops.firemud.account.v1.AcquireStartSessionWorldParticipationRequest; +import net.firedevops.firemud.account.v1.AcquireStartSessionWorldParticipationResponse; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository.StoredEvidence; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationAcquisitionService.AcquiredParticipation; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationAcquisitionService.AcquisitionRequest; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionCurrentAttemptResponse; +import org.jooq.exception.DataAccessException; +import org.springframework.transaction.CannotCreateTransactionException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Standalone unregistered receiver authenticating the exact World peer before request parsing. */ +public final class AccountStartSessionWorldParticipationAcquisitionGrpcService + extends AccountStartSessionWorldParticipationAcquisitionServiceGrpc + .AccountStartSessionWorldParticipationAcquisitionServiceImplBase { + private static final int MAX_REQUEST_BYTES = + WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES + + StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + + 2 * 1024; + private static final int MAX_RESPONSE_BYTES = + MAX_REQUEST_BYTES + + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.MAX_RESPONSE_BYTES + + 2 * 1024; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + + private final AccountStartSessionWorldParticipationAcquisitionService owner; + private final String namespace; + + public AccountStartSessionWorldParticipationAcquisitionGrpcService( + AccountStartSessionWorldParticipationAcquisitionService owner, String namespace) { + this.owner = Objects.requireNonNull(owner, "World participation acquisition owner is required"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.namespace = namespace; + } + + @Override + public void acquireStartSessionWorldParticipation( + AcquireStartSessionWorldParticipationRequest request, + StreamObserver observer) { + Objects.requireNonNull(observer, "response observer is required"); + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + observer.onError(Status.UNAUTHENTICATED.asRuntimeException()); + return; + } + String expectedPeer = "spiffe://firemud/ns/" + namespace + "/sa/world-management-service"; + if (SessionContext.hasAuthenticatedCallerContext() + || !namespace.equals(peer.namespace()) + || !expectedPeer.equals(peer.uri())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + return; + } + if (request == null || request.getSerializedSize() > MAX_REQUEST_BYTES) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + + final AcquisitionRequest acquisition; + try { + acquisition = decodeRequest(request, namespace); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + + try { + AcquiredParticipation acquired = owner.acquire(acquisition); + AcquireStartSessionWorldParticipationResponse response = + toResponse(request, namespace, acquired); + observer.onNext(response); + observer.onCompleted(); + } catch (AccountStartSessionOperatorAuthorizationService.NotFoundException missing) { + fail(observer, Status.NOT_FOUND); + } catch (CannotCreateTransactionException unavailable) { + fail(observer, Status.UNAVAILABLE); + } catch (DataAccessException | org.springframework.dao.DataAccessException failure) { + fail(observer, hasConnectionFailureSqlState(failure) ? Status.UNAVAILABLE : Status.INTERNAL); + } catch (StatusRuntimeException upstream) { + fail(observer, mapUpstreamStatus(Status.fromThrowable(upstream).getCode())); + } catch (IllegalArgumentException invalidEvidence) { + fail(observer, Status.FAILED_PRECONDITION); + } catch (IllegalStateException rejected) { + fail(observer, Status.FAILED_PRECONDITION); + } catch (RuntimeException failure) { + fail(observer, Status.INTERNAL); + } + } + + private static boolean hasConnectionFailureSqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException exception) { + String sqlState = exception.getSQLState(); + if (sqlState != null && sqlState.startsWith("08")) { + return true; + } + } + } + return false; + } + + private static Status mapUpstreamStatus(Status.Code code) { + return switch (code) { + case INVALID_ARGUMENT -> Status.INVALID_ARGUMENT; + case NOT_FOUND -> Status.NOT_FOUND; + case PERMISSION_DENIED -> Status.PERMISSION_DENIED; + case FAILED_PRECONDITION, ABORTED -> Status.FAILED_PRECONDITION; + case UNAVAILABLE, DEADLINE_EXCEEDED, RESOURCE_EXHAUSTED -> Status.UNAVAILABLE; + default -> Status.INTERNAL; + }; + } + + private static void fail(StreamObserver observer, Status status) { + String description = + switch (status.getCode()) { + case NOT_FOUND -> "Original StartSession participation source is unavailable"; + case PERMISSION_DENIED -> "Account rejected the authenticated World caller"; + case INVALID_ARGUMENT -> "World participation acquisition input is invalid"; + case FAILED_PRECONDITION -> "Current Account participation evidence is unavailable"; + case UNAVAILABLE -> "Account World participation acquisition is temporarily unavailable"; + default -> "Account World participation acquisition could not be completed"; + }; + observer.onError(status.withDescription(description).asRuntimeException()); + } + + private static AcquisitionRequest decodeRequest( + AcquireStartSessionWorldParticipationRequest request, String expectedNamespace) { + requireClosed(request, "request"); + if (request.getSerializedSize() > MAX_REQUEST_BYTES + || request.getSchemaVersion() != 1 + || !GrpcPeerIdentity.isValidNamespace(expectedNamespace) + || !expectedNamespace.equals(request.getTargetNamespace())) { + throw new IllegalArgumentException("Unsupported or oversized World-participation request"); + } + UUID acquisitionId = canonicalUuid(request.getAcquisitionRequestId(), "acquisitionRequestId"); + UUID mutationId = canonicalUuid(request.getGameSessionOwnerMutationId(), "ownerMutationId"); + UUID attemptId = canonicalUuid(request.getGameSessionOwnerAttemptId(), "ownerAttemptId"); + UUID instanceId = canonicalUuid(request.getCanonicalGameInstanceId(), "gameInstanceId"); + if (request.getGameSessionOwnerFence() <= 0L) { + throw new IllegalArgumentException("Game Session owner fence must be positive"); + } + byte[] tupleBytes = request.getOriginalPostAuthorizationTuple().toByteArray(); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(tupleBytes); + if (tupleBytes.length == 0 + || tupleBytes.length > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + || !MessageDigest.isEqual(tupleBytes, tuple.canonicalBytes()) + || !StartSessionOperatorAction.ACTION_FAMILY.equals( + tuple.preAuthorizationTuple().actionFamily()) + || !StartSessionOperatorAction.OWNER_SERVICE.equals( + tuple.preAuthorizationTuple().targetOwner()) + || !expectedNamespace.equals( + tuple.preAuthorizationTuple().action().scope().targetNamespace())) { + throw new IllegalArgumentException("Exact canonical original StartSession tuple required"); + } + Set occupied = new HashSet<>(); + occupied.add(mutationId); + occupied.add(attemptId); + occupied.add(instanceId); + occupied.add(tuple.reservationOwnerId()); + occupied.add(tuple.preAuthorizationTuple().actor().accountId()); + occupied.add(tuple.preAuthorizationTuple().action().scope().tenantId()); + occupied.add( + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()) + .issuanceOperationId()); + if (tuple.controlPlaneRequestId().equals(acquisitionId.toString()) + || occupied.contains(acquisitionId)) { + throw new IllegalArgumentException( + "Acquisition correlation must be independent of retained operation identities"); + } + String preparation = request.getPreparationInputJson(); + if (preparation.isBlank() + || !StandardCharsets.UTF_8.newEncoder().canEncode(preparation) + || preparation.getBytes(StandardCharsets.UTF_8).length + > WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES + || !SHA256.matcher(request.getPreparationInputDigest()).matches() + || !request + .getPreparationInputDigest() + .equals(digestPrefixed(preparation.getBytes(StandardCharsets.UTF_8)))) { + throw new IllegalArgumentException( + "Exact bounded World preparation input and digest required"); + } + var canonical = + AcquireStartSessionWorldParticipationRequest.newBuilder() + .setSchemaVersion(1) + .setAcquisitionRequestId(acquisitionId.toString()) + .setTargetNamespace(expectedNamespace) + .setOriginalPostAuthorizationTuple(request.getOriginalPostAuthorizationTuple()) + .setGameSessionOwnerMutationId(mutationId.toString()) + .setGameSessionOwnerAttemptId(attemptId.toString()) + .setGameSessionOwnerFence(request.getGameSessionOwnerFence()) + .setCanonicalGameInstanceId(instanceId.toString()) + .setPreparationInputJson(preparation) + .setPreparationInputDigest(request.getPreparationInputDigest()) + .build(); + if (!canonical.equals(request)) { + throw new IllegalArgumentException("World-participation request is not canonical"); + } + return new AcquisitionRequest( + tupleBytes, + mutationId, + attemptId, + request.getGameSessionOwnerFence(), + instanceId, + preparation, + request.getPreparationInputDigest()); + } + + private static AcquireStartSessionWorldParticipationResponse toResponse( + AcquireStartSessionWorldParticipationRequest request, + String namespace, + AcquiredParticipation acquired) { + Objects.requireNonNull(acquired, "Acquired Account participation is required"); + StoredParticipation participation = acquired.participation(); + StoredEvidence evidence = acquired.originalAttemptEvidence(); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode( + request.getOriginalPostAuthorizationTuple().toByteArray()); + if (participation.participationFence() <= 0L + || !namespace.equals(participation.targetNamespace()) + || !participation.controlPlaneRequestId().equals(tuple.controlPlaneRequestId()) + || !Arrays.equals( + participation.originalPostAuthorizationTuple(), + request.getOriginalPostAuthorizationTuple().toByteArray()) + || !participation + .canonicalTenantId() + .equals(tuple.preAuthorizationTuple().action().scope().tenantId()) + || !participation + .canonicalGameInstanceId() + .toString() + .equals(request.getCanonicalGameInstanceId()) + || !participation + .gameSessionOwnerAttemptId() + .toString() + .equals(request.getGameSessionOwnerAttemptId()) + || participation.gameSessionOwnerFence() != request.getGameSessionOwnerFence() + || !participation.preparationInputJson().equals(request.getPreparationInputJson()) + || !participation.preparationInputDigest().equals(request.getPreparationInputDigest()) + || !participation.participationId().equals(evidence.participationId()) + || !evidence + .gameSessionOwnerMutationId() + .toString() + .equals(request.getGameSessionOwnerMutationId()) + || !SHA256.matcher(evidence.originalResponseDigest()).matches() + || !evidence + .originalResponseDigest() + .equals(digestPrefixed(evidence.originalResponseBytes()))) { + throw new IllegalArgumentException( + "Acquired Account participation changed its request binding"); + } + ReadOriginalStartSessionCurrentAttemptResponse observation; + try { + byte[] retained = evidence.originalResponseBytes(); + if (retained.length == 0 + || retained.length + > OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.MAX_RESPONSE_BYTES) { + throw new IllegalArgumentException("Retained original-attempt evidence is oversized"); + } + observation = ReadOriginalStartSessionCurrentAttemptResponse.parseFrom(retained); + } catch (com.google.protobuf.InvalidProtocolBufferException malformed) { + throw new IllegalArgumentException( + "Retained original-attempt evidence is malformed", malformed); + } + var observedRequest = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromRequest(observation.getRequest()); + var exactObservation = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + observedRequest, observation); + if (!OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE.equals( + exactObservation.phaseState()) + || !namespace.equals(observedRequest.targetNamespace()) + || !Arrays.equals( + request.getOriginalPostAuthorizationTuple().toByteArray(), + observedRequest.canonicalPostAuthorizationTuple()) + || !request + .getGameSessionOwnerMutationId() + .equals(observedRequest.expectedOwnerMutationId().toString()) + || !request + .getGameSessionOwnerAttemptId() + .equals(observedRequest.expectedOwnerAttemptId().toString()) + || request.getGameSessionOwnerFence() != observedRequest.expectedOwnerFence() + || !MessageDigest.isEqual( + StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple), + exactObservation.accountRedemptionProjection()) + || !evidence.result().request().equals(exactObservation.request()) + || !evidence + .result() + .originalLeaseExpiresAt() + .equals(exactObservation.originalLeaseExpiresAt()) + || !MessageDigest.isEqual( + evidence.result().accountRedemptionProjection(), + exactObservation.accountRedemptionProjection()) + || !evidence.originalLeaseExpiresAt().equals(exactObservation.originalLeaseExpiresAt()) + || !Arrays.equals( + evidence.originalResponseBytes(), + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(exactObservation) + .toByteArray())) { + throw new IllegalArgumentException("Retained original-attempt evidence changed its binding"); + } + var response = + AcquireStartSessionWorldParticipationResponse.newBuilder() + .setRequest(request) + .setAccountWorldParticipationId(participation.participationId().toString()) + .setAccountWorldParticipationFence(participation.participationFence()) + .setOriginalAttemptEvidence(observation) + .build(); + if (response.getSerializedSize() > MAX_RESPONSE_BYTES) { + throw new IllegalArgumentException("World-participation response exceeds its wire budget"); + } + return response; + } + + private static void requireClosed(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException( + "World-participation " + label + " contains unknown fields"); + } + } + + private static UUID canonicalUuid(String value, String field) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || NIL_UUID.equals(parsed)) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (RuntimeException malformed) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID", malformed); + } + } + + private static String digestPrefixed(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java new file mode 100644 index 0000000000..3b6ae7a0ff --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java @@ -0,0 +1,470 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository.StoredEvidence; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.Candidate; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptClient; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.databind.json.JsonMapper; + +/** + * Unregistered Account composition that acquires one exact World receiving participation from the + * original Game Session owner attempt and retains its current-attempt observation atomically with + * the participation. + * + *

The Game Session response is a point-in-time observation only. Account revalidates the + * original issuer, redemption, authority and locked source capture around the local write; this + * component does not renew authorization or establish World execution admission. No external + * service or runtime transport is registered here. + */ +public final class AccountStartSessionWorldParticipationAcquisitionService { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final AccountStartSessionOperatorAuthorizationService issuer; + private final AccountStartSessionWorldParticipationRepository participationRepository; + private final AccountStartSessionWorldOriginalAttemptEvidenceRepository attemptEvidenceRepository; + private final OriginalStartSessionCurrentAttemptClient gameSessionClient; + private final TransactionTemplate readbackTransaction; + private final String workloadNamespace; + + public AccountStartSessionWorldParticipationAcquisitionService( + AccountStartSessionOperatorAuthorizationService issuer, + AccountStartSessionWorldParticipationRepository participationRepository, + AccountStartSessionWorldOriginalAttemptEvidenceRepository attemptEvidenceRepository, + OriginalStartSessionCurrentAttemptClient gameSessionClient, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.issuer = + Objects.requireNonNull(issuer, "original Account StartSession issuer is required"); + this.participationRepository = + Objects.requireNonNull( + participationRepository, "World participation repository is required"); + this.attemptEvidenceRepository = + Objects.requireNonNull( + attemptEvidenceRepository, "original-attempt evidence repository is required"); + this.gameSessionClient = + Objects.requireNonNull( + gameSessionClient, "Game Session current-attempt client is required"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + readbackTransaction = + new TransactionTemplate( + Objects.requireNonNull(transactionManager, "Account transaction manager is required")); + readbackTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + readbackTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + readbackTransaction.setReadOnly(false); + } + + /** + * Acquires and reads back the exact immutable Account participation and retained observation. An + * unknown commit is propagated for a later retry with this same original request; no reference is + * renewed and no retry write is attempted during readback. + */ + public AcquiredParticipation acquire(AcquisitionRequest request) { + requireWorldPeer(); + requireNoAmbientTransaction(); + Objects.requireNonNull(request, "World participation acquisition request is required"); + + byte[] originalTupleBytes = request.originalPostAuthorizationTuple(); + StartSessionPostAuthorizationExecutionTuple originalTuple = + decodeOriginalTuple(originalTupleBytes); + if (!"StartSession".equals(originalTuple.preAuthorizationTuple().actionFamily()) + || !"game-session-service".equals(originalTuple.preAuthorizationTuple().targetOwner()) + || !workloadNamespace.equals( + originalTuple.preAuthorizationTuple().action().scope().targetNamespace())) { + throw denied("Exact original human StartSession tuple for this World namespace required"); + } + requireNonnil(request.gameSessionOwnerMutationId(), "Game Session owner mutation ID"); + requireNonnil(request.gameSessionOwnerAttemptId(), "Game Session owner attempt ID"); + requirePositive(request.gameSessionOwnerFence(), "Game Session owner fence"); + requireNonnil(request.canonicalGameInstanceId(), "canonical Game Instance ID"); + requirePreparationInput(request.preparationInputJson(), request.preparationInputDigest()); + + Request currentAttemptRequest = + new Request( + freshReadId(originalTuple, request), + workloadNamespace, + originalTupleBytes, + request.gameSessionOwnerAttemptId(), + request.gameSessionOwnerMutationId(), + request.gameSessionOwnerFence()); + + // Game Session is always read before opening Account SQL. A fresh point-in-time read is + // required for every original-request retry; the Account callback below remains the authority. + requireNoAmbientTransaction(); + Result observed = gameSessionClient.read(currentAttemptRequest); + requireNoAmbientTransaction(); + Result exactObservation = exactObservation(currentAttemptRequest, observed, originalTuple); + + Commit commit = + issuer.withCurrentWorldReceivingParticipationCurrentness( + originalTupleBytes, + request.gameSessionOwnerAttemptId(), + request.gameSessionOwnerFence(), + capture -> { + Candidate candidate = + new Candidate( + originalTuple, + capture, + request.canonicalGameInstanceId(), + request.gameSessionOwnerAttemptId(), + request.gameSessionOwnerFence(), + request.preparationInputJson(), + request.preparationInputDigest()); + StoredParticipation participation = + participationRepository.createOrReadExact(candidate); + StoredEvidence evidence = + attemptEvidenceRepository.retainCurrentExact(participation, exactObservation); + requireStoredEvidenceBinding( + participation, currentAttemptRequest, originalTuple, evidence); + return new Commit(candidate, participation, evidence, currentAttemptRequest); + }); + + requireNoAmbientTransaction(); + Readback readback = + Objects.requireNonNull( + readbackTransaction.execute( + ignored -> { + Optional participation = + Objects.requireNonNull( + participationRepository.findCurrentExact(commit.candidate()), + "Current participation lookup returned no optional"); + if (participation.isEmpty()) { + throw denied("Committed exact World participation is not readable as current"); + } + StoredParticipation actualParticipation = participation.orElseThrow(); + StoredEvidence actualEvidence = + attemptEvidenceRepository + .findCurrentExact(actualParticipation, commit.request()) + .orElseThrow( + () -> + denied( + "Committed original Game Session attempt evidence is not readable")); + return new Readback(actualParticipation, actualEvidence); + }), + "Account World participation readback transaction returned no result"); + + if (!sameParticipation(commit.participation(), readback.participation()) + || !sameStoredEvidence(commit.evidence(), readback.evidence())) { + throw denied("Committed World participation or original-attempt proof readback differs"); + } + requireStoredEvidenceBinding( + readback.participation(), commit.request(), originalTuple, readback.evidence()); + return new AcquiredParticipation(readback.participation(), readback.evidence()); + } + + private Result exactObservation( + Request expected, + Result observed, + StartSessionPostAuthorizationExecutionTuple originalTuple) { + if (observed == null) { + throw denied("Exact current original Game Session attempt evidence is unavailable"); + } + try { + var canonicalResponse = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(observed); + Result exact = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + expected, canonicalResponse); + if (!OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE.equals(exact.phaseState()) + || !sameRequest(expected, exact.request(), false) + || !MessageDigest.isEqual( + StartSessionAccountRedemptionProjection.fromOriginalTuple(originalTuple), + exact.accountRedemptionProjection())) { + throw denied( + "Current Game Session attempt or full Account redemption projection differs from the original issuer"); + } + return exact; + } catch (IllegalArgumentException malformed) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact current original Game Session attempt evidence is malformed") + .withCause(malformed) + .asRuntimeException(); + } + } + + private void requireStoredEvidenceBinding( + StoredParticipation participation, + Request expectedRequest, + StartSessionPostAuthorizationExecutionTuple originalTuple, + StoredEvidence evidence) { + if (evidence == null + || !participation.participationId().equals(evidence.participationId()) + || !expectedRequest.expectedOwnerMutationId().equals(evidence.gameSessionOwnerMutationId()) + || !sameRequest(expectedRequest, evidence.result().request(), false) + || !OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE.equals( + evidence.result().phaseState()) + || !MessageDigest.isEqual( + StartSessionAccountRedemptionProjection.fromOriginalTuple(originalTuple), + evidence.result().accountRedemptionProjection()) + || !evidence.originalLeaseExpiresAt().equals(evidence.result().originalLeaseExpiresAt())) { + throw denied("Retained original Game Session attempt proof differs from the exact request"); + } + try { + var response = + net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionCurrentAttemptResponse + .parseFrom(evidence.originalResponseBytes()); + Result decoded = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + evidence.result().request(), response); + if (!sameResult(evidence.result(), decoded) + || !Arrays.equals( + evidence.originalResponseBytes(), + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(decoded) + .toByteArray())) { + throw denied("Retained original Game Session response bytes are not canonical readback"); + } + } catch (com.google.protobuf.InvalidProtocolBufferException malformed) { + throw Status.FAILED_PRECONDITION + .withDescription("Retained original Game Session response is not a complete wire value") + .withCause(malformed) + .asRuntimeException(); + } catch (IllegalArgumentException malformed) { + throw Status.FAILED_PRECONDITION + .withDescription("Retained original Game Session response is malformed") + .withCause(malformed) + .asRuntimeException(); + } + } + + private static boolean sameParticipation( + StoredParticipation expected, StoredParticipation actual) { + if (!expected.participationId().equals(actual.participationId()) + || expected.participationFence() != actual.participationFence() + || !expected.controlPlaneRequestId().equals(actual.controlPlaneRequestId()) + || !Arrays.equals( + expected.originalPostAuthorizationTuple(), actual.originalPostAuthorizationTuple()) + || !expected.targetNamespace().equals(actual.targetNamespace()) + || !expected.canonicalTenantId().equals(actual.canonicalTenantId()) + || !expected.canonicalGameInstanceId().equals(actual.canonicalGameInstanceId()) + || !expected.gameSessionOwnerAttemptId().equals(actual.gameSessionOwnerAttemptId()) + || expected.gameSessionOwnerFence() != actual.gameSessionOwnerFence() + || !expected.preparationInputJson().equals(actual.preparationInputJson()) + || !expected.preparationInputDigest().equals(actual.preparationInputDigest()) + || expected.producerXid() != actual.producerXid() + || !expected.createdAt().equals(actual.createdAt())) { + return false; + } + List expectedSources = + expected.sources().stream() + .sorted(java.util.Comparator.comparing(SourceEvidence::key)) + .toList(); + List actualSources = + actual.sources().stream() + .sorted(java.util.Comparator.comparing(SourceEvidence::key)) + .toList(); + if (expectedSources.size() != actualSources.size()) return false; + for (int index = 0; index < expectedSources.size(); index++) { + var left = expectedSources.get(index); + var right = actualSources.get(index); + if (!left.key().equals(right.key()) + || !Arrays.equals(left.canonicalBytes(), right.canonicalBytes())) return false; + } + return true; + } + + private static boolean sameStoredEvidence(StoredEvidence expected, StoredEvidence actual) { + return expected.participationId().equals(actual.participationId()) + && expected.gameSessionOwnerMutationId().equals(actual.gameSessionOwnerMutationId()) + && expected.originalLeaseExpiresAt().equals(actual.originalLeaseExpiresAt()) + && Arrays.equals(expected.originalResponseBytes(), actual.originalResponseBytes()) + && expected.originalResponseDigest().equals(actual.originalResponseDigest()) + && sameResult(expected.result(), actual.result()); + } + + private static boolean sameResult(Result expected, Result actual) { + return expected.originalLeaseExpiresAt().equals(actual.originalLeaseExpiresAt()) + && sameRequest(expected.request(), actual.request(), true) + && Arrays.equals( + expected.accountRedemptionProjection(), actual.accountRedemptionProjection()); + } + + private static boolean sameRequest(Request expected, Request actual, boolean compareReadId) { + return (!compareReadId || expected.readRequestId().equals(actual.readRequestId())) + && expected.targetNamespace().equals(actual.targetNamespace()) + && Arrays.equals( + expected.canonicalPostAuthorizationTuple(), actual.canonicalPostAuthorizationTuple()) + && expected.expectedOwnerAttemptId().equals(actual.expectedOwnerAttemptId()) + && expected.expectedOwnerMutationId().equals(actual.expectedOwnerMutationId()) + && expected.expectedOwnerFence() == actual.expectedOwnerFence(); + } + + private static StartSessionPostAuthorizationExecutionTuple decodeOriginalTuple( + byte[] tupleBytes) { + if (tupleBytes == null) throw denied("Complete original StartSession tuple is required"); + try { + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(tupleBytes); + if (!Arrays.equals(tupleBytes, tuple.canonicalBytes())) { + throw denied("Original StartSession tuple is not exact canonical bytes"); + } + return tuple; + } catch (IllegalArgumentException malformed) { + throw Status.FAILED_PRECONDITION + .withDescription("Complete canonical original StartSession tuple required") + .withCause(malformed) + .asRuntimeException(); + } + } + + private static UUID freshReadId( + StartSessionPostAuthorizationExecutionTuple tuple, AcquisitionRequest request) { + Set occupied = new HashSet<>(); + occupied.addAll( + List.of( + tuple.reservationOwnerId(), + tuple.preAuthorizationTuple().actor().accountId(), + tuple.preAuthorizationTuple().action().scope().tenantId(), + request.gameSessionOwnerMutationId(), + request.gameSessionOwnerAttemptId(), + request.canonicalGameInstanceId(), + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()) + .issuanceOperationId())); + UUID result; + do { + result = UUID.randomUUID(); + } while (occupied.contains(result)); + return result; + } + + private static void requirePreparationInput(String json, String digest) { + Objects.requireNonNull(json, "exact preparation input JSON is required"); + Objects.requireNonNull(digest, "preparation input digest is required"); + if (json.isBlank() + || !StandardCharsets.UTF_8.newEncoder().canEncode(json) + || json.getBytes(StandardCharsets.UTF_8).length + > WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES + || !SHA256.matcher(digest).matches() + || !digest.equals(digestPrefixed(json.getBytes(StandardCharsets.UTF_8)))) { + throw denied("Exact bounded World preparation input and digest required"); + } + } + + private void requireWorldPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified World workload identity required") + .asRuntimeException(); + } + String expectedUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + if (SessionContext.hasAuthenticatedCallerContext() + || !workloadNamespace.equals(peer.namespace()) + || !expectedUri.equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace World workload without end-user context required") + .asRuntimeException(); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription( + "World participation acquisition requires remote currentness outside Account SQL") + .asRuntimeException(); + } + } + + private static void requireNonnil(UUID value, String name) { + if (value == null || NIL_UUID.equals(value)) { + throw Status.FAILED_PRECONDITION + .withDescription(name + " must be a canonical non-nil UUID") + .asRuntimeException(); + } + } + + private static void requirePositive(long value, String name) { + if (value <= 0L) { + throw Status.FAILED_PRECONDITION + .withDescription(name + " must be positive") + .asRuntimeException(); + } + } + + private static String digestPrefixed(byte[] value) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static StatusRuntimeException denied(String description) { + return Status.FAILED_PRECONDITION.withDescription(description).asRuntimeException(); + } + + /** Raw bounded DTO; validation and canonical decoding occur only after exact peer auth. */ + public record AcquisitionRequest( + byte[] originalPostAuthorizationTuple, + UUID gameSessionOwnerMutationId, + UUID gameSessionOwnerAttemptId, + long gameSessionOwnerFence, + UUID canonicalGameInstanceId, + String preparationInputJson, + String preparationInputDigest) { + public AcquisitionRequest { + originalPostAuthorizationTuple = + originalPostAuthorizationTuple == null ? null : originalPostAuthorizationTuple.clone(); + } + + @Override + public byte[] originalPostAuthorizationTuple() { + return originalPostAuthorizationTuple == null ? null : originalPostAuthorizationTuple.clone(); + } + } + + /** Exact participation plus retained observation; neither value is World admission authority. */ + public record AcquiredParticipation( + StoredParticipation participation, StoredEvidence originalAttemptEvidence) { + public AcquiredParticipation { + Objects.requireNonNull(participation); + Objects.requireNonNull(originalAttemptEvidence); + } + } + + private record Commit( + Candidate candidate, + StoredParticipation participation, + StoredEvidence evidence, + Request request) {} + + private record Readback(StoredParticipation participation, StoredEvidence evidence) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadGrpcService.java new file mode 100644 index 0000000000..1ae6b50507 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadGrpcService.java @@ -0,0 +1,103 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.sql.SQLException; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountStartSessionWorldParticipationHistoricalReadServiceGrpc; +import net.firedevops.firemud.account.v1.ReadHistoricalStartSessionWorldParticipationRequest; +import net.firedevops.firemud.account.v1.ReadHistoricalStartSessionWorldParticipationResponse; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationHistoricalReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.jooq.exception.DataAccessException; +import org.springframework.transaction.CannotCreateTransactionException; + +/** Standalone unregistered same-namespace Account historical tuple-to-participation receiver. */ +public final class AccountStartSessionWorldParticipationHistoricalReadGrpcService + extends AccountStartSessionWorldParticipationHistoricalReadServiceGrpc + .AccountStartSessionWorldParticipationHistoricalReadServiceImplBase { + private final AccountStartSessionWorldParticipationHistoricalReadService owner; + private final String workloadNamespace; + + public AccountStartSessionWorldParticipationHistoricalReadGrpcService( + AccountStartSessionWorldParticipationHistoricalReadService owner, String workloadNamespace) { + this.owner = Objects.requireNonNull(owner, "historical participation owner is required"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Resolves retained coordinates only after authenticating World without end-user context. */ + @Override + public void readHistoricalStartSessionWorldParticipation( + ReadHistoricalStartSessionWorldParticipationRequest request, + StreamObserver observer) { + Objects.requireNonNull(observer, "response observer is required"); + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + observer.onError(Status.UNAUTHENTICATED.asRuntimeException()); + return; + } + if (SessionContext.hasAuthenticatedCallerContext() + || !workloadNamespace.equals(peer.namespace()) + || !peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service")) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + if (request == null) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + // Bind the raw selector before decoding any other caller-controlled request fields. + if (!workloadNamespace.equals(request.getTargetNamespace())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + + final net.firedevops.firemud.common.account.startsession + .AccountStartSessionWorldParticipationHistoricalReadRequest + decoded; + try { + decoded = AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromRequest(request); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + + try { + var evidence = owner.read(decoded); + observer.onNext( + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.toResponse( + decoded, evidence)); + observer.onCompleted(); + } catch (StatusRuntimeException failure) { + observer.onError(failure); + } catch (IllegalArgumentException | IllegalStateException mismatch) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + } catch (CannotCreateTransactionException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } catch (DataAccessException | org.springframework.dao.DataAccessException failure) { + observer.onError( + (hasConnectionFailureSqlState(failure) ? Status.UNAVAILABLE : Status.INTERNAL) + .asRuntimeException()); + } catch (RuntimeException failure) { + observer.onError(Status.INTERNAL.asRuntimeException()); + } + } + + private static boolean hasConnectionFailureSqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException exception) { + String sqlState = exception.getSQLState(); + if (sqlState != null && sqlState.startsWith("08")) { + return true; + } + } + } + return false; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java new file mode 100644 index 0000000000..231b98da08 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java @@ -0,0 +1,129 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import java.util.Objects; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationHistoricalReadEvidence; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationHistoricalReadRequest; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered lookup-only Account read for exact historical World StartSession reconciliation. + * + *

It returns retained identity only. It does not establish fresh currentness, admit or restart + * World execution, renew an authorization reference, or prove the original Game Session operation. + */ +public final class AccountStartSessionWorldParticipationHistoricalReadService { + private final AccountStartSessionWorldParticipationRepository repository; + private final TransactionTemplate ownerTransaction; + private final String workloadNamespace; + + public AccountStartSessionWorldParticipationHistoricalReadService( + AccountStartSessionWorldParticipationRepository repository, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.repository = Objects.requireNonNull(repository, "participation repository is required"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + ownerTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ownerTransaction.setReadOnly(false); + } + + /** + * Resolves the exact retained participation from its complete original tuple, including after + * original ingress expiry or prior immutable terminal settlement. + */ + public AccountStartSessionWorldParticipationHistoricalReadEvidence read( + AccountStartSessionWorldParticipationHistoricalReadRequest request) { + requireWorldPeer(); + requireNoAmbientTransaction(); + Objects.requireNonNull(request, "historical participation request is required"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw Status.PERMISSION_DENIED + .withDescription( + "Historical participation namespace differs from the configured World peer") + .asRuntimeException(); + } + + StoredParticipation participation = + Objects.requireNonNull( + ownerTransaction.execute( + ignored -> + repository + .findHistoricalForOriginalTuple(request.originalPostAuthorizationTuple()) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription( + "Exact historical World participation is unavailable") + .asRuntimeException())), + "Account historical participation transaction returned no result"); + + if (!java.security.MessageDigest.isEqual( + participation.originalPostAuthorizationTuple(), + request.originalPostAuthorizationTuple()) + || !request + .decodedOriginalTuple() + .controlPlaneRequestId() + .equals(participation.controlPlaneRequestId()) + || !workloadNamespace.equals(participation.targetNamespace())) { + throw Status.FAILED_PRECONDITION + .withDescription( + "Stored World participation differs from the complete original tuple lookup") + .asRuntimeException(); + } + try { + return new AccountStartSessionWorldParticipationHistoricalReadEvidence( + request, + participation.participationId(), + participation.participationFence(), + participation.gameSessionOwnerAttemptId(), + participation.gameSessionOwnerFence(), + participation.canonicalGameInstanceId(), + participation.preparationInputJson(), + participation.preparationInputDigest()); + } catch (IllegalArgumentException malformedStorage) { + throw Status.FAILED_PRECONDITION + .withDescription("Stored World participation identity is not exact") + .withCause(malformedStorage) + .asRuntimeException(); + } + } + + private void requireWorldPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified World workload identity required") + .asRuntimeException(); + } + if (SessionContext.hasAuthenticatedCallerContext() + || !workloadNamespace.equals(peer.namespace()) + || !peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service")) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace World workload without end-user context required") + .asRuntimeException(); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription( + "Historical World participation read requires an independent Account transaction") + .asRuntimeException(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java new file mode 100644 index 0000000000..5b3e786ca4 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java @@ -0,0 +1,198 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredSettlement; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminalReadClient; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminalReadGrpcCodec; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminalReadRequest; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered Account composition that settles only authenticated exact World StartSession + * terminal readback. Historical settlement is not fresh authorization, admission, or renewal. + * + *

The World owner recovery verifier and Game Session original-claim producer remain separate + * prerequisites; this composition alone is not end-to-end execution proof. + */ +public final class AccountStartSessionWorldParticipationSettlementService { + private final AccountStartSessionWorldParticipationRepository repository; + private final WorldStartSessionExecutionTerminalReadClient worldClient; + private final TransactionTemplate ownerTransaction; + private final String workloadNamespace; + + public AccountStartSessionWorldParticipationSettlementService( + AccountStartSessionWorldParticipationRepository repository, + WorldStartSessionExecutionTerminalReadClient worldClient, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.repository = Objects.requireNonNull(repository, "participation repository is required"); + this.worldClient = Objects.requireNonNull(worldClient, "World terminal client is required"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + ownerTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ownerTransaction.setReadOnly(false); + } + + /** + * Settles or recovers one exact participation using World-owned historical terminal evidence. The + * request supplies only the immutable participation lookup identity; all terminal-read fields are + * derived from Account's retained participation. + */ + public StoredSettlement settle(UUID participationId, long participationFence) { + requireWorldPeer(); + requireNoAmbientTransaction(); + Objects.requireNonNull(participationId, "participationId is required"); + if (participationId.equals(new UUID(0L, 0L)) || participationFence <= 0L) { + throw new IllegalArgumentException("Non-nil participation ID and positive fence required"); + } + + Lookup lookup = + Objects.requireNonNull( + ownerTransaction.execute( + ignored -> { + StoredParticipation participation = + repository + .findHistoricalExact(participationId, participationFence) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription( + "Exact historical World participation is unavailable") + .asRuntimeException()); + if (!workloadNamespace.equals(participation.targetNamespace())) { + throw Status.PERMISSION_DENIED + .withDescription( + "World participation target namespace differs from authenticated peer") + .asRuntimeException(); + } + Optional settled = + repository.findSettlementExact(participationId, participationFence); + return new Lookup(participation, settled.orElse(null)); + }), + "Account participation lookup transaction returned no result"); + if (lookup.settlement() != null) return lookup.settlement(); + + WorldStartSessionExecutionTerminalReadRequest request = requestFor(lookup.participation()); + requireNoAmbientTransaction(); + WorldStartSessionExecutionTerminal terminal = worldClient.read(request); + if (terminal == null) { + throw Status.FAILED_PRECONDITION + .withDescription( + "World StartSession execution remains unresolved without exact terminal proof") + .asRuntimeException(); + } + // Reuse the closed Common codec's complete identity check. The client already performs this + // decode for a real response; this round trip keeps the service boundary explicit and testable. + var response = WorldStartSessionExecutionTerminalReadGrpcCodec.toResponse(request, terminal); + WorldStartSessionExecutionTerminal exactTerminal = + WorldStartSessionExecutionTerminalReadGrpcCodec.fromResponse(request, response); + + requireNoAmbientTransaction(); + StoredSettlement committed = + Objects.requireNonNull( + ownerTransaction.execute(ignored -> repository.settleExact(exactTerminal)), + "Account terminal settlement transaction returned no receipt"); + + // This lookup-only transaction establishes durable post-commit readback. It must not call + // settleExact again, since doing so could hide an uncertain first commit as an exact replay. + requireNoAmbientTransaction(); + StoredSettlement readback = + Objects.requireNonNull( + ownerTransaction.execute( + ignored -> + repository + .findSettlementExact(participationId, participationFence) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription( + "Committed World terminal settlement is not readable") + .asRuntimeException())), + "Account terminal settlement readback transaction returned no receipt"); + if (!sameSettlement(committed, readback)) { + throw Status.FAILED_PRECONDITION + .withDescription("Committed World terminal settlement readback differs") + .asRuntimeException(); + } + return readback; + } + + private WorldStartSessionExecutionTerminalReadRequest requestFor( + StoredParticipation participation) { + return new WorldStartSessionExecutionTerminalReadRequest( + freshReadId(participation), + participation.targetNamespace(), + participation.originalPostAuthorizationTuple(), + participation.participationId(), + participation.participationFence(), + participation.gameSessionOwnerAttemptId(), + participation.gameSessionOwnerFence(), + participation.canonicalGameInstanceId(), + participation.preparationInputJson()); + } + + private static UUID freshReadId(StoredParticipation participation) { + UUID readId; + do { + readId = UUID.randomUUID(); + } while (readId.equals(participation.participationId()) + || readId.equals(participation.gameSessionOwnerAttemptId()) + || readId.equals(participation.canonicalGameInstanceId()) + || readId.equals( + net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple + .decode(participation.originalPostAuthorizationTuple()) + .reservationOwnerId())); + return readId; + } + + private void requireWorldPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified World workload identity required") + .asRuntimeException(); + } + if (SessionContext.hasAuthenticatedCallerContext() + || !workloadNamespace.equals(peer.namespace()) + || !peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service")) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace World workload without end-user context required") + .asRuntimeException(); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("World terminal settlement requires independent Account transactions") + .asRuntimeException(); + } + } + + private static boolean sameSettlement(StoredSettlement left, StoredSettlement right) { + return left.participationId().equals(right.participationId()) + && left.outcome() == right.outcome() + && left.worldExecutionFence() == right.worldExecutionFence() + && left.terminalDigest().equals(right.terminalDigest()) + && java.util.Arrays.equals(left.terminalBytes(), right.terminalBytes()); + } + + private record Lookup(StoredParticipation participation, StoredSettlement settlement) {} +} diff --git a/services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql b/services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql new file mode 100644 index 0000000000..7986eb96bf --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql @@ -0,0 +1,253 @@ +CREATE TABLE account_start_session_capture_source_version_allocator ( + allocator_id BOOLEAN PRIMARY KEY DEFAULT TRUE CHECK (allocator_id), + last_source_version BIGINT NOT NULL DEFAULT 0 CHECK (last_source_version >= 0), + last_control_plane_request_id VARCHAR(128), + last_transaction_id VARCHAR(20), + CHECK ((last_source_version = 0 AND last_control_plane_request_id IS NULL AND last_transaction_id IS NULL) + OR (last_source_version > 0 AND last_control_plane_request_id IS NOT NULL + AND last_transaction_id IS NOT NULL + AND last_transaction_id ~ '^[1-9][0-9]{0,19}$' + AND last_transaction_id::NUMERIC <= 18446744073709551615)) +); +INSERT INTO account_start_session_capture_source_version_allocator (allocator_id) VALUES (TRUE); + +CREATE TABLE account_start_session_capture_source_fence_allocator ( + allocator_id BOOLEAN PRIMARY KEY DEFAULT TRUE CHECK (allocator_id), + last_source_fence BIGINT NOT NULL DEFAULT 0 CHECK (last_source_fence >= 0), + last_control_plane_request_id VARCHAR(128), + last_transaction_id VARCHAR(20), + CHECK ((last_source_fence = 0 AND last_control_plane_request_id IS NULL AND last_transaction_id IS NULL) + OR (last_source_fence > 0 AND last_control_plane_request_id IS NOT NULL + AND last_transaction_id IS NOT NULL + AND last_transaction_id ~ '^[1-9][0-9]{0,19}$' + AND last_transaction_id::NUMERIC <= 18446744073709551615)) +); +INSERT INTO account_start_session_capture_source_fence_allocator (allocator_id) VALUES (TRUE); + +CREATE TABLE account_start_session_authority_captures ( + control_plane_request_id VARCHAR(128) PRIMARY KEY + CHECK (octet_length(control_plane_request_id) BETWEEN 1 AND 128), + account_uuid UUID NOT NULL REFERENCES accounts(account_uuid) ON DELETE RESTRICT, + tenant_uuid UUID NOT NULL REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id) + ON DELETE RESTRICT, + target_owner VARCHAR(64) NOT NULL CHECK (target_owner = 'game-session-service'), + logging_workload_uri VARCHAR(256) NOT NULL + CHECK (logging_workload_uri ~ '^spiffe://firemud/ns/[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?/sa/logging-admin-service$'), + reservation_owner_id UUID NOT NULL CHECK (reservation_owner_id <> '00000000-0000-0000-0000-000000000000'::UUID), + reservation_claim_fence BIGINT NOT NULL CHECK (reservation_claim_fence > 0), + pre_authorization_tuple BYTEA NOT NULL CHECK (octet_length(pre_authorization_tuple) BETWEEN 1 AND 8192), + mutation_digest VARCHAR(64) NOT NULL CHECK (mutation_digest ~ '^[0-9a-f]{64}$'), + control_ui_operation_id UUID NOT NULL + REFERENCES account_control_ui_issuance_operations(operation_id) ON DELETE RESTRICT, + control_ui_token_jti UUID NOT NULL CHECK (control_ui_token_jti <> '00000000-0000-0000-0000-000000000000'::UUID), + control_ui_token_hash VARCHAR(64) NOT NULL CHECK (control_ui_token_hash ~ '^[0-9a-f]{64}$'), + control_ui_signer_receipt_sha256 VARCHAR(64) NOT NULL + CHECK (control_ui_signer_receipt_sha256 ~ '^[0-9a-f]{64}$'), + issuance_fence BIGINT NOT NULL CHECK (issuance_fence > 0), + issuance_fence_source_version BIGINT NOT NULL CHECK (issuance_fence_source_version > 0), + captured_at TIMESTAMPTZ NOT NULL, + snapshot_sha256 VARCHAR(64) NOT NULL CHECK (snapshot_sha256 ~ '^[0-9a-f]{64}$'), + canonical_snapshot_bytes BYTEA NOT NULL + CHECK (octet_length(canonical_snapshot_bytes) BETWEEN 1 AND 245760), + source_version BIGINT NOT NULL CHECK (source_version > 0), + source_fence BIGINT NOT NULL CHECK (source_fence > 0), + linearization VARCHAR(20) NOT NULL + CHECK (linearization ~ '^[1-9][0-9]{0,19}$' + AND linearization::NUMERIC <= 18446744073709551615), + canonical_sha256 VARCHAR(64) NOT NULL CHECK (canonical_sha256 ~ '^[0-9a-f]{64}$'), + canonical_capture_bytes BYTEA NOT NULL + CHECK (octet_length(canonical_capture_bytes) BETWEEN 1 AND 16384), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_start_session_capture_total_size_check + CHECK (octet_length(canonical_snapshot_bytes) + octet_length(canonical_capture_bytes) <= 262144), + CONSTRAINT account_start_session_capture_source_version_unique UNIQUE (source_version), + CONSTRAINT account_start_session_capture_source_fence_unique UNIQUE (source_fence), + CONSTRAINT account_start_session_capture_snapshot_digest + CHECK (snapshot_sha256 = encode(sha256(canonical_snapshot_bytes), 'hex')), + CONSTRAINT account_start_session_capture_reference_digest + CHECK (canonical_sha256 = encode(sha256(canonical_capture_bytes), 'hex')) +); + +-- [jooq ignore start] +ALTER TABLE account_start_session_authority_captures + ADD CONSTRAINT account_start_session_capture_captured_at_millis + CHECK (date_trunc('milliseconds', captured_at) = captured_at); +-- [jooq ignore stop] + +-- [jooq ignore start] +CREATE FUNCTION account_start_session_authority_capture_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + snapshot JSONB; + reference JSONB; + tuple JSONB; + control_ui RECORD; + allocated_version BIGINT; + allocated_version_request VARCHAR(128); + allocated_version_transaction VARCHAR(20); + allocated_fence BIGINT; + allocated_fence_request VARCHAR(128); + allocated_fence_transaction VARCHAR(20); + capture_transaction VARCHAR(20); +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'StartSession Account source captures are immutable and cannot be deleted' + USING ERRCODE = '23514'; + END IF; + + capture_transaction := pg_current_xact_id()::TEXT; + IF NEW.linearization IS DISTINCT FROM capture_transaction THEN + RAISE EXCEPTION 'StartSession capture linearization must identify its inserting transaction' + USING ERRCODE = '23514'; + END IF; + + SELECT last_source_version, last_control_plane_request_id, last_transaction_id + INTO allocated_version, allocated_version_request, allocated_version_transaction + FROM account_start_session_capture_source_version_allocator + WHERE allocator_id = TRUE FOR UPDATE; + SELECT last_source_fence, last_control_plane_request_id, last_transaction_id + INTO allocated_fence, allocated_fence_request, allocated_fence_transaction + FROM account_start_session_capture_source_fence_allocator + WHERE allocator_id = TRUE FOR UPDATE; + IF allocated_version IS DISTINCT FROM NEW.source_version + OR allocated_fence IS DISTINCT FROM NEW.source_fence + OR allocated_version_request IS DISTINCT FROM NEW.control_plane_request_id + OR allocated_fence_request IS DISTINCT FROM NEW.control_plane_request_id + OR allocated_version_transaction IS DISTINCT FROM capture_transaction + OR allocated_fence_transaction IS DISTINCT FROM capture_transaction THEN + RAISE EXCEPTION 'StartSession capture reference is not the exact durable source allocation' + USING ERRCODE = '23514'; + END IF; + + snapshot := convert_from(NEW.canonical_snapshot_bytes, 'UTF8')::JSONB; + reference := convert_from(NEW.canonical_capture_bytes, 'UTF8')::JSONB; + tuple := convert_from(NEW.pre_authorization_tuple, 'UTF8')::JSONB; + IF jsonb_typeof(snapshot) IS DISTINCT FROM 'object' + OR jsonb_typeof(reference) IS DISTINCT FROM 'object' + OR jsonb_typeof(tuple) IS DISTINCT FROM 'object' + OR reference->>'schema' IS DISTINCT FROM 'account-start-session-authority-capture/v1' + OR reference->>'controlPlaneRequestId' IS DISTINCT FROM NEW.control_plane_request_id + OR reference->>'capturedAt' IS DISTINCT FROM + to_char(NEW.captured_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') + OR reference->>'snapshotSha256' IS DISTINCT FROM NEW.snapshot_sha256 + OR reference#>>'{bundleReference,bundleVersion}' IS DISTINCT FROM 'authorityEvidenceBundle/v1' + OR reference#>>'{bundleReference,sourceVersion}' IS DISTINCT FROM NEW.source_version::TEXT + OR reference#>>'{bundleReference,sourceFence}' IS DISTINCT FROM NEW.source_fence::TEXT + OR reference#>>'{bundleReference,linearization}' IS DISTINCT FROM NEW.linearization + OR snapshot->>'schema' IS DISTINCT FROM 'account-start-session-authority-snapshot/v1' + OR snapshot->>'controlPlaneRequestId' IS DISTINCT FROM NEW.control_plane_request_id + OR snapshot->>'accountId' IS DISTINCT FROM NEW.account_uuid::TEXT + OR snapshot->>'tenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR snapshot->>'targetOwner' IS DISTINCT FROM NEW.target_owner + OR snapshot->>'loggingWorkloadUri' IS DISTINCT FROM NEW.logging_workload_uri + OR snapshot->>'reservationOwnerId' IS DISTINCT FROM NEW.reservation_owner_id::TEXT + OR snapshot->>'reservationClaimFence' IS DISTINCT FROM NEW.reservation_claim_fence::TEXT + OR snapshot->>'mutationDigest' IS DISTINCT FROM NEW.mutation_digest + OR snapshot->>'controlUiOperationId' IS DISTINCT FROM NEW.control_ui_operation_id::TEXT + OR snapshot->>'controlUiTokenJti' IS DISTINCT FROM NEW.control_ui_token_jti::TEXT + OR snapshot->>'controlUiTokenHash' IS DISTINCT FROM NEW.control_ui_token_hash + OR snapshot->>'controlUiSignerReceiptSha256' IS DISTINCT FROM NEW.control_ui_signer_receipt_sha256 + OR snapshot->>'issuanceFence' IS DISTINCT FROM NEW.issuance_fence::TEXT + OR snapshot->>'issuanceFenceSourceVersion' IS DISTINCT FROM NEW.issuance_fence_source_version::TEXT + OR decode(snapshot->>'preAuthorizationTuple', 'base64') IS DISTINCT FROM NEW.pre_authorization_tuple THEN + RAISE EXCEPTION 'StartSession capture payload differs from its exact row identity' + USING ERRCODE = '23514'; + END IF; + + IF tuple#>>'{actor,accountId}' IS DISTINCT FROM NEW.account_uuid::TEXT + OR tuple#>>'{scope,tenantId}' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR tuple#>>'{targetOwner,ownerService}' IS DISTINCT FROM 'game-session-service' + OR tuple#>>'{actionFamilyRequestIdentity,requestId}' IS DISTINCT FROM NEW.control_plane_request_id + OR tuple->>'tupleSchemaId' IS DISTINCT FROM 'preAuthorizationReservationTuple' + OR tuple->>'tupleSchemaVersion' IS DISTINCT FROM '1' THEN + RAISE EXCEPTION 'StartSession capture tuple scope or identity is inconsistent' + USING ERRCODE = '23514'; + END IF; + + SELECT operation_id, account_uuid, tenant_uuid, token_jti, token_hash, signer_receipt, status + INTO control_ui + FROM account_control_ui_issuance_operations + WHERE operation_id = NEW.control_ui_operation_id + FOR SHARE; + IF control_ui.operation_id IS NULL + OR control_ui.status IS DISTINCT FROM 'COMMITTED' + OR control_ui.account_uuid IS DISTINCT FROM NEW.account_uuid + OR control_ui.tenant_uuid IS DISTINCT FROM NEW.tenant_uuid + OR control_ui.token_jti IS DISTINCT FROM NEW.control_ui_token_jti + OR control_ui.token_hash IS DISTINCT FROM NEW.control_ui_token_hash + OR encode(sha256(control_ui.signer_receipt), 'hex') IS DISTINCT FROM NEW.control_ui_signer_receipt_sha256 THEN + RAISE EXCEPTION 'StartSession capture is not bound to its original committed ControlUI operation' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_start_session_authority_capture_no_truncate() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'StartSession Account source captures cannot be truncated' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_start_session_authority_capture_immutable + BEFORE INSERT OR UPDATE OR DELETE ON account_start_session_authority_captures + FOR EACH ROW EXECUTE FUNCTION account_start_session_authority_capture_guard(); +CREATE TRIGGER account_start_session_authority_capture_no_truncate + BEFORE TRUNCATE ON account_start_session_authority_captures + FOR EACH STATEMENT EXECUTE FUNCTION account_start_session_authority_capture_no_truncate(); + +CREATE FUNCTION account_start_session_capture_allocator_no_mutation() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' OR TG_OP = 'TRUNCATE' THEN + RAISE EXCEPTION 'StartSession capture allocators cannot be deleted or truncated' + USING ERRCODE = '23514'; + END IF; + IF (to_jsonb(NEW) - ARRAY['last_source_version','last_control_plane_request_id','last_transaction_id']) + IS DISTINCT FROM + (to_jsonb(OLD) - ARRAY['last_source_version','last_control_plane_request_id','last_transaction_id']) + OR NEW.last_source_version <> OLD.last_source_version + 1 + OR NEW.last_control_plane_request_id IS NULL + OR NEW.last_transaction_id IS DISTINCT FROM pg_current_xact_id()::TEXT THEN + RAISE EXCEPTION 'StartSession capture sourceVersion allocator must advance once in its owner transaction' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_start_session_capture_fence_allocator_no_mutation() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' OR TG_OP = 'TRUNCATE' THEN + RAISE EXCEPTION 'StartSession capture allocators cannot be deleted or truncated' + USING ERRCODE = '23514'; + END IF; + IF (to_jsonb(NEW) - ARRAY['last_source_fence','last_control_plane_request_id','last_transaction_id']) + IS DISTINCT FROM + (to_jsonb(OLD) - ARRAY['last_source_fence','last_control_plane_request_id','last_transaction_id']) + OR NEW.last_source_fence <> OLD.last_source_fence + 1 + OR NEW.last_control_plane_request_id IS NULL + OR NEW.last_transaction_id IS DISTINCT FROM pg_current_xact_id()::TEXT THEN + RAISE EXCEPTION 'StartSession capture sourceFence allocator must advance once in its owner transaction' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_start_session_capture_source_version_allocator_guard + BEFORE UPDATE OR DELETE ON account_start_session_capture_source_version_allocator + FOR EACH ROW EXECUTE FUNCTION account_start_session_capture_allocator_no_mutation(); +CREATE TRIGGER account_start_session_capture_source_version_allocator_no_truncate + BEFORE TRUNCATE ON account_start_session_capture_source_version_allocator + FOR EACH STATEMENT EXECUTE FUNCTION account_start_session_authority_capture_no_truncate(); +CREATE TRIGGER account_start_session_capture_source_fence_allocator_guard + BEFORE UPDATE OR DELETE ON account_start_session_capture_source_fence_allocator + FOR EACH ROW EXECUTE FUNCTION account_start_session_capture_fence_allocator_no_mutation(); +CREATE TRIGGER account_start_session_capture_source_fence_allocator_no_truncate + BEFORE TRUNCATE ON account_start_session_capture_source_fence_allocator + FOR EACH STATEMENT EXECUTE FUNCTION account_start_session_authority_capture_no_truncate(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql b/services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql new file mode 100644 index 0000000000..16fbdad0f0 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql @@ -0,0 +1,692 @@ +-- Account-owned participation in the distinct World StartSession execution. This is an +-- integrity fence only: it does not authenticate the World transport or enable execution. +CREATE TABLE account_start_session_world_participations ( + participation_id UUID PRIMARY KEY + CHECK (participation_id <> '00000000-0000-0000-0000-000000000000'::UUID), + participation_fence BIGINT GENERATED ALWAYS AS IDENTITY UNIQUE + CHECK (participation_fence > 0), + control_plane_request_id VARCHAR(128) NOT NULL UNIQUE + CHECK (octet_length(control_plane_request_id) BETWEEN 1 AND 128), + original_post_authorization_tuple BYTEA NOT NULL + CHECK (octet_length(original_post_authorization_tuple) BETWEEN 1 AND 262144), + target_namespace VARCHAR(63) NOT NULL + CHECK (target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + canonical_tenant_id UUID NOT NULL + REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id) ON DELETE RESTRICT + CHECK (canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID), + canonical_game_instance_id UUID NOT NULL + CHECK (canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::UUID), + game_session_owner_attempt_id UUID NOT NULL + CHECK (game_session_owner_attempt_id <> '00000000-0000-0000-0000-000000000000'::UUID), + game_session_owner_fence BIGINT NOT NULL CHECK (game_session_owner_fence > 0), + preparation_input_json TEXT NOT NULL CHECK (length(preparation_input_json) > 0), + preparation_input_digest VARCHAR(71) NOT NULL + CHECK (preparation_input_digest ~ '^sha256:[0-9a-f]{64}$'), + producer_xid BIGINT NOT NULL DEFAULT txid_current(), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_start_session_world_participation_authorization_fk + FOREIGN KEY (control_plane_request_id) + REFERENCES account_start_session_operator_authorizations(control_plane_request_id) + ON DELETE RESTRICT, + CONSTRAINT account_start_session_world_participation_capture_fk + FOREIGN KEY (control_plane_request_id) + REFERENCES account_start_session_authority_captures(control_plane_request_id) + ON DELETE RESTRICT +); + +CREATE TABLE account_start_session_world_participation_sources ( + participation_id UUID NOT NULL + REFERENCES account_start_session_world_participations(participation_id) ON DELETE RESTRICT, + source_key VARCHAR(2048) NOT NULL + CHECK (length(source_key) > 0 AND octet_length(source_key) <= 2048) + REFERENCES account_draft_authorization_source_locks(source_key), + source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) BETWEEN 1 AND 131072), + PRIMARY KEY (participation_id, source_key) +); +CREATE INDEX account_start_session_world_participation_sources_by_key + ON account_start_session_world_participation_sources(source_key, participation_id); + +CREATE TABLE account_start_session_world_participation_settlements ( + participation_id UUID PRIMARY KEY + REFERENCES account_start_session_world_participations(participation_id) ON DELETE RESTRICT, + outcome VARCHAR(16) NOT NULL CHECK (outcome IN ('COMMITTED', 'ABORTED')), + world_execution_fence BIGINT NOT NULL CHECK (world_execution_fence > 0), + terminal_bytes BYTEA NOT NULL CHECK (octet_length(terminal_bytes) BETWEEN 1 AND 25165824), + terminal_digest VARCHAR(71) NOT NULL CHECK (terminal_digest ~ '^sha256:[0-9a-f]{64}$'), + settled_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + CHECK (terminal_digest = 'sha256:' || encode(sha256(terminal_bytes), 'hex')) +); + +-- [jooq ignore start] +CREATE FUNCTION account_start_session_world_participation_source_key(evidence BYTEA) +RETURNS TEXT LANGUAGE plpgsql IMMUTABLE STRICT AS $$ +DECLARE + position_value INTEGER := 1; + parsed BYTEA; + kind_value TEXT; + scope_value TEXT; + source_key_value TEXT; +BEGIN + SELECT frame_value, next_position INTO parsed, position_value + FROM account_publication_authorization_read_frame(evidence, position_value); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM 'account-draft-source-evidence/v1' THEN + RAISE EXCEPTION 'Invalid StartSession participation source schema' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, position_value + FROM account_publication_authorization_read_frame(evidence, position_value); + kind_value := convert_from(parsed, 'UTF8'); + SELECT frame_value, next_position INTO parsed, position_value + FROM account_publication_authorization_read_frame(evidence, position_value); + scope_value := convert_from(parsed, 'UTF8'); + source_key_value := kind_value || ':' || scope_value; + IF length(kind_value) = 0 OR length(scope_value) = 0 + OR length(source_key_value) = 0 OR octet_length(source_key_value) > 2048 THEN + RAISE EXCEPTION 'Invalid StartSession participation source key' USING ERRCODE = '23514'; + END IF; + RETURN source_key_value; +END; +$$; + +CREATE FUNCTION account_start_session_world_participation_validate_input( + input_json TEXT, + input_digest TEXT, + original_tuple BYTEA, + namespace_value TEXT, + tenant_value UUID, + request_value TEXT, + instance_value UUID +) RETURNS VOID LANGUAGE plpgsql IMMUTABLE STRICT AS $$ +DECLARE + input_value JSONB; + tuple_value JSONB; + original_value JSONB; + descriptor_value JSONB; +BEGIN + IF length(input_json) = 0 + OR input_digest !~ '^sha256:[0-9a-f]{64}$' + OR input_digest IS DISTINCT FROM 'sha256:' || encode(sha256(convert_to(input_json, 'UTF8')), 'hex') + OR octet_length(original_tuple) NOT BETWEEN 1 AND 262144 + OR namespace_value !~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + OR tenant_value = '00000000-0000-0000-0000-000000000000'::UUID + OR instance_value = '00000000-0000-0000-0000-000000000000'::UUID + OR length(request_value) = 0 THEN + RAISE EXCEPTION 'Malformed StartSession World participation identity or preparation input' + USING ERRCODE = '23514'; + END IF; + + input_value := input_json::JSONB; + tuple_value := convert_from(original_tuple, 'UTF8')::JSONB; + original_value := tuple_value->'preAuthorizationReservationTuple'; + IF jsonb_typeof(input_value) IS DISTINCT FROM 'object' + OR jsonb_typeof(input_value->'identity') IS DISTINCT FROM 'object' + OR jsonb_typeof(input_value->'gameSessionReadRequest') IS DISTINCT FROM 'object' + OR jsonb_typeof(input_value->'gameSessionReadEvidence') IS DISTINCT FROM 'object' + OR jsonb_typeof(tuple_value) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'StartSession World preparation input or tuple is not an object' + USING ERRCODE = '23514'; + END IF; + descriptor_value := (input_value->'gameSessionReadEvidence'->>'descriptorJson')::JSONB; + IF tuple_value->>'tupleSchemaId' IS DISTINCT FROM 'postAuthorizationExecutionTuple' + OR tuple_value->>'tupleSchemaVersion' IS DISTINCT FROM '1' + OR tuple_value->>'issuanceKind' IS DISTINCT FROM 'human_operator' + OR tuple_value->>'controlPlaneRequestId' IS DISTINCT FROM + original_value->'actionFamilyRequestIdentity'->>'requestId' + OR tuple_value->>'controlPlaneRequestId' IS DISTINCT FROM request_value + OR tuple_value->'scope'->>'targetNamespace' IS DISTINCT FROM namespace_value + OR tuple_value->'scope'->>'tenantId' IS DISTINCT FROM tenant_value::TEXT + OR tuple_value->'targetOwner'->>'ownerService' IS DISTINCT FROM 'game-session-service' + OR original_value->>'actionFamily' IS DISTINCT FROM 'StartSession' + OR (tuple_value->'target'->>'gameTemplateId')::BIGINT IS DISTINCT FROM + (descriptor_value->>'gameTemplateId')::BIGINT + OR input_value->'identity'->>'canonicalGameInstanceId' IS DISTINCT FROM instance_value::TEXT + OR input_value->'gameSessionReadEvidence'->>'canonicalGameInstanceId' IS DISTINCT FROM instance_value::TEXT + OR input_value->'gameSessionReadRequest'->>'canonicalGameInstanceId' IS DISTINCT FROM instance_value::TEXT + OR input_value->'identity'->>'targetNamespace' IS DISTINCT FROM namespace_value + OR input_value->'identity'->>'canonicalTenantId' IS DISTINCT FROM tenant_value::TEXT + OR input_value->'identity'->>'controlPlaneRequestId' IS DISTINCT FROM request_value + OR input_value->'gameSessionReadRequest'->>'targetNamespace' IS DISTINCT FROM namespace_value + OR input_value->'gameSessionReadRequest'->>'canonicalTenantId' IS DISTINCT FROM tenant_value::TEXT + OR input_value->'gameSessionReadRequest'->>'worldSlug' IS DISTINCT FROM + input_value->'identity'->>'worldSlug' + OR input_value->'gameSessionReadRequest'->>'controlPlaneRequestId' IS DISTINCT FROM request_value + OR input_value->'identity'->>'targetNamespace' IS DISTINCT FROM + input_value->'gameSessionReadEvidence'->>'targetNamespace' + OR input_value->'identity'->>'canonicalTenantId' IS DISTINCT FROM + input_value->'gameSessionReadEvidence'->>'canonicalTenantId' + OR input_value->'identity'->>'worldSlug' IS DISTINCT FROM + input_value->'gameSessionReadEvidence'->>'worldSlug' + OR input_value->'identity'->>'controlPlaneRequestId' IS DISTINCT FROM + input_value->'gameSessionReadEvidence'->>'controlPlaneRequestId' + OR input_value->'launchBinding'->>'targetNamespace' IS DISTINCT FROM namespace_value + OR input_value->'launchBinding'->>'canonicalTenantId' IS DISTINCT FROM tenant_value::TEXT + OR input_value->'launchBinding'->>'worldSlug' IS DISTINCT FROM + input_value->'identity'->>'worldSlug' + OR input_value->'launchBinding'->>'controlPlaneRequestId' IS DISTINCT FROM request_value + OR tuple_value->'authorityEvidenceBundle'->'accountProjectionEvidence'->>'expiresAt' IS NULL THEN + RAISE EXCEPTION 'World preparation identity or descriptor differs from the retained StartSession tuple' + USING ERRCODE = '23514'; + END IF; +END; +$$; + +CREATE FUNCTION account_start_session_world_participation_lock_sources(snapshot_value JSONB) +RETURNS TEXT[] LANGUAGE plpgsql VOLATILE STRICT AS $$ +DECLARE + source_value JSONB; + evidence_value BYTEA; + source_key_value TEXT; + key_values TEXT[] := ARRAY[]::TEXT[]; + ordered_values TEXT[]; +BEGIN + IF jsonb_typeof(snapshot_value->'sourceVector') IS DISTINCT FROM 'array' + OR jsonb_array_length(snapshot_value->'sourceVector') < 1 THEN + RAISE EXCEPTION 'StartSession participation requires a complete retained source vector' + USING ERRCODE = '23514'; + END IF; + FOR source_value IN SELECT value FROM jsonb_array_elements(snapshot_value->'sourceVector') LOOP + IF jsonb_typeof(source_value) IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'StartSession source vector entries must be Base64 strings' USING ERRCODE = '23514'; + END IF; + evidence_value := decode(source_value #>> '{}', 'base64'); + source_key_value := account_start_session_world_participation_source_key(evidence_value); + IF source_key_value = ANY(key_values) THEN + RAISE EXCEPTION 'Duplicate StartSession participation source key' USING ERRCODE = '23514'; + END IF; + key_values := array_append(key_values, source_key_value); + END LOOP; + SELECT array_agg(value ORDER BY account_publication_authorization_source_sort_key(value)) + INTO ordered_values FROM unnest(key_values) AS keys(value); + IF key_values IS DISTINCT FROM ordered_values THEN + RAISE EXCEPTION 'StartSession retained source vector is not in canonical source-key order' + USING ERRCODE = '23514'; + END IF; + + FOR source_key_value IN + SELECT value FROM unnest(key_values) AS keys(value) + ORDER BY account_publication_authorization_source_sort_key(value) + LOOP + PERFORM source_key FROM account_draft_authorization_source_locks + WHERE source_key = source_key_value FOR UPDATE NOWAIT; + IF NOT FOUND THEN + RAISE EXCEPTION 'StartSession participation source lock is not provisioned' + USING ERRCODE = '23514'; + END IF; + END LOOP; + RETURN key_values; +END; +$$; + +CREATE FUNCTION account_start_session_world_participation_assert_exclusive( + source_keys TEXT[], snapshot_value JSONB +) +RETURNS VOID LANGUAGE plpgsql STABLE STRICT AS $$ +DECLARE + source_value JSONB; + evidence_value BYTEA; + source_key_value TEXT; +BEGIN + IF EXISTS ( + SELECT 1 FROM account_draft_authorization_changed_scopes changed + JOIN account_draft_authorization_source_changes change USING (change_id) + WHERE changed.source_key = ANY(source_keys) AND change.status = 'WAITING' + ) THEN + RAISE EXCEPTION 'StartSession participation cannot acquire a source with a waiting source change' + USING ERRCODE = '55P03'; + END IF; + -- Match the exact captured hosted-terms evidence, as the existing Draft/publication + -- admission boundary does. An older DISCLOSED record or a shared role/source key + -- does not establish disclosure of this captured hosted-terms source version. + FOR source_value IN SELECT value FROM jsonb_array_elements(snapshot_value->'sourceVector') LOOP + evidence_value := decode(source_value #>> '{}', 'base64'); + source_key_value := account_start_session_world_participation_source_key(evidence_value); + IF source_key_value LIKE 'HOSTED_TERMS:%' AND EXISTS ( + SELECT 1 FROM account_hosted_terms_disclosure_handoffs handoff + JOIN account_hosted_terms_disclosure_sources handoff_source + ON handoff_source.handoff_id = handoff.handoff_id + WHERE handoff.source_key = source_key_value + AND handoff_source.source_key = handoff.source_key + AND handoff_source.source_evidence = evidence_value + AND handoff.status IN ('DISPATCH_AUTHORIZED', 'AMBIGUOUS', 'DISCLOSED') + ) THEN + RAISE EXCEPTION 'StartSession participation cannot acquire an exactly disclosed hosted-terms source' + USING ERRCODE = '55P03'; + END IF; + END LOOP; +END; +$$; + +CREATE FUNCTION account_start_session_world_participation_assert_sources( + participation_value UUID, + snapshot_value JSONB +) RETURNS VOID LANGUAGE plpgsql STABLE STRICT AS $$ +DECLARE + source_value JSONB; + evidence_value BYTEA; + source_key_value TEXT; + key_values TEXT[] := ARRAY[]::TEXT[]; + ordered_values TEXT[]; + source_count INTEGER; +BEGIN + IF jsonb_typeof(snapshot_value->'sourceVector') IS DISTINCT FROM 'array' + OR jsonb_array_length(snapshot_value->'sourceVector') < 1 THEN + RAISE EXCEPTION 'StartSession participation source vector is absent' USING ERRCODE = '23514'; + END IF; + source_count := jsonb_array_length(snapshot_value->'sourceVector'); + IF source_count IS DISTINCT FROM ( + SELECT count(*)::INTEGER FROM account_start_session_world_participation_sources + WHERE participation_id = participation_value) THEN + RAISE EXCEPTION 'StartSession participation has incomplete or extra source children' + USING ERRCODE = '23514'; + END IF; + FOR source_value IN SELECT value FROM jsonb_array_elements(snapshot_value->'sourceVector') LOOP + IF jsonb_typeof(source_value) IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'StartSession source vector entries must be Base64 strings' USING ERRCODE = '23514'; + END IF; + evidence_value := decode(source_value #>> '{}', 'base64'); + source_key_value := account_start_session_world_participation_source_key(evidence_value); + IF source_key_value = ANY(key_values) + OR NOT EXISTS ( + SELECT 1 FROM account_start_session_world_participation_sources source + WHERE source.participation_id = participation_value + AND source.source_key = source_key_value + AND source.source_evidence = evidence_value) THEN + RAISE EXCEPTION 'StartSession source child differs from the exact captured source vector' + USING ERRCODE = '23514'; + END IF; + key_values := array_append(key_values, source_key_value); + END LOOP; + SELECT array_agg(value ORDER BY account_publication_authorization_source_sort_key(value)) + INTO ordered_values FROM unnest(key_values) AS keys(value); + IF key_values IS DISTINCT FROM ordered_values THEN + RAISE EXCEPTION 'StartSession captured source vector is not in canonical source-key order' + USING ERRCODE = '23514'; + END IF; +END; +$$; + +CREATE FUNCTION account_start_session_world_participation_is_settled(participation_value UUID) +RETURNS BOOLEAN LANGUAGE SQL STABLE STRICT AS $$ + SELECT EXISTS ( + SELECT 1 FROM account_start_session_world_participation_settlements settlement + WHERE settlement.participation_id = participation_value) +$$; + +CREATE FUNCTION account_start_session_world_participation_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + authorization_row account_start_session_operator_authorizations%ROWTYPE; + capture account_start_session_authority_captures%ROWTYPE; + tuple_value JSONB; + reservation_value JSONB; + bundle_reference JSONB; + snapshot_value JSONB; + source_keys TEXT[]; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'StartSession World participation is append-only' USING ERRCODE = '23514'; + END IF; + IF NEW.producer_xid IS DISTINCT FROM txid_current() THEN + RAISE EXCEPTION 'StartSession World participation must be created by its producer transaction' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT capture FROM account_start_session_authority_captures + WHERE control_plane_request_id = NEW.control_plane_request_id; + snapshot_value := convert_from(capture.canonical_snapshot_bytes, 'UTF8')::JSONB; + IF snapshot_value->>'schema' IS DISTINCT FROM 'account-start-session-authority-snapshot/v1' + OR snapshot_value->>'controlPlaneRequestId' IS DISTINCT FROM NEW.control_plane_request_id THEN + RAISE EXCEPTION 'StartSession World participation must retain the exact Account capture' + USING ERRCODE = '23514'; + END IF; + source_keys := account_start_session_world_participation_lock_sources(snapshot_value); + PERFORM account_start_session_world_participation_assert_exclusive(source_keys, snapshot_value); + + SELECT * INTO STRICT authorization_row FROM account_start_session_operator_authorizations + WHERE control_plane_request_id = NEW.control_plane_request_id; + tuple_value := convert_from(NEW.original_post_authorization_tuple, 'UTF8')::JSONB; + IF authorization_row.status IS DISTINCT FROM 'REDEEMED' + OR authorization_row.reference_expires_at <= clock_timestamp() + OR tuple_value->'preAuthorizationReservationTuple' IS DISTINCT FROM + convert_from(authorization_row.pre_authorization_tuple, 'UTF8')::JSONB + OR authorization_row.redemption_owner_attempt_id IS DISTINCT FROM NEW.game_session_owner_attempt_id + OR authorization_row.redemption_owner_fence IS DISTINCT FROM NEW.game_session_owner_fence THEN + RAISE EXCEPTION 'StartSession World participation requires the exact unexpired redeemed original authorization' + USING ERRCODE = '23514'; + END IF; + reservation_value := tuple_value->'preAuthorizationReservationTuple'; + bundle_reference := tuple_value->'authorityEvidenceBundleReference'; + IF tuple_value->>'tupleSchemaId' IS DISTINCT FROM 'postAuthorizationExecutionTuple' + OR tuple_value->>'tupleSchemaVersion' IS DISTINCT FROM '1' + OR tuple_value->>'issuanceKind' IS DISTINCT FROM 'human_operator' + OR tuple_value->>'controlPlaneRequestId' IS DISTINCT FROM NEW.control_plane_request_id + OR tuple_value->>'mutationDigest' IS DISTINCT FROM authorization_row.mutation_digest + OR tuple_value->>'authorizationReferenceFingerprint' IS DISTINCT FROM + authorization_row.authorization_reference_fingerprint + OR tuple_value->>'issuanceFence' IS DISTINCT FROM authorization_row.issuance_fence::TEXT + OR tuple_value->>'reservationOwnerId' IS DISTINCT FROM authorization_row.reservation_owner_id::TEXT + OR tuple_value->>'reservationClaimFence' IS DISTINCT FROM authorization_row.reservation_claim_fence::TEXT + OR tuple_value->>'authorityEvidenceBundleReference' IS NULL + OR bundle_reference->>'bundleVersion' IS DISTINCT FROM authorization_row.bundle_version + OR bundle_reference->>'sourceVersion' IS DISTINCT FROM authorization_row.bundle_source_version + OR bundle_reference->>'sourceFence' IS DISTINCT FROM authorization_row.bundle_source_fence + OR bundle_reference->>'linearization' IS DISTINCT FROM authorization_row.bundle_linearization + OR tuple_value->'authorityEvidenceBundle' IS DISTINCT FROM + convert_from(authorization_row.authority_evidence_bundle, 'UTF8')::JSONB + OR authorization_row.redemption_reference_fingerprint IS DISTINCT FROM + authorization_row.authorization_reference_fingerprint + OR authorization_row.redemption_authority_evidence_bundle IS DISTINCT FROM + authorization_row.authority_evidence_bundle + OR capture.pre_authorization_tuple IS DISTINCT FROM authorization_row.pre_authorization_tuple + OR capture.account_uuid IS DISTINCT FROM (tuple_value->'actor'->>'accountId')::UUID + OR capture.tenant_uuid IS DISTINCT FROM NEW.canonical_tenant_id + OR capture.target_owner IS DISTINCT FROM tuple_value->'targetOwner'->>'ownerService' + OR capture.mutation_digest IS DISTINCT FROM authorization_row.mutation_digest + OR capture.reservation_owner_id IS DISTINCT FROM authorization_row.reservation_owner_id + OR capture.reservation_claim_fence IS DISTINCT FROM authorization_row.reservation_claim_fence + OR capture.issuance_fence IS DISTINCT FROM authorization_row.issuance_fence + OR capture.source_version::TEXT IS DISTINCT FROM bundle_reference->>'sourceVersion' + OR capture.source_fence::TEXT IS DISTINCT FROM bundle_reference->>'sourceFence' + OR capture.linearization IS DISTINCT FROM bundle_reference->>'linearization' + OR tuple_value->'scope'->>'targetNamespace' IS DISTINCT FROM NEW.target_namespace + OR tuple_value->'scope'->>'tenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR reservation_value->>'actionFamily' IS DISTINCT FROM 'StartSession' + OR reservation_value->'actionFamilyRequestIdentity'->>'requestId' IS DISTINCT FROM + NEW.control_plane_request_id + OR tuple_value->'targetOwner'->>'ownerService' IS DISTINCT FROM 'game-session-service' THEN + RAISE EXCEPTION 'StartSession World participation differs from its original Account authorization or capture' + USING ERRCODE = '23514'; + END IF; + PERFORM account_start_session_world_participation_validate_input( + NEW.preparation_input_json, NEW.preparation_input_digest, + NEW.original_post_authorization_tuple, NEW.target_namespace, + NEW.canonical_tenant_id, NEW.control_plane_request_id, + NEW.canonical_game_instance_id); + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_start_session_world_participation_source_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + parent_xid BIGINT; +BEGIN + SELECT producer_xid INTO parent_xid FROM account_start_session_world_participations + WHERE participation_id = NEW.participation_id; + IF parent_xid IS DISTINCT FROM txid_current() + OR account_start_session_world_participation_source_key(NEW.source_evidence) IS DISTINCT FROM NEW.source_key THEN + RAISE EXCEPTION 'StartSession sources must accompany the exact original participation transaction' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_start_session_world_participation_complete_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_start_session_world_participations%ROWTYPE; + capture account_start_session_authority_captures%ROWTYPE; + snapshot_value JSONB; + source_keys TEXT[]; +BEGIN + SELECT * INTO STRICT original FROM account_start_session_world_participations + WHERE participation_id = NEW.participation_id; + IF original.producer_xid IS DISTINCT FROM txid_current() THEN + RAISE EXCEPTION 'StartSession participation completion must run in its original transaction' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT capture FROM account_start_session_authority_captures + WHERE control_plane_request_id = original.control_plane_request_id; + snapshot_value := convert_from(capture.canonical_snapshot_bytes, 'UTF8')::JSONB; + source_keys := account_start_session_world_participation_lock_sources(snapshot_value); + PERFORM account_start_session_world_participation_assert_exclusive(source_keys, snapshot_value); + PERFORM account_start_session_world_participation_assert_sources(original.participation_id, snapshot_value); + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_start_session_world_participation_terminal_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_start_session_world_participations%ROWTYPE; + terminal_value JSONB; + terminal_field_count INTEGER; + source_key_value TEXT; + encoded_tuple TEXT; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'StartSession World participation settlement is append-only' USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT original FROM account_start_session_world_participations + WHERE participation_id = NEW.participation_id; + FOR source_key_value IN SELECT source_key + FROM account_start_session_world_participation_sources + WHERE participation_id = NEW.participation_id + ORDER BY account_publication_authorization_source_sort_key(source_key) + LOOP + PERFORM source_key FROM account_draft_authorization_source_locks + WHERE source_key = source_key_value FOR UPDATE NOWAIT; + END LOOP; + PERFORM participation_id FROM account_start_session_world_participations + WHERE participation_id = NEW.participation_id FOR UPDATE NOWAIT; + + IF NEW.terminal_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.terminal_bytes), 'hex') THEN + RAISE EXCEPTION 'World terminal digest does not bind the exact receipt bytes' USING ERRCODE = '23514'; + END IF; + terminal_value := convert_from(NEW.terminal_bytes, 'UTF8')::JSONB; + encoded_tuple := regexp_replace(encode(original.original_post_authorization_tuple, 'base64'), E'[\n\r]', '', 'g'); + IF jsonb_typeof(terminal_value) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'World terminal must be a closed JSON object' USING ERRCODE = '23514'; + END IF; + SELECT count(*)::INTEGER INTO terminal_field_count FROM jsonb_object_keys(terminal_value); + IF terminal_field_count IS DISTINCT FROM 14 THEN + RAISE EXCEPTION 'World terminal must contain exactly fourteen fields' USING ERRCODE = '23514'; + END IF; + IF jsonb_typeof(terminal_value->'schema') IS DISTINCT FROM 'string' + OR jsonb_typeof(terminal_value->'originalPostAuthorizationTupleBase64') IS DISTINCT FROM 'string' + OR jsonb_typeof(terminal_value->'accountWorldParticipationId') IS DISTINCT FROM 'string' + OR jsonb_typeof(terminal_value->'accountWorldParticipationFence') IS DISTINCT FROM 'string' + OR jsonb_typeof(terminal_value->'gameSessionOwnerAttemptId') IS DISTINCT FROM 'string' + OR jsonb_typeof(terminal_value->'gameSessionOwnerFence') IS DISTINCT FROM 'string' + OR jsonb_typeof(terminal_value->'targetNamespace') IS DISTINCT FROM 'string' + OR jsonb_typeof(terminal_value->'canonicalTenantId') IS DISTINCT FROM 'string' + OR jsonb_typeof(terminal_value->'controlPlaneRequestId') IS DISTINCT FROM 'string' + OR jsonb_typeof(terminal_value->'canonicalGameInstanceId') IS DISTINCT FROM 'string' + OR jsonb_typeof(terminal_value->'preparationInputDigest') IS DISTINCT FROM 'string' + OR jsonb_typeof(terminal_value->'preparationInputJson') IS DISTINCT FROM 'string' + OR jsonb_typeof(terminal_value->'worldExecutionFence') IS DISTINCT FROM 'string' + OR jsonb_typeof(terminal_value->'outcome') IS DISTINCT FROM 'string' + OR terminal_value->>'schema' IS DISTINCT FROM 'world-start-session-execution-terminal/v1' + OR terminal_value->>'originalPostAuthorizationTupleBase64' IS DISTINCT FROM encoded_tuple + OR terminal_value->>'accountWorldParticipationId' IS DISTINCT FROM original.participation_id::TEXT + OR terminal_value->>'accountWorldParticipationFence' IS DISTINCT FROM original.participation_fence::TEXT + OR terminal_value->>'gameSessionOwnerAttemptId' IS DISTINCT FROM original.game_session_owner_attempt_id::TEXT + OR terminal_value->>'gameSessionOwnerFence' IS DISTINCT FROM original.game_session_owner_fence::TEXT + OR terminal_value->>'targetNamespace' IS DISTINCT FROM original.target_namespace + OR terminal_value->>'canonicalTenantId' IS DISTINCT FROM original.canonical_tenant_id::TEXT + OR terminal_value->>'controlPlaneRequestId' IS DISTINCT FROM original.control_plane_request_id + OR terminal_value->>'canonicalGameInstanceId' IS DISTINCT FROM original.canonical_game_instance_id::TEXT + OR terminal_value->>'preparationInputDigest' IS DISTINCT FROM original.preparation_input_digest + OR terminal_value->>'preparationInputJson' IS DISTINCT FROM original.preparation_input_json + OR terminal_value->>'worldExecutionFence' !~ '^[1-9][0-9]{0,18}$' + OR (terminal_value->>'worldExecutionFence')::NUMERIC > 9223372036854775807 + OR (terminal_value->>'worldExecutionFence')::BIGINT IS DISTINCT FROM NEW.world_execution_fence + OR terminal_value->>'outcome' IS DISTINCT FROM NEW.outcome THEN + RAISE EXCEPTION 'World terminal is not the exact closed StartSession participation receipt' + USING ERRCODE = '23514'; + END IF; + PERFORM account_start_session_world_participation_validate_input( + original.preparation_input_json, original.preparation_input_digest, + original.original_post_authorization_tuple, original.target_namespace, + original.canonical_tenant_id, original.control_plane_request_id, + original.canonical_game_instance_id); + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_start_session_world_participation_no_mutation() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'StartSession World participation evidence is append-only' USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_start_session_world_participation_validate + BEFORE INSERT ON account_start_session_world_participations + FOR EACH ROW EXECUTE FUNCTION account_start_session_world_participation_insert_guard(); +CREATE TRIGGER account_start_session_world_participation_immutable + BEFORE UPDATE OR DELETE ON account_start_session_world_participations + FOR EACH ROW EXECUTE FUNCTION account_start_session_world_participation_no_mutation(); +CREATE TRIGGER account_start_session_world_participation_no_truncate + BEFORE TRUNCATE ON account_start_session_world_participations + FOR EACH STATEMENT EXECUTE FUNCTION account_start_session_world_participation_no_mutation(); +CREATE TRIGGER account_start_session_world_participation_sources_insert + BEFORE INSERT ON account_start_session_world_participation_sources + FOR EACH ROW EXECUTE FUNCTION account_start_session_world_participation_source_insert_guard(); +CREATE TRIGGER account_start_session_world_participation_sources_immutable + BEFORE UPDATE OR DELETE ON account_start_session_world_participation_sources + FOR EACH ROW EXECUTE FUNCTION account_start_session_world_participation_no_mutation(); +CREATE TRIGGER account_start_session_world_participation_sources_no_truncate + BEFORE TRUNCATE ON account_start_session_world_participation_sources + FOR EACH STATEMENT EXECUTE FUNCTION account_start_session_world_participation_no_mutation(); +CREATE CONSTRAINT TRIGGER account_start_session_world_participation_complete + AFTER INSERT ON account_start_session_world_participations DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_start_session_world_participation_complete_guard(); +CREATE TRIGGER account_start_session_world_participation_settlement_validate + BEFORE INSERT ON account_start_session_world_participation_settlements + FOR EACH ROW EXECUTE FUNCTION account_start_session_world_participation_terminal_guard(); +CREATE TRIGGER account_start_session_world_participation_settlements_immutable + BEFORE UPDATE OR DELETE ON account_start_session_world_participation_settlements + FOR EACH ROW EXECUTE FUNCTION account_start_session_world_participation_no_mutation(); +CREATE TRIGGER account_start_session_world_settlement_no_truncate + BEFORE TRUNCATE ON account_start_session_world_participation_settlements + FOR EACH STATEMENT EXECUTE FUNCTION account_start_session_world_participation_no_mutation(); +-- [jooq ignore stop] + +-- Extend, rather than replace with an older migration body, the current V91/V93/V95/V96/V97 +-- assembled source-writer decision point. The source-key lock order already matches all owners. +-- [jooq ignore start] +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ FOR operation_value IN SELECT DISTINCT s.operation_id + FROM account_draft_authorization_sources s$anchor$; + participation_guard TEXT := $guard$ PERFORM participation.participation_id + FROM account_start_session_world_participations participation + JOIN account_start_session_world_participation_sources source + ON source.participation_id = participation.participation_id + WHERE source.source_key = ANY(source_keys) + AND NOT account_start_session_world_participation_is_settled(participation.participation_id) + ORDER BY participation.participation_id FOR UPDATE OF participation NOWAIT; + IF FOUND THEN + RAISE EXCEPTION 'StartSession World participation remains pending for a required source' + USING ERRCODE = '55P03'; + END IF; +$guard$; +BEGIN + SELECT pg_get_functiondef('account_control_ui_hold_required_sources(TEXT[])'::REGPROCEDURE) + INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one assembled Account Draft source-writer anchor'; + END IF; + EXECUTE replace(original, anchor, participation_guard || anchor); +END; +$migration$; + +-- Pending World participation also excludes the existing source-change terminal writer. Keep +-- its current V91+ body and insert the check only after that body has locked its sorted sources. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ FOR operation IN SELECT DISTINCT source.operation_id + FROM account_draft_authorization_changed_scopes changed$anchor$; + participation_guard TEXT := $guard$ IF EXISTS ( + SELECT 1 FROM account_draft_authorization_changed_scopes changed + JOIN account_start_session_world_participation_sources source + ON source.source_key = changed.source_key + JOIN account_start_session_world_participations participation + ON participation.participation_id = source.participation_id + WHERE changed.change_id = OLD.change_id + AND NOT account_start_session_world_participation_is_settled(participation.participation_id) + ) THEN + PERFORM participation.participation_id + FROM account_draft_authorization_changed_scopes changed + JOIN account_start_session_world_participation_sources source + ON source.source_key = changed.source_key + JOIN account_start_session_world_participations participation + ON participation.participation_id = source.participation_id + WHERE changed.change_id = OLD.change_id + AND NOT account_start_session_world_participation_is_settled(participation.participation_id) + ORDER BY participation.participation_id FOR UPDATE OF participation NOWAIT; + RAISE EXCEPTION 'Pending StartSession World participation excludes source-change completion' + USING ERRCODE = '55P03'; + END IF; +$guard$; +BEGIN + SELECT pg_get_functiondef('account_draft_authorization_source_change_guard()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one current Account source-change terminal anchor'; + END IF; + EXECUTE replace(original, anchor, participation_guard || anchor); +END; +$migration$; + +-- A disclosure dispatch or retry is excluded by every overlapping pending World participation. +-- The repository already takes these source locks before updating the handoff row; NOWAIT keeps +-- raw or incorrectly ordered paths from waiting in an inverse lock order. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ IF OLD.status = 'PREPARED' AND NEW.status = 'DISPATCH_AUTHORIZED'$anchor$; + participation_guard TEXT := $guard$ IF OLD.status IN ('PREPARED', 'AMBIGUOUS') + AND NEW.status = 'DISPATCH_AUTHORIZED' THEN + PERFORM source_lock.source_key + FROM account_draft_authorization_source_locks source_lock + JOIN ( + SELECT OLD.source_key AS source_key + UNION + SELECT handoff_source.source_key + FROM account_hosted_terms_disclosure_sources handoff_source + WHERE handoff_source.handoff_id = OLD.handoff_id + ) exact_source USING (source_key) + ORDER BY account_publication_authorization_source_sort_key(source_lock.source_key) + FOR UPDATE OF source_lock NOWAIT; + IF EXISTS ( + SELECT 1 FROM account_start_session_world_participations participation + JOIN account_start_session_world_participation_sources source + ON source.participation_id = participation.participation_id + WHERE source.source_key IN ( + SELECT OLD.source_key + UNION + SELECT handoff_source.source_key + FROM account_hosted_terms_disclosure_sources handoff_source + WHERE handoff_source.handoff_id = OLD.handoff_id) + AND NOT account_start_session_world_participation_is_settled(participation.participation_id) + ) THEN + PERFORM participation.participation_id + FROM account_start_session_world_participations participation + JOIN account_start_session_world_participation_sources source + ON source.participation_id = participation.participation_id + WHERE source.source_key IN ( + SELECT OLD.source_key + UNION + SELECT handoff_source.source_key + FROM account_hosted_terms_disclosure_sources handoff_source + WHERE handoff_source.handoff_id = OLD.handoff_id) + AND NOT account_start_session_world_participation_is_settled(participation.participation_id) + ORDER BY participation.participation_id FOR UPDATE OF participation NOWAIT; + RAISE EXCEPTION 'Pending StartSession World participation excludes hosted-terms dispatch' + USING ERRCODE = '55P03'; + END IF; + END IF; +$guard$; +BEGIN + SELECT pg_get_functiondef('account_hosted_terms_disclosure_handoff_guard()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one current hosted-terms dispatch transition anchor'; + END IF; + EXECUTE replace(original, anchor, participation_guard || anchor); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql b/services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql new file mode 100644 index 0000000000..6e659424ca --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql @@ -0,0 +1,12 @@ +-- The Account capture source fence is independent from the owner issuance fence. +-- Preserve the canonical positive BIGINT decimal carried by the immutable bundle reference. +-- jOOQ's H2 model gives unnamed historical checks non-portable generated names. +-- [jooq ignore start] +ALTER TABLE account_start_session_operator_authorizations + DROP CONSTRAINT account_start_session_operator_authorizations_check; + +ALTER TABLE account_start_session_operator_authorizations + ADD CONSTRAINT account_ss_operator_bundle_source_fence_canonical_check + CHECK (bundle_source_fence ~ '^[1-9][0-9]{0,18}$' + AND bundle_source_fence::NUMERIC <= 9223372036854775807); +-- [jooq ignore end] diff --git a/services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql b/services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql new file mode 100644 index 0000000000..8ab48f8541 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql @@ -0,0 +1,73 @@ +-- Retain an observation of the exact live original Game Session attempt beside the +-- distinct Account-owned World participation. This is not producer authentication, +-- continuous owner authority, or admission permission. +CREATE TABLE account_start_session_world_original_attempt_evidence ( + participation_id UUID PRIMARY KEY + REFERENCES account_start_session_world_participations(participation_id) ON DELETE RESTRICT, + target_namespace VARCHAR(63) NOT NULL + CHECK (target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + game_session_owner_attempt_id UUID NOT NULL + CHECK (game_session_owner_attempt_id <> '00000000-0000-0000-0000-000000000000'::UUID), + game_session_owner_mutation_id UUID NOT NULL UNIQUE + CHECK (game_session_owner_mutation_id <> '00000000-0000-0000-0000-000000000000'::UUID), + game_session_owner_fence BIGINT NOT NULL CHECK (game_session_owner_fence > 0), + original_lease_expires_at TIMESTAMPTZ NOT NULL + CHECK (isfinite(original_lease_expires_at)), + original_response_bytes BYTEA NOT NULL + CHECK (octet_length(original_response_bytes) BETWEEN 1 AND 525824), + original_response_digest VARCHAR(71) NOT NULL + CHECK (original_response_digest ~ '^sha256:[0-9a-f]{64}$') + CHECK (original_response_digest = 'sha256:' || encode(sha256(original_response_bytes), 'hex')) +); + +-- [jooq ignore start] +CREATE FUNCTION account_ss_world_attempt_evidence_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + parent account_start_session_world_participations%ROWTYPE; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Original StartSession attempt observation is append-only' + USING ERRCODE = '23514'; + END IF; + -- Lock first so a concurrent terminal settlement cannot pass the pending-parent check. + SELECT * INTO STRICT parent FROM account_start_session_world_participations + WHERE participation_id = NEW.participation_id FOR UPDATE; + IF parent.target_namespace IS DISTINCT FROM NEW.target_namespace + OR parent.game_session_owner_attempt_id IS DISTINCT FROM NEW.game_session_owner_attempt_id + OR parent.game_session_owner_fence IS DISTINCT FROM NEW.game_session_owner_fence THEN + RAISE EXCEPTION 'Original StartSession attempt observation differs from its participation' + USING ERRCODE = '23514'; + END IF; + IF account_start_session_world_participation_is_settled(NEW.participation_id) THEN + RAISE EXCEPTION 'Original StartSession attempt observation requires pending participation' + USING ERRCODE = '23514'; + END IF; + -- This is a database-clock freshness guard after any parent lock wait. It does not + -- authenticate Game Session or assert that this point-in-time observation stays current. + IF NEW.original_lease_expires_at <= clock_timestamp() THEN + RAISE EXCEPTION 'Original StartSession attempt observation lease is expired' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_ss_world_attempt_evidence_no_mutation() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Original StartSession attempt observation is append-only' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_ss_world_attempt_evidence_validate + BEFORE INSERT ON account_start_session_world_original_attempt_evidence + FOR EACH ROW EXECUTE FUNCTION account_ss_world_attempt_evidence_insert_guard(); +CREATE TRIGGER account_ss_world_attempt_evidence_immutable + BEFORE UPDATE OR DELETE ON account_start_session_world_original_attempt_evidence + FOR EACH ROW EXECUTE FUNCTION account_ss_world_attempt_evidence_no_mutation(); +CREATE TRIGGER account_ss_world_attempt_evidence_no_truncate + BEFORE TRUNCATE ON account_start_session_world_original_attempt_evidence + FOR EACH STATEMENT EXECUTE FUNCTION account_ss_world_attempt_evidence_no_mutation(); +-- [jooq ignore end] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java new file mode 100644 index 0000000000..ad3851a609 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java @@ -0,0 +1,965 @@ +package integration.net.firedevops.firemud.accountservice.hostedterms; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.sql.Connection; +import java.sql.Statement; +import java.time.Duration; +import java.time.Instant; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsDisclosureHandoff; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsDisclosureHandoff.DisclosureResult; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsDisclosureHandoff.Kind; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsDisclosureHandoff.Outcome; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsDisclosureHandoffRepository; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsDisclosureHandoffRepository.Status; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEncoding; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiOriginalOrderFixture; +import net.firedevops.firemud.accountservice.service.session.AccountOriginalStartSessionAuthorizationProofFixture; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationAcquisitionService; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationAcquisitionService.AcquisitionRequest; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +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; + +/** + * Owner-store proof only. Authority and disclosure evidence below is explicitly test-only; this + * does not authenticate a publisher or implement an external dispatch/receipt owner. + */ +@Testcontainers(disabledWithoutDocker = true) +class HostedTermsDisclosureHandoffPostgresIntegrationTest { + private static final String NAMESPACE = "control-ui-owner-proof"; + private static final Network REDIS_NETWORK = Network.newNetwork(); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(REDIS_NETWORK) + .withNetworkAliases("hosted-terms-redis-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static GenericContainer redisReplica = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(REDIS_NETWORK) + .dependsOn(redis) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "hosted-terms-redis-primary", + "6379"); + + @TempDir Path temporary; + + @Test + void exactRetryAmbiguityAndTerminalEvidenceAreDurableAndImmutable() throws Exception { + Database database = database(); + DraftAuthorizationFenceRepository fences = + new DraftAuthorizationFenceRepository(database.dsl()); + HostedTermsDisclosureHandoffRepository journal = + new HostedTermsDisclosureHandoffRepository(database.dsl(), fences); + HostedTermsDisclosureHandoff handoff = handoff(source("journal")); + + var prepared = tx(database, () -> journal.prepare(handoff)); + assertThat(prepared.status()).isEqualTo(Status.PREPARED); + assertThat(prepared.dispatchAttempts()).isZero(); + var preparedRetry = tx(database, () -> journal.prepare(handoff)); + assertThat(preparedRetry.handoff().canonicalBytes()).containsExactly(handoff.canonicalBytes()); + assertThat(preparedRetry.status()).isEqualTo(Status.PREPARED); + + HostedTermsDisclosureHandoff conflict = + new HostedTermsDisclosureHandoff( + UUID.randomUUID(), + handoff.requestId(), + handoff.kind(), + handoff.sourceKey(), + handoff.predecessorDigest(), + HostedTermsEncoding.digest(new byte[] {99}), + handoff.effectiveAt(), + handoff.sources(), + "test-only-conflicting-authority-bytes".getBytes(StandardCharsets.UTF_8)); + assertThatThrownBy(() -> tx(database, () -> journal.prepare(conflict))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("conflicts"); + + var firstPermit = tx(database, () -> journal.authorizeDispatch(handoff)); + assertThat(firstPermit.newlyAuthorized()).isTrue(); + assertThat(firstPermit.snapshot().status()).isEqualTo(Status.DISPATCH_AUTHORIZED); + assertThat(firstPermit.snapshot().dispatchAttempts()).isEqualTo(1); + assertThat(firstPermit.snapshot().result()).isEmpty(); + var lostPermitRecovery = tx(database, () -> journal.authorizeDispatch(handoff)); + assertThat(lostPermitRecovery.newlyAuthorized()).isFalse(); + assertThat(lostPermitRecovery.snapshot().dispatchAttempts()).isEqualTo(1); + + assertThat(tx(database, () -> journal.recordAmbiguous(handoff)).status()) + .isEqualTo(Status.AMBIGUOUS); + var retryPermit = tx(database, () -> journal.authorizeDispatch(handoff)); + assertThat(retryPermit.newlyAuthorized()).isTrue(); + assertThat(retryPermit.snapshot().dispatchAttempts()).isEqualTo(2); + + DisclosureResult mismatchedBindingResult = + new DisclosureResult( + handoff.handoffId(), + handoff.requestId(), + HostedTermsEncoding.digest(new byte[] {42}), + Outcome.DISCLOSED, + "test-only-mismatched-owner-readback".getBytes(StandardCharsets.UTF_8)); + assertThatThrownBy( + () -> tx(database, () -> journal.recordResult(handoff, mismatchedBindingResult))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not bound to the exact handoff"); + var afterMismatchedBinding = tx(database, () -> journal.read(handoff.handoffId())); + assertThat(afterMismatchedBinding).isPresent(); + assertThat(afterMismatchedBinding.orElseThrow().status()).isEqualTo(Status.DISPATCH_AUTHORIZED); + assertThat(afterMismatchedBinding.orElseThrow().result()).isEmpty(); + + byte[] testOnlyOwnerReadback = + "test-only-authenticated-disclosure-receipt".getBytes(StandardCharsets.UTF_8); + DisclosureResult result = + new DisclosureResult( + handoff.handoffId(), + handoff.requestId(), + HostedTermsEncoding.digest(handoff.canonicalBytes()), + Outcome.DISCLOSED, + testOnlyOwnerReadback); + var disclosed = tx(database, () -> journal.recordResult(handoff, result)); + assertThat(disclosed.status()).isEqualTo(Status.DISCLOSED); + assertThat(disclosed.result().orElseThrow().canonicalBytes()) + .containsExactly(result.canonicalBytes()); + var resultRetry = tx(database, () -> journal.recordResult(handoff, result)); + assertThat(resultRetry.result().orElseThrow().canonicalBytes()) + .containsExactly(result.canonicalBytes()); + Database restarted = reopen(database); + var restartedRead = + tx( + restarted, + () -> + new HostedTermsDisclosureHandoffRepository( + restarted.dsl(), new DraftAuthorizationFenceRepository(restarted.dsl())) + .read(handoff.handoffId())); + assertThat(restartedRead).isPresent(); + assertThat(restartedRead.orElseThrow().status()).isEqualTo(Status.DISCLOSED); + assertThat(restartedRead.orElseThrow().handoff().canonicalBytes()) + .containsExactly(handoff.canonicalBytes()); + + DisclosureResult changedResult = + new DisclosureResult( + handoff.handoffId(), + handoff.requestId(), + HostedTermsEncoding.digest(handoff.canonicalBytes()), + Outcome.DISCLOSED, + "test-only-changed-owner-readback".getBytes(StandardCharsets.UTF_8)); + assertThatThrownBy(() -> tx(database, () -> journal.recordResult(handoff, changedResult))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Changed terminal"); + assertThatThrownBy( + () -> + tx( + database, + () -> { + database + .dsl() + .execute( + "UPDATE account_hosted_terms_disclosure_handoffs " + + "SET result_payload = ? WHERE handoff_id = ?", + "test-only-overwrite".getBytes(StandardCharsets.UTF_8), + handoff.handoffId()); + return null; + })) + .isInstanceOf(DataAccessException.class); + + HostedTermsDisclosureHandoff noDisclosure = handoff(source("definitive-no-disclosure")); + tx(database, () -> journal.prepare(noDisclosure)); + assertThatThrownBy( + () -> + tx( + database, + () -> + journal.recordResult( + noDisclosure, + new DisclosureResult( + noDisclosure.handoffId(), + noDisclosure.requestId(), + HostedTermsEncoding.digest(noDisclosure.canonicalBytes()), + Outcome.DEFINITIVELY_NOT_DISCLOSED, + "test-only-premature-negative".getBytes(StandardCharsets.UTF_8))))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("dispatch authorization"); + tx(database, () -> journal.authorizeDispatch(noDisclosure)); + tx(database, () -> journal.recordAmbiguous(noDisclosure)); + DisclosureResult negativeResult = + new DisclosureResult( + noDisclosure.handoffId(), + noDisclosure.requestId(), + HostedTermsEncoding.digest(noDisclosure.canonicalBytes()), + Outcome.DEFINITIVELY_NOT_DISCLOSED, + "test-only-authenticated-definitive-no-disclosure".getBytes(StandardCharsets.UTF_8)); + var noDisclosureSnapshot = + tx(database, () -> journal.recordResult(noDisclosure, negativeResult)); + assertThat(noDisclosureSnapshot.status()).isEqualTo(Status.DEFINITIVELY_NOT_DISCLOSED); + assertThat(noDisclosureSnapshot.handoff().effectiveAt()).isEqualTo(noDisclosure.effectiveAt()); + assertThat(noDisclosureSnapshot.result().orElseThrow().canonicalBytes()) + .containsExactly(negativeResult.canonicalBytes()); + } + + @Test + void exactAuthorizedReadbackSurvivesLaterPendingParticipationOnNonTermsSource() throws Exception { + // The shared fixture writes genuine Account rows while its upstream claim and peer evidence + // remain test-only; this does not establish a production World authority path. + try (var controlUi = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary)) { + var proof = + new AccountOriginalStartSessionAuthorizationProofFixture(controlUi, temporary, NAMESPACE); + Database database = database(proof.sourceDsl()); + UUID reservationOwner = UUID.randomUUID(); + long reservationFence = 31L; + UUID gameSessionAttempt = UUID.randomUUID(); + UUID gameSessionMutation = UUID.randomUUID(); + long gameSessionFence = 47L; + String requestId = "authorized-disclosure-" + UUID.randomUUID(); + var action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(controlUi.tenantId(), NAMESPACE), + new StartSessionOperatorAction.Target(42L, proof.creatorAccountId()), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "test-only exact authorized-readback regression"); + var original = + proof.issueAndRedeemOriginal( + requestId, + action, + reservationOwner, + reservationFence, + new AccountOriginalStartSessionAuthorizationProofFixture.OwnerAttemptLifecycle() { + @Override + public AccountOriginalStartSessionAuthorizationProofFixture.OwnerClaim reserve( + StartSessionPostAuthorizationExecutionTuple originalTuple) { + return new AccountOriginalStartSessionAuthorizationProofFixture.OwnerClaim( + gameSessionAttempt, gameSessionMutation, gameSessionFence); + } + + @Override + public void attachAccountRedemptionProjection( + AccountOriginalStartSessionAuthorizationProofFixture.OwnerClaim ownerClaim, + StartSessionPostAuthorizationExecutionTuple originalTuple) {} + }); + + byte[] snapshotBytes = + Objects.requireNonNull( + proof + .sourceDsl() + .fetchOne( + "SELECT canonical_snapshot_bytes FROM account_start_session_authority_captures " + + "WHERE control_plane_request_id = ?", + requestId), + "Expected the original Account capture") + .get("canonical_snapshot_bytes", byte[].class); + Map captureSnapshot = + tools.jackson.databind.json.JsonMapper.builder() + .build() + .readValue(snapshotBytes, Map.class); + SourceEvidence source = + ((List) captureSnapshot.get("sourceVector")) + .stream() + .map( + value -> + SourceEvidence.fromStored(Base64.getDecoder().decode((String) value))) + .filter(value -> value.kind() != SourceKind.HOSTED_TERMS) + .findFirst() + .orElseThrow(() -> new IllegalStateException("Expected a non-terms source")); + var journal = + new HostedTermsDisclosureHandoffRepository( + database.dsl(), new DraftAuthorizationFenceRepository(database.dsl())); + var handoff = handoff(source("overlap"), source); + tx(database, () -> journal.prepare(handoff)); + var firstPermit = tx(database, () -> journal.authorizeDispatch(handoff)); + assertThat(firstPermit.newlyAuthorized()).isTrue(); + + UUID gameInstance = UUID.randomUUID(); + String preparationInput = + preparationInput(NAMESPACE, controlUi.tenantId(), requestId, gameInstance, 42L); + AccountStartSessionWorldParticipationAcquisitionService acquisition = + proof.worldParticipationAcquisitionService( + request -> + new Result( + request, + Instant.ofEpochMilli( + Instant.now().plus(Duration.ofMinutes(1)).toEpochMilli()), + StartSessionAccountRedemptionProjection.fromOriginalTuple( + request.originalTuple()))); + var acquisitionRequest = + new AcquisitionRequest( + original.originalTuple().canonicalBytes(), + gameSessionMutation, + gameSessionAttempt, + gameSessionFence, + gameInstance, + preparationInput, + digest(preparationInput)); + var worldPeer = + GrpcPeerIdentity.parseUri( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/world-management-service") + .orElseThrow(); + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, worldPeer) + .call(() -> acquisition.acquire(acquisitionRequest)); + assertThat( + database + .dsl() + .fetch( + "SELECT 1 FROM account_start_session_world_participation_sources s " + + "JOIN account_start_session_world_participations p " + + "ON p.participation_id = s.participation_id " + + "WHERE s.source_key = ? " + + "AND NOT account_start_session_world_participation_is_settled(p.participation_id)", + source.key())) + .isNotEmpty(); + + var recovered = tx(database, () -> journal.authorizeDispatch(handoff)); + assertThat(recovered.newlyAuthorized()).isFalse(); + assertThat(recovered.snapshot().status()).isEqualTo(Status.DISPATCH_AUTHORIZED); + assertThat(recovered.snapshot().dispatchAttempts()).isEqualTo(1); + } + } + + @Test + void preparationRefusesReservedAndUnsettledCommitOrderWithoutRewritingEither() throws Exception { + Database database = database(); + DraftAuthorizationFenceRepository fences = + new DraftAuthorizationFenceRepository(database.dsl()); + HostedTermsDisclosureHandoffRepository journal = + new HostedTermsDisclosureHandoffRepository(database.dsl(), fences); + SourceEvidence source = source("fenced-operation"); + DraftAuthorizationFenceBinding original = draftBinding(source); + HostedTermsDisclosureHandoff handoff = handoff(source); + + tx(database, () -> fences.reserve(original)); + assertThatThrownBy(() -> tx(database, () -> journal.prepare(handoff))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("unsettled original Draft operation"); + assertThat(tx(database, () -> fences.read(original).ordering())) + .isEqualTo(DraftAuthorizationFenceRepository.Ordering.RESERVED); + + tx(database, () -> fences.claimCommitOrder(original)); + assertThatThrownBy(() -> tx(database, () -> journal.prepare(handoff))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("unsettled original Draft operation"); + assertThat(tx(database, () -> fences.read(original).ordering())) + .isEqualTo(DraftAuthorizationFenceRepository.Ordering.COMMIT_ORDER); + + tx( + database, + () -> { + recordOwnerResult(fences, original, Owner.GAME_DESIGN); + return null; + }); + tx( + database, + () -> { + recordOwnerResult(fences, original, Owner.WORLD); + return null; + }); + var prepared = tx(database, () -> journal.prepare(handoff)); + assertThat(prepared.status()).isEqualTo(Status.PREPARED); + assertThat(tx(database, () -> fences.read(original).ordering())) + .isEqualTo(DraftAuthorizationFenceRepository.Ordering.COMMIT_ORDER); + } + + @Test + void preparedHandoffAllowsOriginalOrderingButDispatchWaitsForExactSettlement() throws Exception { + Database database = database(); + DraftAuthorizationFenceRepository fences = + new DraftAuthorizationFenceRepository(database.dsl()); + HostedTermsDisclosureHandoffRepository journal = + new HostedTermsDisclosureHandoffRepository(database.dsl(), fences); + SourceEvidence source = source("prepare-first"); + HostedTermsDisclosureHandoff handoff = handoff(source); + DraftAuthorizationFenceBinding original = draftBinding(source); + + tx(database, () -> journal.prepare(handoff)); + tx(database, () -> fences.reserve(original)); + assertDispatchUnsettled(database, journal, handoff); + tx(database, () -> fences.claimCommitOrder(original)); + assertDispatchUnsettled(database, journal, handoff); + tx( + database, + () -> { + recordOwnerResult(fences, original, Owner.GAME_DESIGN); + return null; + }); + assertDispatchUnsettled(database, journal, handoff); + tx( + database, + () -> { + recordOwnerResult(fences, original, Owner.WORLD); + return null; + }); + assertThat(tx(database, () -> journal.authorizeDispatch(handoff)).newlyAuthorized()).isTrue(); + assertThat(tx(database, () -> fences.reserve(original)).ordering()) + .isEqualTo(DraftAuthorizationFenceRepository.Ordering.COMMIT_ORDER); + assertThat(tx(database, () -> fences.claimCommitOrder(original)).ordering()) + .isEqualTo(DraftAuthorizationFenceRepository.Ordering.COMMIT_ORDER); + assertDisclosureBlocked(database, fences, draftBinding(source)); + } + + @Test + void dispatchGuardUsesOnlyExactChangedTermsEvidenceAndDefinitiveNegativeReleasesIt() + throws Exception { + Database database = database(); + DraftAuthorizationFenceRepository fences = + new DraftAuthorizationFenceRepository(database.dsl()); + HostedTermsDisclosureHandoffRepository journal = + new HostedTermsDisclosureHandoffRepository(database.dsl(), fences); + SourceEvidence changed = source("exact-changed-source"); + SourceEvidence unrelated = source("unrelated-terms-source"); + SourceEvidence account = + new SourceEvidence( + SourceKind.ACCOUNT, + UUID.randomUUID().toString(), + "1", + "1", + null, + null, + "test-only-account-evidence".getBytes(StandardCharsets.UTF_8)); + HostedTermsDisclosureHandoff original = handoff(changed); + HostedTermsDisclosureHandoff handoff = + new HostedTermsDisclosureHandoff( + original.handoffId(), + original.requestId(), + original.kind(), + original.sourceKey(), + original.predecessorDigest(), + original.candidateDigest(), + original.effectiveAt(), + List.of(changed, unrelated, account), + original.authenticatedAuthorityEvidence()); + tx(database, () -> journal.prepare(handoff)); + tx(database, () -> journal.authorizeDispatch(handoff)); + assertDisclosureBlocked(database, fences, draftBinding(changed)); + // Other vector members and newer source bytes cannot inherit the changed source's guard. + tx(database, () -> fences.reserve(draftBinding(unrelated))); + tx(database, () -> fences.reserve(draftBinding(account))); + SourceEvidence newer = + new SourceEvidence( + changed.kind(), + changed.scopeId(), + changed.generation(), + "8", + null, + null, + "test-only-newer-terms-evidence".getBytes(StandardCharsets.UTF_8)); + DraftAuthorizationFenceBinding newerOriginal = draftBinding(newer); + tx(database, () -> fences.reserve(newerOriginal)); + tx(database, () -> fences.claimCommitOrder(newerOriginal)); + tx(database, () -> journal.recordAmbiguous(handoff)); + assertDisclosureBlocked(database, fences, draftBinding(changed)); + assertThat(tx(database, () -> journal.authorizeDispatch(handoff)).newlyAuthorized()).isTrue(); + tx( + database, + () -> + journal.recordResult( + handoff, + new DisclosureResult( + handoff.handoffId(), + handoff.requestId(), + HostedTermsEncoding.digest(handoff.canonicalBytes()), + Outcome.DEFINITIVELY_NOT_DISCLOSED, + "test-only-definitive-negative".getBytes(StandardCharsets.UTF_8)))); + DraftAuthorizationFenceBinding afterNegative = draftBinding(changed); + tx(database, () -> fences.reserve(afterNegative)); + tx(database, () -> fences.claimCommitOrder(afterNegative)); + + SourceEvidence disclosedSource = source("disclosed-guard"); + HostedTermsDisclosureHandoff disclosed = handoff(disclosedSource); + tx(database, () -> journal.prepare(disclosed)); + tx(database, () -> journal.authorizeDispatch(disclosed)); + tx( + database, + () -> + journal.recordResult( + disclosed, + new DisclosureResult( + disclosed.handoffId(), + disclosed.requestId(), + HostedTermsEncoding.digest(disclosed.canonicalBytes()), + Outcome.DISCLOSED, + "test-only-disclosed-result".getBytes(StandardCharsets.UTF_8)))); + assertDisclosureBlocked(database, fences, draftBinding(disclosedSource)); + SourceEvidence differentBytes = + new SourceEvidence( + disclosedSource.kind(), + disclosedSource.scopeId(), + disclosedSource.generation(), + disclosedSource.sourceVersion(), + null, + null, + "test-only-different-source-bytes".getBytes(StandardCharsets.UTF_8)); + tx(database, () -> fences.reserve(draftBinding(differentBytes))); + SourceEvidence newerDisclosed = + new SourceEvidence( + disclosedSource.kind(), + disclosedSource.scopeId(), + disclosedSource.generation(), + "8", + null, + null, + "test-only-new-version".getBytes(StandardCharsets.UTF_8)); + tx(database, () -> fences.reserve(draftBinding(newerDisclosed))); + } + + @Test + void sourceLocksSerializeConcurrentOriginalAcquisitionBeforeDispatch() throws Exception { + concurrentAcquisitionAndDispatch(false); + } + + @Test + void sourceLocksSerializeConcurrentDispatchBeforeOriginalAcquisition() throws Exception { + concurrentAcquisitionAndDispatch(true); + } + + private static void concurrentAcquisitionAndDispatch(boolean dispatchFirst) throws Exception { + Database database = database(); + DraftAuthorizationFenceRepository fences = + new DraftAuthorizationFenceRepository(database.dsl()); + HostedTermsDisclosureHandoffRepository journal = + new HostedTermsDisclosureHandoffRepository(database.dsl(), fences); + SourceEvidence source = source("concurrent-" + dispatchFirst); + HostedTermsDisclosureHandoff handoff = handoff(source); + DraftAuthorizationFenceBinding original = draftBinding(source); + tx(database, () -> journal.prepare(handoff)); + CountDownLatch firstLocked = new CountDownLatch(1); + CountDownLatch releaseFirst = new CountDownLatch(1); + CountDownLatch secondStarted = new CountDownLatch(1); + AtomicInteger firstPid = new AtomicInteger(); + AtomicInteger secondPid = new AtomicInteger(); + var executor = Executors.newFixedThreadPool(2); + try { + var first = + executor.submit( + () -> + tx( + database, + () -> { + firstPid.set( + Objects.requireNonNull( + database.dsl().fetchOne("SELECT pg_backend_pid()"), + "Expected first transaction PostgreSQL backend PID row") + .get(0, Integer.class)); + if (dispatchFirst) { + journal.authorizeDispatch(handoff); + } else { + fences.reserve(original); + fences.claimCommitOrder(original); + } + firstLocked.countDown(); + await(releaseFirst); + return null; + })); + assertThat(firstLocked.await(10, TimeUnit.SECONDS)).isTrue(); + var second = + executor.submit( + () -> + tx( + database, + () -> { + secondPid.set( + Objects.requireNonNull( + database.dsl().fetchOne("SELECT pg_backend_pid()"), + "Expected second transaction PostgreSQL backend PID row") + .get(0, Integer.class)); + secondStarted.countDown(); + if (dispatchFirst) { + fences.reserve(original); + } else { + journal.authorizeDispatch(handoff); + } + return null; + })); + assertThat(secondStarted.await(10, TimeUnit.SECONDS)).isTrue(); + awaitBlocked(database, secondPid.get(), firstPid.get()); + assertThatThrownBy(() -> second.get(200, TimeUnit.MILLISECONDS)) + .isInstanceOf(TimeoutException.class); + releaseFirst.countDown(); + first.get(10, TimeUnit.SECONDS); + assertThatThrownBy(() -> second.get(10, TimeUnit.SECONDS)) + .isInstanceOf(ExecutionException.class) + .hasCauseInstanceOf(IllegalStateException.class) + .hasRootCauseMessage( + dispatchFirst + ? "Exact hosted terms source has authorized disclosure" + : "Disclosure deadline cannot pass an unsettled original Draft operation"); + assertThat(tx(database, () -> journal.read(handoff.handoffId())).orElseThrow().status()) + .isEqualTo(dispatchFirst ? Status.DISPATCH_AUTHORIZED : Status.PREPARED); + } finally { + releaseFirst.countDown(); + executor.shutdownNow(); + } + } + + private static void awaitBlocked(Database database, int waitingPid, int blockerPid) + throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < deadline) { + if (Boolean.TRUE.equals( + Objects.requireNonNull( + database + .dsl() + .fetchOne("SELECT ? = ANY(pg_blocking_pids(?))", blockerPid, waitingPid), + "Expected PostgreSQL blocking-state row") + .get(0, Boolean.class))) { + return; + } + Thread.sleep(10); + } + throw new IllegalStateException( + "Expected original and dispatch transactions to share source locks"); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for test transaction release"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted waiting for test transaction release", interrupted); + } + } + + private static void assertDispatchUnsettled( + Database database, + HostedTermsDisclosureHandoffRepository journal, + HostedTermsDisclosureHandoff handoff) { + assertThatThrownBy(() -> tx(database, () -> journal.authorizeDispatch(handoff))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("unsettled original Draft operation"); + assertThat(tx(database, () -> journal.read(handoff.handoffId())).orElseThrow().status()) + .isEqualTo(Status.PREPARED); + } + + private static void assertDisclosureBlocked( + Database database, + DraftAuthorizationFenceRepository fences, + DraftAuthorizationFenceBinding binding) { + assertThatThrownBy(() -> tx(database, () -> fences.reserve(binding))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Exact hosted terms source has authorized disclosure"); + } + + private static void recordOwnerResult( + DraftAuthorizationFenceRepository fences, + DraftAuthorizationFenceBinding binding, + Owner owner) { + fences.recordOwnerReadback( + binding, + new OwnerReadback( + owner, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + "test-only-owner-result".getBytes(StandardCharsets.UTF_8))); + } + + private static SourceEvidence source(String scopeSuffix) { + return new SourceEvidence( + SourceKind.HOSTED_TERMS, + UUID.nameUUIDFromBytes(scopeSuffix.getBytes(StandardCharsets.UTF_8)).toString(), + null, + "7", + null, + null, + ("test-only-source-evidence-" + scopeSuffix).getBytes(StandardCharsets.UTF_8)); + } + + private static HostedTermsDisclosureHandoff handoff(SourceEvidence source) { + return new HostedTermsDisclosureHandoff( + UUID.randomUUID(), + UUID.randomUUID(), + Kind.CATALOG, + source.key(), + HostedTermsEncoding.digest("test-only-predecessor".getBytes(StandardCharsets.UTF_8)), + HostedTermsEncoding.digest("test-only-candidate".getBytes(StandardCharsets.UTF_8)), + Instant.parse("2026-10-08T00:00:00Z"), + List.of(source), + "test-only-authority-evidence".getBytes(StandardCharsets.UTF_8)); + } + + private static HostedTermsDisclosureHandoff handoff( + SourceEvidence changedTermsSource, SourceEvidence participationSource) { + return new HostedTermsDisclosureHandoff( + UUID.randomUUID(), + UUID.randomUUID(), + Kind.CATALOG, + changedTermsSource.key(), + HostedTermsEncoding.digest("test-only-predecessor".getBytes(StandardCharsets.UTF_8)), + HostedTermsEncoding.digest("test-only-candidate".getBytes(StandardCharsets.UTF_8)), + Instant.parse("2026-10-08T00:00:00Z"), + List.of(changedTermsSource, participationSource), + "test-only-authority-evidence".getBytes(StandardCharsets.UTF_8)); + } + + private static DraftAuthorizationFenceBinding draftBinding(SourceEvidence source) { + UUID actor = UUID.randomUUID(); + DraftCommitBinding complete = + DraftCommitBinding.create( + new TargetProof( + UUID.randomUUID(), + UUID.randomUUID(), + 1, + "test-only-tenant-key", + 2, + "test-only-tenant-key", + "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "test-only-base-commit", + List.of( + new RevisionPayload( + "0", UUID.randomUUID(), DraftCommitBinding.Owner.WORLD_MANAGEMENT, "payload")), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "region", + "region-1", + "aggregate", + "region-1", + "0"))); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + complete.requestId(), + complete.commitId(), + UUID.randomUUID(), + actor, + complete.target().canonicalTenantId(), + complete.target().canonicalVersionId(), + complete.baseCommitId(), + "1", + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + List.of(source)); + } + + private static Database database() throws Exception { + String schema = "terms_disclosure_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = + new DriverManagerDataSource( + postgres.getJdbcUrl() + + (postgres.getJdbcUrl().contains("?") ? "&" : "?") + + "currentSchema=" + + schema, + postgres.getUsername(), + postgres.getPassword()); + try (Connection connection = source.getConnection(); + Statement statement = connection.createStatement()) { + statement.execute("CREATE SCHEMA " + schema); + } + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(source); + Database database = + new Database( + schema, + source, + DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES), + transactionManager, + new TransactionTemplate(transactionManager)); + Flyway.configure() + .dataSource(database.source()) + .schemas(database.schema()) + .defaultSchema(database.schema()) + .placeholders(Map.of("serviceSchema", database.schema())) + .locations("classpath:db/migration") + .target("latest") + .load() + .migrate(); + return database; + } + + private static Database database(DSLContext schemaSource) { + String schema = + Objects.requireNonNull(schemaSource.fetchOne("SELECT current_schema()")) + .get(0, String.class); + String jdbcUrl = postgres.getJdbcUrl(); + DriverManagerDataSource source = + new DriverManagerDataSource( + jdbcUrl + (jdbcUrl.contains("?") ? "&" : "?") + "currentSchema=" + schema, + postgres.getUsername(), + postgres.getPassword()); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(source); + return new Database( + schema, + source, + DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES), + transactionManager, + new TransactionTemplate(transactionManager)); + } + + private static Database reopen(Database original) { + DataSourceTransactionManager transactionManager = + new DataSourceTransactionManager(original.source()); + return new Database( + original.schema(), + original.source(), + DSL.using(new TransactionAwareDataSourceProxy(original.source()), SQLDialect.POSTGRES), + transactionManager, + new TransactionTemplate(transactionManager)); + } + + private static T tx(Database database, Supplier work) { + return database.transactions().execute(status -> work.get()); + } + + private static String preparationInput( + String namespace, UUID tenantId, String requestId, UUID gameInstanceId, long gameTemplateId) + throws Exception { + var json = tools.jackson.databind.json.JsonMapper.builder().build(); + String descriptorJson = json.writeValueAsString(Map.of("gameTemplateId", gameTemplateId)); + return json.writeValueAsString( + Map.of( + "schemaVersion", + 1, + "identity", + Map.of( + "targetNamespace", + namespace, + "canonicalTenantId", + tenantId.toString(), + "controlPlaneRequestId", + requestId, + "canonicalGameInstanceId", + gameInstanceId.toString(), + "worldSlug", + "test-world"), + "gameSessionReadRequest", + Map.of( + "targetNamespace", + namespace, + "canonicalTenantId", + tenantId.toString(), + "controlPlaneRequestId", + requestId, + "canonicalGameInstanceId", + gameInstanceId.toString(), + "worldSlug", + "test-world"), + "gameSessionReadEvidence", + Map.of( + "targetNamespace", + namespace, + "canonicalTenantId", + tenantId.toString(), + "controlPlaneRequestId", + requestId, + "canonicalGameInstanceId", + gameInstanceId.toString(), + "worldSlug", + "test-world", + "descriptorJson", + descriptorJson), + "launchBinding", + Map.of( + "targetNamespace", + namespace, + "canonicalTenantId", + tenantId.toString(), + "controlPlaneRequestId", + requestId, + "worldSlug", + "test-world"))); + } + + private static String digest(String value) throws Exception { + return "sha256:" + + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(StandardCharsets.UTF_8))); + } + + private record Database( + String schema, + DriverManagerDataSource source, + DSLContext dsl, + PlatformTransactionManager transactionManager, + TransactionTemplate transactions) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundlePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundlePersistenceIntegrationTest.java index dbe7ed701c..8070e2c4cd 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundlePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundlePersistenceIntegrationTest.java @@ -101,6 +101,8 @@ void forwardCheckpointRepairRetainsV84OwnersAndCapturesZeroAndPositiveEvidence() assertThat(migrateCheckpointRepair(context)).isEqualTo(1); assertThat(retainedOwnerRows(dsl)).usingRecursiveComparison().isEqualTo(before); + assertThat(migrateCurrentApplicationSchema(context)).isPositive(); + assertThat(retainedOwnerRows(dsl)).usingRecursiveComparison().isEqualTo(before); AccountAuthEvidenceBundle zeroBundle = inTransaction(context, () -> bundles.captureAndPersist(zero.requestId())); assertThat(zeroBundle.fields().get("outboxCheckpoints")) @@ -500,6 +502,18 @@ private static int migrateCheckpointRepair(TestContext context) { .migrationsExecuted; } + private static int migrateCurrentApplicationSchema(TestContext context) { + return Flyway.configure() + .dataSource(context.dataSource()) + .schemas(context.schema()) + .defaultSchema(context.schema()) + .placeholders(Map.of("serviceSchema", context.schema())) + .locations("classpath:db/migration") + .load() + .migrate() + .migrationsExecuted; + } + private static T inTransaction( TestContext context, java.util.function.Supplier operation) { return context.transaction().execute(status -> operation.get()); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java index d6af74fd8a..ba7d05fdbe 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java @@ -4,11 +4,13 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.charset.StandardCharsets; +import java.sql.SQLException; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.time.temporal.ChronoUnit; import java.util.Arrays; +import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -21,12 +23,15 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository; import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.IssuanceCandidate; import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.RedemptionRequest; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle.BundleReference; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.FlywayException; import org.jooq.DSLContext; @@ -63,7 +68,7 @@ static void stopPostgres() { void dropTestOwnedSchemas() { JdbcTemplate jdbc = new JdbcTemplate(POSTGRES.dataSource()); for (String schema : schemas) { - if (!schema.matches("account_start_session_auth_[a-f0-9]{32}")) { + if (!schema.matches("account_start_session_[a-f0-9]{32}")) { throw new IllegalStateException("Refusing to dispose an unowned PostgreSQL schema"); } jdbc.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); @@ -75,6 +80,8 @@ void dropTestOwnedSchemas() { void realPostgresCreateRetryAndRedemptionRetainTheOriginalAuthorityRecord() { Context context = context(); IssuanceCandidate candidate = candidate(context, tuple()); + assertThat(candidate.issuanceFence()) + .isNotEqualTo(Long.parseLong(candidate.bundleReference().sourceFence())); var created = context.inTransaction(() -> context.repository.createOrReadExact(candidate)); IssuanceCandidate differentOutput = withDifferentOutputs(candidate); @@ -100,22 +107,24 @@ void realPostgresCreateRetryAndRedemptionRetainTheOriginalAuthorityRecord() { var replay = context.inTransaction(() -> context.repository.redeemExact(request)); assertThat(redeemed.replay()).isFalse(); assertThat(replay.replay()).isTrue(); - assertThat(replay.authorityEvidenceBundle()).containsExactly(bytes("authority-bundle-v1")); + assertThat(replay.authorityEvidenceBundle()) + .containsExactly(candidate.authorityEvidenceBundle()); var retainedAfterRedemption = context.inTransaction( () -> context.repository.findByControlPlaneRequestId(REQUEST_ID).orElseThrow()); assertThat(retainedAfterRedemption.bundleReference()).isEqualTo(candidate.bundleReference()); assertThat(retainedAfterRedemption.bundleReference().linearization()).isEqualTo("123456789"); - assertThatThrownBy( - () -> - context.inTransactionWithoutResult( - () -> - context.transactionDsl.execute( - "UPDATE account_start_session_operator_authorizations " - + "SET bundle_linearization = ? WHERE control_plane_request_id = ?", - "123456788", - REQUEST_ID))) - .isInstanceOf(IntegrityConstraintViolationException.class); + assertImmutableGuardRejected( + () -> + context.inTransactionWithoutResult( + () -> + context.transactionDsl.execute( + "UPDATE account_start_session_operator_authorizations " + + "SET bundle_linearization = ? WHERE control_plane_request_id = ?", + "123456788", + REQUEST_ID)), + "StartSession authorization evidence is immutable except one exact redemption " + + "or expired envelope erasure"); assertThat( context.inTransaction( () -> @@ -130,7 +139,9 @@ void realPostgresCreateRetryAndRedemptionRetainTheOriginalAuthorityRecord() { @Test void realPostgresAllowsEqualIssueAndRedemptionTimestampsAtMillisecondPrecision() { Context context = context(); - IssuanceCandidate candidate = candidate(context, tuple()); + Instant issuedAt = canonicalMillisecond(databaseNow(context)); + IssuanceCandidate candidate = + candidate(tuple(), issuedAt, issuedAt.plusSeconds(180), issuedAt.plusSeconds(210)); context.inTransaction(() -> context.repository.createOrReadExact(candidate)); RedemptionRequest request = redemption(candidate, OWNER_ATTEMPT_ID, 11L, candidate.issuedAt()); @@ -140,7 +151,7 @@ void realPostgresAllowsEqualIssueAndRedemptionTimestampsAtMillisecondPrecision() var persisted = context.inTransaction( () -> context.repository.findByControlPlaneRequestId(REQUEST_ID).orElseThrow()); - assertThat(persisted.redeemedAt()).isEqualTo(candidate.issuedAt()); + assertThat(persisted.redeemedAt()).isEqualTo(issuedAt); assertThat(persisted.status()) .isEqualTo(AccountStartSessionOperatorAuthorizationRepository.Status.REDEEMED); } @@ -148,7 +159,9 @@ void realPostgresAllowsEqualIssueAndRedemptionTimestampsAtMillisecondPrecision() @Test void realPostgresRejectsRedemptionTimestampEarlierThanIssuance() { Context context = context(); - IssuanceCandidate candidate = candidate(context, tuple()); + Instant issuedAt = canonicalMillisecond(databaseNow(context)); + IssuanceCandidate candidate = + candidate(tuple(), issuedAt, issuedAt.plusSeconds(180), issuedAt.plusSeconds(210)); context.inTransaction(() -> context.repository.createOrReadExact(candidate)); RedemptionRequest request = @@ -164,6 +177,198 @@ void realPostgresRejectsRedemptionTimestampEarlierThanIssuance() { assertThat(persisted.redeemedAt()).isNull(); } + @Test + void realPostgresEnforcesCanonicalPositiveLongRangeForBundleSourceFence() { + Context context = context(); + Instant issuedAt = canonicalMillisecond(databaseNow(context)); + List checkConstraintNames = + context + .adminDsl + .fetch( + "SELECT conname FROM pg_constraint " + + "WHERE conrelid = ?::regclass AND contype = 'c'", + context.schema + ".account_start_session_operator_authorizations") + .getValues("conname", String.class); + assertThat(checkConstraintNames) + .contains("account_ss_operator_bundle_source_fence_canonical_check") + .doesNotContain("account_start_session_operator_authorizations_check"); + + String distinctFenceRequestId = REQUEST_ID + "-source-fence-distinct"; + IssuanceCandidate distinctFences = + candidateWithReference( + tuple(distinctFenceRequestId, "independent Account source and owner fences"), + bundleReference(7L), + issuedAt); + assertThat(distinctFences.issuanceFence()).isEqualTo(31L); + assertThat(distinctFences.bundleReference().sourceFence()).isEqualTo("7"); + assertThat( + context + .inTransaction(() -> context.repository.createOrReadExact(distinctFences)) + .created()) + .isTrue(); + + String maxFenceRequestId = REQUEST_ID + "-source-fence-max"; + IssuanceCandidate maxFence = + candidateWithReference( + tuple(maxFenceRequestId, "maximum Account source fence"), + bundleReference(Long.MAX_VALUE), + issuedAt); + var maxFenceCreated = + context.inTransaction(() -> context.repository.createOrReadExact(maxFence)); + assertThat(maxFenceCreated.created()).isTrue(); + assertThat(maxFenceCreated.issuance().bundleReference().sourceFence()) + .isEqualTo(Long.toString(Long.MAX_VALUE)); + assertThat(maxFenceCreated.issuance().issuanceFence()) + .isNotEqualTo(Long.parseLong(maxFenceCreated.issuance().bundleReference().sourceFence())); + + List invalidSourceFences = List.of("0", "07", "9223372036854775808"); + for (int index = 0; index < invalidSourceFences.size(); index++) { + String requestId = REQUEST_ID + "-source-fence-invalid-" + index; + String invalidSourceFence = invalidSourceFences.get(index); + IssuanceCandidate candidate = + candidateWithReference( + tuple(requestId, "invalid Account source fence"), bundleReference(7L), issuedAt); + int beforeInvalidFence = context.countRows(); + assertThatThrownBy( + () -> insertCandidateWithSourceFence(context, candidate, invalidSourceFence)) + .isInstanceOf(IntegrityConstraintViolationException.class) + .satisfies( + failure -> { + SQLException sqlFailure = findSqlException(failure); + assertThat(sqlFailure.getSQLState()).isEqualTo("23514"); + if (!(sqlFailure instanceof org.postgresql.util.PSQLException postgresFailure)) { + throw new AssertionError( + "Source-fence rejection must be a PostgreSQL exception", sqlFailure); + } + var serverError = postgresFailure.getServerErrorMessage(); + assertThat(serverError).isNotNull(); + assertThat(serverError.getConstraint()) + .isEqualTo("account_ss_operator_bundle_source_fence_canonical_check"); + }); + assertThat(context.countRows()).isEqualTo(beforeInvalidFence); + } + } + + @Test + void v1601ReplacesOnlyTheExactLegacyBundleSourceFenceGuard() { + Context context = contextAt("160"); + Map checksBeforeMigration = checkConstraintDefinitions(context); + String legacyConstraintName = "account_start_session_operator_authorizations_check"; + String canonicalConstraintName = "account_ss_operator_bundle_source_fence_canonical_check"; + + assertThat(checksBeforeMigration) + .containsKey(legacyConstraintName) + .doesNotContainKey(canonicalConstraintName); + var legacyConstraint = + Objects.requireNonNull( + context.adminDsl.fetchOne( + "SELECT pg_get_expr(c.conbin, c.conrelid) AS expression, " + + "c.convalidated, " + + "array_to_string(ARRAY(SELECT a.attname " + + "FROM unnest(c.conkey) AS key(attnum) " + + "JOIN pg_attribute a ON a.attrelid = c.conrelid " + + "AND a.attnum = key.attnum ORDER BY a.attname), ',') AS columns " + + "FROM pg_constraint c " + + "WHERE c.conrelid = ?::regclass AND c.contype = 'c' " + + "AND c.conname = ?", + context.schema + ".account_start_session_operator_authorizations", + legacyConstraintName), + "Expected the legacy source-fence check on the schema-qualified authorization table"); + assertThat(legacyConstraint.get("convalidated", Boolean.class)).isTrue(); + assertThat(legacyConstraint.get("columns", String.class)) + .isEqualTo("bundle_source_fence,issuance_fence"); + assertThat(normalizeCheckExpression(legacyConstraint.get("expression", String.class))) + .isEqualTo("bundle_source_fence~'^[1-9][0-9]{0,18}$'andbundle_source_fence=issuance_fence"); + + Flyway.configure() + .dataSource(context.dataSource) + .schemas(context.schema) + .defaultSchema(context.schema) + .placeholders(Map.of("serviceSchema", context.schema)) + .locations("classpath:db/migration") + .target(org.flywaydb.core.api.MigrationVersion.fromVersion("160.1")) + .load() + .migrate(); + + Map checksAfterMigration = checkConstraintDefinitions(context); + assertThat(checksAfterMigration) + .doesNotContainKey(legacyConstraintName) + .containsKey(canonicalConstraintName); + var canonicalConstraint = + Objects.requireNonNull( + context.adminDsl.fetchOne( + "SELECT pg_get_expr(c.conbin, c.conrelid) AS expression " + + "FROM pg_constraint c " + + "WHERE c.conrelid = ?::regclass AND c.contype = 'c' " + + "AND c.conname = ?", + context.schema + ".account_start_session_operator_authorizations", + canonicalConstraintName), + "Expected the canonical source-fence check after V160.1"); + assertThat(normalizeCheckExpression(canonicalConstraint.get("expression", String.class))) + .contains("bundle_source_fence~'^[1-9][0-9]{0,18}$'") + .contains("bundle_source_fence::numeric<="); + + Map expectedChecksAfterMigration = new HashMap<>(checksBeforeMigration); + expectedChecksAfterMigration.remove(legacyConstraintName); + expectedChecksAfterMigration.put( + canonicalConstraintName, checksAfterMigration.get(canonicalConstraintName)); + assertThat(checksAfterMigration).isEqualTo(expectedChecksAfterMigration); + } + + private Map checkConstraintDefinitions(Context context) { + return context + .adminDsl + .fetch( + "SELECT c.conname, pg_get_constraintdef(c.oid) AS definition " + + "FROM pg_constraint c " + + "WHERE c.conrelid = ?::regclass AND c.contype = 'c'", + context.schema + ".account_start_session_operator_authorizations") + .intoMap( + record -> record.get("conname", String.class), + record -> record.get("definition", String.class)); + } + + private String normalizeCheckExpression(String expression) { + return expression.toLowerCase().replaceAll("[\\s()\\\"]", "").replace("::text", ""); + } + + @Test + void repositoryRejectsClosedBundleWhenItsSourceVersionDiffersFromReference() { + Context context = context(); + IssuanceCandidate candidate = + candidateWithReference( + tuple(), bundleReference(7L), canonicalMillisecond(databaseNow(context))); + BundleReference mismatchedReference = + new BundleReference( + candidate.bundleReference().bundleVersion(), + "13", + candidate.bundleReference().sourceFence(), + candidate.bundleReference().linearization()); + IssuanceCandidate mismatched = + new IssuanceCandidate( + candidate.controlPlaneRequestId(), + candidate.preAuthorizationTuple(), + candidate.mutationDigest(), + candidate.issuanceWorkloadUri(), + candidate.reservationOwnerId(), + candidate.reservationClaimFence(), + candidate.issuanceOperationId(), + candidate.issuanceFence(), + mismatchedReference, + candidate.authorityEvidenceBundle(), + candidate.authorizationReferenceFingerprint(), + candidate.encryptedResponseEnvelope(), + candidate.issuedAt(), + candidate.referenceExpiresAt(), + candidate.responseEnvelopeExpiresAt()); + + assertThatThrownBy( + () -> context.inTransaction(() -> context.repository.createOrReadExact(mismatched))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Account bundle reference differs"); + assertThat(context.countRows()).isZero(); + } + @Test void realPostgresAcceptsCanonicalNfcRequestIdAt128Utf8BytesAndRejectsOversizeBeforeInsert() { Context context = context(); @@ -190,9 +395,24 @@ void realPostgresAcceptsCanonicalNfcRequestIdAt128Utf8BytesAndRejectsOversizeBef "\"requestId\":\"" + boundedRequestId + "\"", "\"requestId\":\"" + oversizedRequestId + "\""); assertThat(malformedTupleJson).contains(oversizedRequestId); + IssuanceCandidate boundaryCandidate = candidate(context, boundaryTuple, boundedRequestId); IssuanceCandidate oversized = - candidate( - context, boundedRequestId, bytes(malformedTupleJson), boundaryTuple.mutationDigest()); + new IssuanceCandidate( + boundedRequestId, + bytes(malformedTupleJson), + boundaryTuple.mutationDigest(), + boundaryCandidate.issuanceWorkloadUri(), + boundaryCandidate.reservationOwnerId(), + boundaryCandidate.reservationClaimFence(), + boundaryCandidate.issuanceOperationId(), + boundaryCandidate.issuanceFence(), + boundaryCandidate.bundleReference(), + boundaryCandidate.authorityEvidenceBundle(), + boundaryCandidate.authorizationReferenceFingerprint(), + boundaryCandidate.encryptedResponseEnvelope(), + boundaryCandidate.issuedAt(), + boundaryCandidate.referenceExpiresAt(), + boundaryCandidate.responseEnvelopeExpiresAt()); int before = context.countRows(); assertThatThrownBy( () -> context.inTransaction(() -> context.repository.createOrReadExact(oversized))) @@ -494,32 +714,53 @@ void expiredReferenceCannotBeConsumedAndSqlGuardsRetainEvidence() { .isInstanceOf( AccountStartSessionOperatorAuthorizationRepository.ReferenceExpiredException.class); - assertThatThrownBy( - () -> - context.inTransactionWithoutResult( - () -> - context.transactionDsl.execute( - "UPDATE account_start_session_operator_authorizations " - + "SET authority_evidence_bundle = ? WHERE control_plane_request_id = ?", - bytes("rewritten"), - REQUEST_ID))) - .isInstanceOf(IntegrityConstraintViolationException.class); - assertThatThrownBy( - () -> - context.inTransactionWithoutResult( - () -> - context.transactionDsl.execute( - "DELETE FROM account_start_session_operator_authorizations " - + "WHERE control_plane_request_id = ?", - REQUEST_ID))) - .isInstanceOf(IntegrityConstraintViolationException.class); + assertImmutableGuardRejected( + () -> + context.inTransactionWithoutResult( + () -> + context.transactionDsl.execute( + "UPDATE account_start_session_operator_authorizations " + + "SET authority_evidence_bundle = ? WHERE control_plane_request_id = ?", + bytes("rewritten"), + REQUEST_ID)), + "StartSession authorization evidence is immutable except one exact redemption " + + "or expired envelope erasure"); + assertImmutableGuardRejected( + () -> + context.inTransactionWithoutResult( + () -> + context.transactionDsl.execute( + "DELETE FROM account_start_session_operator_authorizations " + + "WHERE control_plane_request_id = ?", + REQUEST_ID)), + "StartSession operator authorization evidence cannot be deleted"); assertThatThrownBy( () -> context.inTransactionWithoutResult( () -> context.transactionDsl.execute( "TRUNCATE account_start_session_operator_authorizations"))) - .isInstanceOf(IntegrityConstraintViolationException.class); + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .satisfies( + failure -> { + SQLException sqlFailure = findSqlException(failure); + assertThat(sqlFailure.getSQLState()).isEqualTo("0A000"); + if (!(sqlFailure instanceof org.postgresql.util.PSQLException postgresFailure)) { + throw new AssertionError( + "Foreign-key truncate rejection must be a PostgreSQL exception", sqlFailure); + } + var serverError = postgresFailure.getServerErrorMessage(); + assertThat(serverError).isNotNull(); + assertThat(serverError.getMessage()) + .isEqualTo("cannot truncate a table referenced in a foreign key constraint"); + }); + assertImmutableGuardRejected( + () -> + context.inTransactionWithoutResult( + () -> + context.transactionDsl.execute( + "TRUNCATE account_start_session_operator_authorizations CASCADE")), + "StartSession operator authorization evidence cannot be truncated"); var retained = context.inTransaction( @@ -677,7 +918,7 @@ void responseEnvelopeErasureUsesDatabaseWallClockAndPreservesRedeemedCompactEvid @Test void v126RetainedEnvelopeSurvivesAdditiveErasureMigration() { Context context = contextAt("126"); - IssuanceCandidate candidate = candidate(context, tuple()); + IssuanceCandidate candidate = legacyCandidate(context, tuple()); insertV126Row(context, candidate); Flyway.configure() @@ -703,7 +944,7 @@ void v126RetainedEnvelopeSurvivesAdditiveErasureMigration() { @Test void v1262RetainedMaximumLegacyEnvelopeSurvivesForwardSizeMigration() { Context context = contextAt("126.2"); - IssuanceCandidate base = candidate(context, tuple()); + IssuanceCandidate base = legacyCandidate(context, tuple()); byte[] retainedLegacyEnvelope = new byte[64 * 1024]; Arrays.fill(retainedLegacyEnvelope, (byte) 0x2d); IssuanceCandidate legacy = withEnvelope(base, retainedLegacyEnvelope); @@ -801,7 +1042,7 @@ private Context context() { } private Context contextAt(String targetVersion) { - String schema = "account_start_session_auth_" + UUID.randomUUID().toString().replace("-", ""); + String schema = "account_start_session_" + UUID.randomUUID().toString().replace("-", ""); schemas.add(schema); DriverManagerDataSource dataSource = POSTGRES.dataSource(schema); var migration = @@ -862,12 +1103,49 @@ private static void insertV126Row(Context context, IssuanceCandidate candidate) OffsetDateTime.ofInstant(candidate.responseEnvelopeExpiresAt(), ZoneOffset.UTC)); } + private static void insertCandidateWithSourceFence( + Context context, IssuanceCandidate candidate, String sourceFence) { + context.adminDsl.execute( + "INSERT INTO account_start_session_operator_authorizations " + + "(control_plane_request_id, pre_authorization_tuple, mutation_digest, " + + "issuance_workload_uri, reservation_owner_id, reservation_claim_fence, " + + "issuance_operation_id, issuance_fence, bundle_version, bundle_source_version, " + + "bundle_source_fence, bundle_linearization, authority_evidence_bundle, " + + "authorization_reference_fingerprint, encrypted_response_envelope, issued_at, " + + "reference_expires_at, response_envelope_expires_at, status) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + + "CAST(? AS TIMESTAMPTZ), CAST(? AS TIMESTAMPTZ), " + + "CAST(? AS TIMESTAMPTZ), 'ISSUED')", + candidate.controlPlaneRequestId(), + candidate.preAuthorizationTuple(), + candidate.mutationDigest(), + candidate.issuanceWorkloadUri(), + candidate.reservationOwnerId(), + candidate.reservationClaimFence(), + candidate.issuanceOperationId(), + candidate.issuanceFence(), + candidate.bundleReference().bundleVersion(), + candidate.bundleReference().sourceVersion(), + sourceFence, + candidate.bundleReference().linearization(), + candidate.authorityEvidenceBundle(), + candidate.authorizationReferenceFingerprint(), + candidate.encryptedResponseEnvelope(), + OffsetDateTime.ofInstant(candidate.issuedAt(), ZoneOffset.UTC), + OffsetDateTime.ofInstant(candidate.referenceExpiresAt(), ZoneOffset.UTC), + OffsetDateTime.ofInstant(candidate.responseEnvelopeExpiresAt(), ZoneOffset.UTC)); + } + private static Instant databaseNow(Context context) { return Objects.requireNonNull( (OffsetDateTime) context.adminDsl.fetchValue("SELECT clock_timestamp()")) .toInstant(); } + private static Instant canonicalMillisecond(Instant value) { + return Instant.ofEpochMilli(value.toEpochMilli()); + } + private static Instant canonicalDatabaseNow(Context context) { return databaseNow(context).truncatedTo(ChronoUnit.MILLIS); } @@ -914,6 +1192,14 @@ private static Object raceRedemption( } private static IssuanceCandidate withDifferentOutputs(IssuanceCandidate original) { + UUID operationId = UUID.randomUUID(); + BundleReference reference = + bundleReference(Long.parseLong(original.bundleReference().sourceFence()) + 1L); + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + new String(original.preAuthorizationTuple(), StandardCharsets.UTF_8)); + Instant expiresAt = original.referenceExpiresAt().plusSeconds(1); + long issuanceFence = original.issuanceFence() + 1L; return new IssuanceCandidate( original.controlPlaneRequestId(), original.preAuthorizationTuple(), @@ -921,14 +1207,14 @@ private static IssuanceCandidate withDifferentOutputs(IssuanceCandidate original original.issuanceWorkloadUri(), original.reservationOwnerId(), original.reservationClaimFence(), - UUID.randomUUID(), - original.issuanceFence() + 1L, - bundleReference(original.issuanceFence() + 1L), - bytes("different bundle"), + operationId, + issuanceFence, + reference, + authorityBundle(tuple, operationId, issuanceFence, expiresAt, reference), "arfp/v1/key-2/" + "b".repeat(64), bytes("different encrypted response"), original.issuedAt().plusSeconds(1), - original.referenceExpiresAt().plusSeconds(1), + expiresAt, original.responseEnvelopeExpiresAt().plusSeconds(1)); } @@ -997,9 +1283,36 @@ private static IssuanceCandidate candidate( RESERVATION_OWNER_ID, 3L, ISSUANCE_OPERATION_ID, - 7L, + 31L, bundleReference(7L), - bytes("authority-bundle-v1"), + authorityBundle( + tupleFromBytes(tupleBytes), + ISSUANCE_OPERATION_ID, + 31L, + issuedAt.plusSeconds(180), + bundleReference(7L)), + "arfp/v1/key-1/" + "a".repeat(64), + bytes("encrypted-original-response-envelope"), + issuedAt, + issuedAt.plusSeconds(180), + issuedAt.plusSeconds(210)); + } + + private static IssuanceCandidate legacyCandidate( + Context context, StartSessionPreAuthorizationReservationTuple tuple) { + Instant issuedAt = canonicalDatabaseNow(context).minusSeconds(2); + BundleReference reference = bundleReference(7L); + return new IssuanceCandidate( + tuple.controlPlaneRequestId(), + canonicalBytes(tuple), + tuple.mutationDigest(), + ISSUER_URI, + RESERVATION_OWNER_ID, + 3L, + ISSUANCE_OPERATION_ID, + 7L, + reference, + authorityBundle(tuple, ISSUANCE_OPERATION_ID, 7L, issuedAt.plusSeconds(180), reference), "arfp/v1/key-1/" + "a".repeat(64), bytes("encrypted-original-response-envelope"), issuedAt, @@ -1066,9 +1379,9 @@ private static IssuanceCandidate candidate( RESERVATION_OWNER_ID, 3L, ISSUANCE_OPERATION_ID, - 7L, + 31L, bundleReference(7L), - bytes("authority-bundle-v1"), + authorityBundle(tuple, ISSUANCE_OPERATION_ID, 31L, referenceExpiresAt, bundleReference(7L)), "arfp/v1/key-1/" + "a".repeat(64), bytes("encrypted-original-response-envelope"), issuedAt, @@ -1076,8 +1389,34 @@ private static IssuanceCandidate candidate( responseEnvelopeExpiresAt); } + private static IssuanceCandidate candidateWithReference( + StartSessionPreAuthorizationReservationTuple tuple, + BundleReference reference, + Instant issuedAt) { + UUID operationId = UUID.randomUUID(); + String keyId = UUID.randomUUID().toString().replace("-", ""); + Instant referenceExpiresAt = issuedAt.plusSeconds(180); + return new IssuanceCandidate( + tuple.controlPlaneRequestId(), + canonicalBytes(tuple), + tuple.mutationDigest(), + ISSUER_URI, + RESERVATION_OWNER_ID, + 3L, + operationId, + 31L, + reference, + authorityBundle(tuple, operationId, 31L, referenceExpiresAt, reference), + "arfp/v1/" + keyId + "/" + "a".repeat(64), + bytes("encrypted-original-response-envelope"), + issuedAt, + referenceExpiresAt, + issuedAt.plusSeconds(210)); + } + private static IssuanceCandidate expiredCandidate( StartSessionPreAuthorizationReservationTuple tuple, Instant databaseNow) { + UUID operationId = UUID.randomUUID(); String uniqueFingerprint = "arfp/v1/key-1/" + UUID.randomUUID().toString().replace("-", "") @@ -1089,10 +1428,10 @@ private static IssuanceCandidate expiredCandidate( ISSUER_URI, RESERVATION_OWNER_ID, 3L, - UUID.randomUUID(), - 8L, - bundleReference(8L), - bytes("expired-authority-bundle-v1"), + operationId, + 31L, + bundleReference(7L), + authorityBundle(tuple, operationId, 31L, databaseNow.minusSeconds(60), bundleReference(7L)), uniqueFingerprint, bytes("expired-original-response-envelope"), databaseNow.minusSeconds(240), @@ -1156,6 +1495,114 @@ private static BundleReference bundleReference(long sourceFence) { "authorityEvidenceBundle/v1", "12", Long.toString(sourceFence), "123456789"); } + private static StartSessionPreAuthorizationReservationTuple tupleFromBytes(byte[] tupleBytes) { + return StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + new String(tupleBytes, StandardCharsets.UTF_8)); + } + + private static byte[] authorityBundle( + StartSessionPreAuthorizationReservationTuple tuple, + UUID operationId, + long issuanceFence, + Instant expiresAt, + BundleReference reference) { + String tenantId = tuple.action().scope().tenantId().toString(); + String actorId = tuple.actor().accountId().toString(); + Map authorityTuple = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 1L, + "tenantAuthorityGeneration", Map.of(tenantId, 1L), + "membershipAuthorityGeneration", Map.of(tenantId, 1L), + "privateRealmGrantVersions", List.of()); + Map bundle = + Map.of( + "bundleVersion", StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", + Map.of( + "tenantId", + tenantId, + "targetNamespace", + tuple.action().scope().targetNamespace()), + "actionFamily", + tuple.actionFamily(), + "applicableAccountId", + actorId, + "applicableTenantId", + tenantId), + "accountProjectionEvidence", + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", + reference.sourceVersion(), + "projectionStatus", + "CURRENT", + "evaluatedAt", + Instant.parse("2026-10-09T00:00:00Z").toString(), + "expiresAt", + expiresAt.toString()), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", operationId.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", "human_operator", + "authorityTuple", authorityTuple, + "membershipVersion", Map.of(tenantId, 2L), + "issuanceFence", Long.toString(issuanceFence), + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + actorId, + "controlUiTokenJti", + UUID.fromString("2e19f788-10d2-4f33-aed6-9a46db136dcc").toString(), + "role", + "tenantAdmin", + "accountGeneration", + "1", + "tenantGeneration", + "1")); + return AccountControlUiAuthority.canonical(bundle); + } + + private static void assertImmutableGuardRejected( + ThrowingCallable action, String expectedDiagnostic) { + assertThatThrownBy(action) + .isInstanceOf(IntegrityConstraintViolationException.class) + .satisfies( + failure -> { + SQLException sqlFailure = findSqlException(failure); + assertThat(sqlFailure.getSQLState()).isEqualTo("23514"); + if (!(sqlFailure instanceof org.postgresql.util.PSQLException postgresFailure)) { + throw new AssertionError( + "Immutable guard rejection must be a PostgreSQL exception", sqlFailure); + } + var serverError = postgresFailure.getServerErrorMessage(); + assertThat(serverError).isNotNull(); + assertThat(serverError.getMessage()).isEqualTo(expectedDiagnostic); + }); + } + + private static SQLException findSqlException(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sqlFailure) return sqlFailure; + } + throw new AssertionError("Immutable guard rejection did not retain its SQLException", failure); + } + private static final UUID TENANT_ID = UUID.fromString("6d1e5ce5-6127-4d35-88b8-7a6f40692038"); private static final UUID TARGET_ACCOUNT_ID = UUID.fromString("1df91ae6-5125-4e47-9f1d-2e45eab8a4a0"); @@ -1203,11 +1650,12 @@ void inTransactionWithoutResult(Runnable action) { } int countRows() { - return Objects.requireNonNull( + var row = + Objects.requireNonNull( adminDsl.fetchOne( "SELECT count(*) FROM account_start_session_operator_authorizations"), - "Missing Account StartSession authorization row-count readback") - .get(0, Integer.class); + "COUNT query must return a row"); + return Objects.requireNonNull(row.get(0, Integer.class), "COUNT query must return a value"); } } } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java new file mode 100644 index 0000000000..a1eae6d397 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java @@ -0,0 +1,638 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository.StoredEvidence; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle.BundleReference; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * PostgreSQL proof for exact retry, lock-wait expiry, pending-parent, and immutable-row behavior. + * + *

The fixture deliberately inserts a synthetic Account participation with triggers disabled and + * supplies a synthetic Game Session observation. It proves database/repository binding only; it + * does not claim authenticated cross-owner source evidence or a genuine Game Session producer. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest { + private static final UUID OWNER_MUTATION_ID = + UUID.fromString("f7811486-2bd4-41a0-9bf7-a351ce3a0c8f"); + private static final UUID OWNER_ATTEMPT_ID = + UUID.fromString("c0df9691-cba5-4274-a49d-0bc7b2158ef7"); + private static final long OWNER_FENCE = 47L; + private static final String NAMESPACE = "world-runtime"; + + @Container + static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void exactRetryPreservesFirstBytesAndExpiryAfterLockWaitCannotCreateOrRefreshEvidence() + throws Exception { + String schema = "ss_world_attempt_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(source)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + AccountStartSessionWorldOriginalAttemptEvidenceRepository repository = + new AccountStartSessionWorldOriginalAttemptEvidenceRepository(dsl); + Fixture fixture = fixture(); + StoredParticipation parent = + transaction.execute( + status -> insertSyntheticParent(dsl, fixture, UUID.randomUUID(), false)); + assertThat(parent).isNotNull(); + + Instant retryExpiry = databaseNow(dsl).plusMillis(6_000L); + Result firstObservation = observation(fixture, UUID.randomUUID(), retryExpiry); + StoredEvidence first = + transaction.execute(status -> repository.retainCurrentExact(parent, firstObservation)); + assertThat(first).isNotNull(); + assertThat(first.gameSessionOwnerMutationId()).isEqualTo(OWNER_MUTATION_ID); + + Request freshCorrelation = request(fixture, UUID.randomUUID()); + Result exactRetryObservation = + new Result(freshCorrelation, first.originalLeaseExpiresAt(), fixture.accountProjection()); + StoredEvidence exactRetry = + transaction.execute(status -> repository.retainCurrentExact(parent, exactRetryObservation)); + assertThat(exactRetry.originalResponseBytes()).containsExactly(first.originalResponseBytes()); + assertThat(exactRetry.originalResponseDigest()).isEqualTo(first.originalResponseDigest()); + assertThat(exactRetry.result().request().readRequestId()) + .isEqualTo(first.result().request().readRequestId()); + StoredEvidence current = + transaction.execute( + status -> + repository + .findCurrentExact(parent, request(fixture, UUID.randomUUID())) + .orElseThrow()); + assertThat(current.originalResponseBytes()).containsExactly(first.originalResponseBytes()); + assertThat(current.originalResponseDigest()).isEqualTo(first.originalResponseDigest()); + + Result changedMutation = + new Result( + new Request( + UUID.randomUUID(), + NAMESPACE, + fixture.tuple().canonicalBytes(), + OWNER_ATTEMPT_ID, + UUID.fromString("1f2d6f4e-1202-4bdb-bcd4-f3c14e4cc764"), + OWNER_FENCE), + retryExpiry, + fixture.accountProjection()); + assertThatThrownBy( + () -> + transaction.execute( + status -> repository.retainCurrentExact(parent, changedMutation))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts"); + + assertAppendOnly(dsl, parent.participationId()); + assertLeaseExpiresWhileParentLocked( + dsl, transaction, repository, parent, fixture, exactRetryObservation); + + assertThatThrownBy( + () -> + transaction.execute( + status -> repository.findCurrentExact(parent, freshCorrelation).orElseThrow())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("unavailable"); + StoredEvidence historical = + transaction.execute( + status -> + repository + .findHistoricalExact(parent, request(fixture, UUID.randomUUID())) + .orElseThrow()); + assertThat(historical.originalLeaseExpiresAt()).isEqualTo(retryExpiry); + assertThat(historical.originalResponseBytes()).containsExactly(first.originalResponseBytes()); + } + + @Test + void freshInsertLeaseIsRecheckedAfterWaitingForTheExactParentLock() throws Exception { + String schema = "ss_world_attempt_wait_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(source)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + AccountStartSessionWorldOriginalAttemptEvidenceRepository repository = + new AccountStartSessionWorldOriginalAttemptEvidenceRepository(dsl); + Fixture fixture = fixture(); + StoredParticipation parent = + transaction.execute( + status -> insertSyntheticParent(dsl, fixture, UUID.randomUUID(), false)); + assertThat(parent).isNotNull(); + + Instant expiry = databaseNow(dsl).plusMillis(3_000L); + Result observation = observation(fixture, UUID.randomUUID(), expiry); + assertLeaseExpiresWhileParentLocked(dsl, transaction, repository, parent, fixture, observation); + Record evidenceCount = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM account_start_session_world_original_attempt_evidence " + + "WHERE participation_id = ?", + parent.participationId()), + "evidence count query returned no row"); + assertThat(evidenceCount.get(0, Long.class)).isZero(); + + Instant expiredAt = databaseNow(dsl).minusSeconds(1L); + Result expiredObservation = observation(fixture, UUID.randomUUID(), expiredAt); + byte[] expiredResponse = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(expiredObservation) + .toByteArray(); + assertGuardRejected( + () -> + dsl.execute( + "INSERT INTO account_start_session_world_original_attempt_evidence " + + "(participation_id, target_namespace, game_session_owner_attempt_id, " + + "game_session_owner_mutation_id, game_session_owner_fence, " + + "original_lease_expires_at, original_response_bytes, original_response_digest) " + + "VALUES (?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?)", + parent.participationId(), + NAMESPACE, + fixture.ownerAttemptId(), + OWNER_MUTATION_ID, + OWNER_FENCE, + OffsetDateTime.ofInstant(expiredAt, ZoneOffset.UTC), + expiredResponse, + "sha256:" + sha256Hex(expiredResponse)), + "Original StartSession attempt observation lease is expired"); + Record expiredEvidenceCount = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM account_start_session_world_original_attempt_evidence " + + "WHERE participation_id = ?", + parent.participationId()), + "evidence count query returned no row"); + assertThat(expiredEvidenceCount.get(0, Long.class)).isZero(); + } + + @Test + void settledParticipationCannotReceiveNewObservation() { + String schema = "ss_world_attempt_settled_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(source)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + AccountStartSessionWorldOriginalAttemptEvidenceRepository repository = + new AccountStartSessionWorldOriginalAttemptEvidenceRepository(dsl); + Fixture fixture = fixture(); + UUID participationId = UUID.randomUUID(); + StoredParticipation parent = + transaction.execute( + status -> { + StoredParticipation inserted = + insertSyntheticParent(dsl, fixture, participationId, true); + return inserted; + }); + + assertThatThrownBy( + () -> + transaction.execute( + status -> + repository.retainCurrentExact( + parent, + observation( + fixture, UUID.randomUUID(), databaseNow(dsl).plusSeconds(30))))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("unavailable"); + } + + private static void assertAppendOnly(DSLContext dsl, UUID participationId) { + String table = "account_start_session_world_original_attempt_evidence"; + assertGuardRejected( + () -> + dsl.execute( + "UPDATE " + + table + + " SET original_response_digest = original_response_digest " + + "WHERE participation_id = ?", + participationId), + "Original StartSession attempt observation is append-only"); + assertGuardRejected( + () -> dsl.execute("DELETE FROM " + table + " WHERE participation_id = ?", participationId), + "Original StartSession attempt observation is append-only"); + assertGuardRejected( + () -> dsl.execute("TRUNCATE " + table + " CASCADE"), + "Original StartSession attempt observation is append-only"); + Record evidenceCount = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM " + table + " WHERE participation_id = ?", participationId), + "append-only evidence count query returned no row"); + assertThat(evidenceCount.get(0, Long.class)).isEqualTo(1L); + } + + private static void assertGuardRejected( + org.assertj.core.api.ThrowableAssert.ThrowingCallable action, String expectedDiagnostic) { + assertThatThrownBy(action) + .satisfies( + failure -> { + SQLException sqlFailure = findSqlException(failure); + assertThat(sqlFailure.getSQLState()).isEqualTo("23514"); + if (!(sqlFailure instanceof org.postgresql.util.PSQLException postgresFailure)) { + throw new AssertionError( + "Attempt evidence guard rejection must be a PostgreSQL exception", sqlFailure); + } + var serverError = postgresFailure.getServerErrorMessage(); + assertThat(serverError).isNotNull(); + assertThat(serverError.getMessage()).isEqualTo(expectedDiagnostic); + }); + } + + private static SQLException findSqlException(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sqlException) return sqlException; + } + throw new AssertionError("Guard rejection must retain its SQL exception", failure); + } + + private static void assertLeaseExpiresWhileParentLocked( + DSLContext dsl, + TransactionTemplate transaction, + AccountStartSessionWorldOriginalAttemptEvidenceRepository repository, + StoredParticipation parent, + Fixture fixture, + Result observation) + throws Exception { + ExecutorService executor = Executors.newFixedThreadPool(2); + CountDownLatch parentLocked = new CountDownLatch(1); + CountDownLatch releaseParent = new CountDownLatch(1); + try { + Future holder = + executor.submit( + () -> + transaction.execute( + status -> { + dsl.fetchOne( + "SELECT participation_id FROM account_start_session_world_participations " + + "WHERE participation_id = ? FOR UPDATE", + parent.participationId()); + parentLocked.countDown(); + await(releaseParent); + return null; + })); + assertTrue(parentLocked.await(5, TimeUnit.SECONDS), "parent lock holder did not start"); + CountDownLatch writerStarted = new CountDownLatch(1); + Future writer = + executor.submit( + () -> { + writerStarted.countDown(); + return transaction.execute( + status -> repository.retainCurrentExact(parent, observation)); + }); + assertTrue(writerStarted.await(5, TimeUnit.SECONDS), "evidence writer did not start"); + awaitBlockedOnParentLock(dsl); + while (observation.originalLeaseExpiresAt().isAfter(databaseNow(dsl))) { + Thread.sleep(25L); + } + releaseParent.countDown(); + holder.get(5, TimeUnit.SECONDS); + assertThatThrownBy(() -> writer.get(5, TimeUnit.SECONDS)) + .isInstanceOf(ExecutionException.class) + .hasCauseInstanceOf(IllegalStateException.class) + .hasRootCauseMessage("Exact original StartSession attempt evidence unavailable"); + } finally { + releaseParent.countDown(); + executor.shutdownNow(); + } + } + + private static void awaitBlockedOnParentLock(DSLContext dsl) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (System.nanoTime() < deadline) { + Record row = + dsl.fetchOne( + "SELECT count(*) FROM pg_stat_activity " + + "WHERE cardinality(pg_blocking_pids(pid)) > 0 " + + "AND query ILIKE '%account_start_session_world_participations%' "); + if (row != null && row.get(0, Long.class) > 0L) return; + Thread.sleep(20L); + } + throw new AssertionError("evidence writer did not block behind the Account participation lock"); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("test lock release was not signaled"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("test lock holder was interrupted", interrupted); + } + } + + private static StoredParticipation insertSyntheticParent( + DSLContext dsl, Fixture fixture, UUID participationId, boolean settled) { + dsl.execute("SET LOCAL session_replication_role = replica"); + dsl.execute( + "INSERT INTO account_start_session_world_participations " + + "(participation_id, participation_fence, control_plane_request_id, " + + "original_post_authorization_tuple, target_namespace, canonical_tenant_id, " + + "canonical_game_instance_id, game_session_owner_attempt_id, game_session_owner_fence, " + + "preparation_input_json, preparation_input_digest, created_at) " + + "OVERRIDING SYSTEM VALUE VALUES (?, 41, ?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ)) ", + participationId, + fixture.tuple().controlPlaneRequestId(), + fixture.tuple().canonicalBytes(), + NAMESPACE, + fixture.tenantId(), + fixture.gameInstanceId(), + OWNER_ATTEMPT_ID, + OWNER_FENCE, + fixture.preparationJson(), + fixture.preparationDigest(), + OffsetDateTime.ofInstant(Instant.parse("2026-10-09T00:00:00Z"), ZoneOffset.UTC)); + if (settled) { + byte[] terminal = "synthetic settled parent".getBytes(StandardCharsets.UTF_8); + dsl.execute( + "INSERT INTO account_start_session_world_participation_settlements " + + "(participation_id, outcome, world_execution_fence, terminal_bytes, terminal_digest) " + + "VALUES (?, 'ABORTED', 1, ?, ?)", + participationId, + terminal, + "sha256:" + sha256Hex(terminal)); + } + dsl.execute("SET LOCAL session_replication_role = origin"); + Record row = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM account_start_session_world_participations WHERE participation_id = ?", + participationId), + "synthetic Account participation insert produced no row"); + return new StoredParticipation( + UUID.fromString(row.get("participation_id", UUID.class).toString()), + row.get("participation_fence", Long.class), + row.get("control_plane_request_id", String.class), + row.get("original_post_authorization_tuple", byte[].class), + row.get("target_namespace", String.class), + row.get("canonical_tenant_id", UUID.class), + row.get("canonical_game_instance_id", UUID.class), + row.get("game_session_owner_attempt_id", UUID.class), + row.get("game_session_owner_fence", Long.class), + row.get("preparation_input_json", String.class), + row.get("preparation_input_digest", String.class), + row.get("producer_xid", Long.class), + row.get("created_at", OffsetDateTime.class), + List.of()); + } + + private static Fixture fixture() { + UUID actorId = UUID.fromString("d888ddc4-4a62-4b25-9bab-c4f94860c2ca"); + UUID tenantId = UUID.fromString("6d1e5ce5-6127-4d35-88b8-7a6f40692038"); + UUID targetAccountId = UUID.fromString("1df91ae6-5125-4e47-9f1d-2e45eab8a4a0"); + UUID reservationOwnerId = UUID.fromString("ca1b63bf-f09f-4a55-96bf-a1fd2e22349e"); + String requestId = "start-session/original-attempt/" + UUID.randomUUID(); + StartSessionPreAuthorizationReservationTuple preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + requestId, + actorId, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(tenantId, NAMESPACE), + new StartSessionOperatorAction.Target(17L, targetAccountId), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "Synthetic Account participation integration proof")); + byte[] bundle = authorityBundle(preTuple, actorId, tenantId, requestId); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service", + "arfp/v1/key-1/" + "a".repeat(64), + reservationOwnerId, + 7L, + bundle, + new BundleReference("authorityEvidenceBundle/v1", "11", "13", "17")); + String preparationJson = "{\"identity\":{\"worldSlug\":\"synthetic-arena\"}}"; + return new Fixture( + tuple, + tenantId, + UUID.fromString("51c67424-324e-486d-b3ad-45b6e85c1a0d"), + OWNER_ATTEMPT_ID, + preparationJson, + "sha256:" + sha256Hex(preparationJson.getBytes(StandardCharsets.UTF_8)), + accountProjection(tuple)); + } + + private static byte[] authorityBundle( + StartSessionPreAuthorizationReservationTuple tuple, + UUID actorId, + UUID tenantId, + String requestId) { + String tenant = tenantId.toString(); + String actor = actorId.toString(); + Map authorityTuple = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 1L, + "tenantAuthorityGeneration", Map.of(tenant, 1L), + "membershipAuthorityGeneration", Map.of(tenant, 1L), + "privateRealmGrantVersions", List.of()); + return AccountControlUiAuthority.canonical( + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", + Map.of("tenantId", tenant, "targetNamespace", NAMESPACE), + "actionFamily", + "StartSession", + "applicableAccountId", + actor, + "applicableTenantId", + tenant), + "accountProjectionEvidence", + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "c".repeat(64), + "sourceEvidenceVersion", + "11", + "projectionStatus", + "CURRENT", + "evaluatedAt", + "2026-10-09T00:00:00Z", + "expiresAt", + "2026-10-09T00:03:00Z"), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", + "44444444-4444-4444-8444-444444444444", + "controlPlaneRequestId", + requestId, + "actionFamilyRequestIdentity", + Map.of("requestIdentityKind", "controlPlaneRequestId", "requestId", requestId), + "mutationDigest", + tuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + authorityTuple, + "membershipVersion", + Map.of(tenant, 2L), + "issuanceFence", + "9", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + actor, + "controlUiTokenJti", + "55555555-5555-4555-8555-555555555555", + "role", + "tenantAdmin", + "accountGeneration", + "1", + "tenantGeneration", + "1"))); + } + + private static Result observation(Fixture fixture, UUID readId, Instant expiry) { + return new Result(request(fixture, readId), expiry, fixture.accountProjection()); + } + + private static Request request(Fixture fixture, UUID readId) { + return new Request( + readId, + NAMESPACE, + fixture.tuple().canonicalBytes(), + fixture.ownerAttemptId(), + OWNER_MUTATION_ID, + OWNER_FENCE); + } + + private static byte[] accountProjection(StartSessionPostAuthorizationExecutionTuple tuple) { + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + return AccountControlUiAuthority.canonical( + Map.of( + "projectionSchemaId", + "accountStartSessionRedemptionProjection", + "projectionSchemaVersion", + "1", + "authorizationReferenceFingerprint", + tuple.authorizationReferenceFingerprint(), + "authorityEvidenceBundle", + bundle.jsonValue(), + "issuanceOperationId", + bundle.issuanceOperationId().toString(), + "issuanceFence", + 9L)); + } + + private static Instant databaseNow(DSLContext dsl) { + Record row = + Objects.requireNonNull( + dsl.fetchOne("SELECT clock_timestamp()"), "database clock query returned no row"); + return row.get(0, OffsetDateTime.class).toInstant(); + } + + private static String sha256Hex(byte[] bytes) { + try { + return java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new AssertionError(impossible); + } + } + + private record Fixture( + StartSessionPostAuthorizationExecutionTuple tuple, + UUID tenantId, + UUID gameInstanceId, + UUID ownerAttemptId, + String preparationJson, + String preparationDigest, + byte[] accountProjection) { + private Fixture { + accountProjection = accountProjection.clone(); + } + + @Override + public byte[] accountProjection() { + return accountProjection.clone(); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java new file mode 100644 index 0000000000..d8ed35617a --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java @@ -0,0 +1,601 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.SQLException; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiOriginalOrderFixture; +import net.firedevops.firemud.accountservice.service.session.AccountOriginalStartSessionAuthorizationProofFixture; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationAcquisitionService.AcquisitionRequest; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationHistoricalReadService; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationHistoricalReadEvidence; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationHistoricalReadRequest; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +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; + +/** + * PostgreSQL proof for Account World participation guards, storage, and original-tuple recovery. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountStartSessionWorldParticipationPostgresIntegrationTest { + private static final String NAMESPACE = "control-ui-owner-proof"; + private static final String WORLD_PEER_URI = + "spiffe://firemud/ns/control-ui-owner-proof/sa/world-management-service"; + private static final long GAME_TEMPLATE_ID = 42L; + 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("world-participation-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", + "world-participation-primary", + "6379"); + + @TempDir Path temporary; + + @Test + void originalTupleRecoversCommittedParticipationAfterLostResponseAndLeaseExpiry() + throws Exception { + try (var controlUi = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary)) { + var proof = + new AccountOriginalStartSessionAuthorizationProofFixture(controlUi, temporary, NAMESPACE); + String requestId = "tuple-recovery-" + UUID.randomUUID(); + UUID reservationOwnerId = UUID.randomUUID(); + UUID gameSessionAttemptId = UUID.randomUUID(); + UUID gameSessionMutationId = UUID.randomUUID(); + UUID gameInstanceId = UUID.randomUUID(); + long reservationClaimFence = 31L; + long gameSessionOwnerFence = 47L; + var action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(controlUi.tenantId(), NAMESPACE), + new StartSessionOperatorAction.Target(GAME_TEMPLATE_ID, proof.creatorAccountId()), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "test-only lost World participation response recovery"); + var original = + proof.issueAndRedeemOriginal( + requestId, + action, + reservationOwnerId, + reservationClaimFence, + gameSessionAttemptId, + gameSessionOwnerFence); + byte[] originalTupleBytes = original.originalTuple().canonicalBytes(); + String preparationInput = + preparationInput( + NAMESPACE, + controlUi.tenantId(), + requestId, + gameInstanceId, + "tuple-recovery-world", + GAME_TEMPLATE_ID); + String preparationDigest = digest(preparationInput); + Instant leaseExpiresAt = + Instant.ofEpochMilli(databaseNow(proof.sourceDsl()).toEpochMilli()).plusSeconds(4L); + // The Game Session point-in-time observation is stipulated; Account's original issue, + // redemption, source capture, acquisition gates, and PostgreSQL retention are real. + var acquisition = + proof.worldParticipationAcquisitionService( + request -> + new Result( + request, + leaseExpiresAt, + StartSessionAccountRedemptionProjection.fromOriginalTuple( + original.originalTuple()))); + + // Discard the owner response to model transport loss. The database row is used only as a + // physical proof oracle; it is not supplied to the historical lookup request. + withWorldPeer( + () -> + acquisition.acquire( + new AcquisitionRequest( + originalTupleBytes, + gameSessionMutationId, + gameSessionAttemptId, + gameSessionOwnerFence, + gameInstanceId, + preparationInput, + preparationDigest))); + + var sql = + physicalSql(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword(), proof); + awaitDatabaseExpiry(sql.dsl(), leaseExpiresAt); + var committedRow = + Objects.requireNonNull( + sql.dsl() + .fetchOne( + "SELECT participation_id, participation_fence " + + "FROM account_start_session_world_participations " + + "WHERE control_plane_request_id = ?", + requestId), + "Committed participation must remain physically retained"); + UUID committedParticipationId = committedRow.get("participation_id", UUID.class); + long committedParticipationFence = committedRow.get("participation_fence", Long.class); + var transaction = new TransactionTemplate(sql.transactionManager()); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var attemptRepository = + new AccountStartSessionWorldOriginalAttemptEvidenceRepository(sql.dsl()); + var expiredParticipation = + transaction.execute( + status -> + new AccountStartSessionWorldParticipationRepository(sql.dsl()) + .findHistoricalExact(committedParticipationId, committedParticipationFence) + .orElseThrow()); + var expiredAttemptRequest = + new Request( + UUID.randomUUID(), + NAMESPACE, + originalTupleBytes, + gameSessionAttemptId, + gameSessionMutationId, + gameSessionOwnerFence); + assertThatThrownBy( + () -> + transaction.execute( + status -> + attemptRepository + .findCurrentExact(expiredParticipation, expiredAttemptRequest) + .orElseThrow())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("unavailable"); + var retainedAttempt = + transaction.execute( + status -> + attemptRepository + .findHistoricalExact(expiredParticipation, expiredAttemptRequest) + .orElseThrow()); + assertThat(retainedAttempt.originalLeaseExpiresAt()).isEqualTo(leaseExpiresAt); + assertThat(retainedAttempt.result().request().canonicalPostAuthorizationTuple()) + .containsExactly(originalTupleBytes); + + var historicalService = + new AccountStartSessionWorldParticipationHistoricalReadService( + new AccountStartSessionWorldParticipationRepository(sql.dsl()), + sql.transactionManager(), + NAMESPACE); + var historicalRequest = + new AccountStartSessionWorldParticipationHistoricalReadRequest( + UUID.randomUUID(), NAMESPACE, originalTupleBytes); + AccountStartSessionWorldParticipationHistoricalReadEvidence recovered = + withWorldPeer(() -> historicalService.read(historicalRequest)); + assertThat(recovered.accountWorldParticipationId()).isEqualTo(committedParticipationId); + assertThat(recovered.accountWorldParticipationFence()).isEqualTo(committedParticipationFence); + assertThat(recovered.gameSessionOwnerAttemptId()).isEqualTo(gameSessionAttemptId); + assertThat(recovered.gameSessionOwnerFence()).isEqualTo(gameSessionOwnerFence); + assertThat(recovered.canonicalGameInstanceId()).isEqualTo(gameInstanceId); + assertThat(recovered.preparationInputJson()).isEqualTo(preparationInput); + assertThat(recovered.preparationInputDigest()).isEqualTo(preparationDigest); + assertThat(historicalRequest.readRequestId()) + .isNotEqualTo(original.originalTuple().preAuthorizationTuple().actor().accountId()); + assertThat( + sql.dsl() + .fetchCount( + DSL.table("account_start_session_world_participation_sources"), + DSL.field("participation_id").eq(committedParticipationId))) + .isPositive(); + + var changedTuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + original.originalTuple().preAuthorizationTuple(), + original.originalTuple().authenticatedWorkloadIdentity(), + changedFingerprint(original.originalTuple().authorizationReferenceFingerprint()), + original.originalTuple().reservationOwnerId(), + original.originalTuple().reservationClaimFence(), + original.originalTuple().authorityEvidenceBundleBytes(), + original.originalTuple().bundleReference()); + var changedTupleRequest = + new AccountStartSessionWorldParticipationHistoricalReadRequest( + UUID.randomUUID(), NAMESPACE, changedTuple.canonicalBytes()); + assertThatThrownBy(() -> withWorldPeer(() -> historicalService.read(changedTupleRequest))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Exact StartSession World participation evidence unavailable"); + + var absentOriginal = + proof.issueAndRedeemOriginal( + "tuple-recovery-absent-" + UUID.randomUUID(), + action, + UUID.randomUUID(), + reservationClaimFence + 1L, + UUID.randomUUID(), + gameSessionOwnerFence + 1L); + var missingTupleRequest = + new AccountStartSessionWorldParticipationHistoricalReadRequest( + UUID.randomUUID(), NAMESPACE, absentOriginal.originalTuple().canonicalBytes()); + assertThatThrownBy(() -> withWorldPeer(() -> historicalService.read(missingTupleRequest))) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + } + } + + @Test + void latestMigrationsInstallParticipationGuardsAndPreserveAssembledSourceExclusions() { + String schema = "ss_world_part_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = DSL.using(source, SQLDialect.POSTGRES); + + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM unnest(ARRAY[" + + "'account_start_session_world_participations', " + + "'account_start_session_world_participation_sources', " + + "'account_start_session_world_participation_settlements']::TEXT[]) " + + "AS names(name) WHERE to_regclass(name) IS NOT NULL"), + "participation table inventory query must return a row") + .get(0, Long.class)) + .isEqualTo(3L); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT attidentity FROM pg_attribute " + + "WHERE attrelid = 'account_start_session_world_participations'::regclass " + + "AND attname = 'participation_fence' AND NOT attisdropped"), + "participation fence column must exist") + .get(0, String.class)) + .isEqualTo("a"); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM pg_constraint WHERE contype = 'f' AND conrelid IN (" + + "'account_start_session_world_participations'::regclass, " + + "'account_start_session_world_participation_sources'::regclass, " + + "'account_start_session_world_participation_settlements'::regclass)"), + "participation foreign-key query must return a row") + .get(0, Long.class)) + .isEqualTo(6L); + + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM pg_trigger WHERE NOT tgisinternal " + + "AND tgname = 'account_start_session_world_participation_complete' " + + "AND tgrelid = 'account_start_session_world_participations'::regclass " + + "AND tgconstraint <> 0 AND tgdeferrable AND tginitdeferred"), + "deferred participation completion trigger query must return a row") + .get(0, Long.class)) + .isEqualTo(1L); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM pg_trigger WHERE NOT tgisinternal " + + "AND tgrelid IN ('account_start_session_world_participations'::regclass, " + + "'account_start_session_world_participation_sources'::regclass, " + + "'account_start_session_world_participation_settlements'::regclass) " + + "AND tgname IN (" + + "'account_start_session_world_participation_validate', " + + "'account_start_session_world_participation_immutable', " + + "'account_start_session_world_participation_no_truncate', " + + "'account_start_session_world_participation_sources_insert', " + + "'account_start_session_world_participation_sources_immutable', " + + "'account_start_session_world_participation_sources_no_truncate', " + + "'account_start_session_world_participation_complete', " + + "'account_start_session_world_participation_settlement_validate', " + + "'account_start_session_world_participation_settlements_immutable', " + + "'account_start_session_world_settlement_no_truncate')"), + "participation protection trigger query must return a row") + .get(0, Long.class)) + .isEqualTo(10L); + + String holdGuard = functionDefinition(dsl, "account_control_ui_hold_required_sources(text[])"); + assertThat(holdGuard) + .contains( + "account_draft_authorization_sources", + "account_draft_authorization_is_settled(operation_value)", + "account_selected_publication_sources", + "account_selected_publication_authorizations", + "account_game_logic_intake_sources", + "account_game_logic_intake_authorizations", + "account_game_logic_intake_source_read_sources", + "account_game_logic_intake_source_read_is_pending(s.operation_id)", + "account_start_session_world_participations participation", + "account_start_session_world_participation_is_settled(participation.participation_id)", + "FOR UPDATE OF participation NOWAIT"); + assertThat(holdGuard.indexOf("FOR UPDATE NOWAIT")) + .isLessThan(holdGuard.indexOf("FROM account_start_session_world_participations")); + + String sourceChangeGuard = + functionDefinition(dsl, "account_draft_authorization_source_change_guard()"); + assertThat(sourceChangeGuard) + .contains( + "account_draft_authorization_changed_scopes", + "account_draft_authorization_is_settled(operation)", + "account_start_session_world_participation_is_settled(participation.participation_id)", + "Pending StartSession World participation excludes source-change completion"); + + String disclosureGuard = + functionDefinition(dsl, "account_hosted_terms_disclosure_handoff_guard()"); + assertThat(disclosureGuard) + .contains( + "OLD.status IN ('PREPARED', 'AMBIGUOUS')", + "NEW.status = 'DISPATCH_AUTHORIZED'", + "OLD.status = 'DISPATCH_AUTHORIZED' AND NEW.status = 'AMBIGUOUS'", + "account_hosted_terms_disclosure_sources", + "account_start_session_world_participation_is_settled(participation.participation_id)", + "Pending StartSession World participation excludes hosted-terms dispatch"); + + String acquisitionExclusion = + functionDefinition( + dsl, "account_start_session_world_participation_assert_exclusive(text[],jsonb)"); + assertThat(acquisitionExclusion) + .contains( + "change.status = 'WAITING'", + "source_key_value LIKE 'HOSTED_TERMS:%'", + "handoff.source_key = source_key_value", + "handoff_source.source_key = handoff.source_key", + "handoff_source.source_evidence = evidence_value", + "handoff.status IN ('DISPATCH_AUTHORIZED', 'AMBIGUOUS', 'DISCLOSED')"); + assertThat(acquisitionExclusion).doesNotContain("handoff.source_key = ANY(source_keys)"); + + for (String table : + new String[] { + "account_start_session_world_participations", + "account_start_session_world_participation_sources", + "account_start_session_world_participation_settlements" + }) { + assertGuardRejected( + () -> dsl.execute("TRUNCATE " + table + " CASCADE"), + "StartSession World participation evidence is append-only"); + assertThat( + Objects.requireNonNull( + dsl.fetchOne("SELECT count(*) FROM " + table), + "post-TRUNCATE table state query must return a row") + .get(0, Long.class)) + .as("rejected TRUNCATE must leave the empty table unchanged") + .isZero(); + } + } + + private static void assertGuardRejected( + org.assertj.core.api.ThrowableAssert.ThrowingCallable action, String expectedDiagnostic) { + assertThatThrownBy(action) + .satisfies( + failure -> { + SQLException sqlFailure = findSqlException(failure); + assertThat(sqlFailure.getSQLState()).isEqualTo("23514"); + if (!(sqlFailure instanceof org.postgresql.util.PSQLException postgresFailure)) { + throw new AssertionError( + "Participation guard rejection must be a PostgreSQL exception", sqlFailure); + } + var serverError = postgresFailure.getServerErrorMessage(); + assertThat(serverError).isNotNull(); + assertThat(serverError.getMessage()).isEqualTo(expectedDiagnostic); + }); + } + + private static SQLException findSqlException(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sqlException) return sqlException; + } + throw new AssertionError("Guard rejection must retain its SQL exception", failure); + } + + private static String functionDefinition(DSLContext dsl, String signature) { + return Objects.requireNonNull( + dsl.fetchOne("SELECT pg_get_functiondef(?::regprocedure)", signature), + "function definition query must return a row") + .get(0, String.class); + } + + private static PhysicalSql physicalSql( + String jdbcUrl, + String username, + String password, + AccountOriginalStartSessionAuthorizationProofFixture proof) { + String schema = + Objects.requireNonNull( + proof.sourceDsl().fetchOne("SELECT current_schema() AS schema_name"), + "Account test schema must be available") + .get("schema_name", String.class); + DriverManagerDataSource source = new DriverManagerDataSource(jdbcUrl, username, password); + source.setSchema(schema); + return new PhysicalSql( + new DataSourceTransactionManager(source), + DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES)); + } + + private record PhysicalSql(DataSourceTransactionManager transactionManager, DSLContext dsl) {} + + private static Instant databaseNow(DSLContext dsl) { + return Objects.requireNonNull( + dsl.fetchOne("SELECT clock_timestamp() AS observed_at"), + "PostgreSQL clock must return the current instant") + .get("observed_at", OffsetDateTime.class) + .toInstant(); + } + + private static void awaitDatabaseExpiry(DSLContext dsl, Instant expiresAt) throws Exception { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10L); + while (!databaseNow(dsl).isAfter(expiresAt)) { + if (System.nanoTime() >= deadline) { + throw new IllegalStateException("PostgreSQL clock did not pass the retained lease expiry"); + } + Thread.sleep(25L); + } + } + + private static T withWorldPeer(Supplier action) { + Context current = Context.current(); + Context scoped = + current.withValue( + GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(WORLD_PEER_URI).orElseThrow()); + Context previous = scoped.attach(); + try { + return action.get(); + } finally { + scoped.detach(previous); + } + } + + private static String changedFingerprint(String fingerprint) { + char finalCharacter = fingerprint.charAt(fingerprint.length() - 1); + return fingerprint.substring(0, fingerprint.length() - 1) + (finalCharacter == '0' ? '1' : '0'); + } + + private static String digest(String value) { + try { + return "sha256:" + + java.util.HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static String preparationInput( + String namespace, + UUID tenantId, + String requestId, + UUID gameInstanceId, + String worldSlug, + long gameTemplateId) + throws Exception { + var json = tools.jackson.databind.json.JsonMapper.builder().build(); + String descriptorJson = json.writeValueAsString(Map.of("gameTemplateId", gameTemplateId)); + return json.writeValueAsString( + Map.of( + "schemaVersion", + 1, + "identity", + Map.of( + "targetNamespace", + namespace, + "canonicalTenantId", + tenantId.toString(), + "controlPlaneRequestId", + requestId, + "canonicalGameInstanceId", + gameInstanceId.toString(), + "worldSlug", + worldSlug), + "gameSessionReadRequest", + Map.of( + "targetNamespace", + namespace, + "canonicalTenantId", + tenantId.toString(), + "controlPlaneRequestId", + requestId, + "canonicalGameInstanceId", + gameInstanceId.toString(), + "worldSlug", + worldSlug), + "gameSessionReadEvidence", + Map.of( + "targetNamespace", + namespace, + "canonicalTenantId", + tenantId.toString(), + "controlPlaneRequestId", + requestId, + "canonicalGameInstanceId", + gameInstanceId.toString(), + "worldSlug", + worldSlug, + "descriptorJson", + descriptorJson), + "launchBinding", + Map.of( + "targetNamespace", + namespace, + "canonicalTenantId", + tenantId.toString(), + "controlPlaneRequestId", + requestId, + "worldSlug", + worldSlug))); + } +} 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 840d8eb920..56dca09c66 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 @@ -77,6 +77,7 @@ import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidenceServiceGrpc; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; import org.jooq.impl.DSL; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; @@ -498,6 +499,7 @@ void realSignerLifecycleIssuesAuthenticatesAndClaimsExactOriginalAccountOrder() operatorAuthorizationContext( actors, operations, + f.dsl, loggingTransport.accountClient(), operatorRepository, () -> @@ -731,6 +733,7 @@ void realSignerLifecycleIssuesAuthenticatesAndClaimsExactOriginalAccountOrder() private AnnotationConfigApplicationContext operatorAuthorizationContext( AccountControlUiActorService actors, AccountControlUiIssuanceRepository issuanceOperations, + DSLContext accountDsl, StartSessionReservationEvidenceClient reservationEvidence, AccountStartSessionOperatorAuthorizationRepository repository, OwnerKeySource ownerKeySource, @@ -760,6 +763,7 @@ private AnnotationConfigApplicationContext operatorAuthorizationContext( "PT1M"))); context.registerBean(AccountControlUiActorService.class, () -> actors); context.registerBean(AccountControlUiIssuanceRepository.class, () -> issuanceOperations); + context.registerBean(DSLContext.class, () -> accountDsl); context.registerBean(StartSessionReservationEvidenceClient.class, () -> reservationEvidence); context.registerBean( AccountStartSessionOperatorAuthorizationRepository.class, () -> repository); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java index dbbd1bcddd..3f15f37032 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java @@ -28,6 +28,7 @@ import java.time.Clock; import java.time.Duration; import java.time.Instant; +import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; @@ -39,10 +40,12 @@ import java.util.Set; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.PasswordResetToken; import net.firedevops.firemud.accountservice.repository.AccountAuthEvidenceBundleRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; @@ -54,8 +57,14 @@ import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.RecoveredCredential; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository; import net.firedevops.firemud.accountservice.service.AccountGenerationProjection; +import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider; import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection; @@ -1053,15 +1062,8 @@ private void exerciseActiveTransition() throws Exception { new BeforeSecondTransactionManager( database.manager(), () -> - inTransaction( - database, - () -> { - AccountRepository accounts = new AccountRepository(dsl, sources); - Account changed = accounts.findByAccountUuid(accountId).orElseThrow(); - changed.setEmailVerified(true); - accounts.save(changed); - return null; - })); + commitPasswordResetAuthorityChange( + database, dsl, authorities, outbox, sources, accountId)); AccountGameplayDelegationCommittedIssuanceOwner postCheckRaceOwner = new AccountGameplayDelegationCommittedIssuanceOwner( issuance, @@ -1081,14 +1083,16 @@ private void exerciseActiveTransition() throws Exception { AccountAuthorityGenerationRepository.AuthorityScope.account(accountId))); assertThat(changedAccountAuthority.generation()) .isGreaterThan(sourceSnapshot.account().generation()); - assertThatThrownBy( - () -> - inTransaction( - database, - () -> sources.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountId))) - .isInstanceOf( - AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException.class) - .hasNoCause(); + var refreshedSources = + inTransaction( + database, () -> sources.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountId)); + assertThat(refreshedSources.account().generation()) + .isEqualTo(changedAccountAuthority.generation()); + assertThat(refreshedSources.account().generation()) + .isGreaterThan(sourceSnapshot.account().generation()); + assertThat(refreshedSources.account().sourceVersion()) + .isNotEqualTo(sourceSnapshot.account().sourceVersion()); + assertThat(refreshedSources.issuer()).isEqualTo(sourceSnapshot.issuer()); assertThat(writerProvider.openedConnections()) .isEqualTo(connectionsBeforeAuthorityChange + 2); assertThat(writerProvider.trace(connectionsBeforeAuthorityChange)) @@ -1946,6 +1950,81 @@ private static UUID createFreshAccount( }); } + private static void commitPasswordResetAuthorityChange( + TestContext context, + DSLContext dsl, + AccountAuthorityGenerationRepository authorities, + AccountAuthorityOutboxRepository outbox, + AccountAuthoritySourceEvidenceRepository sources, + UUID accountId) { + AccountRepository accounts = new AccountRepository(dsl, sources); + AccountPasswordResetOperationRepository resetOperations = + new AccountPasswordResetOperationRepository(dsl); + AccountLogoutAllOperationRepository logoutAllOperations = + new AccountLogoutAllOperationRepository(dsl); + AccountSecurityStateOperationRepository securityStateOperations = + new AccountSecurityStateOperationRepository(dsl); + AccountPasswordResetDraftSourceChangeRepository sourceChanges = + new AccountPasswordResetDraftSourceChangeRepository(dsl); + PasswordResetTokenRepository resetTokens = new PasswordResetTokenRepository(dsl); + String rawToken = "active-transition-reset-" + UUID.randomUUID(); + + inTransaction( + context, + () -> { + Account account = accounts.findByAccountUuid(accountId).orElseThrow(); + PasswordResetToken token = new PasswordResetToken(); + token.setAccount(account); + token.setToken(rawToken); + token.setExpiresAt(LocalDateTime.now().plusHours(2)); + resetTokens.save(token); + return null; + }); + + AccountServiceImpl accountService = + new AccountServiceImpl( + accounts, + authorities, + sources, + outbox, + resetOperations, + logoutAllOperations, + securityStateOperations, + sourceChanges, + null, // audit outbox + null, // connect scopes + null, // join operations + null, // email login challenges + null, // realm grants + null, // tenant memberships + null, // account mapper is not on the password-reset path + null, // profiles + null, // profile mapper + null, // payment transactions + null, // subscriptions + null, // external account identities + resetTokens, + null, // email verification tokens + null, // notifications + null, + null, + null, + null, + null, + null, + null, + null, + context.manager()); + inTransaction( + context, + () -> { + accountService.completePasswordReset( + new CompletePasswordResetRequest( + rawToken, "active-transition-password-" + UUID.randomUUID())); + return null; + }); + } + private String writeResponseKeyring() throws Exception { Path root = temporaryDirectory.resolve("response-keyring-" + UUID.randomUUID()); Files.createDirectories(root); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java new file mode 100644 index 0000000000..ea1e799ff4 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java @@ -0,0 +1,167 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.SQLException; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** PostgreSQL proof of V158 allocator ownership and capture-table statement protection. */ +@Testcontainers(disabledWithoutDocker = true) +class AccountStartSessionAuthorityCapturePostgresIntegrationTest { + @Container + static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void migrationInstallsIndependentAllocatorsAndRejectsUnownedMutationAndTruncate() { + String schema = "start_session_capture_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = DSL.using(source, SQLDialect.POSTGRES); + + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT last_source_version FROM account_start_session_capture_source_version_allocator"), + "capture sourceVersion allocator row must exist") + .get(0, Long.class)) + .isZero(); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT last_source_fence FROM account_start_session_capture_source_fence_allocator"), + "capture sourceFence allocator row must exist") + .get(0, Long.class)) + .isZero(); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM pg_trigger WHERE NOT tgisinternal " + + "AND tgname IN ('account_start_session_authority_capture_immutable', " + + "'account_start_session_authority_capture_no_truncate', " + + "'account_start_session_capture_source_version_allocator_guard', " + + "'account_start_session_capture_source_fence_allocator_guard')"), + "V158 protection trigger query must return a row") + .get(0, Long.class)) + .isEqualTo(4L); + + var actorId = UUID.fromString("11111111-1111-4111-8111-111111111111"); + var tuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "capture-integration-request", + actorId, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope( + UUID.fromString("22222222-2222-4222-8222-222222222222"), "operator-test"), + new StartSessionOperatorAction.Target( + 42L, UUID.fromString("33333333-3333-4333-8333-333333333333")), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "capture tuple guard regression")); + String tupleJson = tuple.canonicalJson(); + String tupleMutationDigest = tuple.mutationDigest(); + assertThat(tupleJson).doesNotContain("mutationDigest"); + assertThat(tupleMutationDigest).matches("[0-9a-f]{64}"); + assertThat( + Objects.requireNonNull( + dsl.fetchOne("SELECT (?::jsonb)->>'mutationDigest' AS tuple_digest", tupleJson), + "canonical pretuple query must return a row") + .get("tuple_digest", String.class)) + .isNull(); + String captureGuard = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT pg_get_functiondef('account_start_session_authority_capture_guard()'::regprocedure)"), + "V158 capture guard function must exist") + .get(0, String.class); + assertThat(captureGuard) + .contains("snapshot->>'mutationDigest' IS DISTINCT FROM NEW.mutation_digest") + .doesNotContain("tuple->>'mutationDigest'"); + + assertGuardRejected( + () -> + dsl.execute( + "UPDATE account_start_session_capture_source_version_allocator " + + "SET last_source_version = last_source_version + 1"), + "StartSession capture sourceVersion allocator must advance once in its owner transaction"); + assertGuardRejected( + () -> + dsl.execute( + "UPDATE account_start_session_capture_source_fence_allocator " + + "SET last_source_fence = last_source_fence + 1"), + "StartSession capture sourceFence allocator must advance once in its owner transaction"); + assertGuardRejected( + () -> dsl.execute("DELETE FROM account_start_session_capture_source_version_allocator"), + "StartSession capture allocators cannot be deleted or truncated"); + assertGuardRejected( + () -> dsl.execute("DELETE FROM account_start_session_capture_source_fence_allocator"), + "StartSession capture allocators cannot be deleted or truncated"); + assertGuardRejected( + () -> dsl.execute("TRUNCATE account_start_session_capture_source_version_allocator"), + "StartSession Account source captures cannot be truncated"); + assertGuardRejected( + () -> dsl.execute("TRUNCATE account_start_session_capture_source_fence_allocator"), + "StartSession Account source captures cannot be truncated"); + assertGuardRejected( + () -> dsl.execute("TRUNCATE account_start_session_authority_captures CASCADE"), + "StartSession Account source captures cannot be truncated"); + assertThat( + Objects.requireNonNull( + dsl.fetchOne("SELECT count(*) FROM account_start_session_authority_captures"), + "V158 capture count query must return a row") + .get(0, Long.class)) + .isZero(); + } + + private static void assertGuardRejected( + org.assertj.core.api.ThrowableAssert.ThrowingCallable action, String expectedDiagnostic) { + assertThatThrownBy(action) + .satisfies( + failure -> { + SQLException sqlFailure = findSqlException(failure); + assertThat(sqlFailure.getSQLState()).isEqualTo("23514"); + if (!(sqlFailure instanceof org.postgresql.util.PSQLException postgresFailure)) { + throw new AssertionError( + "Capture guard rejection must be a PostgreSQL exception", sqlFailure); + } + var serverError = postgresFailure.getServerErrorMessage(); + assertThat(serverError).isNotNull(); + assertThat(serverError.getMessage()).isEqualTo(expectedDiagnostic); + }); + } + + private static SQLException findSqlException(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sqlException) return sqlException; + } + throw new AssertionError("Guard rejection must retain its SQL exception", failure); + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationPostgresIntegrationTest.java new file mode 100644 index 0000000000..14039ddd35 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationPostgresIntegrationTest.java @@ -0,0 +1,785 @@ +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.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.sql.SQLException; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.Function; +import javax.crypto.spec.SecretKeySpec; +import net.firedevops.firemud.accountservice.client.StartSessionReservationEvidenceClient; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.Candidate; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredSettlement; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.KeyMaterial; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.Snapshot; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle.BundleReference; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; +import net.firedevops.firemud.test.TestContainerImages; +import org.jooq.DSLContext; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +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.core.type.TypeReference; +import tools.jackson.databind.json.JsonMapper; + +/** + * PostgreSQL proof of Account's immutable World participation storage behind its actual signer, + * current-actor, V128 capture, and original operator issuance/redemption owners. + * + *

The test stipulates Logging's claim response, the Game Session attempt/fence supplied to its + * real Account redemption, and the World terminal producer value. Its in-process peer contexts do + * not prove mTLS transport, authenticated Game Session production, a genuine World producer, or + * runtime activation. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AccountStartSessionWorldParticipationPostgresIntegrationTest { + private static final String NAMESPACE = "control-ui-owner-proof"; + private static final long ORIGINAL_GAME_TEMPLATE_ID = 42L; + private static final String LOGGING_PEER_URI = + "spiffe://firemud/ns/control-ui-owner-proof/sa/logging-admin-service"; + private static final String GAME_SESSION_PEER_URI = + "spiffe://firemud/ns/control-ui-owner-proof/sa/game-session-service"; + private static final String WORLD_PEER_URI = + "spiffe://firemud/ns/control-ui-owner-proof/sa/world-management-service"; + 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("world-participation-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", + "world-participation-primary", + "6379"); + + @TempDir Path temporary; + + @Test + void realAccountCaptureAndRedemptionBackExactParticipationAndTypedSettlement() throws Exception { + try (var controlUi = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary)) { + var creator = controlUi.issueCreator(); + var account = creator.sources(); + var actorService = creator.actors(); + String requestId = "world-participation-" + UUID.randomUUID(); + UUID reservationOwnerId = UUID.randomUUID(); + long reservationClaimFence = 31L; + UUID gameSessionAttemptId = UUID.randomUUID(); + long gameSessionOwnerFence = 47L; + UUID gameInstanceId = UUID.randomUUID(); + String preparationInputJson = + preparationInput( + NAMESPACE, + account.tenant, + requestId, + gameInstanceId, + "owner-proof-world", + ORIGINAL_GAME_TEMPLATE_ID); + String preparationInputDigest = digest(preparationInputJson); + + var preAuthorizationTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + requestId, + account.account.getAccountUuid(), + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(account.tenant, NAMESPACE), + new StartSessionOperatorAction.Target( + ORIGINAL_GAME_TEMPLATE_ID, account.account.getAccountUuid()), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "test-only StartSession World participation storage proof")); + + // This client response is explicitly stipulated Logging claim evidence. Account still runs + // its real typed-claim checks, source capture, signing, currentness, issuance, and + // redemption. + var claimClient = mock(StartSessionReservationEvidenceClient.class); + var claim = + stipulatedLoggingClaim( + preAuthorizationTuple, reservationOwnerId, reservationClaimFence, Instant.now()); + when(claimClient.readCurrentClaimEvidence( + preAuthorizationTuple, + reservationOwnerId, + reservationClaimFence, + reservationOwnerId, + reservationClaimFence, + StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .thenReturn(claim); + + var operatorRepository = new AccountStartSessionOperatorAuthorizationRepository(account.dsl); + var captureRepository = new AccountStartSessionAuthorityCaptureRepository(account.dsl); + var fingerprintKeys = fingerprintKeys(); + var operatorResponseCryptography = responseCryptography(temporary); + var operatorAuthorization = + new AccountStartSessionOperatorAuthorizationService( + actorService, + new AccountControlUiIssuanceRepository(account.dsl), + captureRepository, + claimClient, + operatorRepository, + fingerprintKeys, + operatorResponseCryptography, + account.terms, + account.manager, + Clock.systemUTC(), + new SecureRandom(), + LOGGING_PEER_URI, + GAME_SESSION_PEER_URI, + Duration.ofMinutes(2), + Duration.ofSeconds(30)); + + var authorization = + withPeer( + LOGGING_PEER_URI, + () -> + operatorAuthorization.issue( + new AccountStartSessionOperatorAuthorizationService.IssueRequest( + creator.compact(), + preAuthorizationTuple.canonicalJson().getBytes(StandardCharsets.UTF_8), + reservationOwnerId, + reservationClaimFence, + reservationOwnerId, + reservationClaimFence))); + var issuedRecord = + account.tx(() -> operatorRepository.findByControlPlaneRequestId(requestId).orElseThrow()); + + // The exact Account issuance result becomes the original post-authorization tuple. The + // target owner is still Game Session; World is only the same-namespace receiver. + var originalTuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + preAuthorizationTuple, + LOGGING_PEER_URI, + authorization.authorizationReferenceFingerprint(), + reservationOwnerId, + reservationClaimFence, + authorization.authorityEvidenceBundle(), + new BundleReference( + authorization.bundleReference().bundleVersion(), + authorization.bundleReference().sourceVersion(), + authorization.bundleReference().sourceFence(), + authorization.bundleReference().linearization())); + assertThat(authorization.originalAccountPostAuthorizationTuple()) + .containsExactly(originalTuple.canonicalBytes()); + assertThat(originalTuple.preAuthorizationTuple().targetOwner()) + .isEqualTo("game-session-service"); + + UUID recoveryClaimOwnerId = UUID.randomUUID(); + var recoveryClaim = + claim.toBuilder() + .setClaimOwnerId(recoveryClaimOwnerId.toString()) + .setClaimFence(2L) + .setPurpose( + StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_RECOVER) + .build(); + when(claimClient.readCurrentClaimEvidence( + preAuthorizationTuple, + reservationOwnerId, + reservationClaimFence, + recoveryClaimOwnerId, + 2L, + StartSessionReservationEvidenceClient.Purpose.RECOVER)) + .thenReturn(recoveryClaim); + var recovered = + withPeer( + LOGGING_PEER_URI, + () -> + operatorAuthorization.recover( + new AccountStartSessionOperatorAuthorizationService.RecoverRequest( + preAuthorizationTuple.canonicalJson().getBytes(StandardCharsets.UTF_8), + reservationOwnerId, + reservationClaimFence, + recoveryClaimOwnerId, + 2L))); + assertThat(recovered.originalAccountPostAuthorizationTuple()) + .containsExactly(originalTuple.canonicalBytes()); + var recoveredRecord = + account.tx(() -> operatorRepository.findByControlPlaneRequestId(requestId).orElseThrow()); + assertThat(recoveredRecord.encryptedResponseEnvelope()) + .containsExactly(issuedRecord.encryptedResponseEnvelope()); + + // Account performs its real one-time redemption. The Game Session peer and attempt/fence + // are stipulated test inputs, not evidence from an authenticated Game Session producer. + var redemption = + withPeer( + GAME_SESSION_PEER_URI, + () -> + operatorAuthorization.redeem( + new AccountStartSessionOperatorAuthorizationService.RedeemRequest( + preAuthorizationTuple.canonicalJson().getBytes(StandardCharsets.UTF_8), + recovered.operatorAuthorizationReference(), + recovered.authorizationReferenceFingerprint(), + reservationOwnerId, + reservationClaimFence, + gameSessionAttemptId, + gameSessionOwnerFence))); + assertThat(redemption.originalAccountPostAuthorizationTuple()) + .containsExactly(originalTuple.canonicalBytes()); + + var redeemed = + account.tx(() -> operatorRepository.findByControlPlaneRequestId(requestId).orElseThrow()); + assertThat(redeemed.status()) + .isEqualTo(AccountStartSessionOperatorAuthorizationRepository.Status.REDEEMED); + assertThat(redeemed.redemptionOwnerAttemptId()).isEqualTo(gameSessionAttemptId); + assertThat(redeemed.redemptionOwnerFence()).isEqualTo(gameSessionOwnerFence); + assertThat(redeemed.issuanceFence()).isPositive(); + assertThat(redeemed.encryptedResponseEnvelope()) + .containsExactly(issuedRecord.encryptedResponseEnvelope()); + + var repository = new AccountStartSessionWorldParticipationRepository(account.dsl); + var initialCapture = + new java.util.concurrent.atomic.AtomicReference(); + var initialCandidate = new java.util.concurrent.atomic.AtomicReference(); + StoredParticipation first = + withWorldCurrentness( + operatorAuthorization, + originalTuple, + gameSessionAttemptId, + gameSessionOwnerFence, + capture -> { + assertActiveReadCommittedTransaction(); + initialCapture.set(capture); + var candidate = + candidate( + originalTuple, + capture, + gameInstanceId, + gameSessionAttemptId, + gameSessionOwnerFence, + preparationInputJson, + preparationInputDigest); + initialCandidate.set(candidate); + return repository.createOrReadExact(candidate); + }); + + var capture = initialCapture.get(); + assertThat(capture).isNotNull(); + assertThat(capture.controlPlaneRequestId()).isEqualTo(requestId); + assertThat(capture.sourceVersion()).isPositive(); + assertThat(capture.sourceFence()).isPositive(); + assertThat(account.dsl.fetchCount(DSL.table("account_start_session_authority_captures"))) + .isEqualTo(1); + var captureRow = + account.dsl.fetchOne( + "SELECT source_version, source_fence, issuance_fence, " + + "issuance_fence_source_version, canonical_snapshot_bytes " + + "FROM account_start_session_authority_captures " + + "WHERE control_plane_request_id = ?", + requestId); + assertThat(captureRow).isNotNull(); + assertThat(captureRow.get("source_version", Long.class)).isEqualTo(capture.sourceVersion()); + assertThat(captureRow.get("source_fence", Long.class)).isEqualTo(capture.sourceFence()); + assertThat(captureRow.get("issuance_fence", Long.class)).isEqualTo(redeemed.issuanceFence()); + assertThat(captureRow.get("canonical_snapshot_bytes", byte[].class)) + .containsExactly(capture.snapshotBytes()); + Map captureSnapshot = captureSnapshot(capture); + assertThat(captureSnapshot.get("issuanceFence")) + .isEqualTo(Long.toString(redeemed.issuanceFence())); + assertThat(captureSnapshot.get("issuanceFenceSourceVersion")) + .isEqualTo(Long.toString(captureRow.get("issuance_fence_source_version", Long.class))); + assertThat(captureSnapshot.get("controlUiSignerReceiptSha256").toString()) + .matches("[0-9a-f]{64}"); + + assertThat(first.participationId()).isNotEqualTo(new UUID(0L, 0L)); + assertThat(first.participationFence()).isPositive(); + assertThat(first.producerXid()).isPositive(); + assertThat(first.originalPostAuthorizationTuple()) + .containsExactly(originalTuple.canonicalBytes()); + assertThat(first.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(first.canonicalTenantId()).isEqualTo(account.tenant); + assertThat(first.canonicalGameInstanceId()).isEqualTo(gameInstanceId); + assertThat(first.gameSessionOwnerAttemptId()).isEqualTo(gameSessionAttemptId); + assertThat(first.gameSessionOwnerFence()).isEqualTo(gameSessionOwnerFence); + assertThat(first.preparationInputJson()).isEqualTo(preparationInputJson); + assertThat(first.preparationInputDigest()).isEqualTo(preparationInputDigest); + assertThat(capturedSourceVector(capture)) + .containsExactlyElementsOf( + first.sources().stream() + .map(source -> Base64.getEncoder().encodeToString(source.canonicalBytes())) + .toList()); + + StoredParticipation exactRetry = + withWorldCurrentness( + operatorAuthorization, + originalTuple, + gameSessionAttemptId, + gameSessionOwnerFence, + currentCapture -> { + assertThat(currentCapture.canonicalBytes()) + .containsExactly(capture.canonicalBytes()); + return repository.createOrReadExact(initialCandidate.get()); + }); + assertThat(exactRetry.participationId()).isEqualTo(first.participationId()); + assertThat(exactRetry.participationFence()).isEqualTo(first.participationFence()); + assertThat(exactRetry.originalPostAuthorizationTuple()) + .containsExactly(first.originalPostAuthorizationTuple()); + assertThat( + exactRetry.sources().stream() + .map(source -> Base64.getEncoder().encodeToString(source.canonicalBytes())) + .toList()) + .isEqualTo( + first.sources().stream() + .map(source -> Base64.getEncoder().encodeToString(source.canonicalBytes())) + .toList()); + + var changedPreparation = + preparationInput( + NAMESPACE, + account.tenant, + requestId, + gameInstanceId, + "changed-owner-proof-world", + ORIGINAL_GAME_TEMPLATE_ID); + var changedCandidate = + candidate( + originalTuple, + capture, + gameInstanceId, + gameSessionAttemptId, + gameSessionOwnerFence, + changedPreparation, + digest(changedPreparation)); + assertThatThrownBy( + () -> + withWorldCurrentness( + operatorAuthorization, + originalTuple, + gameSessionAttemptId, + gameSessionOwnerFence, + ignored -> repository.createOrReadExact(changedCandidate))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("StartSession World participation conflicts with its immutable binding"); + assertThatThrownBy( + () -> + withWorldCurrentness( + operatorAuthorization, + originalTuple, + UUID.randomUUID(), + gameSessionOwnerFence, + ignored -> repository.createOrReadExact(initialCandidate.get()))) + .isInstanceOf(IllegalStateException.class); + + assertThatThrownBy(() -> repository.createOrReadExact(initialCandidate.get())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Writable Account READ_COMMITTED transaction required"); + + long fenceSequenceBeforeHistoricalRead = participationFenceSequence(account.dsl); + StoredParticipation historical = + account.tx( + () -> + repository + .findHistoricalExact(first.participationId(), first.participationFence()) + .orElseThrow()); + long fenceSequenceAfterHistoricalRead = participationFenceSequence(account.dsl); + assertThat(historical.participationId()).isEqualTo(first.participationId()); + assertThat(historical.participationFence()).isEqualTo(first.participationFence()); + assertThat(historical.originalPostAuthorizationTuple()) + .containsExactly(first.originalPostAuthorizationTuple()); + assertThat( + historical.sources().stream() + .map(source -> Base64.getEncoder().encodeToString(source.canonicalBytes())) + .toList()) + .isEqualTo( + first.sources().stream() + .map(source -> Base64.getEncoder().encodeToString(source.canonicalBytes())) + .toList()); + assertThat(fenceSequenceAfterHistoricalRead).isEqualTo(fenceSequenceBeforeHistoricalRead); + var issuanceAfterHistoricalRead = + account.tx(() -> operatorRepository.findByControlPlaneRequestId(requestId).orElseThrow()); + assertThat(issuanceAfterHistoricalRead.referenceExpiresAt()) + .isEqualTo(redeemed.referenceExpiresAt()); + assertThat(issuanceAfterHistoricalRead.responseEnvelopeExpiresAt()) + .isEqualTo(redeemed.responseEnvelopeExpiresAt()); + assertThat(account.tx(() -> repository.findHistoricalExact(UUID.randomUUID(), 1L))).isEmpty(); + + var committedTerminal = + terminal(first, WorldStartSessionExecutionTerminal.Outcome.COMMITTED, 73L); + StoredSettlement committed = account.tx(() -> repository.settleExact(committedTerminal)); + StoredSettlement exactSettlementRetry = + account.tx(() -> repository.settleExact(committedTerminal)); + assertThat(committed.participationId()).isEqualTo(first.participationId()); + assertThat(committed.outcome()) + .isEqualTo(WorldStartSessionExecutionTerminal.Outcome.COMMITTED); + assertThat(committed.worldExecutionFence()).isEqualTo(73L); + assertThat(exactSettlementRetry.terminalBytes()).containsExactly(committed.terminalBytes()); + assertThat(exactSettlementRetry.terminalDigest()).isEqualTo(committed.terminalDigest()); + assertThat( + account + .tx( + () -> + repository + .findSettlementExact( + first.participationId(), first.participationFence()) + .orElseThrow()) + .terminalBytes()) + .containsExactly(committed.terminalBytes()); + + var conflictingTerminal = + terminal(first, WorldStartSessionExecutionTerminal.Outcome.ABORTED, 74L); + assertThatThrownBy(() -> account.tx(() -> repository.settleExact(conflictingTerminal))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("StartSession World participation conflicts with its immutable binding"); + assertGuardRejected( + () -> + account.dsl.execute( + "UPDATE account_start_session_world_participation_settlements " + + "SET outcome = 'ABORTED' WHERE participation_id = ?", + first.participationId()), + "StartSession World participation evidence is append-only"); + assertThat( + account.tx( + () -> + repository + .findSettlementExact(first.participationId(), first.participationFence()) + .orElseThrow() + .terminalBytes())) + .containsExactly(committed.terminalBytes()); + + var absentParentTerminal = + new WorldStartSessionExecutionTerminal( + first.originalPostAuthorizationTuple(), + UUID.randomUUID(), + first.participationFence() + 1L, + first.gameSessionOwnerAttemptId(), + first.gameSessionOwnerFence(), + first.targetNamespace(), + first.canonicalTenantId(), + first.controlPlaneRequestId(), + first.canonicalGameInstanceId(), + first.preparationInputDigest(), + first.preparationInputJson(), + 75L, + WorldStartSessionExecutionTerminal.Outcome.COMMITTED); + assertThatThrownBy(() -> account.tx(() -> repository.settleExact(absentParentTerminal))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Exact StartSession World participation evidence unavailable"); + assertThat( + account.tx( + () -> + repository.findSettlementExact( + absentParentTerminal.accountWorldParticipationId(), + absentParentTerminal.accountWorldParticipationFence()))) + .isEmpty(); + + // The terminal is a typed test collaborator. Its validity proves Account storage binding, + // not a World producer, Game Session owner, transport peer, or execution result. + assertThat(account.dsl.fetchCount(DSL.table("account_start_session_world_participations"))) + .isEqualTo(1); + assertThat( + account.dsl.fetchCount( + DSL.table("account_start_session_world_participation_sources"))) + .isEqualTo(first.sources().size()); + assertThat( + account.dsl.fetchCount( + DSL.table("account_start_session_world_participation_settlements"))) + .isEqualTo(1); + } + } + + private static void assertGuardRejected( + org.assertj.core.api.ThrowableAssert.ThrowingCallable action, String expectedDiagnostic) { + assertThatThrownBy(action) + .satisfies( + failure -> { + SQLException sqlFailure = findSqlException(failure); + assertThat(sqlFailure.getSQLState()).isEqualTo("23514"); + if (!(sqlFailure instanceof org.postgresql.util.PSQLException postgresFailure)) { + throw new AssertionError( + "Participation settlement guard rejection must be a PostgreSQL exception", + sqlFailure); + } + var serverError = postgresFailure.getServerErrorMessage(); + assertThat(serverError).isNotNull(); + assertThat(serverError.getMessage()).isEqualTo(expectedDiagnostic); + }); + } + + private static SQLException findSqlException(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sqlException) return sqlException; + } + throw new AssertionError("Guard rejection must retain its SQL exception", failure); + } + + private static Candidate candidate( + StartSessionPostAuthorizationExecutionTuple originalTuple, + AccountStartSessionAuthorityCapture capture, + UUID gameInstanceId, + UUID gameSessionAttemptId, + long gameSessionOwnerFence, + String preparationInputJson, + String preparationInputDigest) { + return new Candidate( + originalTuple, + capture, + gameInstanceId, + gameSessionAttemptId, + gameSessionOwnerFence, + preparationInputJson, + preparationInputDigest); + } + + /** + * Stipulated structurally complete identity/descriptor envelope for Account storage validation. + * The echoed World and Game Session fields are test input, not authenticated producer evidence. + */ + private static String preparationInput( + String namespace, + UUID tenantId, + String requestId, + UUID gameInstanceId, + String worldSlug, + long gameTemplateId) + throws Exception { + String descriptorJson = JSON.writeValueAsString(Map.of("gameTemplateId", gameTemplateId)); + return JSON.writeValueAsString( + Map.of( + "schemaVersion", + 1, + "identity", + Map.of( + "targetNamespace", + namespace, + "canonicalTenantId", + tenantId.toString(), + "controlPlaneRequestId", + requestId, + "canonicalGameInstanceId", + gameInstanceId.toString(), + "worldSlug", + worldSlug), + "gameSessionReadRequest", + Map.of( + "targetNamespace", + namespace, + "canonicalTenantId", + tenantId.toString(), + "controlPlaneRequestId", + requestId, + "canonicalGameInstanceId", + gameInstanceId.toString(), + "worldSlug", + worldSlug), + "gameSessionReadEvidence", + Map.of( + "targetNamespace", + namespace, + "canonicalTenantId", + tenantId.toString(), + "controlPlaneRequestId", + requestId, + "canonicalGameInstanceId", + gameInstanceId.toString(), + "worldSlug", + worldSlug, + "descriptorJson", + descriptorJson), + "launchBinding", + Map.of( + "targetNamespace", + namespace, + "canonicalTenantId", + tenantId.toString(), + "controlPlaneRequestId", + requestId, + "worldSlug", + worldSlug))); + } + + private static WorldStartSessionExecutionTerminal terminal( + StoredParticipation participation, + WorldStartSessionExecutionTerminal.Outcome outcome, + long worldExecutionFence) { + return new WorldStartSessionExecutionTerminal( + participation.originalPostAuthorizationTuple(), + participation.participationId(), + participation.participationFence(), + participation.gameSessionOwnerAttemptId(), + participation.gameSessionOwnerFence(), + participation.targetNamespace(), + participation.canonicalTenantId(), + participation.controlPlaneRequestId(), + participation.canonicalGameInstanceId(), + participation.preparationInputDigest(), + participation.preparationInputJson(), + worldExecutionFence, + outcome); + } + + private static T withWorldCurrentness( + AccountStartSessionOperatorAuthorizationService operatorAuthorization, + StartSessionPostAuthorizationExecutionTuple originalTuple, + UUID gameSessionAttemptId, + long gameSessionOwnerFence, + Function callback) { + try (var ignored = AccountControlUiOwnerSourcesFixture.withPeer(WORLD_PEER_URI)) { + return operatorAuthorization.withCurrentWorldReceivingParticipationCurrentness( + originalTuple.canonicalBytes(), gameSessionAttemptId, gameSessionOwnerFence, callback); + } + } + + private static T withPeer(String peerUri, java.util.concurrent.Callable action) { + try (var ignored = AccountControlUiOwnerSourcesFixture.withPeer(peerUri)) { + return action.call(); + } catch (RuntimeException failure) { + throw failure; + } catch (Exception failure) { + throw new IllegalStateException("Test peer-scoped Account owner action failed", failure); + } + } + + private static ReadCurrentClaimEvidenceResponse stipulatedLoggingClaim( + StartSessionPreAuthorizationReservationTuple tuple, + UUID reservationOwnerId, + long reservationClaimFence, + Instant now) { + return ReadCurrentClaimEvidenceResponse.newBuilder() + .setControlPlaneRequestId(tuple.controlPlaneRequestId()) + .setPreAuthorizationTupleJson( + com.google.protobuf.ByteString.copyFrom(tuple.canonicalJson(), StandardCharsets.UTF_8)) + .setMutationDigest(tuple.mutationDigest()) + .setReservationOwnerId(reservationOwnerId.toString()) + .setReservationClaimFence(reservationClaimFence) + .setClaimOwnerId(reservationOwnerId.toString()) + .setClaimFence(reservationClaimFence) + .setObservedAtEpochMillis(now.minusSeconds(1).toEpochMilli()) + .setClaimExpiresAtEpochMillis(now.plus(Duration.ofMinutes(5)).toEpochMilli()) + .setPurpose( + StartSessionReservationEvidencePurpose.START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE) + .build(); + } + + private static AccountOperatorAuthorizationFingerprintKeyring fingerprintKeys() { + byte[] key = new byte[32]; + Arrays.fill(key, (byte) 0x51); + return new AccountOperatorAuthorizationFingerprintKeyring( + () -> + new Snapshot( + new KeyMaterial("test-active", new SecretKeySpec(key, "HmacSHA256")), List.of()), + Clock.systemUTC(), + Duration.ofMinutes(2)); + } + + private static AccountResponseEnvelopeCryptography responseCryptography(Path temporary) + throws Exception { + byte[] key = new byte[32]; + Arrays.fill(key, (byte) 0x26); + Path root = Files.createDirectories(temporary.resolve("operator-response-envelope")); + Files.writeString( + root.resolve("keyring"), + "firemud-account-response-envelope-keyring-v1\nactive test-response " + + Base64.getUrlEncoder().withoutPadding().encodeToString(key) + + "\n"); + return new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring(root.toString()), Clock.systemUTC(), new SecureRandom()); + } + + private static Map captureSnapshot(AccountStartSessionAuthorityCapture capture) + throws Exception { + return JSON.readValue(capture.snapshotBytes(), new TypeReference<>() {}); + } + + @SuppressWarnings("unchecked") + private static List capturedSourceVector(AccountStartSessionAuthorityCapture capture) + throws Exception { + return (List) captureSnapshot(capture).get("sourceVector"); + } + + private static long participationFenceSequence(DSLContext dsl) { + String sequence = + java.util.Objects.requireNonNull( + java.util.Objects.requireNonNull( + dsl.fetchOne( + "SELECT pg_get_serial_sequence(" + + "'account_start_session_world_participations', 'participation_fence')")) + .get(0, String.class)); + return java.util.Objects.requireNonNull( + java.util.Objects.requireNonNull(dsl.fetchOne("SELECT last_value FROM " + sequence)) + .get(0, Long.class)); + } + + private static String digest(String value) throws Exception { + return "sha256:" + + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(StandardCharsets.UTF_8))); + } + + private static void assertActiveReadCommittedTransaction() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceWorldParticipationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceWorldParticipationTest.java new file mode 100644 index 0000000000..110290b1c5 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceWorldParticipationTest.java @@ -0,0 +1,288 @@ +package unit.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.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; + +import java.sql.Connection; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import org.jooq.ConnectionRunnable; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.Result; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Synthetic unit proof for Account's World-participation exclusion seam. */ +class DraftAuthorizationFenceWorldParticipationTest { + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void worldParticipationAdmissionRequiresWritableReadCommittedOwnerTransaction() throws Exception { + Fixture fixture = new Fixture(false); + + assertThatThrownBy( + () -> + fixture.repository.requireWorldParticipationDisclosureAdmission( + List.of(fixture.source))) + .isInstanceOf(IllegalStateException.class); + + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertThatThrownBy( + () -> + fixture.repository.requireWorldParticipationDisclosureAdmission( + List.of(fixture.source))) + .isInstanceOf(IllegalStateException.class); + + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + fixture.begin(); + fixture.autoCommit = true; + assertThatThrownBy( + () -> + fixture.repository.requireWorldParticipationDisclosureAdmission( + List.of(fixture.source))) + .isInstanceOf(IllegalStateException.class); + + fixture.autoCommit = false; + fixture.isolation = Connection.TRANSACTION_REPEATABLE_READ; + assertThatThrownBy( + () -> + fixture.repository.requireWorldParticipationDisclosureAdmission( + List.of(fixture.source))) + .isInstanceOf(IllegalStateException.class); + + assertThat(fixture.lockedKeys).isEmpty(); + } + + @Test + void pendingWorldParticipationBlocksDisclosureAdmissionAndChecksSortedExactKeys() + throws Exception { + Fixture fixture = new Fixture(true); + fixture.begin(); + SourceEvidence first = source("a-first"); + SourceEvidence second = source("z-second"); + fixture.pendingWorldKey = second.key(); + + assertThatThrownBy( + () -> + fixture.repository.requireWorldParticipationDisclosureAdmission( + List.of(second, first))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("World participation remains pending"); + + assertThat(fixture.lockedKeys).containsExactly(first.key(), second.key()); + assertThat(fixture.worldKeys).containsExactly(first.key(), second.key()); + assertThat(fixture.eventOrder) + .containsExactly( + "lock:" + first.key(), + "lock-row:" + first.key(), + "lock:" + second.key(), + "lock-row:" + second.key(), + "world:" + first.key(), + "world:" + second.key()); + assertThat(fixture.worldSql.getFirst()) + .contains("JOIN account_start_session_world_participations") + .contains("NOT account_start_session_world_participation_is_settled"); + } + + @Test + void disclosurePreparationRejectsPendingWorldParticipationWithoutOwnerOperationReads() + throws Exception { + Fixture fixture = new Fixture(true); + fixture.begin(); + + assertThatThrownBy( + () -> fixture.repository.requireDisclosurePreparation(List.of(fixture.source))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("World participation remains pending"); + + assertThat(fixture.worldKeys).containsExactly(fixture.source.key()); + assertThat(fixture.fetchedSql) + .anyMatch(statement -> statement.contains("account_draft_authorization_source_changes")) + .anyMatch(statement -> statement.contains("account_selected_publication_sources")) + .anyMatch(statement -> statement.contains("account_game_logic_intake_sources")); + assertThat(fixture.fetchedSql) + .noneMatch( + statement -> + statement.contains("account_draft_authorization_fences") + || statement.contains( + "SELECT operation_id FROM account_draft_authorization_sources")); + assertThat(fixture.sql).noneMatch(statement -> statement.contains("UPDATE ")); + } + + @Test + void pendingWorldParticipationBlocksSourceMutationAndAbortWhileSettledKeepsPriorAdmission() + throws Exception { + Fixture pending = new Fixture(true); + pending.begin(); + SourceChange pendingChange = sourceChange(pending.source); + pending.installWaitingChange(pendingChange); + + assertThat(pending.repository.sourceMutationPermitted(pendingChange)).isFalse(); + assertThat(pending.repository.sourceAbortPermitted(pendingChange)).isFalse(); + assertThat(pending.sql).noneMatch(statement -> statement.contains("UPDATE ")); + + Fixture settled = new Fixture(false); + settled.begin(); + SourceChange settledChange = sourceChange(settled.source); + settled.installWaitingChange(settledChange); + + assertThat(settled.repository.sourceMutationPermitted(settledChange)).isTrue(); + assertThat(settled.repository.sourceAbortPermitted(settledChange)).isTrue(); + assertThat(settled.worldKeys).containsExactly(settled.source.key(), settled.source.key()); + } + + @Test + void disclosureSourceLockPreservesTheExisting512ByteBoundWithoutAliasing() throws Exception { + Fixture fixture = new Fixture(false); + fixture.begin(); + SourceEvidence boundary = source("x".repeat(499)); + assertThat(boundary.key().getBytes(java.nio.charset.StandardCharsets.UTF_8)).hasSize(512); + + fixture.repository.lockDisclosureSources(List.of(boundary)); + + assertThat(fixture.lockedKeys).containsExactly(boundary.key()); + assertThatThrownBy( + () -> fixture.repository.lockDisclosureSources(List.of(source("x".repeat(500))))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("existing Account source-lock bound"); + } + + private static SourceChange sourceChange(SourceEvidence source) { + return new SourceChange(UUID.randomUUID(), List.of(source), new byte[] {1, 2, 3}); + } + + private static SourceEvidence source(String scope) { + return new SourceEvidence( + SourceKind.HOSTED_TERMS, scope, null, "1", null, null, new byte[] {4, 5, 6}); + } + + private static final class Fixture { + private final DSLContext dsl = mock(DSLContext.class); + private final Connection connection = mock(Connection.class); + private final SourceEvidence source = source("world-participation-test"); + private final DraftAuthorizationFenceRepository repository = + new DraftAuthorizationFenceRepository(dsl); + private final List lockedKeys = new ArrayList<>(); + private final List worldKeys = new ArrayList<>(); + private final List worldSql = new ArrayList<>(); + private final List eventOrder = new ArrayList<>(); + private final List sql = new ArrayList<>(); + private final List fetchedSql = new ArrayList<>(); + private final Result emptyRows = rows(true); + private final Result matchingRows = rows(false); + private final Record lockRow = mock(Record.class); + private final Record changeRow = mock(Record.class); + private final boolean worldPending; + private boolean autoCommit; + private String pendingWorldKey; + private int isolation = Connection.TRANSACTION_READ_COMMITTED; + private Result changedRows = emptyRows; + + private Fixture(boolean worldPending) throws Exception { + this.worldPending = worldPending; + doAnswer(invocation -> autoCommit).when(connection).getAutoCommit(); + doAnswer(invocation -> false).when(connection).isReadOnly(); + doAnswer(invocation -> isolation).when(connection).getTransactionIsolation(); + doAnswer( + invocation -> { + invocation.getArgument(0).run(connection); + return null; + }) + .when(dsl) + .connection(any(ConnectionRunnable.class)); + doAnswer( + invocation -> { + String statement = invocation.getArgument(0); + sql.add(statement); + if (statement.startsWith("INSERT INTO account_draft_authorization_source_locks")) { + String sourceKey = invocation.getArgument(1, String.class); + lockedKeys.add(sourceKey); + eventOrder.add("lock:" + sourceKey); + } + return 1; + }) + .when(dsl) + .execute(anyString(), any(Object[].class)); + doAnswer( + invocation -> { + String statement = invocation.getArgument(0); + fetchedSql.add(statement); + if (statement.contains("account_start_session_world_participation_sources")) { + String sourceKey = invocation.getArgument(1, String.class); + worldKeys.add(sourceKey); + worldSql.add(statement); + eventOrder.add("world:" + sourceKey); + return worldPending + && (pendingWorldKey == null || pendingWorldKey.equals(sourceKey)) + ? matchingRows + : emptyRows; + } + if (statement.contains("account_draft_authorization_changed_scopes")) { + return changedRows; + } + return emptyRows; + }) + .when(dsl) + .fetch(anyString(), any(Object[].class)); + doAnswer( + invocation -> { + String statement = invocation.getArgument(0); + fetchedSql.add(statement); + if (statement.contains("account_draft_authorization_source_changes")) { + return changeRow; + } + if (statement.contains("account_draft_authorization_source_locks")) { + String sourceKey = invocation.getArgument(1, String.class); + eventOrder.add("lock-row:" + sourceKey); + } + return lockRow; + }) + .when(dsl) + .fetchOne(anyString(), any(Object[].class)); + } + + private void begin() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } + + private void installWaitingChange(SourceChange change) { + doReturn(change.canonicalBytes()).when(changeRow).get("binding", byte[].class); + doReturn("WAITING").when(changeRow).get("status", String.class); + changedRows = rowsWithSource(change.sources().getFirst().key()); + } + } + + @SuppressWarnings("unchecked") + private static Result rows(boolean empty) { + Result result = mock(Result.class); + doReturn(empty).when(result).isEmpty(); + doReturn(List.of()).when(result).getValues("operation_id", UUID.class); + doReturn(List.of()).when(result).getValues("source_key", String.class); + return result; + } + + @SuppressWarnings("unchecked") + private static Result rowsWithSource(String sourceKey) { + Result result = mock(Result.class); + doReturn(List.of(sourceKey)).when(result).getValues("source_key", String.class); + doReturn(false).when(result).isEmpty(); + return result; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java index fbdffb7bb8..b674202308 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java @@ -160,7 +160,6 @@ void rejectsEveryResponseIdentityFieldUnknownFieldsAndStaleTimes() throws Except .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_RECOVER) .build(), valid.toBuilder().setObservedAtEpochMillis(0L).build(), - valid.toBuilder().setObservedAtEpochMillis(NOW_EPOCH_MILLIS + 1L).build(), valid.toBuilder() .setClaimExpiresAtEpochMillis(valid.getObservedAtEpochMillis()) .build(), @@ -189,6 +188,35 @@ void rejectsEveryResponseIdentityFieldUnknownFieldsAndStaleTimes() throws Except } } + @Test + void acceptsProducerObservationAfterLocalNowWhenClaimRemainsOrderedAndUnexpired() + throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple(); + AtomicReference response = new AtomicReference<>(); + try (InProcessFixture fixture = inProcessFixture(request -> response.get())) { + StartSessionReservationEvidenceClient client = client(fixture.stub()); + ReadCurrentClaimEvidenceResponse futureObservation = + validResponse( + request(tuple, StartSessionReservationEvidenceClient.Purpose.ISSUE), + tuple.mutationDigest()) + .toBuilder() + .setObservedAtEpochMillis(NOW_EPOCH_MILLIS + 1L) + .setClaimExpiresAtEpochMillis(NOW_EPOCH_MILLIS + 30_000L) + .build(); + response.set(futureObservation); + + assertThat( + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .isEqualTo(futureObservation); + } + } + @Test void invalidInputIsRejectedBeforeAnyRpc() throws Exception { StartSessionPreAuthorizationReservationTuple tuple = tuple(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java index 591d17a77f..1bbffbc433 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java @@ -18,7 +18,9 @@ import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.Snapshot; import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography; import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeKeyring; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionAuthorityCaptureRepository; import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService; +import org.jooq.DSLContext; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.convert.ApplicationConversionService; @@ -62,6 +64,8 @@ void ownerCompositionIsAbsentWhenTheOptInIsMissingOrFalse() { assertThat(context) .doesNotHaveBean(AccountOperatorAuthorizationFingerprintKeyring.class); assertThat(context).doesNotHaveBean(AccountResponseEnvelopeCryptography.class); + assertThat(context) + .doesNotHaveBean(AccountStartSessionAuthorityCaptureRepository.class); }); contextRunner() @@ -72,6 +76,8 @@ void ownerCompositionIsAbsentWhenTheOptInIsMissingOrFalse() { assertThat(context).hasNotFailed(); assertThat(context) .doesNotHaveBean(AccountStartSessionOperatorAuthorizationService.class); + assertThat(context) + .doesNotHaveBean(AccountStartSessionAuthorityCaptureRepository.class); }); } @@ -97,7 +103,7 @@ private static boolean reservationEvidenceClientBeanDefinition(String enabled) { } @Test - void explicitOptInFailsForTheMissingOwnerDependency() { + void explicitOptInFailsClosedWhenOwnerAndKeySourcesAreUnavailable() { contextRunner() .withUserConfiguration( AccountStartSessionOperatorAuthorizationConfiguration.class, @@ -127,6 +133,9 @@ void explicitOptInUsesSuppliedCollaboratorsAndQualifiedOperatorCryptography() { assertThat(context).hasNotFailed(); assertThat(context) .hasSingleBean(AccountStartSessionOperatorAuthorizationService.class); + assertThat(context).hasSingleBean(DSLContext.class); + assertThat(context) + .hasSingleBean(AccountStartSessionAuthorityCaptureRepository.class); assertThat(context) .hasSingleBean(AccountOperatorAuthorizationFingerprintKeyring.class); assertThat(context.getBeansOfType(AccountResponseEnvelopeCryptography.class)) @@ -134,6 +143,11 @@ void explicitOptInUsesSuppliedCollaboratorsAndQualifiedOperatorCryptography() { .containsKeys( "genericAccountResponseEnvelopeCryptography", OPERATOR_RESPONSE_CRYPTOGRAPHY_BEAN); + assertThat( + ReflectionTestUtils.getField( + context.getBean(AccountStartSessionAuthorityCaptureRepository.class), + "dsl")) + .isSameAs(context.getBean(DSLContext.class)); AccountResponseEnvelopeCryptography genericCryptography = context.getBean( @@ -271,6 +285,11 @@ AccountControlUiIssuanceRepository issuanceOperations() { return mock(AccountControlUiIssuanceRepository.class); } + @Bean + DSLContext accountDsl() { + return mock(DSLContext.class); + } + @Bean StartSessionReservationEvidenceClient reservationEvidence() { return mock(StartSessionReservationEvidenceClient.class); @@ -308,6 +327,11 @@ AccountControlUiIssuanceRepository issuanceOperations() { return mock(AccountControlUiIssuanceRepository.class); } + @Bean + DSLContext accountDsl() { + return mock(DSLContext.class); + } + @Bean StartSessionReservationEvidenceClient reservationEvidence() { return mock(StartSessionReservationEvidenceClient.class); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffTest.java new file mode 100644 index 0000000000..9cf194dec4 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffTest.java @@ -0,0 +1,217 @@ +package unit.net.firedevops.firemud.accountservice.hostedterms; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsDisclosureHandoff; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsDisclosureHandoff.DisclosureResult; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsDisclosureHandoff.Kind; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsDisclosureHandoff.Outcome; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEncoding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import org.junit.jupiter.api.Test; + +class HostedTermsDisclosureHandoffTest { + @Test + void canonicalBindingSortsCompleteSourceVectorAndCopiesEveryArray() { + byte[] hostedEvidence = new byte[] {1, 2, 3}; + byte[] tenantEvidence = new byte[] {4, 5, 6}; + SourceEvidence hosted = + new SourceEvidence( + SourceKind.HOSTED_TERMS, + UUID.randomUUID().toString(), + null, + "7", + null, + null, + hostedEvidence); + SourceEvidence tenant = + new SourceEvidence( + SourceKind.TENANT, UUID.randomUUID().toString(), "3", "8", null, null, tenantEvidence); + hostedEvidence[0] = 99; + tenantEvidence[0] = 99; + byte[] authorityBytes = "test-only-authority-evidence".getBytes(StandardCharsets.UTF_8); + HostedTermsDisclosureHandoff handoff = handoff(hosted, tenant, authorityBytes); + authorityBytes[0] = 99; + + assertThat(handoff.sources().stream().map(SourceEvidence::key).toList()) + .containsExactly(hosted.key(), tenant.key()); + assertThat(handoff.sources().getFirst().evidence()).containsExactly(1, 2, 3); + assertThat(handoff.authenticatedAuthorityEvidence()) + .containsExactly("test-only-authority-evidence".getBytes(StandardCharsets.UTF_8)); + + byte[] returned = handoff.authenticatedAuthorityEvidence(); + returned[0] = 88; + SourceEvidence returnedSource = handoff.sources().getFirst(); + byte[] returnedSourceBytes = returnedSource.evidence(); + returnedSourceBytes[0] = 77; + assertThat(handoff.authenticatedAuthorityEvidence()) + .containsExactly("test-only-authority-evidence".getBytes(StandardCharsets.UTF_8)); + assertThat(handoff.sources().getFirst().evidence()).containsExactly(1, 2, 3); + assertThat(HostedTermsDisclosureHandoff.fromStored(handoff.canonicalBytes()).canonicalBytes()) + .containsExactly(handoff.canonicalBytes()); + } + + @Test + void exactDigestBindsEveryDisclosureFieldAndRejectsChangedOrMalformedInputs() { + SourceEvidence source = hostedSource("source-v7"); + HostedTermsDisclosureHandoff original = + new HostedTermsDisclosureHandoff( + UUID.randomUUID(), + UUID.randomUUID(), + Kind.CATALOG, + source.key(), + HostedTermsEncoding.digest(new byte[] {1}), + HostedTermsEncoding.digest(new byte[] {2}), + Instant.parse("2026-10-08T00:00:00.123456Z"), + List.of(source), + "test-only-authority-evidence".getBytes(StandardCharsets.UTF_8)); + + String originalDigest = HostedTermsEncoding.digest(original.canonicalBytes()); + assertThat(originalDigest) + .isNotEqualTo(HostedTermsEncoding.digest(changed(original, "candidate").canonicalBytes())) + .isNotEqualTo(HostedTermsEncoding.digest(changed(original, "effectiveAt").canonicalBytes())) + .isNotEqualTo(HostedTermsEncoding.digest(changed(original, "requestId").canonicalBytes())) + .isNotEqualTo( + HostedTermsEncoding.digest(changed(original, "authorityEvidence").canonicalBytes())); + assertThatThrownBy( + () -> + new HostedTermsDisclosureHandoff( + UUID.randomUUID(), + UUID.randomUUID(), + Kind.CATALOG, + source.key(), + original.predecessorDigest(), + original.candidateDigest(), + Instant.parse("2026-10-08T00:00:00.123456789Z"), + List.of(source), + new byte[] {1})) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("microsecond"); + assertThatThrownBy( + () -> + new HostedTermsDisclosureHandoff( + original.handoffId(), + original.requestId(), + original.kind(), + original.sourceKey(), + original.predecessorDigest(), + original.candidateDigest(), + original.effectiveAt(), + List.of(source, source), + new byte[] {1})) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Distinct complete sorted source evidence"); + byte[] trailing = + java.util.Arrays.copyOf(original.canonicalBytes(), original.canonicalBytes().length + 1); + assertThatThrownBy(() -> HostedTermsDisclosureHandoff.fromStored(trailing)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void disclosureResultPreservesBindingDigestAndCopiesAuthenticatedBytes() { + SourceEvidence source = hostedSource("source-result"); + HostedTermsDisclosureHandoff handoff = handoff(source, null, new byte[] {9}); + byte[] evidence = "test-only-authenticated-owner-readback".getBytes(StandardCharsets.UTF_8); + DisclosureResult result = + new DisclosureResult( + handoff.handoffId(), + handoff.requestId(), + HostedTermsEncoding.digest(handoff.canonicalBytes()), + Outcome.DISCLOSED, + evidence); + evidence[0] = 0; + + assertThat(result.authenticatedEvidence()) + .containsExactly("test-only-authenticated-owner-readback".getBytes(StandardCharsets.UTF_8)); + assertThat(DisclosureResult.fromStored(result.canonicalBytes()).canonicalBytes()) + .containsExactly(result.canonicalBytes()); + String changedBindingDigest = HostedTermsEncoding.digest(new byte[] {4}); + DisclosureResult changedBinding = + new DisclosureResult( + handoff.handoffId(), + handoff.requestId(), + changedBindingDigest, + Outcome.DISCLOSED, + new byte[] {1}); + assertThat(changedBinding.bindingDigest()).isEqualTo(changedBindingDigest); + assertThat(changedBinding.canonicalBytes()).isNotEqualTo(result.canonicalBytes()); + } + + @Test + void environmentBindingUsesItsIndependentNamespacedHostedTermsSource() { + SourceEvidence boundary = + new SourceEvidence( + SourceKind.HOSTED_TERMS, + "environment-boundary/production", + null, + "9", + null, + null, + new byte[] {6, 7}); + HostedTermsDisclosureHandoff handoff = + new HostedTermsDisclosureHandoff( + UUID.randomUUID(), + UUID.randomUUID(), + Kind.ENVIRONMENT_BINDING, + boundary.key(), + HostedTermsEncoding.digest(new byte[] {4}), + HostedTermsEncoding.digest(new byte[] {5}), + Instant.parse("2026-10-08T00:00:00Z"), + List.of(boundary), + "test-only-authority-evidence".getBytes(StandardCharsets.UTF_8)); + assertThat(handoff.sourceKey()).isEqualTo("HOSTED_TERMS:environment-boundary/production"); + assertThat(HostedTermsDisclosureHandoff.fromStored(handoff.canonicalBytes()).kind()) + .isEqualTo(Kind.ENVIRONMENT_BINDING); + } + + private static HostedTermsDisclosureHandoff handoff( + SourceEvidence primary, SourceEvidence additional, byte[] authorityEvidence) { + return new HostedTermsDisclosureHandoff( + UUID.randomUUID(), + UUID.randomUUID(), + Kind.CATALOG, + primary.key(), + HostedTermsEncoding.digest(new byte[] {1}), + HostedTermsEncoding.digest(new byte[] {2}), + Instant.parse("2026-10-08T00:00:00.123456Z"), + additional == null ? List.of(primary) : List.of(additional, primary), + authorityEvidence); + } + + private static SourceEvidence hostedSource(String scope) { + return new SourceEvidence( + SourceKind.HOSTED_TERMS, + UUID.nameUUIDFromBytes(scope.getBytes(StandardCharsets.UTF_8)).toString(), + null, + "7", + null, + null, + new byte[] {3, 4, 5}); + } + + private static HostedTermsDisclosureHandoff changed( + HostedTermsDisclosureHandoff original, String field) { + return new HostedTermsDisclosureHandoff( + original.handoffId(), + field.equals("requestId") ? UUID.randomUUID() : original.requestId(), + original.kind(), + original.sourceKey(), + original.predecessorDigest(), + field.equals("candidate") + ? HostedTermsEncoding.digest(new byte[] {3}) + : original.candidateDigest(), + field.equals("effectiveAt") + ? original.effectiveAt().plusSeconds(1) + : original.effectiveAt(), + original.sources(), + field.equals("authorityEvidence") + ? new byte[] {42} + : original.authenticatedAuthorityEvidence()); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffWorldParticipationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffWorldParticipationTest.java new file mode 100644 index 0000000000..ff03a440a1 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffWorldParticipationTest.java @@ -0,0 +1,293 @@ +package net.firedevops.firemud.accountservice.hostedterms; + +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.doReturn; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.sql.Connection; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsDisclosureHandoff.Kind; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsDisclosureHandoffRepository.Status; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import org.jooq.ConnectionRunnable; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.Result; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Synthetic repository-unit proof for the disclosure/World-participation seam. */ +class HostedTermsDisclosureHandoffWorldParticipationTest { + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void preparationDeniesPendingWorldParticipationBeforeWritingDisclosureJournal() throws Exception { + Fixture fixture = new Fixture(Status.PREPARED, false); + fixture.begin(); + doAnswer( + invocation -> { + throw new IllegalStateException( + "Original StartSession World participation remains pending"); + }) + .when(fixture.fenceRepository) + .requireDisclosurePreparation(fixture.handoff.sources()); + + assertThatThrownBy(() -> fixture.repository.prepare(fixture.handoff)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("World participation remains pending"); + + verify(fixture.fenceRepository).lockDisclosureSources(fixture.handoff.sources()); + verify(fixture.fenceRepository).requireDisclosurePreparation(fixture.handoff.sources()); + assertThat(fixture.executedSql).isEmpty(); + } + + @Test + void dispatchDenialLocksSourcesBeforeReadingJournalAndDoesNotAdvanceAmbiguousRetry() + throws Exception { + Fixture fixture = new Fixture(Status.AMBIGUOUS, true); + fixture.begin(); + doAnswer( + invocation -> { + throw new IllegalStateException( + "Original StartSession World participation remains pending"); + }) + .when(fixture.fenceRepository) + .requireWorldParticipationDisclosureAdmission(fixture.handoff.sources()); + + assertThatThrownBy(() -> fixture.repository.authorizeDispatch(fixture.handoff)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("World participation remains pending"); + + verify(fixture.fenceRepository) + .requireWorldParticipationDisclosureAdmission(fixture.handoff.sources()); + verify(fixture.fenceRepository).lockDisclosureSources(fixture.handoff.sources()); + verify(fixture.fenceRepository, never()) + .requireDisclosurePreparation(fixture.handoff.sources()); + var order = inOrder(fixture.fenceRepository, fixture.dsl); + order.verify(fixture.fenceRepository).lockDisclosureSources(fixture.handoff.sources()); + order.verify(fixture.dsl, times(2)).fetch(anyString(), any(Object[].class)); + order + .verify(fixture.fenceRepository) + .requireWorldParticipationDisclosureAdmission(fixture.handoff.sources()); + assertThat(fixture.journalReads).isEqualTo(1); + assertThat(fixture.executedSql).isEmpty(); + } + + @Test + void settledWorldParticipationKeepsAmbiguousRetryAndSourceLockOrdering() throws Exception { + Fixture fixture = new Fixture(Status.AMBIGUOUS, true); + fixture.begin(); + + var permit = fixture.repository.authorizeDispatch(fixture.handoff); + + assertThat(permit.newlyAuthorized()).isTrue(); + assertThat(permit.snapshot().status()).isEqualTo(Status.DISPATCH_AUTHORIZED); + assertThat(permit.snapshot().dispatchAttempts()).isEqualTo(3); + var order = inOrder(fixture.fenceRepository, fixture.dsl); + order.verify(fixture.fenceRepository).lockDisclosureSources(fixture.handoff.sources()); + order.verify(fixture.dsl, times(2)).fetch(anyString(), any(Object[].class)); + order + .verify(fixture.fenceRepository) + .requireWorldParticipationDisclosureAdmission(fixture.handoff.sources()); + order.verify(fixture.dsl, times(2)).fetch(anyString(), any(Object[].class)); + verify(fixture.fenceRepository, never()) + .requireDisclosurePreparation(fixture.handoff.sources()); + assertThat(fixture.executedSql) + .containsExactly( + "UPDATE account_hosted_terms_disclosure_handoffs" + + " SET status = 'DISPATCH_AUTHORIZED', dispatch_attempts = dispatch_attempts + 1 " + + "WHERE handoff_id = ? AND status = ?"); + } + + @Test + void exactAuthorizedReadbackDoesNotRecheckParticipationOrAdvanceDispatch() throws Exception { + Fixture fixture = new Fixture(Status.DISPATCH_AUTHORIZED, true); + fixture.begin(); + + var permit = fixture.repository.authorizeDispatch(fixture.handoff); + + assertThat(permit.newlyAuthorized()).isFalse(); + assertThat(permit.snapshot().status()).isEqualTo(Status.DISPATCH_AUTHORIZED); + assertThat(permit.snapshot().dispatchAttempts()).isEqualTo(2); + var order = inOrder(fixture.fenceRepository, fixture.dsl); + order.verify(fixture.fenceRepository).lockDisclosureSources(fixture.handoff.sources()); + order.verify(fixture.dsl, times(4)).fetch(anyString(), any(Object[].class)); + verify(fixture.fenceRepository, never()) + .requireWorldParticipationDisclosureAdmission(fixture.handoff.sources()); + verify(fixture.fenceRepository, never()) + .requireDisclosurePreparation(fixture.handoff.sources()); + assertThat(fixture.journalReads).isEqualTo(2); + assertThat(fixture.executedSql).isEmpty(); + } + + @Test + void preparedDispatchRetainsPreparationGuardAfterParticipationAdmission() throws Exception { + Fixture fixture = new Fixture(Status.PREPARED, true); + fixture.begin(); + + var permit = fixture.repository.authorizeDispatch(fixture.handoff); + + assertThat(permit.newlyAuthorized()).isTrue(); + var order = inOrder(fixture.fenceRepository, fixture.dsl); + order.verify(fixture.fenceRepository).lockDisclosureSources(fixture.handoff.sources()); + order.verify(fixture.dsl, times(2)).fetch(anyString(), any(Object[].class)); + order + .verify(fixture.fenceRepository) + .requireWorldParticipationDisclosureAdmission(fixture.handoff.sources()); + order.verify(fixture.fenceRepository).requireDisclosurePreparation(fixture.handoff.sources()); + assertThat(fixture.executedSql).hasSize(1); + } + + private static final class Fixture { + private final DSLContext dsl = mock(DSLContext.class); + private final Connection connection = mock(Connection.class); + private final DraftAuthorizationFenceRepository fenceRepository = + mock(DraftAuthorizationFenceRepository.class); + private final HostedTermsDisclosureHandoff handoff = handoff(); + private final HostedTermsDisclosureHandoffRepository repository = + new HostedTermsDisclosureHandoffRepository(dsl, fenceRepository); + private final List executedSql = new ArrayList<>(); + private final Record handoffRow; + private final Record sourceRow; + private final Result handoffRows; + private final Result sourceRows; + private final Result noRows = result(List.of()); + private int journalReads; + + private Fixture(Status initialStatus, boolean includeHandoff) throws Exception { + Map handoffFields = new HashMap<>(); + handoffFields.put("handoff_id", handoff.handoffId()); + handoffFields.put("request_id", handoff.requestId()); + handoffFields.put("kind", handoff.kind().name()); + handoffFields.put("source_key", handoff.sourceKey()); + handoffFields.put("predecessor_digest", handoff.predecessorDigest()); + handoffFields.put("candidate_digest", handoff.candidateDigest()); + handoffFields.put( + "effective_at", OffsetDateTime.ofInstant(handoff.effectiveAt(), ZoneOffset.UTC)); + handoffFields.put("binding", handoff.canonicalBytes()); + handoffFields.put("binding_digest", HostedTermsEncoding.digest(handoff.canonicalBytes())); + handoffFields.put("status", initialStatus.name()); + handoffFields.put("dispatch_attempts", 2); + handoffFields.put("result_outcome", null); + handoffFields.put("result_payload", null); + handoffFields.put("result_digest", null); + handoffFields.put("result_recorded_at", null); + handoffFields.put("created_at", OffsetDateTime.parse("2026-10-08T00:00:00Z")); + handoffRow = record(handoffFields); + + SourceEvidence source = handoff.sources().getFirst(); + Map sourceFields = new HashMap<>(); + sourceFields.put("source_key", source.key()); + sourceFields.put("source_evidence", source.canonicalBytes()); + sourceFields.put( + "source_evidence_digest", HostedTermsEncoding.digest(source.canonicalBytes())); + sourceRow = record(sourceFields); + handoffRows = result(includeHandoff ? List.of(handoffRow) : List.of()); + sourceRows = result(List.of(sourceRow)); + + doReturn(false).when(connection).getAutoCommit(); + doReturn(false).when(connection).isReadOnly(); + doReturn(Connection.TRANSACTION_READ_COMMITTED).when(connection).getTransactionIsolation(); + doAnswer( + invocation -> { + invocation.getArgument(0).run(connection); + return null; + }) + .when(dsl) + .connection(any(ConnectionRunnable.class)); + doAnswer( + invocation -> { + String statement = invocation.getArgument(0); + executedSql.add(statement); + if (statement.contains("dispatch_attempts = dispatch_attempts + 1")) { + handoffFields.put("status", Status.DISPATCH_AUTHORIZED.name()); + handoffFields.put("dispatch_attempts", 3); + } + return 1; + }) + .when(dsl) + .execute(anyString(), any(Object[].class)); + doAnswer( + invocation -> { + String statement = invocation.getArgument(0); + if (statement.contains("account_hosted_terms_disclosure_handoffs")) { + journalReads++; + return handoffRows; + } + if (statement.contains("account_hosted_terms_disclosure_sources")) { + return sourceRows; + } + return noRows; + }) + .when(dsl) + .fetch(anyString(), any(Object[].class)); + } + + private void begin() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } + } + + private static HostedTermsDisclosureHandoff handoff() { + SourceEvidence source = + new SourceEvidence( + SourceKind.HOSTED_TERMS, + UUID.randomUUID().toString(), + null, + "7", + null, + null, + new byte[] {1, 2, 3}); + return new HostedTermsDisclosureHandoff( + UUID.randomUUID(), + UUID.randomUUID(), + Kind.CATALOG, + source.key(), + HostedTermsEncoding.digest(new byte[] {4}), + HostedTermsEncoding.digest(new byte[] {5}), + Instant.parse("2026-10-08T00:00:00.123456Z"), + List.of(source), + "test-only-authority-evidence".getBytes(java.nio.charset.StandardCharsets.UTF_8)); + } + + @SuppressWarnings("unchecked") + private static Record record(Map fields) { + Record record = mock(Record.class); + doAnswer(invocation -> fields.get(invocation.getArgument(0))) + .when(record) + .get(anyString(), any(Class.class)); + return record; + } + + @SuppressWarnings("unchecked") + private static Result result(List records) { + Result result = mock(Result.class); + doReturn(records.size()).when(result).size(); + doReturn(records.isEmpty()).when(result).isEmpty(); + doReturn(records.isEmpty() ? null : records.getFirst()).when(result).getFirst(); + doAnswer(invocation -> records.stream()).when(result).stream(); + return result; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryTest.java index 3881ebc725..55cd33a991 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryTest.java @@ -6,6 +6,7 @@ import java.sql.SQLException; import java.time.Instant; import java.time.OffsetDateTime; +import java.util.List; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository; @@ -13,6 +14,8 @@ import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.RedemptionRequest; import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.Status; import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle.BundleReference; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture.Values; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import org.jooq.Field; @@ -50,11 +53,42 @@ void clearTransactionState() { TransactionSynchronizationManager.clear(); } + @Test + void timestampWritesAndExpiryPredicateUseExplicitPostgresTypes() { + MockStore store = new MockStore(); + var repository = repository(store); + var candidate = candidate(tuple()); + var created = inTransaction(() -> repository.createOrReadExact(candidate)); + var redeemed = + inTransaction( + () -> repository.redeemExact(redemption(candidate, OWNER_ATTEMPT_ID, 8L, OWNER_URI))); + + assertThat(created.issuance().issuedAt()).isEqualTo(candidate.issuedAt()); + assertThat(redeemed).isNotNull(); + assertThat(store.queries) + .anySatisfy( + sql -> + assertThat(sql) + .contains( + "cast(? as timestamptz), cast(? as timestamptz), " + + "cast(? as timestamptz), 'issued'")) + .anySatisfy( + sql -> + assertThat(sql) + .contains( + "redeemed_at = cast(? as timestamptz)", + "reference_expires_at > cast(? as timestamptz)")); + } + @Test void exactDuplicateReturnsOriginalOutputAndNeverReplacesIt() { MockStore store = new MockStore(); AccountStartSessionOperatorAuthorizationRepository repository = repository(store); IssuanceCandidate first = candidate(tuple()); + UUID changedOperationId = UUID.randomUUID(); + long changedIssuanceFence = first.issuanceFence() + 1L; + long changedSourceFence = Long.parseLong(first.bundleReference().sourceFence()) + 1L; + BundleReference changedReference = bundleReference(changedSourceFence); IssuanceCandidate changedOutput = new IssuanceCandidate( first.controlPlaneRequestId(), @@ -63,10 +97,15 @@ void exactDuplicateReturnsOriginalOutputAndNeverReplacesIt() { first.issuanceWorkloadUri(), first.reservationOwnerId(), first.reservationClaimFence(), - UUID.randomUUID(), - first.issuanceFence() + 1, - bundleReference(first.issuanceFence() + 1), - bytes("different bundle"), + changedOperationId, + changedIssuanceFence, + changedReference, + authorityBundle( + tuple(), + changedOperationId, + changedIssuanceFence, + first.referenceExpiresAt().plusSeconds(1), + changedReference), fingerprint("e"), bytes("different encrypted envelope"), first.issuedAt().plusSeconds(1), @@ -80,17 +119,18 @@ void exactDuplicateReturnsOriginalOutputAndNeverReplacesIt() { assertThat(created.created()).isTrue(); assertThat(duplicate.created()).isFalse(); + assertThat(first.issuanceFence()) + .isNotEqualTo(Long.parseLong(first.bundleReference().sourceFence())); assertThat(duplicate.issuance().issuanceOperationId()).isEqualTo(ISSUANCE_OPERATION_ID); - assertThat(duplicate.issuance().issuanceFence()).isEqualTo(4L); + assertThat(duplicate.issuance().issuanceFence()).isEqualTo(31L); assertThat(duplicate.issuance().bundleReference()).isEqualTo(first.bundleReference()); assertThat(duplicate.issuance().authorizationReferenceFingerprint()) .isEqualTo(fingerprint("a")); - assertThat(duplicate.issuance().authorityEvidenceBundle()).containsExactly(bytes("bundle-v1")); + assertThat(duplicate.issuance().authorityEvidenceBundle()) + .containsExactly(first.authorityEvidenceBundle()); assertThat(duplicate.issuance().encryptedResponseEnvelope()) .containsExactly(bytes("ciphertext-envelope")); assertThat(store.insertCount.get()).isEqualTo(1); - assertThat(store.lastInsertSql) - .contains("cast(? as timestamptz), cast(? as timestamptz), cast(? as timestamptz)"); assertThat(store.lastLockSql).contains("for update"); byte[] exposedTuple = duplicate.issuance().preAuthorizationTuple(); @@ -98,7 +138,7 @@ void exactDuplicateReturnsOriginalOutputAndNeverReplacesIt() { assertThat(duplicate.issuance().preAuthorizationTuple()) .containsExactly(first.preAuthorizationTuple()); assertThat(duplicate.issuance().toString()) - .doesNotContain("tuple-v1", "bundle-v1", "ciphertext-envelope"); + .doesNotContain("tuple-v1", "authorityEvidenceBundle/v1", "ciphertext-envelope"); } @Test @@ -192,7 +232,7 @@ void fingerprintKeyIdUsesCanonicalAlphabetAndAllowsMaximumLength() { } @Test - void bundleReferenceFenceMustMatchTheDurableIssuanceFenceBeforeSql() { + void bundleSourceVersionMustMatchWhileSourceFenceRemainsIndependentOfIssuanceFence() { MockStore store = new MockStore(); AccountStartSessionOperatorAuthorizationRepository repository = repository(store); IssuanceCandidate valid = candidate(tuple()); @@ -206,7 +246,11 @@ void bundleReferenceFenceMustMatchTheDurableIssuanceFenceBeforeSql() { valid.reservationClaimFence(), valid.issuanceOperationId(), valid.issuanceFence(), - bundleReference(valid.issuanceFence() + 1L), + new BundleReference( + valid.bundleReference().bundleVersion(), + "13", + valid.bundleReference().sourceFence(), + valid.bundleReference().linearization()), valid.authorityEvidenceBundle(), valid.authorizationReferenceFingerprint(), valid.encryptedResponseEnvelope(), @@ -214,9 +258,11 @@ void bundleReferenceFenceMustMatchTheDurableIssuanceFenceBeforeSql() { valid.referenceExpiresAt(), valid.responseEnvelopeExpiresAt()); + assertThat(valid.issuanceFence()) + .isNotEqualTo(Long.parseLong(valid.bundleReference().sourceFence())); assertThatThrownBy(() -> inTransaction(() -> repository.createOrReadExact(mismatchedReference))) .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("source fence"); + .hasMessageContaining("bundle reference"); assertThat(store.databaseCallCount.get()).isZero(); } @@ -311,8 +357,24 @@ void canonicalNonUuidRequestIdRetriesAtExactMultibyteUtf8Bound() { "\"requestId\":\"" + boundedRequestId + "\"", "\"requestId\":\"" + oversizedRequestId + "\""); assertThat(malformedTupleJson).contains(oversizedRequestId); + IssuanceCandidate boundaryCandidate = candidate(boundaryTuple, boundedRequestId); IssuanceCandidate oversized = - candidate(boundedRequestId, bytes(malformedTupleJson), boundaryTuple.mutationDigest()); + new IssuanceCandidate( + boundedRequestId, + bytes(malformedTupleJson), + boundaryTuple.mutationDigest(), + boundaryCandidate.issuanceWorkloadUri(), + boundaryCandidate.reservationOwnerId(), + boundaryCandidate.reservationClaimFence(), + boundaryCandidate.issuanceOperationId(), + boundaryCandidate.issuanceFence(), + boundaryCandidate.bundleReference(), + boundaryCandidate.authorityEvidenceBundle(), + boundaryCandidate.authorizationReferenceFingerprint(), + boundaryCandidate.encryptedResponseEnvelope(), + boundaryCandidate.issuedAt(), + boundaryCandidate.referenceExpiresAt(), + boundaryCandidate.responseEnvelopeExpiresAt()); int callsBeforeMalformedTuple = store.databaseCallCount.get(); assertThatThrownBy(() -> inTransaction(() -> repository.createOrReadExact(oversized))) .isInstanceOf(IllegalArgumentException.class); @@ -335,15 +397,12 @@ void redemptionConsumesOnceAndExactRetryReturnsSameAuthorityOnlyResult() { assertThat(first.authorizationReferenceFingerprint()).isEqualTo(fingerprint("a")); assertThat(retry.authorizationReferenceFingerprint()) .isEqualTo(first.authorizationReferenceFingerprint()); - assertThat(first.authorityEvidenceBundle()).containsExactly(bytes("bundle-v1")); + assertThat(first.authorityEvidenceBundle()) + .containsExactly(candidate.authorityEvidenceBundle()); assertThat(retry.authorityEvidenceBundle()).containsExactly(first.authorityEvidenceBundle()); assertThat(first.issuanceOperationId()).isEqualTo(ISSUANCE_OPERATION_ID); assertThat(store.redemptionUpdateCount.get()).isEqualTo(1); - assertThat(store.lastRedemptionSql) - .contains( - "redeemed_at = cast(? as timestamptz)", - "reference_expires_at > cast(? as timestamptz)"); - assertThat(first.toString()).doesNotContain("bundle-v1", "ciphertext-envelope"); + assertThat(first.toString()).doesNotContain("ciphertext-envelope"); } @Test @@ -472,6 +531,7 @@ private static IssuanceCandidate candidate( } private static IssuanceCandidate candidate(String requestId, byte[] tupleBytes, String digest) { + BundleReference reference = bundleReference(7L); return new IssuanceCandidate( requestId, tupleBytes, @@ -480,9 +540,14 @@ private static IssuanceCandidate candidate(String requestId, byte[] tupleBytes, RESERVATION_OWNER_ID, 2L, ISSUANCE_OPERATION_ID, - 4L, - bundleReference(4L), - bytes("bundle-v1"), + 31L, + reference, + authorityBundle( + tupleFromBytes(tupleBytes), + ISSUANCE_OPERATION_ID, + 31L, + NOW.plusSeconds(180), + reference), fingerprint("a"), bytes("ciphertext-envelope"), NOW, @@ -492,6 +557,10 @@ private static IssuanceCandidate candidate(String requestId, byte[] tupleBytes, private static IssuanceCandidate expiredCandidate( StartSessionPreAuthorizationReservationTuple tuple) { + Instant issuedAt = NOW.minusSeconds(240); + Instant referenceExpiresAt = NOW.minusSeconds(60); + Instant responseEnvelopeExpiresAt = NOW.minusSeconds(30); + BundleReference reference = bundleReference(7L); return new IssuanceCandidate( tuple.controlPlaneRequestId(), canonicalBytes(tuple), @@ -500,14 +569,14 @@ private static IssuanceCandidate expiredCandidate( RESERVATION_OWNER_ID, 2L, ISSUANCE_OPERATION_ID, - 4L, - bundleReference(4L), - bytes("bundle-v1"), + 31L, + reference, + authorityBundle(tuple, ISSUANCE_OPERATION_ID, 31L, issuedAt, referenceExpiresAt, reference), fingerprint("a"), bytes("expired-ciphertext-envelope"), - NOW.minusSeconds(240), - NOW.minusSeconds(60), - NOW.minusSeconds(30)); + issuedAt, + referenceExpiresAt, + responseEnvelopeExpiresAt); } private static IssuanceCandidate withFingerprint(IssuanceCandidate original, String fingerprint) { @@ -584,6 +653,47 @@ private static BundleReference bundleReference(long sourceFence) { "authorityEvidenceBundle/v1", "12", Long.toString(sourceFence), "123456789"); } + private static StartSessionPreAuthorizationReservationTuple tupleFromBytes(byte[] tupleBytes) { + return StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + new String(tupleBytes, java.nio.charset.StandardCharsets.UTF_8)); + } + + private static byte[] authorityBundle( + StartSessionPreAuthorizationReservationTuple tuple, + UUID operationId, + long issuanceFence, + Instant expiresAt, + BundleReference reference) { + return authorityBundle(tuple, operationId, issuanceFence, NOW, expiresAt, reference); + } + + private static byte[] authorityBundle( + StartSessionPreAuthorizationReservationTuple tuple, + UUID operationId, + long issuanceFence, + Instant evaluatedAt, + Instant expiresAt, + BundleReference reference) { + return StartSessionAuthorityEvidenceBundleFixture.canonicalBytes( + tuple, + new Values( + operationId, + "sha256:" + "a".repeat(64), + reference.sourceVersion(), + "CURRENT", + evaluatedAt, + expiresAt, + 1L, + 1L, + 1L, + 1L, + 2L, + issuanceFence, + UUID.fromString("2e19f788-10d2-4f33-aed6-9a46db136dcc"), + "1", + "1")); + } + private static T inTransaction(java.util.function.Supplier action) { TransactionSynchronizationManager.setActualTransactionActive(true); try { @@ -653,9 +763,8 @@ private static final class MockStore implements MockDataProvider { private final AtomicInteger databaseCallCount = new AtomicInteger(); private final AtomicInteger insertCount = new AtomicInteger(); private final AtomicInteger redemptionUpdateCount = new AtomicInteger(); + private final List queries = new java.util.ArrayList<>(); private final AtomicInteger erasureUpdateCount = new AtomicInteger(); - private String lastInsertSql = ""; - private String lastRedemptionSql = ""; private String lastErasureSql = ""; private String lastLockSql = ""; private StoredRow row; @@ -664,9 +773,9 @@ private static final class MockStore implements MockDataProvider { public MockResult[] execute(MockExecuteContext context) throws SQLException { databaseCallCount.incrementAndGet(); String sql = context.sql().stripLeading().toLowerCase(java.util.Locale.ROOT); + queries.add(sql); Object[] bind = context.bindings(); if (sql.startsWith("insert into account_start_session_operator_authorizations")) { - lastInsertSql = sql; if (row == null) { row = StoredRow.fromInsert(bind); insertCount.incrementAndGet(); @@ -688,7 +797,6 @@ public MockResult[] execute(MockExecuteContext context) throws SQLException { erasureUpdateCount.incrementAndGet(); return new MockResult[] {new MockResult(1)}; } - lastRedemptionSql = sql; if (row == null || !"ISSUED".equals(row.status)) { return new MockResult[] {new MockResult(0)}; } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepositoryTest.java new file mode 100644 index 0000000000..8748f650f3 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepositoryTest.java @@ -0,0 +1,339 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository.StoredEvidence; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle.BundleReference; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture.Values; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import org.junit.jupiter.api.Test; + +/** Unit proof of exact closed-codec observation binding; no Game Session producer is exercised. */ +class AccountStartSessionWorldOriginalAttemptEvidenceRepositoryTest { + private static final String REQUEST_ID = + "start-session/original-attempt/2355f292-ab9c-458c-8d52-aef18b9254e8"; + private static final UUID PARTICIPATION_ID = + UUID.fromString("fa3555ac-e039-4827-9e04-eb0fa8cd37d4"); + private static final UUID ACTOR_ID = UUID.fromString("d888ddc4-4a62-4b25-9bab-c4f94860c2ca"); + private static final UUID TENANT_ID = UUID.fromString("6d1e5ce5-6127-4d35-88b8-7a6f40692038"); + private static final UUID TARGET_ACCOUNT_ID = + UUID.fromString("1df91ae6-5125-4e47-9f1d-2e45eab8a4a0"); + private static final UUID RESERVATION_OWNER_ID = + UUID.fromString("ca1b63bf-f09f-4a55-96bf-a1fd2e22349e"); + private static final UUID GAME_INSTANCE_ID = + UUID.fromString("51c67424-324e-486d-b3ad-45b6e85c1a0d"); + private static final UUID OWNER_ATTEMPT_ID = + UUID.fromString("c0df9691-cba5-4274-a49d-0bc7b2158ef7"); + private static final UUID OWNER_MUTATION_ID = + UUID.fromString("f7811486-2bd4-41a0-9bf7-a351ce3a0c8f"); + private static final long OWNER_FENCE = 47L; + private static final String NAMESPACE = "world-runtime"; + private static final String LOGGING_URI = + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; + private static final BundleReference BUNDLE_REFERENCE = + new BundleReference("authorityEvidenceBundle/v1", "11", "13", "17"); + private static final Instant NOW = Instant.parse("2026-10-09T00:00:00Z"); + + @Test + void closedCodecReadbackBindsCompleteTupleProjectionAndRejectsSubmicrosecondExpiry() { + Fixture fixture = fixture(); + Request expected = request(fixture, UUID.fromString("6a3922eb-96f5-4cc5-8e43-85c1bb3f49c0")); + Result exact = + new Result( + expected, Instant.parse("2026-10-09T00:02:00.123456Z"), fixture.accountProjection()); + byte[] completeResponse = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(exact).toByteArray(); + + Result decoded = + AccountStartSessionWorldOriginalAttemptEvidenceRepository.validateResponse( + expected, completeResponse, fixture.parent()); + + assertThat(decoded.originalLeaseExpiresAt()).isEqualTo(exact.originalLeaseExpiresAt()); + assertThat(decoded.accountRedemptionProjection()).containsExactly(fixture.accountProjection()); + assertThat(decoded.request().expectedOwnerMutationId()).isEqualTo(OWNER_MUTATION_ID); + assertThat(decoded.phaseState()) + .isEqualTo(OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE); + + Result subMicrosecond = + new Result( + expected, Instant.parse("2026-10-09T00:02:00.123456789Z"), fixture.accountProjection()); + byte[] roundedTimestampCandidate = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(subMicrosecond) + .toByteArray(); + assertThatThrownBy( + () -> + AccountStartSessionWorldOriginalAttemptEvidenceRepository.validateResponse( + expected, roundedTimestampCandidate, fixture.parent())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts"); + + byte[] changedProjection = "not the exact Account projection".getBytes(StandardCharsets.UTF_8); + Result wrongProjection = + new Result(expected, exact.originalLeaseExpiresAt(), changedProjection); + assertThatThrownBy( + () -> + AccountStartSessionWorldOriginalAttemptEvidenceRepository.validateResponse( + expected, + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(wrongProjection) + .toByteArray(), + fixture.parent())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts"); + } + + @Test + void freshReadCorrelationIsNotDurableIdentityButEveryOwnerBindingFieldIs() { + Fixture fixture = fixture(); + Request first = request(fixture, UUID.fromString("6a3922eb-96f5-4cc5-8e43-85c1bb3f49c0")); + Request retry = request(fixture, UUID.fromString("21fa4d95-98f0-4c19-a5b6-864bd0467f94")); + + assertThatCode( + () -> + AccountStartSessionWorldOriginalAttemptEvidenceRepository + .requireSameSemanticRequest(first, retry)) + .doesNotThrowAnyException(); + + assertMismatch( + first, + fixture.namespace(), + fixture.parent().originalPostAuthorizationTuple(), + OWNER_ATTEMPT_ID, + OWNER_MUTATION_ID, + OWNER_FENCE + 1L); + assertMismatch( + first, + fixture.namespace(), + fixture.parent().originalPostAuthorizationTuple(), + UUID.fromString("274c7a54-2f2a-409f-9eac-7b8a7733e590"), + OWNER_MUTATION_ID, + OWNER_FENCE); + assertMismatch( + first, + fixture.namespace(), + fixture.parent().originalPostAuthorizationTuple(), + OWNER_ATTEMPT_ID, + UUID.fromString("1f2d6f4e-1202-4bdb-bcd4-f3c14e4cc764"), + OWNER_FENCE); + assertThatThrownBy( + () -> + new Request( + UUID.randomUUID(), + "other-runtime", + fixture.parent().originalPostAuthorizationTuple(), + OWNER_ATTEMPT_ID, + OWNER_MUTATION_ID, + OWNER_FENCE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("target the exact requested namespace"); + + Request changedTuple = + new Request( + UUID.fromString("578bc4d6-6a96-4bb9-a6f9-2d4d54f0c547"), + fixture.namespace(), + tupleFor("Changed exact tuple").canonicalBytes(), + OWNER_ATTEMPT_ID, + OWNER_MUTATION_ID, + OWNER_FENCE); + assertThatThrownBy( + () -> + AccountStartSessionWorldOriginalAttemptEvidenceRepository + .requireSameSemanticRequest(first, changedTuple)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts"); + } + + @Test + void storedResponseIsDefensiveAndItsDigestCoversTheCompleteResponseBytes() { + Fixture fixture = fixture(); + Request request = request(fixture, UUID.fromString("6a3922eb-96f5-4cc5-8e43-85c1bb3f49c0")); + Result result = new Result(request, NOW.plusSeconds(120), fixture.accountProjection()); + byte[] bytes = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(result).toByteArray(); + String digest = "sha256:" + sha256Hex(bytes); + StoredEvidence stored = + new StoredEvidence( + PARTICIPATION_ID, + OWNER_MUTATION_ID, + result.originalLeaseExpiresAt(), + bytes, + digest, + result); + bytes[0] ^= 0x01; + + assertThat(stored.originalResponseBytes()) + .containsExactly( + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(result).toByteArray()); + assertThat(stored.originalResponseDigest()).isEqualTo(digest); + assertThat(stored.toString()) + .contains("projection=") + .contains("responseBytes="); + assertThatThrownBy( + () -> + new StoredEvidence( + PARTICIPATION_ID, + OWNER_MUTATION_ID, + result.originalLeaseExpiresAt(), + new byte[] {1}, + digest, + result)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("digest differs"); + } + + private static void assertMismatch( + Request expected, String namespace, byte[] tuple, UUID attempt, UUID mutation, long fence) { + Request changed = new Request(UUID.randomUUID(), namespace, tuple, attempt, mutation, fence); + assertThatThrownBy( + () -> + AccountStartSessionWorldOriginalAttemptEvidenceRepository + .requireSameSemanticRequest(expected, changed)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts"); + } + + private static Request request(Fixture fixture, UUID readId) { + return new Request( + readId, + fixture.namespace(), + fixture.parent().originalPostAuthorizationTuple(), + OWNER_ATTEMPT_ID, + OWNER_MUTATION_ID, + OWNER_FENCE); + } + + private static Fixture fixture() { + StartSessionPostAuthorizationExecutionTuple tuple = + tupleFor("Original attempt evidence repository proof"); + String preparationJson = "{\"identity\":{\"worldSlug\":\"arena\"}}"; + StoredParticipation parent = + new StoredParticipation( + PARTICIPATION_ID, + 41L, + REQUEST_ID, + tuple.canonicalBytes(), + NAMESPACE, + TENANT_ID, + GAME_INSTANCE_ID, + OWNER_ATTEMPT_ID, + OWNER_FENCE, + preparationJson, + "sha256:" + sha256Hex(preparationJson.getBytes(StandardCharsets.UTF_8)), + 2_147_483_651L, + OffsetDateTime.ofInstant(NOW, ZoneOffset.UTC), + List.of()); + return new Fixture(parent, tuple, accountProjection(tuple)); + } + + private static StartSessionPostAuthorizationExecutionTuple tupleFor(String auditReason) { + StartSessionPreAuthorizationReservationTuple preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + REQUEST_ID, + ACTOR_ID, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, NAMESPACE), + new StartSessionOperatorAction.Target(17L, TARGET_ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + auditReason)); + byte[] bundle = authorityBundle(preTuple); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + LOGGING_URI, + "arfp/v1/key-1/" + "a".repeat(64), + RESERVATION_OWNER_ID, + 7L, + bundle, + BUNDLE_REFERENCE); + return tuple; + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + return StartSessionAuthorityEvidenceBundleFixture.canonicalBytes( + tuple, + new Values( + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "sha256:" + "c".repeat(64), + BUNDLE_REFERENCE.sourceVersion(), + "CURRENT", + NOW, + NOW.plusSeconds(180), + 1L, + 1L, + 1L, + 1L, + 2L, + 9L, + UUID.fromString("55555555-5555-4555-8555-555555555555"), + "1", + "1")); + } + + private static byte[] accountProjection(StartSessionPostAuthorizationExecutionTuple tuple) { + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + return AccountControlUiAuthority.canonical( + Map.of( + "projectionSchemaId", + "accountStartSessionRedemptionProjection", + "projectionSchemaVersion", + "1", + "authorizationReferenceFingerprint", + tuple.authorizationReferenceFingerprint(), + "authorityEvidenceBundle", + bundle.jsonValue(), + "issuanceOperationId", + bundle.issuanceOperationId().toString(), + "issuanceFence", + 9L)); + } + + private static String sha256Hex(byte[] bytes) { + try { + return java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new AssertionError(impossible); + } + } + + private record Fixture( + StoredParticipation parent, + StartSessionPostAuthorizationExecutionTuple tuple, + byte[] accountProjection) { + private Fixture { + accountProjection = accountProjection.clone(); + } + + private String namespace() { + return NAMESPACE; + } + + @Override + public byte[] accountProjection() { + return accountProjection.clone(); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepositoryTest.java new file mode 100644 index 0000000000..816e265401 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepositoryTest.java @@ -0,0 +1,985 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.jooq.impl.DSL.field; +import static org.jooq.impl.DSL.name; +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.when; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.Candidate; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionAuthorityCapture; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle.BundleReference; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture.Values; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; +import org.jooq.ConnectionRunnable; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.jooq.impl.SQLDataType; +import org.jooq.tools.jdbc.MockConnection; +import org.jooq.tools.jdbc.MockDataProvider; +import org.jooq.tools.jdbc.MockResult; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Mocked jOOQ rows prove storage composition only, not PostgreSQL guards or authenticated proof. + */ +class AccountStartSessionWorldParticipationRepositoryTest { + private static final String REQUEST_ID = + "start-session/operator/2355f292-ab9c-458c-8d52-aef18b9254e8"; + private static final UUID ACTOR_ID = UUID.fromString("d888ddc4-4a62-4b25-9bab-c4f94860c2ca"); + private static final UUID TENANT_ID = UUID.fromString("6d1e5ce5-6127-4d35-88b8-7a6f40692038"); + private static final UUID TARGET_ACCOUNT_ID = + UUID.fromString("1df91ae6-5125-4e47-9f1d-2e45eab8a4a0"); + private static final UUID RESERVATION_OWNER_ID = + UUID.fromString("ca1b63bf-f09f-4a55-96bf-a1fd2e22349e"); + private static final UUID GAME_INSTANCE_ID = + UUID.fromString("51c67424-324e-486d-b3ad-45b6e85c1a0d"); + private static final UUID OWNER_ATTEMPT_ID = + UUID.fromString("c0df9691-cba5-4274-a49d-0bc7b2158ef7"); + private static final UUID PARTICIPATION_ID = + UUID.fromString("fa3555ac-e039-4827-9e04-eb0fa8cd37d4"); + private static final Instant NOW = Instant.parse("2026-10-09T00:00:00Z"); + private static final String LOGGING_URI = + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; + private static final BundleReference BUNDLE_REFERENCE = + new BundleReference("authorityEvidenceBundle/v1", "11", "13", "17"); + private static final Field PARTICIPATION_ID_FIELD = + field(name("participation_id"), SQLDataType.UUID); + private static final Field PARTICIPATION_FENCE_FIELD = + field(name("participation_fence"), SQLDataType.BIGINT); + private static final Field REQUEST_ID_FIELD = + field(name("control_plane_request_id"), SQLDataType.VARCHAR); + private static final Field ORIGINAL_TUPLE_FIELD = + field(name("original_post_authorization_tuple"), SQLDataType.VARBINARY); + private static final Field NAMESPACE_FIELD = + field(name("target_namespace"), SQLDataType.VARCHAR); + private static final Field TENANT_FIELD = + field(name("canonical_tenant_id"), SQLDataType.UUID); + private static final Field GAME_INSTANCE_FIELD = + field(name("canonical_game_instance_id"), SQLDataType.UUID); + private static final Field OWNER_ATTEMPT_FIELD = + field(name("game_session_owner_attempt_id"), SQLDataType.UUID); + private static final Field OWNER_FENCE_FIELD = + field(name("game_session_owner_fence"), SQLDataType.BIGINT); + private static final Field PREPARATION_JSON_FIELD = + field(name("preparation_input_json"), SQLDataType.VARCHAR); + private static final Field PREPARATION_DIGEST_FIELD = + field(name("preparation_input_digest"), SQLDataType.VARCHAR); + private static final Field PRODUCER_XID_FIELD = + field(name("producer_xid"), SQLDataType.BIGINT); + private static final Field CREATED_AT_FIELD = + field(name("created_at"), SQLDataType.OFFSETDATETIME); + private static final Field UNKNOWN_FIELD = + field(name("future_unreviewed_column"), SQLDataType.VARCHAR); + private static final Field CAPTURE_REQUEST_ID_FIELD = + field(name("control_plane_request_id"), SQLDataType.VARCHAR); + private static final Field CAPTURE_ACCOUNT_FIELD = + field(name("account_uuid"), SQLDataType.UUID); + private static final Field CAPTURE_TENANT_FIELD = + field(name("tenant_uuid"), SQLDataType.UUID); + private static final Field CAPTURE_TARGET_OWNER_FIELD = + field(name("target_owner"), SQLDataType.VARCHAR); + private static final Field CAPTURE_LOGGING_URI_FIELD = + field(name("logging_workload_uri"), SQLDataType.VARCHAR); + private static final Field CAPTURE_RESERVATION_OWNER_FIELD = + field(name("reservation_owner_id"), SQLDataType.UUID); + private static final Field CAPTURE_RESERVATION_FENCE_FIELD = + field(name("reservation_claim_fence"), SQLDataType.BIGINT); + private static final Field CAPTURE_PRE_TUPLE_FIELD = + field(name("pre_authorization_tuple"), SQLDataType.VARBINARY); + private static final Field CAPTURE_MUTATION_DIGEST_FIELD = + field(name("mutation_digest"), SQLDataType.VARCHAR); + private static final Field CAPTURE_OPERATION_ID_FIELD = + field(name("control_ui_operation_id"), SQLDataType.UUID); + private static final Field CAPTURE_TOKEN_JTI_FIELD = + field(name("control_ui_token_jti"), SQLDataType.UUID); + private static final Field CAPTURE_TOKEN_HASH_FIELD = + field(name("control_ui_token_hash"), SQLDataType.VARCHAR); + private static final Field CAPTURE_RECEIPT_DIGEST_FIELD = + field(name("control_ui_signer_receipt_sha256"), SQLDataType.VARCHAR); + private static final Field CAPTURE_ISSUANCE_FENCE_FIELD = + field(name("issuance_fence"), SQLDataType.BIGINT); + private static final Field CAPTURE_ISSUANCE_SOURCE_VERSION_FIELD = + field(name("issuance_fence_source_version"), SQLDataType.BIGINT); + private static final Field CAPTURED_AT_FIELD = + field(name("captured_at"), SQLDataType.OFFSETDATETIME); + private static final Field CAPTURE_SNAPSHOT_DIGEST_FIELD = + field(name("snapshot_sha256"), SQLDataType.VARCHAR); + private static final Field CAPTURE_SNAPSHOT_BYTES_FIELD = + field(name("canonical_snapshot_bytes"), SQLDataType.VARBINARY); + private static final Field CAPTURE_SOURCE_VERSION_FIELD = + field(name("source_version"), SQLDataType.BIGINT); + private static final Field CAPTURE_SOURCE_FENCE_FIELD = + field(name("source_fence"), SQLDataType.BIGINT); + private static final Field CAPTURE_LINEARIZATION_FIELD = + field(name("linearization"), SQLDataType.VARCHAR); + private static final Field CAPTURE_CANONICAL_DIGEST_FIELD = + field(name("canonical_sha256"), SQLDataType.VARCHAR); + private static final Field CAPTURE_CANONICAL_BYTES_FIELD = + field(name("canonical_capture_bytes"), SQLDataType.VARBINARY); + private static final Field CAPTURE_CREATED_AT_FIELD = + field(name("created_at"), SQLDataType.OFFSETDATETIME); + private static final Field SOURCE_PARTICIPATION_ID_FIELD = + field(name("participation_id"), SQLDataType.UUID); + private static final Field SOURCE_KEY_FIELD = + field(name("source_key"), SQLDataType.VARCHAR); + private static final Field SOURCE_EVIDENCE_FIELD = + field(name("source_evidence"), SQLDataType.VARBINARY); + private static final Field SETTLEMENT_PARTICIPATION_ID_FIELD = + field(name("participation_id"), SQLDataType.UUID); + private static final Field SETTLEMENT_OUTCOME_FIELD = + field(name("outcome"), SQLDataType.VARCHAR); + private static final Field SETTLEMENT_WORLD_FENCE_FIELD = + field(name("world_execution_fence"), SQLDataType.BIGINT); + private static final Field SETTLEMENT_TERMINAL_BYTES_FIELD = + field(name("terminal_bytes"), SQLDataType.VARBINARY); + private static final Field SETTLEMENT_TERMINAL_DIGEST_FIELD = + field(name("terminal_digest"), SQLDataType.VARCHAR); + private static final Field SETTLEMENT_SETTLED_AT_FIELD = + field(name("settled_at"), SQLDataType.OFFSETDATETIME); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void typedReadbackRetainsTheExactCandidateAndRejectsChangedImmutableFields() { + Fixture fixture = fixture(); + StoredParticipation stored = + AccountStartSessionWorldParticipationRepository.decodeParticipation( + participationRow(fixture.candidate()), List.of(fixture.source())); + + AccountStartSessionWorldParticipationRepository.requireSameCandidate( + fixture.candidate(), stored); + assertThat(stored.participationId()).isEqualTo(PARTICIPATION_ID); + assertThat(stored.participationFence()).isEqualTo(41L); + assertThat(stored.producerXid()).isEqualTo(2_147_483_651L); + assertThat(stored.originalPostAuthorizationTuple()) + .containsExactly(fixture.candidate().originalPostAuthorizationTuple()); + + Candidate changedPreparation = + new Candidate( + fixture.candidate().originalTuple(), + fixture.candidate().capture(), + fixture.candidate().canonicalGameInstanceId(), + fixture.candidate().gameSessionOwnerAttemptId(), + fixture.candidate().gameSessionOwnerFence(), + "{\"changed\":true}", + digest("{\"changed\":true}")); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationRepository.requireSameCandidate( + changedPreparation, stored)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts"); + } + + @Test + void participationReadbackRejectsUnknownDatabaseColumns() { + Fixture fixture = fixture(); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationRepository.decodeParticipation( + participationRow(fixture.candidate(), true), List.of(fixture.source()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("unavailable"); + } + + @Test + void sourceReadbackRejectsMissingAndSubstitutedChildren() { + Fixture fixture = fixture(); + SourceEvidence substituted = + new SourceEvidence( + SourceKind.ACCOUNT, + ACTOR_ID.toString(), + "1", + "2", + "account/test", + "1", + bytes("substituted evidence")); + + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationRepository.requireExactSources( + List.of(fixture.source()), List.of())) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationRepository.requireExactSources( + List.of(fixture.source()), List.of(substituted))) + .isInstanceOf(IllegalStateException.class); + AccountStartSessionWorldParticipationRepository.requireExactSources( + List.of(fixture.source()), List.of(fixture.source())); + } + + @Test + void terminalMustRepeatEveryStoredIdentityAndPreparationField() { + Fixture fixture = fixture(); + Candidate candidate = fixture.candidate(); + StoredParticipation stored = + AccountStartSessionWorldParticipationRepository.decodeParticipation( + participationRow(candidate), List.of(fixture.source())); + WorldStartSessionExecutionTerminal exact = terminal(candidate, 41L, OWNER_ATTEMPT_ID, 8L); + + AccountStartSessionWorldParticipationRepository.requireTerminalMatches(stored, exact); + + WorldStartSessionExecutionTerminal changedAttempt = + terminal(candidate, 41L, UUID.fromString("274c7a54-2f2a-409f-9eac-7b8a7733e590"), 8L); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationRepository.requireTerminalMatches( + stored, changedAttempt)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts"); + } + + @Test + void persistenceDeniesAbsentReadOnlyAndWrongIsolationTransactionsBeforeSql() { + AtomicInteger databaseCalls = new AtomicInteger(); + MockDataProvider provider = + context -> { + databaseCalls.incrementAndGet(); + return new MockResult[0]; + }; + var repository = + new AccountStartSessionWorldParticipationRepository( + DSL.using(new MockConnection(provider), SQLDialect.POSTGRES)); + Candidate candidate = fixture().candidate(); + + assertThatThrownBy(() -> repository.createOrReadExact(candidate)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("READ_COMMITTED"); + + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertThatThrownBy(() -> repository.createOrReadExact(candidate)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("READ_COMMITTED"); + TransactionSynchronizationManager.clear(); + + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_SERIALIZABLE); + assertThatThrownBy(() -> repository.createOrReadExact(candidate)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("READ_COMMITTED"); + assertThat(databaseCalls.get()).isZero(); + } + + @Test + void findCurrentExactReadsRetainedCaptureParentAndEveryChildWithoutWriting() throws Exception { + Fixture fixture = fixture(); + List reads = new java.util.ArrayList<>(); + AtomicReference writes = new AtomicReference<>(); + AccountStartSessionWorldParticipationRepository repository = + mockedRepository(fixture, reads, writes, null); + beginWritableTransaction(); + + var found = repository.findCurrentExact(fixture.candidate()); + + assertThat(found).isPresent(); + assertThat(found.orElseThrow().participationId()).isEqualTo(PARTICIPATION_ID); + assertThat(found.orElseThrow().sources()).hasSize(1); + assertThat(found.orElseThrow().sources().get(0).canonicalBytes()) + .containsExactly(fixture.source().canonicalBytes()); + assertThat(reads) + .anyMatch(sql -> sql.contains("account_start_session_authority_captures")) + .anyMatch(sql -> sql.contains("account_start_session_world_participations")) + .anyMatch(sql -> sql.contains("account_start_session_world_participation_sources")) + .anyMatch(sql -> sql.contains("account_start_session_world_participation_settlements")); + assertThat(reads) + .allMatch(sql -> !sql.toLowerCase(java.util.Locale.ROOT).contains("for update")); + assertThat(writes.get()).isNull(); + } + + @Test + void findHistoricalForOriginalTupleResolvesTheRetainedIdentityAndVerifiesItsSources() + throws Exception { + Fixture fixture = fixture(); + List reads = new java.util.ArrayList<>(); + AtomicReference writes = new AtomicReference<>(); + AccountStartSessionWorldParticipationRepository repository = + mockedRepository(fixture, reads, writes, null); + beginWritableTransaction(); + + var found = + repository.findHistoricalForOriginalTuple( + fixture.candidate().originalPostAuthorizationTuple()); + + assertThat(found).isPresent(); + assertThat(found.orElseThrow().participationId()).isEqualTo(PARTICIPATION_ID); + assertThat(found.orElseThrow().participationFence()).isEqualTo(41L); + assertThat(found.orElseThrow().originalPostAuthorizationTuple()) + .containsExactly(fixture.candidate().originalPostAuthorizationTuple()); + assertThat(found.orElseThrow().sources()).hasSize(1); + assertThat(found.orElseThrow().sources().get(0).canonicalBytes()) + .containsExactly(fixture.source().canonicalBytes()); + assertThat(reads) + .anyMatch(sql -> sql.contains("WHERE control_plane_request_id = ?")) + .anyMatch(sql -> sql.contains("account_start_session_authority_captures")) + .anyMatch(sql -> sql.contains("account_start_session_world_participation_sources")); + assertThat(reads) + .allMatch(sql -> !sql.toLowerCase(java.util.Locale.ROOT).contains("for update")); + assertThat(writes.get()).isNull(); + } + + @Test + void findHistoricalForOriginalTupleRejectsSameRequestIdWithChangedCompleteTuple() + throws Exception { + Fixture fixture = fixture(); + StartSessionPostAuthorizationExecutionTuple retained = fixture.candidate().originalTuple(); + byte[] changedTuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + retained.preAuthorizationTuple(), + retained.authenticatedWorkloadIdentity(), + retained.authorizationReferenceFingerprint(), + retained.reservationOwnerId(), + retained.reservationClaimFence() + 1L, + retained.authorityEvidenceBundleBytes(), + retained.bundleReference()) + .canonicalBytes(); + List reads = new java.util.ArrayList<>(); + AtomicReference writes = new AtomicReference<>(); + AccountStartSessionWorldParticipationRepository repository = + mockedRepository(fixture, reads, writes, null); + beginWritableTransaction(); + + assertThatThrownBy(() -> repository.findHistoricalForOriginalTuple(changedTuple)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("unavailable"); + + assertThat(reads).hasSize(1); + assertThat(reads.get(0)).contains("WHERE control_plane_request_id = ?"); + assertThat(writes.get()).isNull(); + } + + @Test + void findHistoricalForOriginalTupleReturnsEmptyWhenRequestIdentityHasNoRetainedRow() + throws Exception { + Fixture fixture = fixture(); + List reads = new java.util.ArrayList<>(); + AtomicReference writes = new AtomicReference<>(); + AccountStartSessionWorldParticipationRepository repository = + mockedRepository(fixture, reads, writes, null, true); + beginWritableTransaction(); + + var found = + repository.findHistoricalForOriginalTuple( + fixture.candidate().originalPostAuthorizationTuple()); + + assertThat(found).isEmpty(); + assertThat(reads).hasSize(1); + assertThat(reads.get(0)).contains("WHERE control_plane_request_id = ?"); + assertThat(writes.get()).isNull(); + } + + @Test + void findHistoricalForOriginalTupleRejectsMissingOrChangedSourceChildren() throws Exception { + Fixture fixture = fixture(); + SourceEvidence changedSource = + new SourceEvidence( + SourceKind.ACCOUNT, + ACTOR_ID.toString(), + "1", + "1", + "account/test", + "1", + bytes("changed retained source evidence")); + + for (List children : + List.of(List.of(), List.of(changedSource))) { + List reads = new java.util.ArrayList<>(); + AtomicReference writes = new AtomicReference<>(); + AccountStartSessionWorldParticipationRepository repository = + mockedRepository(fixture, reads, writes, null, false, children); + beginWritableTransaction(); + + assertThatThrownBy( + () -> + repository.findHistoricalForOriginalTuple( + fixture.candidate().originalPostAuthorizationTuple())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("evidence unavailable"); + assertThat(reads) + .anyMatch(sql -> sql.contains("account_start_session_authority_captures")) + .anyMatch(sql -> sql.contains("account_start_session_world_participation_sources")); + assertThat(writes.get()).isNull(); + TransactionSynchronizationManager.clear(); + } + } + + @Test + void settleExactInsertsAndReadsBackTheSameTypedTerminalAfterHistoricalIdentityCheck() + throws Exception { + Fixture fixture = fixture(); + WorldStartSessionExecutionTerminal terminal = + terminal(fixture.candidate(), 41L, OWNER_ATTEMPT_ID, 8L); + List reads = new java.util.ArrayList<>(); + AtomicReference writes = new AtomicReference<>(); + AccountStartSessionWorldParticipationRepository repository = + mockedRepository(fixture, reads, writes, terminal); + beginWritableTransaction(); + + var stored = repository.settleExact(terminal); + + assertThat(stored.participationId()).isEqualTo(PARTICIPATION_ID); + assertThat(stored.outcome()).isEqualTo(terminal.outcome()); + assertThat(stored.worldExecutionFence()).isEqualTo(terminal.worldExecutionFence()); + assertThat(stored.terminalBytes()).containsExactly(terminal.canonicalBytes()); + assertThat(stored.terminalDigest()).isEqualTo(terminal.digest()); + assertThat(reads) + .anyMatch(sql -> sql.contains("account_start_session_authority_captures")) + .anyMatch(sql -> sql.contains("account_start_session_world_participations")) + .anyMatch(sql -> sql.contains("account_start_session_world_participation_sources")) + .anyMatch( + sql -> + sql.startsWith("INSERT INTO account_start_session_world_participation_settlements")) + .anyMatch(sql -> sql.contains("account_start_session_world_participation_settlements")); + assertThat(writes.get()).isNotNull().hasSize(5); + assertThat(writes.get()[0]).isEqualTo(PARTICIPATION_ID); + assertThat(writes.get()[1]).isEqualTo(terminal.outcome().name()); + assertThat(writes.get()[2]).isEqualTo(terminal.worldExecutionFence()); + assertThat((byte[]) writes.get()[3]).containsExactly(terminal.canonicalBytes()); + assertThat(writes.get()[4]).isEqualTo(terminal.digest()); + } + + @Test + void settleExactRejectsSubstitutedOriginalAttemptBeforeSettlementInsert() throws Exception { + Fixture fixture = fixture(); + WorldStartSessionExecutionTerminal changedAttempt = + terminal( + fixture.candidate(), 41L, UUID.fromString("274c7a54-2f2a-409f-9eac-7b8a7733e590"), 8L); + List reads = new java.util.ArrayList<>(); + AtomicReference writes = new AtomicReference<>(); + AccountStartSessionWorldParticipationRepository repository = + mockedRepository(fixture, reads, writes, null); + beginWritableTransaction(); + + assertThatThrownBy(() -> repository.settleExact(changedAttempt)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts"); + assertThat(writes.get()).isNull(); + } + + @Test + void findSettlementExactReadsBackOnlyTheExactHistoricalReceiptWithoutWriting() throws Exception { + Fixture fixture = fixture(); + WorldStartSessionExecutionTerminal terminal = + terminal(fixture.candidate(), 41L, OWNER_ATTEMPT_ID, 8L); + List sqlCalls = new java.util.ArrayList<>(); + AtomicReference writes = new AtomicReference<>(); + AccountStartSessionWorldParticipationRepository repository = + mockedRepository(fixture, sqlCalls, writes, terminal); + beginWritableTransaction(); + + var found = repository.findSettlementExact(PARTICIPATION_ID, 41L); + + assertThat(found).isPresent(); + assertThat(found.orElseThrow().terminalBytes()).containsExactly(terminal.canonicalBytes()); + assertThat(found.orElseThrow().terminalDigest()).isEqualTo(terminal.digest()); + assertThat(sqlCalls) + .anyMatch(sql -> sql.contains("account_start_session_authority_captures")) + .anyMatch(sql -> sql.contains("account_start_session_world_participations")) + .anyMatch(sql -> sql.contains("account_start_session_world_participation_sources")) + .anyMatch(sql -> sql.contains("account_start_session_world_participation_settlements")); + assertThat(sqlCalls) + .allMatch(sql -> !sql.toLowerCase(java.util.Locale.ROOT).contains("for update")); + assertThat(writes.get()).isNull(); + } + + @Test + void findSettlementExactReturnsEmptyForMissingReceiptOrParticipationWithoutWriting() + throws Exception { + Fixture fixture = fixture(); + List missingReceiptCalls = new java.util.ArrayList<>(); + AtomicReference missingReceiptWrites = new AtomicReference<>(); + AccountStartSessionWorldParticipationRepository missingReceiptRepository = + mockedRepository(fixture, missingReceiptCalls, missingReceiptWrites, null); + beginWritableTransaction(); + + assertThat(missingReceiptRepository.findSettlementExact(PARTICIPATION_ID, 41L)).isEmpty(); + assertThat(missingReceiptWrites.get()).isNull(); + + TransactionSynchronizationManager.clear(); + List missingParentCalls = new java.util.ArrayList<>(); + AtomicReference missingParentWrites = new AtomicReference<>(); + AccountStartSessionWorldParticipationRepository missingParentRepository = + mockedRepository(fixture, missingParentCalls, missingParentWrites, null, true); + beginWritableTransaction(); + + assertThat(missingParentRepository.findSettlementExact(PARTICIPATION_ID, 41L)).isEmpty(); + assertThat(missingParentWrites.get()).isNull(); + assertThat(missingParentCalls) + .noneMatch(sql -> sql.contains("account_start_session_world_participation_settlements")); + } + + @Test + void findSettlementExactRejectsReceiptWithSubstitutedOriginalAttemptWithoutWriting() + throws Exception { + Fixture fixture = fixture(); + WorldStartSessionExecutionTerminal changedAttempt = + terminal( + fixture.candidate(), 41L, UUID.fromString("274c7a54-2f2a-409f-9eac-7b8a7733e590"), 8L); + List sqlCalls = new java.util.ArrayList<>(); + AtomicReference writes = new AtomicReference<>(); + AccountStartSessionWorldParticipationRepository repository = + mockedRepository(fixture, sqlCalls, writes, changedAttempt); + beginWritableTransaction(); + + assertThatThrownBy(() -> repository.findSettlementExact(PARTICIPATION_ID, 41L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("unavailable"); + assertThat(writes.get()).isNull(); + } + + private static AccountStartSessionWorldParticipationRepository mockedRepository( + Fixture fixture, + List sqlCalls, + AtomicReference writes, + WorldStartSessionExecutionTerminal settlement) + throws Exception { + return mockedRepository(fixture, sqlCalls, writes, settlement, false); + } + + private static AccountStartSessionWorldParticipationRepository mockedRepository( + Fixture fixture, + List sqlCalls, + AtomicReference writes, + WorldStartSessionExecutionTerminal settlement, + boolean missingParticipation) + throws Exception { + return mockedRepository( + fixture, sqlCalls, writes, settlement, missingParticipation, List.of(fixture.source())); + } + + private static AccountStartSessionWorldParticipationRepository mockedRepository( + Fixture fixture, + List sqlCalls, + AtomicReference writes, + WorldStartSessionExecutionTerminal settlement, + boolean missingParticipation, + List sourceChildren) + throws Exception { + DSLContext dsl = mock(DSLContext.class); + Connection connection = mock(Connection.class); + when(connection.getAutoCommit()).thenReturn(false); + when(connection.isReadOnly()).thenReturn(false); + when(connection.getTransactionIsolation()).thenReturn(Connection.TRANSACTION_READ_COMMITTED); + doAnswer( + invocation -> { + invocation.getArgument(0).run(connection); + return null; + }) + .when(dsl) + .connection(any(ConnectionRunnable.class)); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0); + sqlCalls.add(sql); + if (sql.contains("account_start_session_authority_captures")) { + return captureRow(fixture.candidate()); + } + if (sql.contains("account_start_session_world_participations")) { + return missingParticipation ? null : participationRow(fixture.candidate()); + } + if (sql.contains("account_start_session_world_participation_settlements")) { + return settlement == null ? null : settlementRow(settlement); + } + throw new AssertionError("Unexpected participation repository query: " + sql); + }); + when(dsl.fetch(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0); + sqlCalls.add(sql); + if (!sql.contains("account_start_session_world_participation_sources")) { + throw new AssertionError( + "Unexpected participation repository result query: " + sql); + } + return sourceRows(PARTICIPATION_ID, sourceChildren); + }); + when(dsl.execute(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0); + sqlCalls.add(sql); + writes.set((Object[]) invocation.getRawArguments()[1]); + return 1; + }); + return new AccountStartSessionWorldParticipationRepository(dsl); + } + + private static void beginWritableTransaction() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + private static Record participationRow(Candidate candidate) { + return participationRow(candidate, false); + } + + private static Record participationRow(Candidate candidate, boolean withUnknownColumn) { + Record row; + if (withUnknownColumn) { + row = + DSL.using(SQLDialect.POSTGRES) + .newRecord( + PARTICIPATION_ID_FIELD, + PARTICIPATION_FENCE_FIELD, + REQUEST_ID_FIELD, + ORIGINAL_TUPLE_FIELD, + NAMESPACE_FIELD, + TENANT_FIELD, + GAME_INSTANCE_FIELD, + OWNER_ATTEMPT_FIELD, + OWNER_FENCE_FIELD, + PREPARATION_JSON_FIELD, + PREPARATION_DIGEST_FIELD, + PRODUCER_XID_FIELD, + CREATED_AT_FIELD, + UNKNOWN_FIELD); + row.setValue(UNKNOWN_FIELD, "unreviewed"); + } else { + row = + DSL.using(SQLDialect.POSTGRES) + .newRecord( + PARTICIPATION_ID_FIELD, + PARTICIPATION_FENCE_FIELD, + REQUEST_ID_FIELD, + ORIGINAL_TUPLE_FIELD, + NAMESPACE_FIELD, + TENANT_FIELD, + GAME_INSTANCE_FIELD, + OWNER_ATTEMPT_FIELD, + OWNER_FENCE_FIELD, + PREPARATION_JSON_FIELD, + PREPARATION_DIGEST_FIELD, + PRODUCER_XID_FIELD, + CREATED_AT_FIELD); + } + row.setValue(PARTICIPATION_ID_FIELD, PARTICIPATION_ID); + row.setValue(PARTICIPATION_FENCE_FIELD, 41L); + row.setValue(REQUEST_ID_FIELD, candidate.controlPlaneRequestId()); + row.setValue(ORIGINAL_TUPLE_FIELD, candidate.originalPostAuthorizationTuple()); + row.setValue(NAMESPACE_FIELD, candidate.targetNamespace()); + row.setValue(TENANT_FIELD, candidate.canonicalTenantId()); + row.setValue(GAME_INSTANCE_FIELD, candidate.canonicalGameInstanceId()); + row.setValue(OWNER_ATTEMPT_FIELD, candidate.gameSessionOwnerAttemptId()); + row.setValue(OWNER_FENCE_FIELD, candidate.gameSessionOwnerFence()); + row.setValue(PREPARATION_JSON_FIELD, candidate.preparationInputJson()); + row.setValue(PREPARATION_DIGEST_FIELD, candidate.preparationInputDigest()); + row.setValue(PRODUCER_XID_FIELD, 2_147_483_651L); + row.setValue(CREATED_AT_FIELD, OffsetDateTime.ofInstant(NOW, ZoneOffset.UTC)); + return row; + } + + private static Record captureRow(Candidate candidate) { + var tuple = candidate.originalTuple(); + var capture = candidate.capture(); + Record row = + DSL.using(SQLDialect.POSTGRES) + .newRecord( + CAPTURE_REQUEST_ID_FIELD, + CAPTURE_ACCOUNT_FIELD, + CAPTURE_TENANT_FIELD, + CAPTURE_TARGET_OWNER_FIELD, + CAPTURE_LOGGING_URI_FIELD, + CAPTURE_RESERVATION_OWNER_FIELD, + CAPTURE_RESERVATION_FENCE_FIELD, + CAPTURE_PRE_TUPLE_FIELD, + CAPTURE_MUTATION_DIGEST_FIELD, + CAPTURE_OPERATION_ID_FIELD, + CAPTURE_TOKEN_JTI_FIELD, + CAPTURE_TOKEN_HASH_FIELD, + CAPTURE_RECEIPT_DIGEST_FIELD, + CAPTURE_ISSUANCE_FENCE_FIELD, + CAPTURE_ISSUANCE_SOURCE_VERSION_FIELD, + CAPTURED_AT_FIELD, + CAPTURE_SNAPSHOT_DIGEST_FIELD, + CAPTURE_SNAPSHOT_BYTES_FIELD, + CAPTURE_SOURCE_VERSION_FIELD, + CAPTURE_SOURCE_FENCE_FIELD, + CAPTURE_LINEARIZATION_FIELD, + CAPTURE_CANONICAL_DIGEST_FIELD, + CAPTURE_CANONICAL_BYTES_FIELD, + CAPTURE_CREATED_AT_FIELD); + row.setValue(CAPTURE_REQUEST_ID_FIELD, candidate.controlPlaneRequestId()); + row.setValue(CAPTURE_ACCOUNT_FIELD, tuple.preAuthorizationTuple().actor().accountId()); + row.setValue(CAPTURE_TENANT_FIELD, candidate.canonicalTenantId()); + row.setValue(CAPTURE_TARGET_OWNER_FIELD, "game-session-service"); + row.setValue(CAPTURE_LOGGING_URI_FIELD, tuple.authenticatedWorkloadIdentity()); + row.setValue(CAPTURE_RESERVATION_OWNER_FIELD, tuple.reservationOwnerId()); + row.setValue(CAPTURE_RESERVATION_FENCE_FIELD, tuple.reservationClaimFence()); + row.setValue( + CAPTURE_PRE_TUPLE_FIELD, + tuple.preAuthorizationTuple().canonicalJson().getBytes(StandardCharsets.UTF_8)); + row.setValue(CAPTURE_MUTATION_DIGEST_FIELD, tuple.mutationDigest()); + row.setValue( + CAPTURE_OPERATION_ID_FIELD, UUID.fromString("44444444-4444-4444-8444-444444444444")); + row.setValue(CAPTURE_TOKEN_JTI_FIELD, UUID.fromString("55555555-5555-4555-8555-555555555555")); + row.setValue(CAPTURE_TOKEN_HASH_FIELD, "b".repeat(64)); + row.setValue(CAPTURE_RECEIPT_DIGEST_FIELD, sha256Hex(bytes("receipt"))); + row.setValue(CAPTURE_ISSUANCE_FENCE_FIELD, 9L); + row.setValue(CAPTURE_ISSUANCE_SOURCE_VERSION_FIELD, 10L); + OffsetDateTime capturedAt = OffsetDateTime.parse(capture.capturedAt().replace("Z", "+00:00")); + row.setValue(CAPTURED_AT_FIELD, capturedAt); + row.setValue(CAPTURE_SNAPSHOT_DIGEST_FIELD, capture.snapshotSha256()); + row.setValue(CAPTURE_SNAPSHOT_BYTES_FIELD, capture.snapshotBytes()); + row.setValue(CAPTURE_SOURCE_VERSION_FIELD, capture.sourceVersion()); + row.setValue(CAPTURE_SOURCE_FENCE_FIELD, capture.sourceFence()); + row.setValue(CAPTURE_LINEARIZATION_FIELD, capture.linearization()); + row.setValue(CAPTURE_CANONICAL_DIGEST_FIELD, capture.canonicalSha256()); + row.setValue(CAPTURE_CANONICAL_BYTES_FIELD, capture.canonicalBytes()); + row.setValue(CAPTURE_CREATED_AT_FIELD, capturedAt); + return row; + } + + private static org.jooq.Result> sourceRows( + UUID participationId, List sources) { + var context = DSL.using(SQLDialect.POSTGRES); + var result = + context.newResult(SOURCE_PARTICIPATION_ID_FIELD, SOURCE_KEY_FIELD, SOURCE_EVIDENCE_FIELD); + for (SourceEvidence source : sources) { + var row = + context.newRecord(SOURCE_PARTICIPATION_ID_FIELD, SOURCE_KEY_FIELD, SOURCE_EVIDENCE_FIELD); + row.setValue(SOURCE_PARTICIPATION_ID_FIELD, participationId); + row.setValue(SOURCE_KEY_FIELD, source.key()); + row.setValue(SOURCE_EVIDENCE_FIELD, source.canonicalBytes()); + result.add(row); + } + return result; + } + + private static Record settlementRow(WorldStartSessionExecutionTerminal terminal) { + Record row = + DSL.using(SQLDialect.POSTGRES) + .newRecord( + SETTLEMENT_PARTICIPATION_ID_FIELD, + SETTLEMENT_OUTCOME_FIELD, + SETTLEMENT_WORLD_FENCE_FIELD, + SETTLEMENT_TERMINAL_BYTES_FIELD, + SETTLEMENT_TERMINAL_DIGEST_FIELD, + SETTLEMENT_SETTLED_AT_FIELD); + row.setValue(SETTLEMENT_PARTICIPATION_ID_FIELD, terminal.accountWorldParticipationId()); + row.setValue(SETTLEMENT_OUTCOME_FIELD, terminal.outcome().name()); + row.setValue(SETTLEMENT_WORLD_FENCE_FIELD, terminal.worldExecutionFence()); + row.setValue(SETTLEMENT_TERMINAL_BYTES_FIELD, terminal.canonicalBytes()); + row.setValue(SETTLEMENT_TERMINAL_DIGEST_FIELD, terminal.digest()); + row.setValue(SETTLEMENT_SETTLED_AT_FIELD, OffsetDateTime.ofInstant(NOW, ZoneOffset.UTC)); + return row; + } + + private static WorldStartSessionExecutionTerminal terminal( + Candidate candidate, long participationFence, UUID attemptId, long ownerFence) { + return new WorldStartSessionExecutionTerminal( + candidate.originalPostAuthorizationTuple(), + PARTICIPATION_ID, + participationFence, + attemptId, + ownerFence, + candidate.targetNamespace(), + candidate.canonicalTenantId(), + candidate.controlPlaneRequestId(), + candidate.canonicalGameInstanceId(), + candidate.preparationInputDigest(), + candidate.preparationInputJson(), + 19L, + WorldStartSessionExecutionTerminal.Outcome.COMMITTED); + } + + private static Fixture fixture() { + SourceEvidence source = + new SourceEvidence( + SourceKind.ACCOUNT, + ACTOR_ID.toString(), + "1", + "1", + "account/test", + "1", + bytes("retained source evidence")); + StartSessionPreAuthorizationReservationTuple preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + REQUEST_ID, + ACTOR_ID, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target(17L, TARGET_ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "World participation repository proof")); + byte[] bundle = authorityBundle(preTuple); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + LOGGING_URI, + "arfp/v1/key-1/" + "a".repeat(64), + RESERVATION_OWNER_ID, + 7L, + bundle, + BUNDLE_REFERENCE); + byte[] snapshot = + AccountControlUiAuthority.canonical( + Map.ofEntries( + Map.entry("schema", "account-start-session-authority-snapshot/v1"), + Map.entry("controlPlaneRequestId", REQUEST_ID), + Map.entry( + "preAuthorizationTuple", + Base64.getEncoder() + .encodeToString(preTuple.canonicalJson().getBytes(StandardCharsets.UTF_8))), + Map.entry("mutationDigest", preTuple.mutationDigest()), + Map.entry("accountId", ACTOR_ID.toString()), + Map.entry("tenantId", TENANT_ID.toString()), + Map.entry("targetOwner", "game-session-service"), + Map.entry("loggingWorkloadUri", LOGGING_URI), + Map.entry("reservationOwnerId", RESERVATION_OWNER_ID.toString()), + Map.entry("reservationClaimFence", "7"), + Map.entry("controlUiOperationId", "44444444-4444-4444-8444-444444444444"), + Map.entry("controlUiTokenJti", "55555555-5555-4555-8555-555555555555"), + Map.entry("controlUiTokenHash", "b".repeat(64)), + Map.entry( + "controlUiSignerReceipt", Base64.getEncoder().encodeToString(bytes("receipt"))), + Map.entry("controlUiSignerReceiptSha256", sha256Hex(bytes("receipt"))), + Map.entry( + "sourceVectorEvidence", + Base64.getEncoder().encodeToString(source.canonicalBytes())), + Map.entry( + "sourceVector", + List.of(Base64.getEncoder().encodeToString(source.canonicalBytes()))), + Map.entry("outboxCheckpoints", List.of()), + Map.entry( + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 1L, + "tenantAuthorityGeneration", Map.of(TENANT_ID.toString(), 1L), + "membershipAuthorityGeneration", Map.of(TENANT_ID.toString(), 1L), + "privateRealmGrantVersions", List.of())), + Map.entry("membershipVersion", Map.of(TENANT_ID.toString(), 2L)), + Map.entry("accountIdentitySource", Map.of("source", "fixture")), + Map.entry("issuanceFence", "9"), + Map.entry("issuanceFenceSourceVersion", "10"))); + var capture = capture(REQUEST_ID, 11L, 13L, "17", "2026-10-09T00:00:00.000Z", snapshot); + String preparationJson = "{\"identity\":{\"worldSlug\":\"arena\"}}"; + Candidate candidate = + new Candidate( + tuple, + capture, + GAME_INSTANCE_ID, + OWNER_ATTEMPT_ID, + 8L, + preparationJson, + digest(preparationJson)); + return new Fixture(candidate, source); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + return StartSessionAuthorityEvidenceBundleFixture.canonicalBytes( + tuple, + new Values( + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "sha256:" + "c".repeat(64), + BUNDLE_REFERENCE.sourceVersion(), + "CURRENT", + NOW, + NOW.plusSeconds(180), + 1L, + 1L, + 1L, + 1L, + 2L, + 9L, + UUID.fromString("55555555-5555-4555-8555-555555555555"), + "1", + "1")); + } + + private static AccountStartSessionAuthorityCapture capture( + String requestId, + long sourceVersion, + long sourceFence, + String linearization, + String capturedAt, + byte[] snapshot) { + try { + Method factory = + net.firedevops.firemud.accountservice.service.session.AccountStartSessionAuthorityCapture + .class + .getDeclaredMethod( + "create", + String.class, + long.class, + long.class, + String.class, + String.class, + byte[].class); + factory.setAccessible(true); + return (net.firedevops.firemud.accountservice.service.session + .AccountStartSessionAuthorityCapture) + factory.invoke( + null, requestId, sourceVersion, sourceFence, linearization, capturedAt, snapshot); + } catch (InvocationTargetException failure) { + if (failure.getCause() instanceof RuntimeException runtime) throw runtime; + throw new AssertionError("Unexpected capture fixture failure", failure.getCause()); + } catch (ReflectiveOperationException failure) { + throw new AssertionError("Could not create exact capture fixture", failure); + } + } + + private static String digest(String value) { + return "sha256:" + sha256Hex(value.getBytes(StandardCharsets.UTF_8)); + } + + private static String sha256Hex(byte[] bytes) { + try { + byte[] digest = java.security.MessageDigest.getInstance("SHA-256").digest(bytes); + return java.util.HexFormat.of().formatHex(digest); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new AssertionError(impossible); + } + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private record Fixture(Candidate candidate, SourceEvidence source) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java index 43b12e5b5a..bc16e51c62 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java @@ -30,7 +30,6 @@ import net.firedevops.firemud.account.v1.RecoverOperatorAuthorizationReferenceResponse; import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationRequest; import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationResponse; -import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.RedemptionResult; import net.firedevops.firemud.accountservice.service.impl.StartSessionOperatorAuthorizationGrpcService; import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring; import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography; @@ -42,8 +41,13 @@ import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RecoverRequest; import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RedeemRequest; import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RedeemedOperationProjection; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RedemptionResult; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture.Values; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import net.firedevops.firemud.common.security.SessionContext; import org.junit.jupiter.api.AfterEach; @@ -117,7 +121,13 @@ void issueRecoverAndRedeemMapExactTypedInputsAndResponses() { when(ownerService.redeem(any())) .thenReturn( new RedemptionResult( - FINGERPRINT, bytes("redemption-bundle"), ISSUANCE_OPERATION_ID, 9L, true)); + FINGERPRINT, + StartSessionPostAuthorizationExecutionTuple.decode(originalPostAuthorizationTuple()) + .authorityEvidenceBundleBytes(), + ISSUANCE_OPERATION_ID, + 9L, + true, + originalPostAuthorizationTuple())); TestObserver issueObserver = callIssue(issueRequest(tupleBytes), LOGGING_URI); @@ -129,7 +139,9 @@ void issueRecoverAndRedeemMapExactTypedInputsAndResponses() { assertThat(issueObserver.value.getExpiresAt().getSeconds()) .isEqualTo(Instant.parse("2026-10-09T00:03:00Z").getEpochSecond()); assertThat(issueObserver.value.getAuthorityEvidenceBundle().toByteArray()) - .containsExactly(bytes("authority-bundle")); + .containsExactly( + StartSessionPostAuthorizationExecutionTuple.decode(originalPostAuthorizationTuple()) + .authorityEvidenceBundleBytes()); assertThat(issueObserver.value.getBundleReference().getBundleVersion()) .isEqualTo(AccountStartSessionOperatorAuthorityBundle.BUNDLE_VERSION); assertThat(issueObserver.value.getBundleReference().getSourceVersion()).isEqualTo("17"); @@ -137,6 +149,8 @@ void issueRecoverAndRedeemMapExactTypedInputsAndResponses() { assertThat(issueObserver.value.getBundleReference().getLinearization()).isEqualTo("3"); assertThat(issueObserver.value.getAuthenticatedLoggingWorkloadIdentity()) .isEqualTo(LOGGING_URI); + assertThat(issueObserver.value.getOriginalAccountPostAuthorizationTuple().toByteArray()) + .containsExactly(originalPostAuthorizationTuple()); var issueCaptor = org.mockito.ArgumentCaptor.forClass(IssueRequest.class); verify(ownerService).issue(issueCaptor.capture()); @@ -155,6 +169,8 @@ void issueRecoverAndRedeemMapExactTypedInputsAndResponses() { .isEqualTo(AUTHORIZATION_REFERENCE); assertThat(recoverObserver.value.getAuthenticatedLoggingWorkloadIdentity()) .isEqualTo(LOGGING_URI); + assertThat(recoverObserver.value.getOriginalAccountPostAuthorizationTuple().toByteArray()) + .containsExactly(originalPostAuthorizationTuple()); var recoverCaptor = org.mockito.ArgumentCaptor.forClass(RecoverRequest.class); verify(ownerService).recover(recoverCaptor.capture()); assertThat(recoverCaptor.getValue().canonicalTupleBytes()).containsExactly(tupleBytes); @@ -168,11 +184,15 @@ void issueRecoverAndRedeemMapExactTypedInputsAndResponses() { assertThat(redeemObserver.failure).isNull(); assertThat(redeemObserver.value.getAuthorizationReferenceFingerprint()).isEqualTo(FINGERPRINT); assertThat(redeemObserver.value.getAuthorityEvidenceBundle().toByteArray()) - .containsExactly(bytes("redemption-bundle")); + .containsExactly( + StartSessionPostAuthorizationExecutionTuple.decode(originalPostAuthorizationTuple()) + .authorityEvidenceBundleBytes()); assertThat(redeemObserver.value.getIssuanceOperationId()) .isEqualTo(ISSUANCE_OPERATION_ID.toString()); assertThat(redeemObserver.value.getIssuanceFence()).isEqualTo(9L); assertThat(redeemObserver.value.getReplay()).isTrue(); + assertThat(redeemObserver.value.getOriginalAccountPostAuthorizationTuple().toByteArray()) + .containsExactly(originalPostAuthorizationTuple()); var redeemCaptor = org.mockito.ArgumentCaptor.forClass(RedeemRequest.class); verify(ownerService).redeem(redeemCaptor.capture()); assertThat(redeemCaptor.getValue().canonicalTupleBytes()).containsExactly(tupleBytes); @@ -242,6 +262,24 @@ void readsExactRedeemedOperationProjectionWithoutCredentialMaterial() { verifyNoMoreInteractions(ownerService); } + @Test + void exactOriginalGameSessionRedeemerMayReadCredentialFreeProjection() { + byte[] tupleBytes = canonicalTupleBytes(); + when(ownerService.readRedeemedOperationProjection(any())) + .thenReturn(redeemedOperationProjection(tupleBytes)); + + TestObserver observer = + callReadProjection(readProjectionRequest(tupleBytes), GAME_SESSION_URI); + + assertThat(observer.failure).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(observer.value.getAuthenticatedRedeemerWorkloadIdentity()) + .isEqualTo(GAME_SESSION_URI); + assertThat(observer.value.getCanonicalPreAuthorizationTupleBytes().toByteArray()) + .containsExactly(tupleBytes); + verify(ownerService).readRedeemedOperationProjection(any()); + } + @Test void deniesWrongPeerBeforeParsingAndRejectsMalformedProjectionRead() { ReadRedeemedOperationProjectionRequest malformed = @@ -250,7 +288,7 @@ void deniesWrongPeerBeforeParsingAndRejectsMalformedProjectionRead() { new String[] { null, "spiffe://firemud/ns/other/sa/game-design-service", - GAME_SESSION_URI, + "spiffe://firemud/ns/other/sa/game-session-service", LOGGING_URI, ACCOUNT_URI }) { @@ -623,7 +661,7 @@ private static byte[] canonicalTupleBytes() { new StartSessionOperatorAction( StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, - new StartSessionOperatorAction.Scope(TENANT_ID, "tenant-runtime"), + new StartSessionOperatorAction.Scope(TENANT_ID, NAMESPACE), new StartSessionOperatorAction.Target(42L, TARGET_ACCOUNT_ID), StartSessionOperatorAction.ExpectedVersion.ABSENT, new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), @@ -635,13 +673,51 @@ private static byte[] canonicalTupleBytes() { } private static AuthorizationResponse authorizationResponse() { + byte[] tupleBytes = originalPostAuthorizationTuple(); + var tuple = StartSessionPostAuthorizationExecutionTuple.decode(tupleBytes); return new AuthorizationResponse( AUTHORIZATION_REFERENCE, FINGERPRINT, Instant.parse("2026-10-09T00:03:00Z"), - bytes("authority-bundle"), + tuple.authorityEvidenceBundleBytes(), new AccountStartSessionOperatorAuthorityBundle.BundleReference( - AccountStartSessionOperatorAuthorityBundle.BUNDLE_VERSION, "17", "4", "3")); + AccountStartSessionOperatorAuthorityBundle.BUNDLE_VERSION, "17", "4", "3"), + tupleBytes); + } + + private static byte[] originalPostAuthorizationTuple() { + StartSessionPreAuthorizationReservationTuple preTuple = + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + new String(canonicalTupleBytes(), StandardCharsets.UTF_8)); + byte[] authorityBundle = + StartSessionAuthorityEvidenceBundleFixture.canonicalBytes( + preTuple, + new Values( + ISSUANCE_OPERATION_ID, + "sha256:" + "a".repeat(64), + "17", + "CURRENT", + Instant.parse("2026-10-09T00:00:00Z"), + Instant.parse("2026-10-09T00:03:00Z"), + 1L, + 2L, + 3L, + 4L, + 5L, + 9L, + UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"), + "2", + "3")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + LOGGING_URI, + FINGERPRINT, + RESERVATION_OWNER_ID, + 3L, + authorityBundle, + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "4", "3")) + .canonicalBytes(); } private static UnknownFieldSet unknownFields() { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepositoryTest.java new file mode 100644 index 0000000000..38e341c74e --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepositoryTest.java @@ -0,0 +1,679 @@ +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.jooq.impl.DSL.field; +import static org.jooq.impl.DSL.name; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.startsWith; +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.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.lang.reflect.InvocationTargetException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.OffsetDateTime; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority.Snapshot; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.jooq.impl.SQLDataType; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountStartSessionAuthorityCaptureRepositoryTest { + private static final String REQUEST_ID = "capture-repository-unit"; + private static final String CAPTURED_AT = "2026-10-10T12:34:56.789Z"; + private static final UUID ACCOUNT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID RESERVATION_OWNER_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID CONTROL_UI_OPERATION_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID CONTROL_UI_TOKEN_JTI = + UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final long ISSUANCE_EXPIRES_AT_EPOCH_SECOND = 1_900_000_000L; + private static final long REGISTRY_CLEANUP_MARGIN_MILLIS = 300_000L; + + private static final Field CONTROL_PLANE_REQUEST_ID = + field(name("control_plane_request_id"), SQLDataType.VARCHAR); + private static final Field ACCOUNT_UUID = field(name("account_uuid"), SQLDataType.UUID); + private static final Field TENANT_UUID = field(name("tenant_uuid"), SQLDataType.UUID); + private static final Field TARGET_OWNER = + field(name("target_owner"), SQLDataType.VARCHAR); + private static final Field LOGGING_WORKLOAD_URI = + field(name("logging_workload_uri"), SQLDataType.VARCHAR); + private static final Field RESERVATION_OWNER_UUID = + field(name("reservation_owner_id"), SQLDataType.UUID); + private static final Field RESERVATION_CLAIM_FENCE = + field(name("reservation_claim_fence"), SQLDataType.BIGINT); + private static final Field MUTATION_DIGEST = + field(name("mutation_digest"), SQLDataType.VARCHAR); + private static final Field CONTROL_UI_OPERATION_UUID = + field(name("control_ui_operation_id"), SQLDataType.UUID); + private static final Field CONTROL_UI_TOKEN_UUID = + field(name("control_ui_token_jti"), SQLDataType.UUID); + private static final Field CONTROL_UI_TOKEN_HASH = + field(name("control_ui_token_hash"), SQLDataType.VARCHAR); + private static final Field SIGNER_RECEIPT_SHA256 = + field(name("control_ui_signer_receipt_sha256"), SQLDataType.VARCHAR); + private static final Field ISSUANCE_FENCE = + field(name("issuance_fence"), SQLDataType.BIGINT); + private static final Field ISSUANCE_FENCE_SOURCE_VERSION = + field(name("issuance_fence_source_version"), SQLDataType.BIGINT); + private static final Field CAPTURED_AT_FIELD = + field(name("captured_at"), SQLDataType.VARCHAR); + private static final Field SNAPSHOT_SHA256 = + field(name("snapshot_sha256"), SQLDataType.VARCHAR); + private static final Field SNAPSHOT_BYTES = + field(name("canonical_snapshot_bytes"), SQLDataType.VARBINARY); + private static final Field SOURCE_VERSION = + field(name("source_version"), SQLDataType.BIGINT); + private static final Field SOURCE_FENCE = field(name("source_fence"), SQLDataType.BIGINT); + private static final Field LINEARIZATION = + field(name("linearization"), SQLDataType.VARCHAR); + private static final Field CANONICAL_SHA256 = + field(name("canonical_sha256"), SQLDataType.VARCHAR); + private static final Field CANONICAL_BYTES = + field(name("canonical_capture_bytes"), SQLDataType.VARBINARY); + private static final Field PRE_AUTHORIZATION_TUPLE = + field(name("pre_authorization_tuple"), SQLDataType.VARBINARY); + private static final Field ISSUANCE_REQUEST_ID = + field(name("request_id"), SQLDataType.UUID); + private static final Field ISSUANCE_OPERATION_ID = + field(name("operation_id"), SQLDataType.UUID); + private static final Field ISSUANCE_TOKEN_JTI = field(name("token_jti"), SQLDataType.UUID); + private static final Field ISSUANCE_CALLER_CONTEXT_ID = + field(name("caller_context_id"), SQLDataType.UUID); + private static final Field ISSUANCE_CALLER_WORKLOAD = + field(name("caller_workload"), SQLDataType.VARCHAR); + private static final Field ISSUANCE_REQUEST_MAC_KEY_ID = + field(name("request_mac_key_id"), SQLDataType.VARCHAR); + private static final Field ISSUANCE_REQUEST_DIGEST = + field(name("request_digest"), SQLDataType.VARCHAR); + private static final Field ISSUANCE_STATUS = field(name("status"), SQLDataType.VARCHAR); + private static final Field ISSUANCE_TOKEN_HASH = + field(name("token_hash"), SQLDataType.VARCHAR); + private static final Field ISSUANCE_CLAIMS = + field(name("claims_payload"), SQLDataType.VARBINARY); + private static final Field ISSUANCE_SOURCES = + field(name("source_payload"), SQLDataType.VARBINARY); + private static final Field ISSUANCE_BUNDLE = + field(name("bundle_payload"), SQLDataType.VARBINARY); + private static final Field ISSUANCE_SIGNER_RECEIPT = + field(name("signer_receipt"), SQLDataType.VARBINARY); + private static final Field ISSUANCE_PENDING_REGISTRY = + field(name("pending_registry"), SQLDataType.VARBINARY); + private static final Field ISSUANCE_ACTIVE_REGISTRY = + field(name("active_registry"), SQLDataType.VARBINARY); + private static final Field ISSUANCE_CREATED_AT = + field(name("issued_at_epoch_second"), SQLDataType.BIGINT); + private static final Field ISSUANCE_EXPIRES_AT = + field(name("expires_at_epoch_second"), SQLDataType.BIGINT); + private static final Field ISSUANCE_REGISTRY_CLEANUP_DEADLINE = + field(name("registry_cleanup_deadline_epoch_millis"), SQLDataType.BIGINT); + private static final Field ISSUANCE_RECOVERY_EXPIRES_AT = + field(name("recovery_expires_at"), SQLDataType.OFFSETDATETIME); + + private static final String NAMESPACE = "gameplay"; + private static final String LOGGING_PEER_URI = + "spiffe://firemud/ns/gameplay/sa/logging-admin-service"; + private static final String WORLD_PEER_URI = + "spiffe://firemud/ns/gameplay/sa/world-management-service"; + private static final String GAME_SESSION_PEER_URI = + "spiffe://firemud/ns/gameplay/sa/game-session-service"; + + @AfterEach + void clearContext() { + TransactionSynchronizationManager.clear(); + SessionContext.clear(); + } + + @Test + void decodesCanonicalSnapshotUuidsFromTypedJooqUuidColumns() { + CaptureFixture fixture = fixture(ACCOUNT_ID.toString()); + + assertThat(fixture.row().get(ACCOUNT_UUID, UUID.class)).isEqualTo(ACCOUNT_ID); + assertThat(fixture.row().get(TENANT_UUID, UUID.class)).isEqualTo(TENANT_ID); + assertThat(decode(fixture.row()).sameStoredValue(fixture.capture())).isTrue(); + } + + @Test + void rejectsWrongMissingAndMalformedSnapshotUuidEvidence() { + assertUnavailable(fixture("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa").row()); + assertUnavailable(fixture("not-a-uuid").row()); + assertUnavailable(fixture(null).row()); + + CaptureFixture missingStoredUuid = fixture(ACCOUNT_ID.toString()); + missingStoredUuid.row().setValue(ACCOUNT_UUID, (UUID) null); + assertUnavailable(missingStoredUuid.row()); + } + + @Test + void worldReceivingLookupAcceptsWorldPeerAndRetainedLoggingIssuer() { + WorldLookupFixture fixture = worldLookupFixture(true); + beginOwnerTransaction(); + + AccountStartSessionAuthorityCapture observed = + withPeer(WORLD_PEER_URI, NAMESPACE, "world-management-service") + .call( + () -> + fixture + .repository() + .lockReadExactCurrentFromWorldReceiving( + fixture.current(), + fixture.tuple(), + LOGGING_PEER_URI, + RESERVATION_OWNER_ID, + 7L, + WORLD_PEER_URI)); + + assertThat(observed.sameStoredValue(fixture.capture())).isTrue(); + verify(fixture.dsl(), times(1)) + .fetchOne(startsWith("SELECT control_plane_request_id"), any(Object[].class)); + verifyNoMoreInteractions(fixture.dsl()); + } + + @Test + void worldReceivingLookupRejectsWrongPeerAndNamespaceBeforeStorage() { + WorldLookupFixture fixture = worldLookupFixture(true); + beginOwnerTransaction(); + + assertUnavailable( + () -> + withPeer(LOGGING_PEER_URI, NAMESPACE, "logging-admin-service") + .call( + () -> + fixture + .repository() + .lockReadExactCurrentFromWorldReceiving( + fixture.current(), + fixture.tuple(), + LOGGING_PEER_URI, + RESERVATION_OWNER_ID, + 7L, + WORLD_PEER_URI))); + assertUnavailable( + () -> + withPeer( + "spiffe://firemud/ns/other/sa/world-management-service", + "other", + "world-management-service") + .call( + () -> + fixture + .repository() + .lockReadExactCurrentFromWorldReceiving( + fixture.current(), + fixture.tuple(), + LOGGING_PEER_URI, + RESERVATION_OWNER_ID, + 7L, + WORLD_PEER_URI))); + + verifyNoInteractions(fixture.dsl()); + } + + @Test + void worldReceivingLookupRejectsAmbientEndUserContextBeforeStorage() { + WorldLookupFixture fixture = worldLookupFixture(true); + beginOwnerTransaction(); + SessionContext.setContext("account-user", List.of("tenantAdmin"), Map.of()); + + assertUnavailable( + () -> + withPeer(WORLD_PEER_URI, NAMESPACE, "world-management-service") + .call( + () -> + fixture + .repository() + .lockReadExactCurrentFromWorldReceiving( + fixture.current(), + fixture.tuple(), + LOGGING_PEER_URI, + RESERVATION_OWNER_ID, + 7L, + WORLD_PEER_URI))); + + verifyNoInteractions(fixture.dsl()); + } + + @Test + void worldReceivingLookupDoesNotCreateMissingOriginalCapture() { + WorldLookupFixture fixture = worldLookupFixture(false); + beginOwnerTransaction(); + + assertUnavailable( + () -> + withPeer(WORLD_PEER_URI, NAMESPACE, "world-management-service") + .call( + () -> + fixture + .repository() + .lockReadExactCurrentFromWorldReceiving( + fixture.current(), + fixture.tuple(), + LOGGING_PEER_URI, + RESERVATION_OWNER_ID, + 7L, + WORLD_PEER_URI))); + + verify(fixture.dsl(), times(1)) + .fetchOne(startsWith("SELECT control_plane_request_id"), any(Object[].class)); + verifyNoMoreInteractions(fixture.dsl()); + } + + @Test + void existingExactCurrentReadStillRequiresLoggingPeer() { + WorldLookupFixture fixture = worldLookupFixture(true); + beginOwnerTransaction(); + + assertUnavailable( + () -> + withPeer(WORLD_PEER_URI, NAMESPACE, "world-management-service") + .call( + () -> + fixture + .repository() + .lockReadExactCurrent( + fixture.current(), + fixture.tuple(), + LOGGING_PEER_URI, + RESERVATION_OWNER_ID, + 7L))); + assertThat( + withPeer(LOGGING_PEER_URI, NAMESPACE, "logging-admin-service") + .call( + () -> + fixture + .repository() + .lockReadExactCurrent( + fixture.current(), + fixture.tuple(), + LOGGING_PEER_URI, + RESERVATION_OWNER_ID, + 7L)) + .sameStoredValue(fixture.capture())) + .isTrue(); + } + + private static CaptureFixture fixture(String snapshotAccountId) { + Map snapshot = new LinkedHashMap<>(); + snapshot.put("schema", "account-start-session-authority-snapshot/v1"); + snapshot.put( + "preAuthorizationTuple", + java.util.Base64.getEncoder() + .encodeToString("canonical tuple".getBytes(StandardCharsets.UTF_8))); + snapshot.put("mutationDigest", "a".repeat(64)); + if (snapshotAccountId != null) snapshot.put("accountId", snapshotAccountId); + snapshot.put("tenantId", TENANT_ID.toString()); + snapshot.put("targetOwner", "game-session-service"); + snapshot.put("loggingWorkloadUri", "spiffe://firemud/ns/gameplay/sa/logging-admin-service"); + snapshot.put("reservationOwnerId", RESERVATION_OWNER_ID.toString()); + snapshot.put("reservationClaimFence", "7"); + snapshot.put("controlUiOperationId", CONTROL_UI_OPERATION_ID.toString()); + snapshot.put("controlUiTokenJti", CONTROL_UI_TOKEN_JTI.toString()); + snapshot.put("controlUiTokenHash", "b".repeat(64)); + snapshot.put("controlUiSignerReceiptSha256", "c".repeat(64)); + snapshot.put("issuanceFence", "9"); + snapshot.put("issuanceFenceSourceVersion", "10"); + + byte[] snapshotBytes = AccountControlUiAuthority.canonical(snapshot); + AccountStartSessionAuthorityCapture capture = + AccountStartSessionAuthorityCapture.create( + REQUEST_ID, 11L, 13L, "17", CAPTURED_AT, snapshotBytes); + + Record row = + DSL.using(SQLDialect.POSTGRES) + .newRecord( + CONTROL_PLANE_REQUEST_ID, + ACCOUNT_UUID, + TENANT_UUID, + TARGET_OWNER, + LOGGING_WORKLOAD_URI, + RESERVATION_OWNER_UUID, + RESERVATION_CLAIM_FENCE, + MUTATION_DIGEST, + CONTROL_UI_OPERATION_UUID, + CONTROL_UI_TOKEN_UUID, + CONTROL_UI_TOKEN_HASH, + SIGNER_RECEIPT_SHA256, + ISSUANCE_FENCE, + ISSUANCE_FENCE_SOURCE_VERSION, + CAPTURED_AT_FIELD, + SNAPSHOT_SHA256, + SNAPSHOT_BYTES, + SOURCE_VERSION, + SOURCE_FENCE, + LINEARIZATION, + CANONICAL_SHA256, + CANONICAL_BYTES); + row.setValue(CONTROL_PLANE_REQUEST_ID, REQUEST_ID); + row.setValue(ACCOUNT_UUID, ACCOUNT_ID); + row.setValue(TENANT_UUID, TENANT_ID); + row.setValue(TARGET_OWNER, "game-session-service"); + row.setValue(LOGGING_WORKLOAD_URI, "spiffe://firemud/ns/gameplay/sa/logging-admin-service"); + row.setValue(RESERVATION_OWNER_UUID, RESERVATION_OWNER_ID); + row.setValue(RESERVATION_CLAIM_FENCE, 7L); + row.setValue(MUTATION_DIGEST, "a".repeat(64)); + row.setValue(CONTROL_UI_OPERATION_UUID, CONTROL_UI_OPERATION_ID); + row.setValue(CONTROL_UI_TOKEN_UUID, CONTROL_UI_TOKEN_JTI); + row.setValue(CONTROL_UI_TOKEN_HASH, "b".repeat(64)); + row.setValue(SIGNER_RECEIPT_SHA256, "c".repeat(64)); + row.setValue(ISSUANCE_FENCE, 9L); + row.setValue(ISSUANCE_FENCE_SOURCE_VERSION, 10L); + row.setValue(CAPTURED_AT_FIELD, CAPTURED_AT); + row.setValue(SNAPSHOT_SHA256, capture.snapshotSha256()); + row.setValue(SNAPSHOT_BYTES, capture.snapshotBytes()); + row.setValue(SOURCE_VERSION, 11L); + row.setValue(SOURCE_FENCE, 13L); + row.setValue(LINEARIZATION, "17"); + row.setValue(CANONICAL_SHA256, capture.canonicalSha256()); + row.setValue(CANONICAL_BYTES, capture.canonicalBytes()); + return new CaptureFixture(row, capture); + } + + private static AccountStartSessionAuthorityCapture decode(Record row) { + try { + var method = + AccountStartSessionAuthorityCaptureRepository.class.getDeclaredMethod( + "decode", Record.class); + method.setAccessible(true); + return (AccountStartSessionAuthorityCapture) + method.invoke( + new AccountStartSessionAuthorityCaptureRepository(DSL.using(SQLDialect.POSTGRES)), + row); + } catch (InvocationTargetException failure) { + if (failure.getCause() instanceof RuntimeException runtime) throw runtime; + throw new AssertionError("Unexpected capture decode failure", failure.getCause()); + } catch (ReflectiveOperationException failure) { + throw new AssertionError("Could not invoke capture decoder", failure); + } + } + + private static void assertUnavailable(Record row) { + assertThatThrownBy(() -> decode(row)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account StartSession source capture is unavailable"); + } + + private static void assertUnavailable(ThrowingCallable action) { + assertThatThrownBy(action) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account StartSession source capture is unavailable"); + } + + private static WorldLookupFixture worldLookupFixture(boolean capturePresent) { + StartSessionPreAuthorizationReservationTuple tuple = tuple(); + Snapshot source = sourceSnapshot(); + var stored = issuance(tuple); + CaptureFixture capture = worldCapture(tuple, source, stored); + DSLContext dsl = mock(DSLContext.class); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenReturn(capturePresent ? capture.row() : null); + return new WorldLookupFixture( + dsl, + new AccountStartSessionAuthorityCaptureRepository(dsl), + new AccountControlUiActorService.Current(stored, source), + tuple, + capture.capture()); + } + + private static StartSessionPreAuthorizationReservationTuple tuple() { + var action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, NAMESPACE), + new StartSessionOperatorAction.Target(71L, ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "capture lookup test"); + return StartSessionPreAuthorizationReservationTuple.createHuman(REQUEST_ID, ACCOUNT_ID, action); + } + + private static Snapshot sourceSnapshot() { + SourceEvidence sourceEvidence = + new SourceEvidence( + SourceKind.TENANT, + TENANT_ID.toString(), + "3", + "4", + null, + null, + "exact tenant source".getBytes(StandardCharsets.UTF_8)); + try { + var constructor = + Snapshot.class.getDeclaredConstructor( + UUID.class, + UUID.class, + Map.class, + Map.class, + long.class, + long.class, + List.class, + byte[].class, + List.class, + Map.class); + constructor.setAccessible(true); + return constructor.newInstance( + ACCOUNT_ID, + TENANT_ID, + Map.of("issuerAuthGeneration", 1L), + Map.of(TENANT_ID.toString(), 2L), + 9L, + 10L, + List.of(sourceEvidence), + "exact source vector".getBytes(StandardCharsets.UTF_8), + List.of(), + Map.of("sourceRowId", 17L, "provenance", "canonical", "sourceNumericId", 17L)); + } catch (ReflectiveOperationException failure) { + throw new AssertionError("Could not construct the captured Account source fixture", failure); + } + } + + private static AccountControlUiIssuanceRepository.Stored issuance( + StartSessionPreAuthorizationReservationTuple tuple) { + Record row = + DSL.using(SQLDialect.POSTGRES) + .newRecord( + ISSUANCE_REQUEST_ID, + ISSUANCE_OPERATION_ID, + ISSUANCE_TOKEN_JTI, + ACCOUNT_UUID, + TENANT_UUID, + ISSUANCE_CALLER_CONTEXT_ID, + ISSUANCE_CALLER_WORKLOAD, + ISSUANCE_REQUEST_MAC_KEY_ID, + ISSUANCE_REQUEST_DIGEST, + ISSUANCE_STATUS, + ISSUANCE_TOKEN_HASH, + ISSUANCE_CLAIMS, + ISSUANCE_SOURCES, + ISSUANCE_BUNDLE, + ISSUANCE_SIGNER_RECEIPT, + ISSUANCE_PENDING_REGISTRY, + ISSUANCE_ACTIVE_REGISTRY, + ISSUANCE_CREATED_AT, + ISSUANCE_EXPIRES_AT, + ISSUANCE_REGISTRY_CLEANUP_DEADLINE, + ISSUANCE_RECOVERY_EXPIRES_AT); + row.setValue(ISSUANCE_REQUEST_ID, CONTROL_UI_OPERATION_ID); + row.setValue(ISSUANCE_OPERATION_ID, CONTROL_UI_OPERATION_ID); + row.setValue(ISSUANCE_TOKEN_JTI, CONTROL_UI_TOKEN_JTI); + row.setValue(ACCOUNT_UUID, tuple.actor().accountId()); + row.setValue(TENANT_UUID, tuple.action().scope().tenantId()); + row.setValue( + ISSUANCE_CALLER_CONTEXT_ID, UUID.fromString("66666666-6666-4666-8666-666666666666")); + row.setValue(ISSUANCE_CALLER_WORKLOAD, LOGGING_PEER_URI); + row.setValue(ISSUANCE_REQUEST_MAC_KEY_ID, "capture-test-key"); + row.setValue(ISSUANCE_REQUEST_DIGEST, "request-digest"); + row.setValue(ISSUANCE_STATUS, "COMMITTED"); + row.setValue(ISSUANCE_TOKEN_HASH, "b".repeat(64)); + row.setValue(ISSUANCE_CLAIMS, "claims".getBytes(StandardCharsets.UTF_8)); + row.setValue(ISSUANCE_SOURCES, "sources".getBytes(StandardCharsets.UTF_8)); + row.setValue(ISSUANCE_BUNDLE, "bundle".getBytes(StandardCharsets.UTF_8)); + row.setValue( + ISSUANCE_SIGNER_RECEIPT, "original signer receipt".getBytes(StandardCharsets.UTF_8)); + row.setValue(ISSUANCE_PENDING_REGISTRY, "pending".getBytes(StandardCharsets.UTF_8)); + row.setValue(ISSUANCE_ACTIVE_REGISTRY, "active".getBytes(StandardCharsets.UTF_8)); + row.setValue(ISSUANCE_CREATED_AT, 1_800_000_000L); + row.setValue(ISSUANCE_EXPIRES_AT, ISSUANCE_EXPIRES_AT_EPOCH_SECOND); + row.setValue( + ISSUANCE_REGISTRY_CLEANUP_DEADLINE, + ISSUANCE_EXPIRES_AT_EPOCH_SECOND * 1_000L + REGISTRY_CLEANUP_MARGIN_MILLIS); + row.setValue(ISSUANCE_RECOVERY_EXPIRES_AT, OffsetDateTime.parse("2040-01-01T00:00:00Z")); + return new AccountControlUiIssuanceRepository.Stored(row); + } + + private static CaptureFixture worldCapture( + StartSessionPreAuthorizationReservationTuple tuple, + Snapshot source, + AccountControlUiIssuanceRepository.Stored stored) { + byte[] tupleBytes = tuple.canonicalJson().getBytes(StandardCharsets.UTF_8); + Map snapshot = new LinkedHashMap<>(); + snapshot.put("schema", "account-start-session-authority-snapshot/v1"); + snapshot.put("controlPlaneRequestId", tuple.controlPlaneRequestId()); + snapshot.put("preAuthorizationTuple", Base64.getEncoder().encodeToString(tupleBytes)); + snapshot.put("mutationDigest", tuple.mutationDigest()); + snapshot.put("accountId", stored.accountId.toString()); + snapshot.put("tenantId", stored.tenantId.toString()); + snapshot.put("targetOwner", tuple.targetOwner()); + snapshot.put("loggingWorkloadUri", LOGGING_PEER_URI); + snapshot.put("reservationOwnerId", RESERVATION_OWNER_ID.toString()); + snapshot.put("reservationClaimFence", "7"); + snapshot.put("controlUiOperationId", stored.operationId.toString()); + snapshot.put("controlUiTokenJti", stored.jti.toString()); + snapshot.put("controlUiTokenHash", stored.tokenHash); + snapshot.put( + "controlUiSignerReceipt", Base64.getEncoder().encodeToString(stored.signerReceipt)); + snapshot.put("controlUiSignerReceiptSha256", sha256(stored.signerReceipt)); + snapshot.put("sourceVectorEvidence", Base64.getEncoder().encodeToString(source.evidence())); + snapshot.put( + "sourceVector", + source.sources().stream() + .map(value -> Base64.getEncoder().encodeToString(value.canonicalBytes())) + .toList()); + snapshot.put("outboxCheckpoints", source.outboxCheckpoints()); + snapshot.put("authorityTuple", source.authorityTuple()); + snapshot.put("membershipVersion", source.membershipVersion()); + snapshot.put("accountIdentitySource", source.accountIdentitySource()); + snapshot.put("issuanceFence", Long.toString(source.issuanceFence())); + snapshot.put("issuanceFenceSourceVersion", Long.toString(source.issuanceFenceSourceVersion())); + byte[] snapshotBytes = AccountControlUiAuthority.canonical(Map.copyOf(snapshot)); + AccountStartSessionAuthorityCapture capture = + AccountStartSessionAuthorityCapture.create( + tuple.controlPlaneRequestId(), 11L, 13L, "17", CAPTURED_AT, snapshotBytes); + Record row = + DSL.using(SQLDialect.POSTGRES) + .newRecord( + CONTROL_PLANE_REQUEST_ID, + ACCOUNT_UUID, + TENANT_UUID, + TARGET_OWNER, + LOGGING_WORKLOAD_URI, + RESERVATION_OWNER_UUID, + RESERVATION_CLAIM_FENCE, + PRE_AUTHORIZATION_TUPLE, + MUTATION_DIGEST, + CONTROL_UI_OPERATION_UUID, + CONTROL_UI_TOKEN_UUID, + CONTROL_UI_TOKEN_HASH, + SIGNER_RECEIPT_SHA256, + ISSUANCE_FENCE, + ISSUANCE_FENCE_SOURCE_VERSION, + CAPTURED_AT_FIELD, + SNAPSHOT_SHA256, + SNAPSHOT_BYTES, + SOURCE_VERSION, + SOURCE_FENCE, + LINEARIZATION, + CANONICAL_SHA256, + CANONICAL_BYTES); + row.setValue(CONTROL_PLANE_REQUEST_ID, tuple.controlPlaneRequestId()); + row.setValue(ACCOUNT_UUID, tuple.actor().accountId()); + row.setValue(TENANT_UUID, tuple.action().scope().tenantId()); + row.setValue(TARGET_OWNER, tuple.targetOwner()); + row.setValue(LOGGING_WORKLOAD_URI, LOGGING_PEER_URI); + row.setValue(RESERVATION_OWNER_UUID, RESERVATION_OWNER_ID); + row.setValue(RESERVATION_CLAIM_FENCE, 7L); + row.setValue(PRE_AUTHORIZATION_TUPLE, tupleBytes); + row.setValue(MUTATION_DIGEST, tuple.mutationDigest()); + row.setValue(CONTROL_UI_OPERATION_UUID, stored.operationId); + row.setValue(CONTROL_UI_TOKEN_UUID, stored.jti); + row.setValue(CONTROL_UI_TOKEN_HASH, stored.tokenHash); + row.setValue(SIGNER_RECEIPT_SHA256, sha256(stored.signerReceipt)); + row.setValue(ISSUANCE_FENCE, source.issuanceFence()); + row.setValue(ISSUANCE_FENCE_SOURCE_VERSION, source.issuanceFenceSourceVersion()); + row.setValue(CAPTURED_AT_FIELD, CAPTURED_AT); + row.setValue(SNAPSHOT_SHA256, capture.snapshotSha256()); + row.setValue(SNAPSHOT_BYTES, capture.snapshotBytes()); + row.setValue(SOURCE_VERSION, capture.sourceVersion()); + row.setValue(SOURCE_FENCE, capture.sourceFence()); + row.setValue(LINEARIZATION, capture.linearization()); + row.setValue(CANONICAL_SHA256, capture.canonicalSha256()); + row.setValue(CANONICAL_BYTES, capture.canonicalBytes()); + return new CaptureFixture(row, capture); + } + + private static String sha256(byte[] bytes) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new AssertionError("SHA-256 is required", impossible); + } + } + + private static void beginOwnerTransaction() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } + + private static PeerContext withPeer(String uri, String namespace, String service) { + return new PeerContext(new GrpcPeerIdentity(uri, namespace, service)); + } + + private record CaptureFixture(Record row, AccountStartSessionAuthorityCapture capture) {} + + private record WorldLookupFixture( + DSLContext dsl, + AccountStartSessionAuthorityCaptureRepository repository, + AccountControlUiActorService.Current current, + StartSessionPreAuthorizationReservationTuple tuple, + AccountStartSessionAuthorityCapture capture) {} + + private record PeerContext(GrpcPeerIdentity peer) { + T call(Supplier action) { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureTest.java new file mode 100644 index 0000000000..4ad82f5835 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureTest.java @@ -0,0 +1,139 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.Map; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import org.junit.jupiter.api.Test; + +class AccountStartSessionAuthorityCaptureTest { + @Test + void referenceIdentifiesTheDurableCaptureAndRetainsIndependentFenceValues() { + byte[] snapshot = + AccountControlUiAuthority.canonical( + Map.of( + "accountSourceVersion", "41", + "issuanceFence", "9", + "issuanceFenceSourceVersion", "12", + "sourceVector", java.util.List.of("vector-entry"), + "outboxCheckpoints", java.util.List.of(Map.of("stream", "account/one", "seq", "7")), + "tuple", "exact-tuple")); + + // The two independent numeric domains may coincide; the bundle reference still denotes the + // durable capture allocations and never substitutes them for the actual Account fence. + var capture = + AccountStartSessionAuthorityCapture.create( + "control-plane-request-1", + 9L, + 9L, + "18446744073709551615", + "2026-10-10T12:34:56.789Z", + snapshot); + + assertThat(capture.bundleReference().sourceVersion()).isEqualTo("9"); + assertThat(capture.bundleReference().sourceFence()).isEqualTo("9"); + assertThat(capture.bundleReference().linearization()).isEqualTo("18446744073709551615"); + assertThat(capture.capturedAt()).isEqualTo("2026-10-10T12:34:56.789Z"); + assertThat(capture.snapshotSha256()).hasSize(64); + assertThat(capture.canonicalSha256()).hasSize(64); + assertThat(capture.canonicalBytes()) + .contains("account-start-session-authority-capture/v1".getBytes(StandardCharsets.UTF_8)); + + var readBack = + AccountStartSessionAuthorityCapture.fromStorage( + capture.controlPlaneRequestId(), + capture.sourceVersion(), + capture.sourceFence(), + capture.linearization(), + capture.capturedAt(), + capture.snapshotBytes(), + capture.snapshotSha256(), + capture.canonicalBytes(), + capture.canonicalSha256()); + assertThat(readBack.sameStoredValue(capture)).isTrue(); + assertThat(readBack.bundleReference()).isEqualTo(capture.bundleReference()); + } + + @Test + void snapshotBytesAndReferenceBytesAreDefensiveAndChangingFenceSourceChangesCapture() { + byte[] originalSnapshot = + AccountControlUiAuthority.canonical( + Map.of( + "issuanceFence", + "25", + "issuanceFenceSourceVersion", + "31", + "sourceVector", + java.util.List.of("same-vector"), + "checkpoints", + java.util.List.of("same-checkpoint"))); + var original = + AccountStartSessionAuthorityCapture.create( + "control-plane-request-2", + 44L, + 57L, + "812", + "2026-10-10T12:34:56.789Z", + originalSnapshot); + + byte[] returnedSnapshot = original.snapshotBytes(); + byte[] returnedReference = original.canonicalBytes(); + returnedSnapshot[0] ^= 1; + returnedReference[0] ^= 1; + assertThat(original.snapshotBytes()).isEqualTo(originalSnapshot); + assertThat(original.canonicalBytes()) + .contains("account-start-session-authority-capture/v1".getBytes(StandardCharsets.UTF_8)); + + byte[] changedFenceVersion = + AccountControlUiAuthority.canonical( + Map.of( + "issuanceFence", + "25", + "issuanceFenceSourceVersion", + "32", + "sourceVector", + java.util.List.of("same-vector"), + "checkpoints", + java.util.List.of("same-checkpoint"))); + var changed = + AccountStartSessionAuthorityCapture.create( + "control-plane-request-2", + 45L, + 58L, + "813", + "2026-10-10T12:34:56.790Z", + changedFenceVersion); + + assertThat(original.sameSnapshot(changed)).isFalse(); + assertThat(original.bundleReference()).isNotEqualTo(changed.bundleReference()); + } + + @Test + void rejectsMismatchedRetainedCaptureDigestAndNonPositiveCaptureAllocations() { + byte[] snapshot = AccountControlUiAuthority.canonical(Map.of("source", "owner")); + var capture = + AccountStartSessionAuthorityCapture.create( + "control-plane-request-3", 1L, 2L, "3", "2026-10-10T12:34:56.789Z", snapshot); + + assertThatThrownBy( + () -> + AccountStartSessionAuthorityCapture.fromStorage( + capture.controlPlaneRequestId(), + 1L, + 2L, + "3", + capture.capturedAt(), + snapshot, + "0".repeat(64), + capture.canonicalBytes(), + capture.canonicalSha256())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountStartSessionAuthorityCapture.create( + "control-plane-request-3", 0L, 2L, "3", "2026-10-10T12:34:56.789Z", snapshot)) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java index fffac6fc00..7ea43c5a67 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java @@ -8,9 +8,11 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import java.nio.charset.StandardCharsets; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneOffset; +import java.util.Base64; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -27,25 +29,38 @@ class AccountStartSessionOperatorAuthorityBundleTest { private static final Instant ISSUED_AT = Instant.parse("2026-10-08T11:00:00Z"); @Test - void encodesExactHumanTenantArmAndKeepsOwnerLinearizationSeparate() { + void encodesClosedHumanTenantArmAndBindsCaptureReferenceSeparatelyFromAccountFence() { Fixture fixture = new Fixture(Map.of()); - var linearization = new AccountControlUiIssuanceRepository.OwnerLinearization("123456", 99L); + var capture = fixture.capture(); var bundle = AccountStartSessionOperatorAuthorityBundle.create( fixture.tuple, - fixture.source, + capture, fixture.issuance, UUID.randomUUID(), - linearization, ISSUED_AT, ISSUED_AT.plusSeconds(60)); Map evidence = object(bundle.jsonValue().get("issuanceEvidence")); - var reference = bundle.referenceForSource(fixture.source, linearization); + var reference = bundle.referenceForCapture(capture); assertThat(bundle.jsonValue()) .containsEntry("bundleVersion", "authorityEvidenceBundle/v1") .containsEntry("issuanceKind", "human_operator") - .doesNotContainKey("sourceReference"); + .containsEntry("issuanceFence", Long.toString(fixture.source.issuanceFence())) + .doesNotContainKeys("sourceReference", "captureReference"); + assertThat(object(bundle.jsonValue().get("accountProjectionEvidence"))) + .containsEntry("evaluatedAt", ISSUED_AT.toString()); + assertThat(bundle.jsonValue().keySet()) + .containsExactlyInAnyOrder( + "bundleVersion", + "authorityScope", + "accountProjectionEvidence", + "issuanceOperationIdentity", + "issuanceKind", + "authorityTuple", + "membershipVersion", + "issuanceFence", + "issuanceEvidence"); assertThat(evidence) .containsEntry("evidenceType", "HumanAuthorityEvidence/v1") .containsEntry("actorAccountId", fixture.actorId.toString()) @@ -63,8 +78,12 @@ void encodesExactHumanTenantArmAndKeepsOwnerLinearizationSeparate() { assertThat(reference.asJsonValue()) .containsEntry("bundleVersion", "authorityEvidenceBundle/v1") .containsEntry("sourceVersion", "7") - .containsEntry("sourceFence", "99") + .containsEntry("sourceFence", "31") .containsEntry("linearization", "123456"); + assertThat(reference.sourceFence()).isNotEqualTo(Long.toString(fixture.source.issuanceFence())); + assertThat(new String(capture.snapshotBytes(), StandardCharsets.UTF_8)) + .contains("\"issuanceFence\":\"70\"") + .contains("\"issuanceFenceSourceVersion\":\"107\""); var decoded = AccountStartSessionOperatorAuthorityBundle.decode(bundle.canonicalBytes()); decoded.requireTupleBinding(fixture.tuple); @@ -124,14 +143,13 @@ void strictDecoderRejectsTenantAssuranceAndGlobalBranchEvidence() { @Test void currentSourceMustRetainExactActorGenerationAndSelectedTenant() { Fixture fixture = new Fixture(Map.of()); - var linearization = new AccountControlUiIssuanceRepository.OwnerLinearization("123456", 99L); + var capture = fixture.capture(); var bundle = AccountStartSessionOperatorAuthorityBundle.create( fixture.tuple, - fixture.source, + capture, fixture.issuance, UUID.randomUUID(), - linearization, ISSUED_AT, ISSUED_AT.plusSeconds(60)); var substitutedSource = @@ -143,7 +161,7 @@ void currentSourceMustRetainExactActorGenerationAndSelectedTenant() { substitutedSource, fixture.issuance, fixture.tuple, - bundle.referenceForSource(fixture.source, linearization), + bundle.referenceForCapture(capture), ISSUED_AT.plusSeconds(1))) .isInstanceOf(IllegalStateException.class); } @@ -151,17 +169,16 @@ void currentSourceMustRetainExactActorGenerationAndSelectedTenant() { @Test void expiredOrChangedCurrentAuthorityIsPreconditionFailureButMalformedBundleIsInvalid() { Fixture fixture = new Fixture(Map.of()); - var linearization = new AccountControlUiIssuanceRepository.OwnerLinearization("123456", 99L); + var capture = fixture.capture(); var bundle = AccountStartSessionOperatorAuthorityBundle.create( fixture.tuple, - fixture.source, + capture, fixture.issuance, UUID.randomUUID(), - linearization, ISSUED_AT, ISSUED_AT.plusSeconds(60)); - var reference = bundle.referenceForSource(fixture.source, linearization); + var reference = bundle.referenceForCapture(capture); assertThatThrownBy( () -> @@ -193,17 +210,16 @@ void expiredOrChangedCurrentAuthorityIsPreconditionFailureButMalformedBundleIsIn @Test void sameAttemptReplayAfterEnvelopeHorizonRetainsOriginalSourceLinearization() { Fixture fixture = new Fixture(Map.of()); - var linearization = new AccountControlUiIssuanceRepository.OwnerLinearization("123456", 99L); + var capture = fixture.capture(); var bundle = AccountStartSessionOperatorAuthorityBundle.create( fixture.tuple, - fixture.source, + capture, fixture.issuance, UUID.randomUUID(), - linearization, ISSUED_AT, ISSUED_AT.plusSeconds(60)); - var originalReference = bundle.referenceForSource(fixture.source, linearization); + var originalReference = bundle.referenceForCapture(capture); bundle.requireCurrentSnapshotForExactReplay( fixture.source, fixture.issuance, fixture.tuple, originalReference); @@ -257,6 +273,7 @@ private static final class Fixture { tuple(actorId, tenantId, "request-" + UUID.randomUUID()); final AccountControlUiAuthority.Snapshot source; final AccountControlUiIssuanceRepository.Stored issuance; + final UUID reservationOwnerId = UUID.randomUUID(); Fixture(Map additionalClaims) { source = source(actorId, tenantId, 7L, new byte[] {7}, 1L); @@ -265,13 +282,55 @@ private static final class Fixture { AccountStartSessionOperatorAuthorityBundle create() { return AccountStartSessionOperatorAuthorityBundle.create( - tuple, - source, - issuance, - UUID.randomUUID(), - new AccountControlUiIssuanceRepository.OwnerLinearization("123456", 99L), - ISSUED_AT, - ISSUED_AT.plusSeconds(60)); + tuple, capture(), issuance, UUID.randomUUID(), ISSUED_AT, ISSUED_AT.plusSeconds(60)); + } + + AccountStartSessionAuthorityCapture capture() { + byte[] signerReceipt = issuance.signerReceipt.clone(); + Map snapshot = + Map.ofEntries( + Map.entry("schema", "account-start-session-authority-snapshot/v1"), + Map.entry("controlPlaneRequestId", tuple.controlPlaneRequestId()), + Map.entry( + "preAuthorizationTuple", + Base64.getEncoder() + .encodeToString(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8))), + Map.entry("mutationDigest", tuple.mutationDigest()), + Map.entry("accountId", actorId.toString()), + Map.entry("tenantId", tenantId.toString()), + Map.entry("targetOwner", tuple.targetOwner()), + Map.entry("loggingWorkloadUri", "spiffe://firemud/ns/test/sa/logging-admin-service"), + Map.entry("reservationOwnerId", reservationOwnerId.toString()), + Map.entry("reservationClaimFence", "3"), + Map.entry("controlUiOperationId", issuance.operationId.toString()), + Map.entry("controlUiTokenJti", issuance.jti.toString()), + Map.entry("controlUiTokenHash", issuance.tokenHash), + Map.entry( + "controlUiSignerReceipt", Base64.getEncoder().encodeToString(signerReceipt)), + Map.entry("controlUiSignerReceiptSha256", sha256(signerReceipt)), + Map.entry( + "sourceVectorEvidence", Base64.getEncoder().encodeToString(source.evidence())), + Map.entry( + "sourceVector", + source.sources().stream() + .map( + evidence -> Base64.getEncoder().encodeToString(evidence.canonicalBytes())) + .toList()), + Map.entry("outboxCheckpoints", source.outboxCheckpoints()), + Map.entry("authorityTuple", source.authorityTuple()), + Map.entry("membershipVersion", source.membershipVersion()), + Map.entry("accountIdentitySource", source.accountIdentitySource()), + Map.entry("issuanceFence", Long.toString(source.issuanceFence())), + Map.entry( + "issuanceFenceSourceVersion", + Long.toString(source.issuanceFenceSourceVersion()))); + return AccountStartSessionAuthorityCapture.create( + tuple.controlPlaneRequestId(), + 7L, + 31L, + "123456", + "2026-10-08T11:00:00.000Z", + AccountControlUiAuthority.canonical(snapshot)); } AccountControlUiAuthority.Snapshot source( @@ -293,7 +352,13 @@ AccountControlUiAuthority.Snapshot source( when(snapshot.tenant()).thenReturn(tenant); when(snapshot.authorityTuple()).thenReturn(authorityTuple); when(snapshot.membershipVersion()).thenReturn(Map.of(tenant.toString(), 2L)); + when(snapshot.issuanceFence()).thenReturn(sourceVersion * 10L); + when(snapshot.issuanceFenceSourceVersion()).thenReturn(sourceVersion + 100L); when(snapshot.evidence()).thenReturn(evidence.clone()); + when(snapshot.outboxCheckpoints()) + .thenReturn(List.of(Map.of("stream", "account", "sequence", 1L))); + when(snapshot.accountIdentitySource()) + .thenReturn(Map.of("accountId", actor.toString(), "sourceVersion", sourceVersion)); when(snapshot.sources()) .thenReturn( List.of( @@ -309,6 +374,15 @@ AccountControlUiAuthority.Snapshot source( } } + private static String sha256(byte[] value) { + try { + return java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException unavailable) { + throw new IllegalStateException(unavailable); + } + } + @SuppressWarnings({"unchecked", "rawtypes"}) private static AccountControlUiIssuanceRepository.Stored stored( UUID actorId, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java index 8e2c441e20..f0ad5f07a4 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java @@ -25,6 +25,8 @@ import java.time.OffsetDateTime; import java.time.ZoneId; import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.Base64; import java.util.List; import java.util.Map; import java.util.Optional; @@ -40,16 +42,16 @@ import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository; import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.IssuanceRecord; import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.RedemptionRequest; -import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.RedemptionResult; import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.Status; import net.firedevops.firemud.accountservice.service.session.AccountControlUiActorService.Current; -import net.firedevops.firemud.accountservice.service.session.AccountControlUiIssuanceRepository.OwnerLinearization; import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.ReadRedeemedOperationProjectionRequest; import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RedeemedOperationProjection; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RedemptionResult; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; import org.jooq.Record; @@ -60,6 +62,8 @@ import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.SimpleTransactionStatus; import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.json.JsonMapper; /** Focused flow proof; JWT validation/source locking remain owned by the real actor service. */ class AccountStartSessionOperatorAuthorizationServiceTest { @@ -70,6 +74,8 @@ class AccountStartSessionOperatorAuthorizationServiceTest { private static final String GAME_SESSION_PEER = "spiffe://firemud/ns/test/sa/game-session-service"; private static final String GAME_DESIGN_PEER = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final DateTimeFormatter CAPTURED_AT_FORMAT = + DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC); @TempDir Path temporaryDirectory; @@ -97,6 +103,8 @@ void issuePerformsCryptoOutsideSqlAndRejectsSourceChangeBeforeDurableInsert() { var actors = org.mockito.Mockito.mock(AccountControlUiActorService.class); var issuanceOperations = org.mockito.Mockito.mock(AccountControlUiIssuanceRepository.class); + var captureRepository = + org.mockito.Mockito.mock(AccountStartSessionAuthorityCaptureRepository.class); var claims = org.mockito.Mockito.mock(StartSessionReservationEvidenceClient.class); var repository = org.mockito.Mockito.mock(AccountStartSessionOperatorAuthorizationRepository.class); @@ -112,15 +120,19 @@ void issuePerformsCryptoOutsideSqlAndRejectsSourceChangeBeforeDurableInsert() { when(hostedTerms.captureCurrentEnvironmentBoundary()).thenReturn(environment); when(repository.findByControlPlaneRequestId(tuple.controlPlaneRequestId())) .thenReturn(Optional.empty()); - doAnswer( - ignored -> { - org.assertj.core.api.Assertions.assertThat( - TransactionSynchronizationManager.isActualTransactionActive()) - .isTrue(); - return new OwnerLinearization("123456", 99L); - }) - .when(issuanceOperations) - .captureOwnerLinearization(); + AccountStartSessionAuthorityCapture capture = + capture(tuple, originalSource, stored, requestOwnerId, 10L); + when(captureRepository.prepareOrReadExact(any(), any(), anyString(), any(), anyLong())) + .thenReturn(capture); + when(captureRepository.lockExactCurrent(any(), any(), any(), anyString(), any(), anyLong())) + .thenAnswer( + invocation -> { + Current current = invocation.getArgument(1); + if (current.source() != originalSource) { + throw new IllegalArgumentException("Current Account source changed"); + } + return capture; + }); when(claims.readCurrentClaimEvidence(any(), any(), anyLong(), any(), anyLong(), any())) .thenAnswer( ignored -> { @@ -164,11 +176,25 @@ void issuePerformsCryptoOutsideSqlAndRejectsSourceChangeBeforeDurableInsert() { }) .when(actors) .withCurrent(anyString(), any(), any(), any()); + doAnswer( + invocation -> { + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + @SuppressWarnings("unchecked") + Function action = invocation.getArgument(4); + return action.apply(changed); + } finally { + TransactionSynchronizationManager.clear(); + } + }) + .when(actors) + .withCurrentCommitted(any(), any(), any(), any(), any()); var service = new AccountStartSessionOperatorAuthorizationService( actors, issuanceOperations, + captureRepository, claims, repository, fingerprintKeys, @@ -218,10 +244,16 @@ void ownerIssuesRecoversAndReplaysSameAttemptAcrossReferenceExpiry() throws Exce AccountControlUiAuthority.Snapshot source = source(actorId, tenantId, 7L, new byte[] {1}); AccountControlUiIssuanceRepository.Stored stored = stored(actorId, tenantId, tokenJti, issuerOperationId, source); + AccountStartSessionAuthorityCapture capture = + capture(tuple, source, stored, requestOwnerId, 10L); + Map captures = new ConcurrentHashMap<>(); + captures.put(tuple.controlPlaneRequestId(), capture); Current current = new Current(stored, source); var actors = org.mockito.Mockito.mock(AccountControlUiActorService.class); var issuanceOperations = org.mockito.Mockito.mock(AccountControlUiIssuanceRepository.class); + var captureRepository = + org.mockito.Mockito.mock(AccountStartSessionAuthorityCaptureRepository.class); var claims = org.mockito.Mockito.mock(StartSessionReservationEvidenceClient.class); var repository = org.mockito.Mockito.mock(AccountStartSessionOperatorAuthorizationRepository.class); @@ -244,12 +276,56 @@ void ownerIssuesRecoversAndReplaysSameAttemptAcrossReferenceExpiry() throws Exce when(transactions.getTransaction(any(TransactionDefinition.class))) .thenAnswer(ignored -> new SimpleTransactionStatus()); when(hostedTerms.captureCurrentEnvironmentBoundary()).thenReturn(environment); + when(captureRepository.prepareOrReadExact(any(), any(), anyString(), any(), anyLong())) + .thenAnswer( + invocation -> { + Current requestedCurrent = invocation.getArgument(0); + StartSessionPreAuthorizationReservationTuple requestedTuple = + invocation.getArgument(1); + UUID requestedOwner = invocation.getArgument(3); + long requestedFence = invocation.getArgument(4); + return captures.computeIfAbsent( + requestedTuple.controlPlaneRequestId(), + ignored -> + capture( + requestedTuple, + requestedCurrent.source(), + requestedCurrent.stored(), + requestedOwner, + requestedFence)); + }); + when(captureRepository.lockExactCurrent(any(), any(), any(), anyString(), any(), anyLong())) + .thenAnswer( + invocation -> { + StartSessionPreAuthorizationReservationTuple requestedTuple = + invocation.getArgument(2); + AccountStartSessionAuthorityCapture requestedCapture = + captures.get(requestedTuple.controlPlaneRequestId()); + assertThat(requestedCapture).isNotNull(); + return requestedCapture; + }); + when(captureRepository.lockReadExactCurrent(any(), any(), anyString(), any(), anyLong())) + .thenAnswer( + invocation -> { + StartSessionPreAuthorizationReservationTuple requestedTuple = + invocation.getArgument(1); + AccountStartSessionAuthorityCapture requestedCapture = + captures.get(requestedTuple.controlPlaneRequestId()); + assertThat(requestedCapture).isNotNull(); + return requestedCapture; + }); + AtomicInteger claimReadCount = new AtomicInteger(); when(claims.readCurrentClaimEvidence(any(), any(), anyLong(), any(), anyLong(), any())) .thenAnswer( - invocation -> - claimEvidence( - invocation.getArgument(0), - invocation.getArgument(1))); + invocation -> { + Instant localNow = operationClock.instant(); + Instant observedAt = + claimReadCount.getAndIncrement() == 0 ? localNow.plusSeconds(2) : localNow; + return claimEvidence( + invocation.getArgument(0), + invocation.getArgument(1), + observedAt); + }); Path responseKeyringDirectory = temporaryDirectory.resolve("operator-response"); Files.createDirectories(responseKeyringDirectory); @@ -321,15 +397,13 @@ void ownerIssuesRecoversAndReplaysSameAttemptAcrossReferenceExpiry() throws Exce durableRecords.put( redemption.controlPlaneRequestId(), withRedemption(issuance, redemption)); } - return new RedemptionResult( + return new AccountStartSessionOperatorAuthorizationRepository.RedemptionResult( issuance.authorizationReferenceFingerprint(), issuance.authorityEvidenceBundle(), issuance.issuanceOperationId(), issuance.issuanceFence(), replay); }); - when(issuanceOperations.captureOwnerLinearization()) - .thenReturn(new OwnerLinearization("123456", 99L)); AtomicReference currentForCalls = new AtomicReference<>(current); doAnswer( invocation -> { @@ -362,6 +436,7 @@ void ownerIssuesRecoversAndReplaysSameAttemptAcrossReferenceExpiry() throws Exce new AccountStartSessionOperatorAuthorizationService( actors, issuanceOperations, + captureRepository, claims, repository, fingerprintKeys, @@ -396,6 +471,55 @@ void ownerIssuesRecoversAndReplaysSameAttemptAcrossReferenceExpiry() throws Exce assertThat(record.encryptedResponseEnvelope().length).isLessThanOrEqualTo(160 * 1024); AccountStartSessionOperatorAuthorityBundle bundle = AccountStartSessionOperatorAuthorityBundle.decode(record.authorityEvidenceBundle()); + StartSessionPostAuthorizationExecutionTuple issuedOwnerTuple = + StartSessionPostAuthorizationExecutionTuple.decode( + issued.get().originalAccountPostAuthorizationTuple()); + assertThat(issuedOwnerTuple.preAuthorizationTuple().canonicalJson()) + .isEqualTo(tuple.canonicalJson()); + assertThat(issuedOwnerTuple.authenticatedWorkloadIdentity()).isEqualTo(LOGGING_PEER); + assertThat(issuedOwnerTuple.authorizationReferenceFingerprint()) + .isEqualTo(record.authorizationReferenceFingerprint()); + assertThat(issuedOwnerTuple.reservationOwnerId()).isEqualTo(record.reservationOwnerId()); + assertThat(issuedOwnerTuple.reservationClaimFence()).isEqualTo(record.reservationClaimFence()); + assertThat(issuedOwnerTuple.bundleReference().bundleVersion()) + .isEqualTo(record.bundleReference().bundleVersion()); + assertThat(issuedOwnerTuple.bundleReference().sourceVersion()) + .isEqualTo(record.bundleReference().sourceVersion()); + assertThat(issuedOwnerTuple.bundleReference().sourceFence()) + .isEqualTo(record.bundleReference().sourceFence()); + assertThat(issuedOwnerTuple.bundleReference().linearization()) + .isEqualTo(record.bundleReference().linearization()); + + byte[] decryptedEnvelope = + responseCrypto.decrypt( + new AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope( + record.encryptedResponseEnvelope()), + new AccountResponseEnvelopeCryptography.Binding( + "human-start-session-authorization/v1", + AccountStartSessionOperatorAuthorizationService.envelopeBindingRequestId( + tuple.controlPlaneRequestId()), + MessageDigest.getInstance("SHA-256").digest(exactTuple), + record.issuanceWorkloadUri(), + record.issuanceOperationId().toString(), + Optional.empty(), + Optional.empty(), + Optional.empty(), + record.issuanceFence(), + AccountControlUiAuthority.canonical(bundle.authorityTuple()), + AccountControlUiAuthority.canonical(bundle.membershipVersion()), + bundle.canonicalBytes()), + record.responseEnvelopeExpiresAt()); + Map storedResponse = + JsonMapper.builder().build().readValue(decryptedEnvelope, new TypeReference<>() {}); + assertThat(storedResponse.keySet()) + .containsExactlyInAnyOrder( + "operatorAuthorizationReference", + "authorizationReferenceFingerprint", + "expiresAt", + "authorityEvidenceBundle", + "bundleReference"); + assertThat(storedResponse).doesNotContainKey("originalAccountPostAuthorizationTuple"); + java.util.Arrays.fill(decryptedEnvelope, (byte) 0); assertThat(AccountStartSessionOperatorAuthorizationService.envelopeBindingRequestId(requestId)) .isEqualTo( java.util.HexFormat.of() @@ -418,6 +542,8 @@ void ownerIssuesRecoversAndReplaysSameAttemptAcrossReferenceExpiry() throws Exce .isEqualTo(issued.get().operatorAuthorizationReference()); assertThat(recovered.get().authorityEvidenceBundle()) .containsExactly(issued.get().authorityEvidenceBundle()); + assertThat(recovered.get().originalAccountPostAuthorizationTuple()) + .containsExactly(issued.get().originalAccountPostAuthorizationTuple()); UUID ownerAttemptId = UUID.randomUUID(); long ownerFence = 18L; @@ -434,6 +560,8 @@ void ownerIssuesRecoversAndReplaysSameAttemptAcrossReferenceExpiry() throws Exce operationClock.setInstant(record.referenceExpiresAt().minusMillis(1)); gameSessionContext().run(() -> firstRedemption.set(service.redeem(redeemRequest))); assertThat(firstRedemption.get().replay()).isFalse(); + assertThat(firstRedemption.get().originalAccountPostAuthorizationTuple()) + .containsExactly(issued.get().originalAccountPostAuthorizationTuple()); AtomicReference recoveredRetry = new AtomicReference<>(); operationClock.setInstant(record.referenceExpiresAt().plusSeconds(1)); @@ -448,6 +576,8 @@ void ownerIssuesRecoversAndReplaysSameAttemptAcrossReferenceExpiry() throws Exce .isEqualTo(firstRedemption.get().issuanceOperationId()); assertThat(recoveredRetry.get().issuanceFence()) .isEqualTo(firstRedemption.get().issuanceFence()); + assertThat(recoveredRetry.get().originalAccountPostAuthorizationTuple()) + .containsExactly(firstRedemption.get().originalAccountPostAuthorizationTuple()); AtomicReference postEnvelopeRetry = new AtomicReference<>(); operationClock.setInstant(record.responseEnvelopeExpiresAt()); @@ -635,7 +765,29 @@ void exactRepeatedReadReturnsOriginalRedeemedProjectionAfterCurrentnessRevalidat } @Test - void projectionRequiresExactSameNamespaceGameDesignPeerBeforeTupleParsingOrLookup() { + void exactOriginalGameSessionRedeemerCanReadItsImmutableProjection() { + ReadHarness harness = readHarness(NOW.plusSeconds(30)); + allowCurrent(harness, harness.source()); + AtomicReference result = new AtomicReference<>(); + + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri(GAME_SESSION_PEER).orElseThrow()) + .run( + () -> result.set(harness.service().readRedeemedOperationProjection(harness.request()))); + + assertThat(result.get().redeemerWorkloadUri()).isEqualTo(GAME_SESSION_PEER); + assertThat(result.get().canonicalPreAuthorizationTuple()) + .isEqualTo(harness.record().preAuthorizationTuple()); + verify(harness.repository(), times(2)) + .findByControlPlaneRequestId(harness.tuple().controlPlaneRequestId()); + verifyNoInteractions(harness.claims(), harness.fingerprintKeys(), harness.responseCrypto()); + } + + @Test + void + projectionRequiresExactSameNamespaceGameDesignOrOriginalGameSessionPeerBeforeTupleParsingOrLookup() { ReadHarness harness = readHarness(NOW.plusSeconds(30)); ReadRedeemedOperationProjectionRequest malformed = new ReadRedeemedOperationProjectionRequest( @@ -648,7 +800,9 @@ void projectionRequiresExactSameNamespaceGameDesignPeerBeforeTupleParsingOrLooku for (String wrongPeerUri : List.of( - "spiffe://firemud/ns/other/sa/game-design-service", GAME_SESSION_PEER, LOGGING_PEER)) { + "spiffe://firemud/ns/other/sa/game-design-service", + "spiffe://firemud/ns/other/sa/game-session-service", + LOGGING_PEER)) { Context.current() .withValue( GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(wrongPeerUri).orElseThrow()) @@ -657,7 +811,8 @@ void projectionRequiresExactSameNamespaceGameDesignPeerBeforeTupleParsingOrLooku assertThatThrownBy( () -> harness.service().readRedeemedOperationProjection(malformed)) .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("Exact authenticated internal workload identity")); + .hasMessageContaining( + "Exact authenticated Game Design or original Game Session identity")); } verify(harness.repository(), never()).findByControlPlaneRequestId(anyString()); @@ -886,20 +1041,17 @@ private static ReadHarness readHarness(Instant referenceExpiresAt) { AccountControlUiAuthority.Snapshot source = source(actorId, tenantId, 7L, new byte[] {1}); AccountControlUiIssuanceRepository.Stored stored = stored(actorId, tenantId, tokenJti, issuanceOperationId, source); - OwnerLinearization linearization = new OwnerLinearization("123456", 99L); + Instant capturedAt = + referenceExpiresAt.isAfter(NOW) ? NOW : referenceExpiresAt.minusSeconds(120); + AccountStartSessionAuthorityCapture capture = + capture(tuple, source, stored, reservationOwnerId, 10L, capturedAt); Instant issuedAt = referenceExpiresAt.minusSeconds(50); Instant redeemedAt = referenceExpiresAt.isAfter(NOW) ? NOW.minusSeconds(1) : referenceExpiresAt.minusSeconds(1); var bundle = AccountStartSessionOperatorAuthorityBundle.create( - tuple, - source, - stored, - issuanceOperationId, - linearization, - issuedAt, - referenceExpiresAt); - var bundleReference = bundle.referenceForSource(source, linearization); + tuple, capture, stored, issuanceOperationId, issuedAt, referenceExpiresAt); + var bundleReference = bundle.referenceForCapture(capture); String fingerprint = "arfp/v1/test-key/" + "a".repeat(64); IssuanceRecord record = new IssuanceRecord( @@ -910,7 +1062,7 @@ private static ReadHarness readHarness(Instant referenceExpiresAt) { reservationOwnerId, 10L, issuanceOperationId, - linearization.sourceFence(), + bundle.issuanceFence(), AccountStartSessionOperatorAuthorityBundle.toSharedReference(bundleReference), bundle.canonicalBytes(), fingerprint, @@ -929,6 +1081,8 @@ private static ReadHarness readHarness(Instant referenceExpiresAt) { var actors = org.mockito.Mockito.mock(AccountControlUiActorService.class); var issuanceOperations = org.mockito.Mockito.mock(AccountControlUiIssuanceRepository.class); + var captureRepository = + org.mockito.Mockito.mock(AccountStartSessionAuthorityCaptureRepository.class); var claims = org.mockito.Mockito.mock(StartSessionReservationEvidenceClient.class); var repository = org.mockito.Mockito.mock(AccountStartSessionOperatorAuthorizationRepository.class); @@ -944,10 +1098,13 @@ private static ReadHarness readHarness(Instant referenceExpiresAt) { when(hostedTerms.captureCurrentEnvironmentBoundary()).thenReturn(environment); when(repository.findByControlPlaneRequestId(tuple.controlPlaneRequestId())) .thenReturn(Optional.of(record)); + when(captureRepository.lockReadExactCurrent(any(), any(), anyString(), any(), anyLong())) + .thenReturn(capture); var service = new AccountStartSessionOperatorAuthorizationService( actors, issuanceOperations, + captureRepository, claims, repository, fingerprintKeys, @@ -973,6 +1130,7 @@ private static ReadHarness readHarness(Instant referenceExpiresAt) { actors, claims, repository, + captureRepository, fingerprintKeys, responseCrypto, hostedTerms, @@ -981,6 +1139,7 @@ private static ReadHarness readHarness(Instant referenceExpiresAt) { source, stored, record, + capture, request, actorId, tenantId, @@ -1004,6 +1163,75 @@ private static void allowCurrent( .withCurrentCommitted(any(), any(), any(), any(), any()); } + private static AccountStartSessionAuthorityCapture capture( + StartSessionPreAuthorizationReservationTuple tuple, + AccountControlUiAuthority.Snapshot source, + AccountControlUiIssuanceRepository.Stored stored, + UUID reservationOwnerId, + long reservationClaimFence) { + return capture(tuple, source, stored, reservationOwnerId, reservationClaimFence, NOW); + } + + private static AccountStartSessionAuthorityCapture capture( + StartSessionPreAuthorizationReservationTuple tuple, + AccountControlUiAuthority.Snapshot source, + AccountControlUiIssuanceRepository.Stored stored, + UUID reservationOwnerId, + long reservationClaimFence, + Instant capturedAt) { + byte[] signerReceipt = stored.signerReceipt.clone(); + Map snapshot = + Map.ofEntries( + Map.entry("schema", "account-start-session-authority-snapshot/v1"), + Map.entry("controlPlaneRequestId", tuple.controlPlaneRequestId()), + Map.entry( + "preAuthorizationTuple", + Base64.getEncoder() + .encodeToString(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8))), + Map.entry("mutationDigest", tuple.mutationDigest()), + Map.entry("accountId", tuple.actor().accountId().toString()), + Map.entry("tenantId", tuple.action().scope().tenantId().toString()), + Map.entry("targetOwner", tuple.targetOwner()), + Map.entry("loggingWorkloadUri", LOGGING_PEER), + Map.entry("reservationOwnerId", reservationOwnerId.toString()), + Map.entry("reservationClaimFence", Long.toString(reservationClaimFence)), + Map.entry("controlUiOperationId", stored.operationId.toString()), + Map.entry("controlUiTokenJti", stored.jti.toString()), + Map.entry("controlUiTokenHash", stored.tokenHash), + Map.entry("controlUiSignerReceipt", Base64.getEncoder().encodeToString(signerReceipt)), + Map.entry("controlUiSignerReceiptSha256", sha256(signerReceipt)), + Map.entry( + "sourceVectorEvidence", Base64.getEncoder().encodeToString(source.evidence())), + Map.entry( + "sourceVector", + source.sources().stream() + .map(evidence -> Base64.getEncoder().encodeToString(evidence.canonicalBytes())) + .toList()), + Map.entry("outboxCheckpoints", source.outboxCheckpoints()), + Map.entry("authorityTuple", source.authorityTuple()), + Map.entry("membershipVersion", source.membershipVersion()), + Map.entry("accountIdentitySource", source.accountIdentitySource()), + Map.entry("issuanceFence", Long.toString(source.issuanceFence())), + Map.entry( + "issuanceFenceSourceVersion", Long.toString(source.issuanceFenceSourceVersion()))); + return AccountStartSessionAuthorityCapture.create( + tuple.controlPlaneRequestId(), + 17L, + 31L, + "123456", + CAPTURED_AT_FORMAT.format(capturedAt), + AccountControlUiAuthority.canonical(snapshot)); + } + + private static String sha256(byte[] value) { + try { + return java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException unavailable) { + throw new IllegalStateException(unavailable); + } + } + private static IssuanceRecord asIssued(IssuanceRecord record) { return new IssuanceRecord( record.controlPlaneRequestId(), @@ -1165,6 +1393,7 @@ private record ReadHarness( AccountControlUiActorService actors, StartSessionReservationEvidenceClient claims, AccountStartSessionOperatorAuthorizationRepository repository, + AccountStartSessionAuthorityCaptureRepository captureRepository, AccountOperatorAuthorizationFingerprintKeyring fingerprintKeys, AccountResponseEnvelopeCryptography responseCrypto, AccountHostedTermsService hostedTerms, @@ -1173,6 +1402,7 @@ private record ReadHarness( AccountControlUiAuthority.Snapshot source, AccountControlUiIssuanceRepository.Stored stored, IssuanceRecord record, + AccountStartSessionAuthorityCapture capture, ReadRedeemedOperationProjectionRequest request, UUID actorId, UUID tenantId, @@ -1244,6 +1474,10 @@ private static AccountControlUiAuthority.Snapshot source( when(source.tenant()).thenReturn(tenantId); when(source.authorityTuple()).thenReturn(authorityTuple); when(source.membershipVersion()).thenReturn(membershipVersion); + when(source.issuanceFence()).thenReturn(43L); + when(source.issuanceFenceSourceVersion()).thenReturn(44L); + when(source.outboxCheckpoints()).thenReturn(List.of()); + when(source.accountIdentitySource()).thenReturn(Map.of("provenance", "registered")); when(source.evidence()).thenReturn(evidence.clone()); when(source.sources()) .thenReturn( @@ -1318,6 +1552,11 @@ private static AccountControlUiIssuanceRepository.Stored stored( private static ReadCurrentClaimEvidenceResponse claimEvidence( StartSessionPreAuthorizationReservationTuple tuple, UUID ownerId) { + return claimEvidence(tuple, ownerId, NOW); + } + + private static ReadCurrentClaimEvidenceResponse claimEvidence( + StartSessionPreAuthorizationReservationTuple tuple, UUID ownerId, Instant observedAt) { return ReadCurrentClaimEvidenceResponse.newBuilder() .setControlPlaneRequestId(tuple.controlPlaneRequestId()) .setPreAuthorizationTupleJson( @@ -1327,6 +1566,8 @@ private static ReadCurrentClaimEvidenceResponse claimEvidence( .setReservationClaimFence(10L) .setClaimOwnerId(ownerId.toString()) .setClaimFence(10L) + .setObservedAtEpochMillis(observedAt.minusSeconds(1).toEpochMilli()) + .setClaimExpiresAtEpochMillis(observedAt.plusSeconds(30).toEpochMilli()) .build(); } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionGrpcServiceTest.java new file mode 100644 index 0000000000..42d23fa324 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionGrpcServiceTest.java @@ -0,0 +1,455 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.SQLException; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AcquireStartSessionWorldParticipationRequest; +import net.firedevops.firemud.account.v1.AcquireStartSessionWorldParticipationResponse; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository.StoredEvidence; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationAcquisitionGrpcService; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationAcquisitionService; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationAcquisitionService.AcquiredParticipation; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationAcquisitionService.AcquisitionRequest; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture.Values; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** Synthetic receiver proof only; Account persistence and TLS workload identity are mocked. */ +class AccountStartSessionWorldParticipationAcquisitionGrpcServiceTest { + private static final String NAMESPACE = "world-runtime"; + private static final String WORLD_URI = + "spiffe://firemud/ns/world-runtime/sa/world-management-service"; + private static final UUID ACCOUNT_ID = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TENANT_ID = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID MUTATION_ID = uuid("b9d2f9d9-0438-42c8-829e-fd3392cd9d21"); + private static final UUID ATTEMPT_ID = uuid("4a3fc69f-a18a-4b94-b1d1-2e8b4c3f0e4b"); + private static final UUID GAME_INSTANCE_ID = uuid("c0e30aea-1549-43d9-93af-0e44a3deae32"); + private static final UUID PARTICIPATION_ID = uuid("a8c1e8c8-f237-41b7-918d-ec2281bcac10"); + private static final long PARTICIPATION_FENCE = 31L; + private static final long GAME_SESSION_FENCE = 37L; + private static final String PREPARATION_JSON = + "{\"selected\":\"immutable source\",\"revision\":3}"; + private static final Instant ORIGINAL_LEASE_EXPIRY = Instant.parse("2026-10-12T00:00:00Z"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @AfterEach + void clearThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void rejectsWrongPeerNamespaceAndEndUserBeforeInspectingMalformedRequest() { + var owner = mock(AccountStartSessionWorldParticipationAcquisitionService.class); + var service = new AccountStartSessionWorldParticipationAcquisitionGrpcService(owner, NAMESPACE); + var malformed = AcquireStartSessionWorldParticipationRequest.newBuilder().build(); + + assertCode(Status.Code.UNAUTHENTICATED, invoke(service, null, malformed).error); + assertCode( + Status.Code.PERMISSION_DENIED, + invoke( + service, + identity("spiffe://firemud/ns/world-runtime/sa/game-session-service"), + malformed) + .error); + assertCode( + Status.Code.PERMISSION_DENIED, + invoke( + service, + identity("spiffe://firemud/ns/default/sa/world-management-service"), + malformed) + .error); + assertCode( + Status.Code.PERMISSION_DENIED, + invoke( + service, + identity("spiffe://firemud/ns/other-runtime/sa/world-management-service"), + malformed) + .error); + + SessionContext.setContext("123", List.of(), Map.of()); + assertCode( + Status.Code.PERMISSION_DENIED, invoke(service, identity(WORLD_URI), malformed).error); + verifyNoInteractions(owner); + } + + @Test + void rejectsAmbientSqlUnknownFieldsAndMalformedBindingsBeforeBackendCall() { + var owner = mock(AccountStartSessionWorldParticipationAcquisitionService.class); + var service = new AccountStartSessionWorldParticipationAcquisitionGrpcService(owner, NAMESPACE); + var valid = request(); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode(Status.Code.FAILED_PRECONDITION, invoke(service, identity(WORLD_URI), null).error); + TransactionSynchronizationManager.clear(); + + var unknown = + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + var unsupportedSchema = valid.toBuilder().setSchemaVersion(2).build(); + var wrongNamespace = valid.toBuilder().setTargetNamespace("default").build(); + var malformedUuid = valid.toBuilder().setAcquisitionRequestId("not-a-uuid").build(); + var malformedFence = valid.toBuilder().setGameSessionOwnerFence(0).build(); + var malformedDigest = + valid.toBuilder().setPreparationInputDigest("sha256:" + "0".repeat(64)).build(); + for (var malformed : + List.of( + unknown, + unsupportedSchema, + wrongNamespace, + malformedUuid, + malformedFence, + malformedDigest)) { + assertCode( + Status.Code.INVALID_ARGUMENT, invoke(service, identity(WORLD_URI), malformed).error); + } + assertCode(Status.Code.INVALID_ARGUMENT, invoke(service, identity(WORLD_URI), null).error); + verifyNoInteractions(owner); + } + + @Test + void delegatesExactRequestAndReturnsBoundedFullRetainedObservation() { + var owner = mock(AccountStartSessionWorldParticipationAcquisitionService.class); + var service = new AccountStartSessionWorldParticipationAcquisitionGrpcService(owner, NAMESPACE); + var request = request(); + var expected = acquired(request); + when(owner.acquire(any())).thenReturn(expected); + + var result = invoke(service, identity(WORLD_URI), request); + + assertThat(result.error).isNull(); + assertThat(result.completed).isTrue(); + assertThat(result.response.getRequest()).isEqualTo(request); + assertThat(result.response.getAccountWorldParticipationId()) + .isEqualTo(PARTICIPATION_ID.toString()); + assertThat(result.response.getAccountWorldParticipationFence()).isEqualTo(PARTICIPATION_FENCE); + assertThat(result.response.hasOriginalAttemptEvidence()).isTrue(); + assertThat(result.response.getOriginalAttemptEvidence()) + .isEqualTo( + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse( + expected.originalAttemptEvidence().result())); + assertThat(result.response.getSerializedSize()).isLessThan(1024 * 1024); + + ArgumentCaptor captured = ArgumentCaptor.forClass(AcquisitionRequest.class); + verify(owner).acquire(captured.capture()); + assertThat(captured.getValue().originalPostAuthorizationTuple()) + .containsExactly(request.getOriginalPostAuthorizationTuple().toByteArray()); + assertThat(captured.getValue().gameSessionOwnerMutationId()).isEqualTo(MUTATION_ID); + assertThat(captured.getValue().gameSessionOwnerAttemptId()).isEqualTo(ATTEMPT_ID); + assertThat(captured.getValue().gameSessionOwnerFence()).isEqualTo(GAME_SESSION_FENCE); + assertThat(captured.getValue().canonicalGameInstanceId()).isEqualTo(GAME_INSTANCE_ID); + assertThat(captured.getValue().preparationInputJson()).isEqualTo(PREPARATION_JSON); + assertThat(captured.getValue().preparationInputDigest()).isEqualTo(digest(PREPARATION_JSON)); + + var freshCorrelationRequest = + request.toBuilder().setAcquisitionRequestId(UUID.randomUUID().toString()).build(); + var freshCorrelationReply = invoke(service, identity(WORLD_URI), freshCorrelationRequest); + assertThat(freshCorrelationReply.error).isNull(); + assertThat(freshCorrelationReply.completed).isTrue(); + assertThat(freshCorrelationReply.response.getRequest()).isEqualTo(freshCorrelationRequest); + assertThat(freshCorrelationReply.response.getAccountWorldParticipationId()) + .isEqualTo(result.response.getAccountWorldParticipationId()); + assertThat(freshCorrelationReply.response.getAccountWorldParticipationFence()) + .isEqualTo(result.response.getAccountWorldParticipationFence()); + assertThat(freshCorrelationReply.response.getOriginalAttemptEvidence()) + .isEqualTo(result.response.getOriginalAttemptEvidence()); + } + + @Test + void rejectsSubstitutedBackendEvidenceWithoutExposingOwnerDetails() { + var owner = mock(AccountStartSessionWorldParticipationAcquisitionService.class); + var service = new AccountStartSessionWorldParticipationAcquisitionGrpcService(owner, NAMESPACE); + var request = request(); + var correct = acquired(request); + var substituted = + new StoredEvidence( + uuid("11111111-1111-4111-8111-111111111111"), + MUTATION_ID, + correct.originalAttemptEvidence().originalLeaseExpiresAt(), + correct.originalAttemptEvidence().originalResponseBytes(), + correct.originalAttemptEvidence().originalResponseDigest(), + correct.originalAttemptEvidence().result()); + when(owner.acquire(any())) + .thenReturn(new AcquiredParticipation(correct.participation(), substituted)); + + var result = invoke(service, identity(WORLD_URI), request); + + assertCode(Status.Code.FAILED_PRECONDITION, result.error); + assertThat(Status.fromThrowable(result.error).getDescription()) + .isEqualTo("Current Account participation evidence is unavailable"); + } + + @Test + void classifiesPermanentOwnerFailuresAndDatabaseConnectionErrors() { + assertOwnerFailure( + new AccountStartSessionOperatorAuthorizationService.NotFoundException(), + Status.Code.NOT_FOUND); + assertOwnerFailure( + new IllegalStateException("sensitive owner detail"), Status.Code.FAILED_PRECONDITION); + assertOwnerFailure( + new DataAccessResourceFailureException( + "sensitive database detail", new SQLException("sensitive connection detail", "08006")), + Status.Code.UNAVAILABLE); + assertOwnerFailure( + new DataAccessResourceFailureException( + "sensitive database detail", new SQLException("sensitive database detail", "23505")), + Status.Code.INTERNAL); + assertOwnerFailure(new RuntimeException("sensitive unexpected detail"), Status.Code.INTERNAL); + } + + @Test + void mapsAllowlistedUpstreamStatusesAndRedactsTheirDescriptions() { + assertOwnerFailure( + Status.NOT_FOUND.withDescription("sensitive upstream detail").asRuntimeException(), + Status.Code.NOT_FOUND); + assertOwnerFailure( + Status.RESOURCE_EXHAUSTED.withDescription("sensitive upstream detail").asRuntimeException(), + Status.Code.UNAVAILABLE); + assertOwnerFailure( + Status.UNKNOWN.withDescription("sensitive upstream detail").asRuntimeException(), + Status.Code.INTERNAL); + } + + private static void assertOwnerFailure(RuntimeException failure, Status.Code expected) { + var owner = mock(AccountStartSessionWorldParticipationAcquisitionService.class); + when(owner.acquire(any())).thenThrow(failure); + var service = new AccountStartSessionWorldParticipationAcquisitionGrpcService(owner, NAMESPACE); + + var result = invoke(service, identity(WORLD_URI), request()); + + assertCode(expected, result.error); + String description = Status.fromThrowable(result.error).getDescription(); + assertThat(description).isNotBlank(); + assertThat(description).doesNotContain("sensitive"); + } + + private static Invocation invoke( + AccountStartSessionWorldParticipationAcquisitionGrpcService service, + GrpcPeerIdentity peer, + AcquireStartSessionWorldParticipationRequest request) { + var result = new Invocation(); + Context context = Context.current(); + if (peer != null) context = context.withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + service.acquireStartSessionWorldParticipation(request, result); + } finally { + context.detach(previous); + } + return result; + } + + private static GrpcPeerIdentity identity(String uri) { + return GrpcPeerIdentity.parseUri(uri).orElseThrow(); + } + + private static void assertCode(Status.Code expected, Throwable failure) { + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected); + } + + private static AcquireStartSessionWorldParticipationRequest request() { + var tuple = originalTuple(); + return AcquireStartSessionWorldParticipationRequest.newBuilder() + .setSchemaVersion(1) + .setAcquisitionRequestId("263a218e-1752-47f2-97c3-6273b2ea9f15") + .setTargetNamespace(NAMESPACE) + .setOriginalPostAuthorizationTuple( + com.google.protobuf.ByteString.copyFrom(tuple.canonicalBytes())) + .setGameSessionOwnerMutationId(MUTATION_ID.toString()) + .setGameSessionOwnerAttemptId(ATTEMPT_ID.toString()) + .setGameSessionOwnerFence(GAME_SESSION_FENCE) + .setCanonicalGameInstanceId(GAME_INSTANCE_ID.toString()) + .setPreparationInputJson(PREPARATION_JSON) + .setPreparationInputDigest(digest(PREPARATION_JSON)) + .build(); + } + + private static AcquiredParticipation acquired(AcquireStartSessionWorldParticipationRequest wire) { + var tuple = + StartSessionPostAuthorizationExecutionTuple.decode( + wire.getOriginalPostAuthorizationTuple().toByteArray()); + var observationRequest = + new Request( + uuid("4d66578e-a7cd-4a37-8cfb-30aa4c0c23b3"), + NAMESPACE, + tuple.canonicalBytes(), + ATTEMPT_ID, + MUTATION_ID, + GAME_SESSION_FENCE); + var observation = + new Result( + observationRequest, + ORIGINAL_LEASE_EXPIRY, + StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple)); + byte[] originalResponse = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(observation).toByteArray(); + var participation = + new StoredParticipation( + PARTICIPATION_ID, + PARTICIPATION_FENCE, + tuple.controlPlaneRequestId(), + tuple.canonicalBytes(), + NAMESPACE, + TENANT_ID, + GAME_INSTANCE_ID, + ATTEMPT_ID, + GAME_SESSION_FENCE, + PREPARATION_JSON, + digest(PREPARATION_JSON), + 17L, + OffsetDateTime.parse("2026-10-09T10:20:30.456Z"), + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, + TENANT_ID.toString(), + "2", + "17", + null, + null, + "synthetic current source".getBytes(StandardCharsets.UTF_8)))); + var evidence = + new StoredEvidence( + PARTICIPATION_ID, + MUTATION_ID, + ORIGINAL_LEASE_EXPIRY, + originalResponse, + digestBytes(originalResponse), + observation); + return new AcquiredParticipation(participation, evidence); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple() { + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "world-participation-grpc-test", + ACCOUNT_ID, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, NAMESPACE), + new StartSessionOperatorAction.Target( + 91L, uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a")), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "synthetic World participation transport proof")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"), + 19L, + authorityBundle(preTuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + return StartSessionAuthorityEvidenceBundleFixture.canonicalBytes( + tuple, + new Values( + uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"), + "sha256:" + "a".repeat(64), + "17", + "CURRENT", + Instant.parse("2026-10-09T00:00:00Z"), + Instant.parse("2026-10-10T00:00:00Z"), + 1L, + 2L, + 3L, + 4L, + 5L, + 23L, + uuid("a681bba7-c215-4cf1-a35b-14348912cbdc"), + "2", + "3")); + } + + private static String digest(String value) { + return digestBytes(value.getBytes(StandardCharsets.UTF_8)); + } + + private static String digestBytes(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class Invocation + implements StreamObserver { + private AcquireStartSessionWorldParticipationResponse response; + private Throwable error; + private boolean completed; + + @Override + public void onNext(AcquireStartSessionWorldParticipationResponse value) { + response = value; + } + + @Override + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The test observer retains the callback failure only for assertions") + public void onError(Throwable failure) { + error = failure; + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionServiceTest.java new file mode 100644 index 0000000000..eef8267f9e --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionServiceTest.java @@ -0,0 +1,811 @@ +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.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +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.grpc.Context; +import io.grpc.Status; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository.StoredEvidence; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.Candidate; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationAcquisitionService.AcquiredParticipation; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationAcquisitionService.AcquisitionRequest; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationHistoricalReadRequest; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptClient; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture.Values; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** Synthetic composition proof only; current Game Session and Account storage are mocked. */ +class AccountStartSessionWorldParticipationAcquisitionServiceTest { + private static final String NAMESPACE = "world-runtime"; + private static final UUID ACCOUNT_ID = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TENANT_ID = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID PARTICIPATION_ID = uuid("a8c1e8c8-f237-41b7-918d-ec2281bcac10"); + private static final UUID GAME_SESSION_MUTATION_ID = uuid("b9d2f9d9-0438-42c8-829e-fd3392cd9d21"); + private static final UUID GAME_SESSION_ATTEMPT_ID = uuid("4a3fc69f-a18a-4b94-b1d1-2e8b4c3f0e4b"); + private static final UUID GAME_INSTANCE_ID = uuid("c0e30aea-1549-43d9-93af-0e44a3deae32"); + private static final long PARTICIPATION_FENCE = 31L; + private static final long GAME_SESSION_FENCE = 37L; + private static final String PREPARATION_INPUT = + "{ \"selected\" : \"immutable source\", \"revision\": 3 }\n"; + private static final Instant ORIGINAL_LEASE_EXPIRY = Instant.parse("2026-10-12T00:00:00Z"); + private static final Instant HISTORICAL_RECOVERY_AT = Instant.parse("2026-10-13T00:00:00Z"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @AfterEach + void clearThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesExactWorldPeerWithoutEndUserBeforeDecodingOrCallingDependencies() { + Harness harness = new Harness(); + + assertCode(Status.Code.UNAUTHENTICATED, () -> harness.service.acquire(null)); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> + peer( + NAMESPACE, + "game-session-service", + () -> harness.service.acquire(request(new byte[0])))); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> + peer( + "other-runtime", + "world-management-service", + () -> harness.service.acquire(request(new byte[0])))); + SessionContext.setContext("123", List.of(), Map.of()); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> authorized(() -> harness.service.acquire(request(new byte[0])))); + + verifyNoInteractions(harness.issuer); + verifyNoInteractions(harness.participationRepository); + verifyNoInteractions(harness.attemptEvidenceRepository); + verifyNoInteractions(harness.gameSessionClient); + assertThat(harness.readbackTransactions.begins).isZero(); + } + + @Test + void rejectsAmbientSqlOrSynchronizationBeforeDecodingOrRemoteRead() { + Harness harness = new Harness(); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> harness.service.acquire(request(new byte[0])))); + TransactionSynchronizationManager.clear(); + TransactionSynchronizationManager.initSynchronization(); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> harness.service.acquire(request(new byte[0])))); + + verifyNoInteractions(harness.issuer); + verifyNoInteractions(harness.participationRepository); + verifyNoInteractions(harness.attemptEvidenceRepository); + verifyNoInteractions(harness.gameSessionClient); + assertThat(harness.readbackTransactions.begins).isZero(); + } + + @Test + void rejectsUnavailableOrSubstitutedGameSessionRequestEchoBeforeIssuerCallbackOrWrites() { + List> substitutedEchoes = + List.of( + ignored -> null, + read -> + new Request( + read.readRequestId(), + read.targetNamespace(), + read.canonicalPostAuthorizationTuple(), + uuid("11111111-1111-4111-8111-111111111111"), + read.expectedOwnerMutationId(), + read.expectedOwnerFence()), + read -> + new Request( + read.readRequestId(), + read.targetNamespace(), + read.canonicalPostAuthorizationTuple(), + read.expectedOwnerAttemptId(), + uuid("22222222-2222-4222-8222-222222222222"), + read.expectedOwnerFence()), + read -> + new Request( + read.readRequestId(), + read.targetNamespace(), + read.canonicalPostAuthorizationTuple(), + read.expectedOwnerAttemptId(), + read.expectedOwnerMutationId(), + read.expectedOwnerFence() + 1)); + + for (Function substituteEcho : substitutedEchoes) { + Harness harness = new Harness(); + when(harness.gameSessionClient.read(any(Request.class))) + .thenAnswer( + invocation -> { + assertNoSql(); + harness.steps.add("remote-read"); + Request expected = invocation.getArgument(0); + Request echoed = substituteEcho.apply(expected); + return echoed == null + ? null + : new Result( + echoed, ORIGINAL_LEASE_EXPIRY, projection(harness.tuple, Map.of())); + }); + + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> harness.service.acquire(request(null)))); + + assertThat(harness.steps).containsExactly("remote-read"); + verify(harness.gameSessionClient).read(any(Request.class)); + verify(harness.issuer, times(0)) + .withCurrentWorldReceivingParticipationCurrentness( + any(byte[].class), eq(GAME_SESSION_ATTEMPT_ID), eq(GAME_SESSION_FENCE), any()); + verifyNoInteractions(harness.participationRepository); + verifyNoInteractions(harness.attemptEvidenceRepository); + assertThat(harness.readbackTransactions.begins).isZero(); + } + } + + @Test + void readsGameSessionOutsideSqlThenWritesAtomicallyAndPerformsIndependentLookupOnlyReadback() { + Harness harness = new Harness(); + harness.configureSuccess(); + + AcquiredParticipation acquired = authorized(() -> harness.service.acquire(request(null))); + + assertThat(acquired.participation().participationId()).isEqualTo(PARTICIPATION_ID); + assertThat(acquired.participation().participationFence()).isEqualTo(PARTICIPATION_FENCE); + assertThat(acquired.participation().originalPostAuthorizationTuple()) + .containsExactly(harness.tuple.canonicalBytes()); + assertThat(acquired.participation().sources()).hasSize(1); + assertThat(acquired.originalAttemptEvidence().gameSessionOwnerMutationId()) + .isEqualTo(GAME_SESSION_MUTATION_ID); + assertThat(acquired.originalAttemptEvidence().originalResponseBytes()).isNotEmpty(); + assertThat(harness.steps) + .containsExactly( + "remote-read", + "issuer-currentness", + "participation-write", + "proof-write", + "participation-readback", + "proof-readback"); + assertThat(harness.readbackTransactions.begins).isEqualTo(1); + assertThat(harness.readbackTransactions.commits).isEqualTo(1); + verify(harness.gameSessionClient).read(any(Request.class)); + verify(harness.issuer) + .withCurrentWorldReceivingParticipationCurrentness( + eq(harness.tuple.canonicalBytes()), + eq(GAME_SESSION_ATTEMPT_ID), + eq(GAME_SESSION_FENCE), + any()); + verify(harness.participationRepository).createOrReadExact(any(Candidate.class)); + verify(harness.attemptEvidenceRepository) + .retainCurrentExact(any(StoredParticipation.class), any(Result.class)); + verify(harness.participationRepository).findCurrentExact(any(Candidate.class)); + verify(harness.attemptEvidenceRepository) + .findCurrentExact(any(StoredParticipation.class), any(Request.class)); + } + + @Test + void retriesTheSameOriginalTupleWithFreshGameSessionReadsAndCurrentAccountChecks() { + Harness harness = new Harness(); + harness.configureSuccess(); + var originalRequest = request(null); + + AcquiredParticipation first = authorized(() -> harness.service.acquire(originalRequest)); + AcquiredParticipation second = authorized(() -> harness.service.acquire(originalRequest)); + + ArgumentCaptor requests = ArgumentCaptor.forClass(Request.class); + verify(harness.gameSessionClient, times(2)).read(requests.capture()); + assertThat(requests.getAllValues()).hasSize(2); + assertThat(requests.getAllValues().get(0).readRequestId()) + .isNotEqualTo(requests.getAllValues().get(1).readRequestId()); + for (Request read : requests.getAllValues()) { + assertThat(read.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(read.canonicalPostAuthorizationTuple()) + .containsExactly(harness.tuple.canonicalBytes()); + assertThat(read.expectedOwnerMutationId()).isEqualTo(GAME_SESSION_MUTATION_ID); + assertThat(read.expectedOwnerAttemptId()).isEqualTo(GAME_SESSION_ATTEMPT_ID); + assertThat(read.expectedOwnerFence()).isEqualTo(GAME_SESSION_FENCE); + } + assertThat(first.participation().participationId()) + .isEqualTo(second.participation().participationId()); + assertThat(first.originalAttemptEvidence().originalResponseBytes()) + .containsExactly(second.originalAttemptEvidence().originalResponseBytes()); + assertThat(harness.readbackTransactions.begins).isEqualTo(2); + assertThat(harness.readbackTransactions.commits).isEqualTo(2); + assertThat(harness.steps) + .containsExactly( + "remote-read", + "issuer-currentness", + "participation-write", + "proof-write", + "participation-readback", + "proof-readback", + "remote-read", + "issuer-currentness", + "participation-write", + "proof-write", + "participation-readback", + "proof-readback"); + } + + @Test + void rejectsChangedAccountRedemptionProjectionBeforeCurrentnessOrWrites() { + Harness harness = new Harness(); + harness.configureClientResult(projection(harness.tuple, Map.of("unbound", "changed"))); + + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> harness.service.acquire(request(null)))); + + assertThat(harness.steps).containsExactly("remote-read"); + verify(harness.issuer, times(0)) + .withCurrentWorldReceivingParticipationCurrentness( + any(byte[].class), eq(GAME_SESSION_ATTEMPT_ID), eq(GAME_SESSION_FENCE), any()); + verifyNoInteractions(harness.participationRepository); + verifyNoInteractions(harness.attemptEvidenceRepository); + assertThat(harness.readbackTransactions.begins).isZero(); + } + + @Test + void rejectsChangedCommittedSourceVectorDuringIndependentReadbackWithoutRetryWrite() { + Harness harness = new Harness(); + harness.configureSuccess(); + harness.participationReadback.set( + participation(harness.tuple, List.of(sourceEvidence("different source")))); + + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> harness.service.acquire(request(null)))); + + assertThat(harness.readbackTransactions.begins).isEqualTo(1); + // The lookup-only transaction completes before the exact source-vector comparison denies. + assertThat(harness.readbackTransactions.commits).isEqualTo(1); + verify(harness.participationRepository, times(1)).createOrReadExact(any(Candidate.class)); + verify(harness.participationRepository, times(1)).findCurrentExact(any(Candidate.class)); + } + + @Test + void missingPostCommitReadbackDeniesAndDoesNotRepeatTheParticipationWrite() { + Harness harness = new Harness(); + harness.configureSuccess(); + harness.participationMissingOnReadback = true; + + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> harness.service.acquire(request(null)))); + + assertThat(harness.readbackTransactions.begins).isEqualTo(1); + assertThat(harness.readbackTransactions.rollbacks).isEqualTo(1); + verify(harness.participationRepository, times(1)).createOrReadExact(any(Candidate.class)); + verify(harness.participationRepository, times(1)).findCurrentExact(any(Candidate.class)); + verify(harness.attemptEvidenceRepository, times(1)) + .retainCurrentExact(any(StoredParticipation.class), any(Result.class)); + verify(harness.attemptEvidenceRepository, times(0)) + .findCurrentExact(any(StoredParticipation.class), any(Request.class)); + } + + @Test + void discoversCommittedCoordinatesByExactTupleAfterPostCommitReadbackRefusalAndExpiry() { + Harness harness = new Harness(); + harness.configureSuccess(); + harness.participationMissingOnReadback = true; + + assertThat(ORIGINAL_LEASE_EXPIRY).isBefore(HISTORICAL_RECOVERY_AT); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> harness.service.acquire(request(null)))); + + assertThat(harness.issuerCommits).isEqualTo(1); + assertThat(harness.readbackTransactions.begins).isEqualTo(1); + assertThat(harness.readbackTransactions.commits).isZero(); + assertThat(harness.readbackTransactions.rollbacks).isEqualTo(1); + + when(harness.participationRepository.findHistoricalForOriginalTuple(any(byte[].class))) + .thenAnswer( + invocation -> { + assertWritableReadCommittedTransaction(); + byte[] lookupTuple = invocation.getArgument(0); + assertThat(lookupTuple).containsExactly(harness.tuple.canonicalBytes()); + assertThat(harness.committedParticipation.originalPostAuthorizationTuple()) + .containsExactly(lookupTuple); + assertThat(harness.committedParticipation.sources()).hasSize(1); + assertThat(harness.committedParticipation.sources().get(0).canonicalBytes()) + .containsExactly( + participationSource(sourceEvidence("current source")).canonicalBytes()); + harness.steps.add("historical-tuple-readback"); + return Optional.of(harness.committedParticipation); + }); + var historicalService = + new AccountStartSessionWorldParticipationHistoricalReadService( + harness.participationRepository, harness.readbackTransactions, NAMESPACE); + var readRequest = + new AccountStartSessionWorldParticipationHistoricalReadRequest( + uuid("d1f41bfb-265a-4f3b-8b2a-124cba20ce43"), + NAMESPACE, + harness.tuple.canonicalBytes()); + + var evidence = authorized(() -> historicalService.read(readRequest)); + + assertThat(evidence.request()).isEqualTo(readRequest); + assertThat(evidence.accountWorldParticipationId()).isEqualTo(PARTICIPATION_ID); + assertThat(evidence.accountWorldParticipationFence()).isEqualTo(PARTICIPATION_FENCE); + assertThat(evidence.gameSessionOwnerAttemptId()).isEqualTo(GAME_SESSION_ATTEMPT_ID); + assertThat(evidence.gameSessionOwnerFence()).isEqualTo(GAME_SESSION_FENCE); + assertThat(evidence.canonicalGameInstanceId()).isEqualTo(GAME_INSTANCE_ID); + assertThat(evidence.preparationInputJson()).isEqualTo(PREPARATION_INPUT); + assertThat(evidence.preparationInputDigest()).isEqualTo(digest(PREPARATION_INPUT)); + assertThat(harness.retainedProof.get().originalLeaseExpiresAt()) + .isEqualTo(ORIGINAL_LEASE_EXPIRY) + .isBefore(HISTORICAL_RECOVERY_AT); + assertThat(harness.steps) + .containsExactly( + "remote-read", + "issuer-currentness", + "participation-write", + "proof-write", + "participation-readback", + "historical-tuple-readback"); + assertThat(harness.issuerCommits).isEqualTo(1); + assertThat(harness.readbackTransactions.begins).isEqualTo(2); + assertThat(harness.readbackTransactions.commits).isEqualTo(1); + assertThat(harness.readbackTransactions.rollbacks).isEqualTo(1); + verify(harness.gameSessionClient, times(1)).read(any(Request.class)); + verify(harness.issuer, times(1)) + .withCurrentWorldReceivingParticipationCurrentness( + eq(harness.tuple.canonicalBytes()), + eq(GAME_SESSION_ATTEMPT_ID), + eq(GAME_SESSION_FENCE), + any()); + verify(harness.participationRepository, times(1)).createOrReadExact(any(Candidate.class)); + verify(harness.participationRepository, times(1)).findCurrentExact(any(Candidate.class)); + verify(harness.participationRepository, times(1)) + .findHistoricalForOriginalTuple(any(byte[].class)); + verify(harness.participationRepository, times(0)) + .findSettlementExact(any(UUID.class), anyLong()); + verify(harness.attemptEvidenceRepository, times(1)) + .retainCurrentExact(any(StoredParticipation.class), any(Result.class)); + verify(harness.attemptEvidenceRepository, times(0)) + .findCurrentExact(any(StoredParticipation.class), any(Request.class)); + } + + private static AcquisitionRequest request(byte[] tupleBytes) { + StartSessionPostAuthorizationExecutionTuple tuple = originalTuple(); + return new AcquisitionRequest( + tupleBytes == null ? tuple.canonicalBytes() : tupleBytes, + GAME_SESSION_MUTATION_ID, + GAME_SESSION_ATTEMPT_ID, + GAME_SESSION_FENCE, + GAME_INSTANCE_ID, + PREPARATION_INPUT, + digest(PREPARATION_INPUT)); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple() { + UUID targetOwnerId = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + UUID reservationOwnerId = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + String requestId = "world-participation-original-request"; + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + requestId, + ACCOUNT_ID, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, NAMESPACE), + new StartSessionOperatorAction.Target(91L, targetOwnerId), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "synthetic World participation composition proof")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + reservationOwnerId, + 19L, + authorityBundle(preTuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + return StartSessionAuthorityEvidenceBundleFixture.canonicalBytes( + tuple, + new Values( + uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"), + "sha256:" + "a".repeat(64), + "17", + "CURRENT", + Instant.parse("2026-10-09T00:00:00Z"), + Instant.parse("2026-10-10T00:00:00Z"), + 1L, + 2L, + 3L, + 4L, + 5L, + 23L, + uuid("a681bba7-c215-4cf1-a35b-14348912cbdc"), + "2", + "3")); + } + + private static byte[] projection( + StartSessionPostAuthorizationExecutionTuple tuple, Map additionalFields) { + var bundle = StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + Map projection = + Map.of( + "projectionSchemaId", "accountStartSessionRedemptionProjection", + "projectionSchemaVersion", "1", + "authorizationReferenceFingerprint", tuple.authorizationReferenceFingerprint(), + "authorityEvidenceBundle", bundle.jsonValue(), + "issuanceOperationId", bundle.issuanceOperationId().toString(), + "issuanceFence", Long.parseLong(tuple.issuanceFence())); + if (additionalFields.isEmpty()) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(projection)); + } catch (java.io.IOException impossible) { + throw new IllegalStateException(impossible); + } + } + var changed = new java.util.LinkedHashMap<>(projection); + changed.putAll(additionalFields); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(changed)); + } catch (java.io.IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static AccountStartSessionAuthorityCapture capture( + StartSessionPostAuthorizationExecutionTuple tuple) { + SourceEvidence source = sourceEvidence("current source"); + var bundle = StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + byte[] signerReceipt = "synthetic-signer-receipt".getBytes(StandardCharsets.UTF_8); + Map snapshot = + Map.ofEntries( + Map.entry("schema", "account-start-session-authority-snapshot/v1"), + Map.entry("controlPlaneRequestId", tuple.controlPlaneRequestId()), + Map.entry( + "preAuthorizationTuple", + Base64.getEncoder() + .encodeToString( + tuple + .preAuthorizationTuple() + .canonicalJson() + .getBytes(StandardCharsets.UTF_8))), + Map.entry("mutationDigest", tuple.mutationDigest()), + Map.entry("accountId", tuple.preAuthorizationTuple().actor().accountId().toString()), + Map.entry( + "tenantId", tuple.preAuthorizationTuple().action().scope().tenantId().toString()), + Map.entry("targetOwner", tuple.preAuthorizationTuple().targetOwner()), + Map.entry("loggingWorkloadUri", tuple.authenticatedWorkloadIdentity()), + Map.entry("reservationOwnerId", tuple.reservationOwnerId().toString()), + Map.entry("reservationClaimFence", Long.toString(tuple.reservationClaimFence())), + Map.entry("controlUiOperationId", bundle.issuanceOperationId().toString()), + Map.entry("controlUiTokenJti", "a681bba7-c215-4cf1-a35b-14348912cbdc"), + Map.entry("controlUiTokenHash", "sha256:" + "d".repeat(64)), + Map.entry("controlUiSignerReceipt", Base64.getEncoder().encodeToString(signerReceipt)), + Map.entry("controlUiSignerReceiptSha256", sha256(signerReceipt)), + Map.entry( + "sourceVectorEvidence", + Base64.getEncoder().encodeToString(source.canonicalBytes())), + Map.entry( + "sourceVector", + List.of(Base64.getEncoder().encodeToString(source.canonicalBytes()))), + Map.entry("outboxCheckpoints", Map.of()), + Map.entry("authorityTuple", bundle.authorityTuple()), + Map.entry("membershipVersion", bundle.membershipVersion()), + Map.entry("accountIdentitySource", "ACCOUNT_UUID"), + Map.entry("issuanceFence", tuple.issuanceFence()), + Map.entry("issuanceFenceSourceVersion", "17")); + try { + return AccountStartSessionAuthorityCapture.create( + tuple.controlPlaneRequestId(), + 17L, + 31L, + "123456", + "2026-10-09T00:00:00.000Z", + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(snapshot))); + } catch (java.io.IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static SourceEvidence sourceEvidence(String detail) { + return new SourceEvidence( + SourceKind.ACCOUNT, + ACCOUNT_ID.toString(), + "2", + "17", + null, + null, + detail.getBytes(StandardCharsets.UTF_8)); + } + + private static StoredParticipation participation( + StartSessionPostAuthorizationExecutionTuple tuple, List sources) { + return new StoredParticipation( + PARTICIPATION_ID, + PARTICIPATION_FENCE, + tuple.controlPlaneRequestId(), + tuple.canonicalBytes(), + NAMESPACE, + TENANT_ID, + GAME_INSTANCE_ID, + GAME_SESSION_ATTEMPT_ID, + GAME_SESSION_FENCE, + PREPARATION_INPUT, + digest(PREPARATION_INPUT), + 987L, + OffsetDateTime.parse("2026-10-09T00:00:00Z"), + sources); + } + + private static SourceEvidence participationSource(SourceEvidence source) { + return SourceEvidence.fromStored(source.canonicalBytes()); + } + + private static String digest(String value) { + return "sha256:" + + HexFormat.of().formatHex(sha256Bytes(value.getBytes(StandardCharsets.UTF_8))); + } + + private static byte[] sha256Bytes(byte[] value) { + try { + return MessageDigest.getInstance("SHA-256").digest(value); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static String sha256(byte[] value) { + return HexFormat.of().formatHex(sha256Bytes(value)); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static T authorized(java.util.function.Supplier action) { + return peer(NAMESPACE, "world-management-service", action); + } + + private static T peer( + String namespace, String workload, java.util.function.Supplier action) { + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var prior = context.attach(); + try { + return action.get(); + } finally { + context.detach(prior); + } + } + + private static void assertNoSql() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } + + private static void assertWritableReadCommittedTransaction() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + private static void assertCode(Status.Code code, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code)); + } + + private static final class Harness { + final AccountStartSessionOperatorAuthorizationService issuer = + mock(AccountStartSessionOperatorAuthorizationService.class); + final AccountStartSessionWorldParticipationRepository participationRepository = + mock(AccountStartSessionWorldParticipationRepository.class); + final AccountStartSessionWorldOriginalAttemptEvidenceRepository attemptEvidenceRepository = + mock(AccountStartSessionWorldOriginalAttemptEvidenceRepository.class); + final OriginalStartSessionCurrentAttemptClient gameSessionClient = + mock(OriginalStartSessionCurrentAttemptClient.class); + final OwnerTransactions readbackTransactions = new OwnerTransactions(); + final StartSessionPostAuthorizationExecutionTuple tuple = originalTuple(); + final StoredParticipation committedParticipation = + participation(tuple, List.of(participationSource(sourceEvidence("current source")))); + final AtomicReference participationReadback = + new AtomicReference<>(committedParticipation); + final AtomicReference retainedProof = new AtomicReference<>(); + final List steps = new ArrayList<>(); + int issuerCommits; + final AccountStartSessionWorldParticipationAcquisitionService service = + new AccountStartSessionWorldParticipationAcquisitionService( + issuer, + participationRepository, + attemptEvidenceRepository, + gameSessionClient, + readbackTransactions, + NAMESPACE); + boolean participationMissingOnReadback; + + void configureSuccess() { + configureClientResult(projection(tuple, Map.of())); + doAnswer( + invocation -> { + assertNoSql(); + steps.add("issuer-currentness"); + @SuppressWarnings("unchecked") + Function callback = + invocation.getArgument(3); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + TransactionDefinition.ISOLATION_READ_COMMITTED); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.initSynchronization(); + Object result; + try { + result = callback.apply(capture(tuple)); + } finally { + TransactionSynchronizationManager.clear(); + } + issuerCommits++; + return result; + }) + .when(issuer) + .withCurrentWorldReceivingParticipationCurrentness( + any(byte[].class), eq(GAME_SESSION_ATTEMPT_ID), eq(GAME_SESSION_FENCE), any()); + when(participationRepository.createOrReadExact(any(Candidate.class))) + .thenAnswer( + invocation -> { + assertWritableReadCommittedTransaction(); + steps.add("participation-write"); + return committedParticipation; + }); + when(attemptEvidenceRepository.retainCurrentExact( + any(StoredParticipation.class), any(Result.class))) + .thenAnswer( + invocation -> { + assertWritableReadCommittedTransaction(); + steps.add("proof-write"); + StoredParticipation exactParticipation = invocation.getArgument(0); + Result observation = invocation.getArgument(1); + StoredEvidence existing = retainedProof.get(); + if (existing != null) return existing; + StoredEvidence created = storedEvidence(exactParticipation, observation); + retainedProof.set(created); + return created; + }); + when(participationRepository.findCurrentExact(any(Candidate.class))) + .thenAnswer( + invocation -> { + assertWritableReadCommittedTransaction(); + steps.add("participation-readback"); + return participationMissingOnReadback + ? Optional.empty() + : Optional.of(participationReadback.get()); + }); + when(attemptEvidenceRepository.findCurrentExact( + any(StoredParticipation.class), any(Request.class))) + .thenAnswer( + invocation -> { + assertWritableReadCommittedTransaction(); + steps.add("proof-readback"); + return Optional.ofNullable(retainedProof.get()); + }); + } + + void configureClientResult(byte[] projectionBytes) { + when(gameSessionClient.read(any(Request.class))) + .thenAnswer( + invocation -> { + assertNoSql(); + steps.add("remote-read"); + Request read = invocation.getArgument(0); + return new Result(read, ORIGINAL_LEASE_EXPIRY, projectionBytes); + }); + } + } + + private static StoredEvidence storedEvidence( + StoredParticipation participation, Result observation) { + byte[] responseBytes = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(observation).toByteArray(); + return new StoredEvidence( + participation.participationId(), + GAME_SESSION_MUTATION_ID, + observation.originalLeaseExpiresAt(), + responseBytes, + "sha256:" + sha256(responseBytes), + observation); + } + + private static final class OwnerTransactions extends AbstractPlatformTransactionManager { + private static final long serialVersionUID = 1L; + int begins; + int commits; + int rollbacks; + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) { + assertNoSql(); + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.isReadOnly()).isFalse(); + begins++; + } + + @Override + protected void doCommit(DefaultTransactionStatus status) { + commits++; + } + + @Override + protected void doRollback(DefaultTransactionStatus status) { + rollbacks++; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadGrpcServiceTest.java new file mode 100644 index 0000000000..57329f7d01 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadGrpcServiceTest.java @@ -0,0 +1,371 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.sql.SQLException; +import java.time.Instant; +import java.util.HexFormat; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; +import net.firedevops.firemud.account.v1.ReadHistoricalStartSessionWorldParticipationRequest; +import net.firedevops.firemud.account.v1.ReadHistoricalStartSessionWorldParticipationResponse; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationHistoricalReadEvidence; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationHistoricalReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture.Values; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.transaction.CannotCreateTransactionException; + +/** Verifies authentication-before-codec ordering; this is not mTLS or producer proof. */ +class AccountStartSessionWorldParticipationHistoricalReadGrpcServiceTest { + private static final String NAMESPACE = "world-runtime"; + + private final AccountStartSessionWorldParticipationHistoricalReadService owner = + mock(AccountStartSessionWorldParticipationHistoricalReadService.class); + private final AccountStartSessionWorldParticipationHistoricalReadGrpcService receiver = + new AccountStartSessionWorldParticipationHistoricalReadGrpcService(owner, NAMESPACE); + + @AfterEach + void clearThreadState() { + SessionContext.clear(); + } + + @Test + void authenticatesExactWorldAndAbsentEndUserBeforeRequestDecodeOrOwnerAccess() { + var malformed = ReadHistoricalStartSessionWorldParticipationRequest.newBuilder().build(); + assertRpcStatus(Status.Code.UNAUTHENTICATED, observer -> invoke(malformed, observer)); + assertRpcStatus( + Status.Code.PERMISSION_DENIED, + observer -> + peer( + NAMESPACE, + "game-session-service", + () -> { + invoke(malformed, observer); + return null; + })); + assertRpcStatus( + Status.Code.PERMISSION_DENIED, + observer -> + peer( + "other-runtime", + "world-management-service", + () -> { + invoke(malformed, observer); + return null; + })); + SessionContext.setContext("123", java.util.List.of(), java.util.Map.of()); + assertRpcStatus( + Status.Code.PERMISSION_DENIED, + observer -> + peer( + NAMESPACE, + "world-management-service", + () -> { + invoke(malformed, observer); + return null; + })); + verifyNoInteractions(owner); + } + + @Test + void bindsConfiguredNamespaceBeforeClosedRequestCodecAndRejectsUnknownOrWrongVersion() { + var foreignNamespace = + ReadHistoricalStartSessionWorldParticipationRequest.newBuilder() + .setSchemaVersion(1) + .setReadRequestId("d1f41bfb-265a-4f3b-8b2a-124cba20ce43") + .setTargetNamespace("other-runtime") + .setOriginalPostAuthorizationTuple( + ByteString.copyFrom(originalTuple().canonicalBytes())) + .build(); + var wrongVersion = validWire().toBuilder().setSchemaVersion(2).build(); + UnknownFieldSet unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + var unknownField = validWire().toBuilder().setUnknownFields(unknown).build(); + + assertRpcStatus( + Status.Code.PERMISSION_DENIED, + observer -> + peer( + NAMESPACE, + "world-management-service", + () -> { + invoke(foreignNamespace, observer); + return null; + })); + assertRpcStatus( + Status.Code.INVALID_ARGUMENT, + observer -> + peer( + NAMESPACE, + "world-management-service", + () -> { + invoke(wrongVersion, observer); + return null; + })); + assertRpcStatus( + Status.Code.INVALID_ARGUMENT, + observer -> + peer( + NAMESPACE, + "world-management-service", + () -> { + invoke(unknownField, observer); + return null; + })); + verifyNoInteractions(owner); + } + + @Test + void returnsResolvedCoordinatesForTheExactOriginalTupleLookup() throws Exception { + var wire = validWire(); + var decoded = AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromRequest(wire); + var evidence = + new AccountStartSessionWorldParticipationHistoricalReadEvidence( + decoded, + UUID.fromString("a8c1e8c8-f237-41b7-918d-ec2281bcac10"), + 31L, + UUID.fromString("b9d2f9d9-0438-42c8-829e-fd3392cd9d21"), + 37L, + UUID.fromString("c0e30aea-1549-43d9-93af-0e44a3deae32"), + "{\"retained\":true}", + digest("{\"retained\":true}")); + when(owner.read(decoded)).thenReturn(evidence); + var response = new AtomicReference(); + var completed = new AtomicBoolean(); + StreamObserver observer = + new StreamObserver<>() { + @Override + public void onNext(ReadHistoricalStartSessionWorldParticipationResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable error) { + throw new AssertionError("historical tuple read unexpectedly failed", error); + } + + @Override + public void onCompleted() { + completed.set(true); + } + }; + + peer( + NAMESPACE, + "world-management-service", + () -> { + invoke(wire, observer); + return null; + }); + + assertThat(completed).isTrue(); + assertThat(response.get().getRequest()).isEqualTo(wire); + assertThat(response.get().getAccountWorldParticipationId()) + .isEqualTo("a8c1e8c8-f237-41b7-918d-ec2281bcac10"); + assertThat(response.get().getAccountWorldParticipationFence()).isEqualTo(31L); + assertThat(response.get().getGameSessionOwnerAttemptId()) + .isEqualTo("b9d2f9d9-0438-42c8-829e-fd3392cd9d21"); + verify(owner).read(decoded); + } + + @Test + void mapsConnectionFailuresToRedactedUnavailable() { + assertOwnerFailure( + new CannotCreateTransactionException("sensitive transaction detail"), + Status.Code.UNAVAILABLE); + assertOwnerFailure( + new org.jooq.exception.DataAccessException( + "sensitive jOOQ detail", new SQLException("sensitive SQL detail", "08006")), + Status.Code.UNAVAILABLE); + assertOwnerFailure( + new DataAccessResourceFailureException( + "sensitive Spring detail", new SQLException("sensitive SQL detail", "08001")), + Status.Code.UNAVAILABLE); + } + + @Test + void mapsNonConnectionPersistenceAndUnexpectedFailuresToRedactedInternal() { + assertOwnerFailure( + new org.jooq.exception.DataAccessException( + "sensitive jOOQ detail", new SQLException("sensitive SQL detail", "23505")), + Status.Code.INTERNAL); + assertOwnerFailure( + new DataIntegrityViolationException( + "sensitive Spring detail", new SQLException("sensitive SQL detail", "23505")), + Status.Code.INTERNAL); + assertOwnerFailure(new RuntimeException("sensitive runtime detail"), Status.Code.INTERNAL); + } + + @Test + void mapsOwnerEvidenceMismatchesToFailedPrecondition() { + assertOwnerFailure( + new IllegalArgumentException("sensitive mismatch detail"), Status.Code.FAILED_PRECONDITION); + assertOwnerFailure( + new IllegalStateException("sensitive mismatch detail"), Status.Code.FAILED_PRECONDITION); + } + + @Test + void preservesExplicitGrpcStatusFailures() { + var expected = Status.PERMISSION_DENIED.withDescription("upstream denial"); + assertOwnerFailure(expected.asRuntimeException(), expected.getCode(), "upstream denial"); + } + + private static ReadHistoricalStartSessionWorldParticipationRequest validWire() { + return ReadHistoricalStartSessionWorldParticipationRequest.newBuilder() + .setSchemaVersion(1) + .setReadRequestId("d1f41bfb-265a-4f3b-8b2a-124cba20ce43") + .setTargetNamespace(NAMESPACE) + .setOriginalPostAuthorizationTuple(ByteString.copyFrom(originalTuple().canonicalBytes())) + .build(); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple() { + String namespace = NAMESPACE; + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "historical-grpc-original-request", + UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"), + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope( + UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"), namespace), + new StartSessionOperatorAction.Target( + 91L, UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a")), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "synthetic historical gRPC boundary test")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + UUID.fromString("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"), + 19L, + StartSessionAuthorityEvidenceBundleFixture.canonicalBytes( + preTuple, + new Values( + UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"), + "sha256:" + "a".repeat(64), + "17", + "CURRENT", + Instant.parse("2020-01-01T00:00:00Z"), + Instant.parse("2020-01-02T00:00:00Z"), + 1L, + 2L, + 3L, + 4L, + 5L, + 23L, + UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"), + "2", + "3")), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static String digest(String json) throws Exception { + return "sha256:" + + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(json.getBytes(StandardCharsets.UTF_8))); + } + + private void invoke( + ReadHistoricalStartSessionWorldParticipationRequest request, + StreamObserver observer) { + receiver.readHistoricalStartSessionWorldParticipation(request, observer); + } + + private void assertOwnerFailure(RuntimeException failure, Status.Code expected) { + assertOwnerFailure(failure, expected, null); + } + + private void assertOwnerFailure( + RuntimeException failure, Status.Code expected, String expectedDescription) { + org.mockito.Mockito.reset(owner); + var wire = validWire(); + var decoded = AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromRequest(wire); + when(owner.read(decoded)).thenThrow(failure); + @SuppressWarnings("unchecked") + var observer = + (StreamObserver) + mock(StreamObserver.class); + + peer( + NAMESPACE, + "world-management-service", + () -> { + invoke(wire, observer); + return null; + }); + + var error = org.mockito.ArgumentCaptor.forClass(Throwable.class); + verify(observer).onError(error.capture()); + Status status = Status.fromThrowable(error.getValue()); + assertThat(status.getCode()).isEqualTo(expected); + if (expectedDescription == null) { + assertThat(String.valueOf(status.getDescription())).doesNotContain("sensitive"); + } else { + assertThat(status.getDescription()).isEqualTo(expectedDescription); + } + verify(owner).read(decoded); + } + + private static void assertRpcStatus( + Status.Code expected, + Consumer> action) { + @SuppressWarnings("unchecked") + var observer = + (StreamObserver) + mock(StreamObserver.class); + action.accept(observer); + var error = org.mockito.ArgumentCaptor.forClass(Throwable.class); + org.mockito.Mockito.verify(observer).onError(error.capture()); + assertThat(Status.fromThrowable(error.getValue()).getCode()).isEqualTo(expected); + } + + private static T peer( + String namespace, String workload, java.util.function.Supplier action) { + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var prior = context.attach(); + try { + return action.get(); + } finally { + context.detach(prior); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadServiceTest.java new file mode 100644 index 0000000000..2859dea367 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadServiceTest.java @@ -0,0 +1,339 @@ +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.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 io.grpc.Context; +import io.grpc.Status; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationHistoricalReadRequest; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture.Values; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Mocked owner-storage boundary only; no PostgreSQL or authenticated Game Session proof. */ +class AccountStartSessionWorldParticipationHistoricalReadServiceTest { + private static final String NAMESPACE = "world-runtime"; + private static final UUID PARTICIPATION_ID = uuid("a8c1e8c8-f237-41b7-918d-ec2281bcac10"); + private static final UUID READ_ID = uuid("d1f41bfb-265a-4f3b-8b2a-124cba20ce43"); + private static final UUID GAME_SESSION_ATTEMPT_ID = uuid("b9d2f9d9-0438-42c8-829e-fd3392cd9d21"); + private static final UUID GAME_INSTANCE_ID = uuid("c0e30aea-1549-43d9-93af-0e44a3deae32"); + private static final long PARTICIPATION_FENCE = 31L; + private static final long GAME_SESSION_FENCE = 37L; + private static final String PREPARATION_INPUT = + "{ \"historical\" : \"retained exactly\", \"revision\": 1 }\n"; + + private final AccountStartSessionWorldParticipationRepository repository = + mock(AccountStartSessionWorldParticipationRepository.class); + private final OwnerTransactions transactions = new OwnerTransactions(); + private final AccountStartSessionWorldParticipationHistoricalReadService service = + new AccountStartSessionWorldParticipationHistoricalReadService( + repository, transactions, NAMESPACE); + + @AfterEach + void clearThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesExactWorldWorkloadAndNoEndUserBeforeRequestOrStorageAccess() { + assertCode(Status.Code.UNAUTHENTICATED, () -> service.read(null)); + for (String workload : List.of("account-service", "game-session-service")) { + assertCode( + Status.Code.PERMISSION_DENIED, () -> peer(NAMESPACE, workload, () -> service.read(null))); + } + assertCode( + Status.Code.PERMISSION_DENIED, + () -> peer("other-runtime", "world-management-service", () -> service.read(null))); + SessionContext.setContext("123", List.of(), Map.of()); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> peer(NAMESPACE, "world-management-service", () -> service.read(null))); + verifyNoInteractions(repository); + assertThat(transactions.begins).isZero(); + } + + @Test + void deniesAmbientSqlOrSynchronizationBeforeValidatingRequestOrStartingOwnerTransaction() { + var request = request(false); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode(Status.Code.FAILED_PRECONDITION, () -> authorized(() -> service.read(request))); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertCode(Status.Code.FAILED_PRECONDITION, () -> authorized(() -> service.read(request))); + verifyNoInteractions(repository); + assertThat(transactions.begins).isZero(); + } + + @Test + void readsExactHistoryAfterIngressExpiryAndPriorSettlementWithoutCurrentnessOrMutation() + throws Exception { + StoredParticipation expired = participation(true); + when(repository.findHistoricalForOriginalTuple(request(true).originalPostAuthorizationTuple())) + .thenAnswer( + call -> { + assertWritableReadCommittedTransaction(); + return Optional.of(expired); + }); + // A prior terminal receipt is deliberately present; historical participation reads do not + // require it, rewrite it, or treat its outcome as fresh execution permission. + when(repository.findSettlementExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn( + Optional.of( + mock(AccountStartSessionWorldParticipationRepository.StoredSettlement.class))); + + var evidence = authorized(() -> service.read(request(true))); + + assertThat(evidence.request()).isEqualTo(request(true)); + assertThat(evidence.request().originalPostAuthorizationTuple()) + .containsExactly(expired.originalPostAuthorizationTuple()); + assertThat(evidence.accountWorldParticipationId()).isEqualTo(PARTICIPATION_ID); + assertThat(evidence.accountWorldParticipationFence()).isEqualTo(PARTICIPATION_FENCE); + assertThat(evidence.gameSessionOwnerAttemptId()).isEqualTo(GAME_SESSION_ATTEMPT_ID); + assertThat(evidence.gameSessionOwnerFence()).isEqualTo(GAME_SESSION_FENCE); + assertThat(evidence.canonicalGameInstanceId()).isEqualTo(GAME_INSTANCE_ID); + assertThat(evidence.preparationInputJson()).isEqualTo(PREPARATION_INPUT); + assertThat(evidence.preparationInputDigest()).isEqualTo(digest(PREPARATION_INPUT)); + assertThat(transactions.begins).isEqualTo(1); + assertThat(transactions.commits).isEqualTo(1); + assertNoSql(); + verify(repository) + .findHistoricalForOriginalTuple(request(true).originalPostAuthorizationTuple()); + verifyNoMoreInteractions(repository); + } + + @Test + void absentMismatchedNamespaceAndMismatchedRetainedIdentityFailClosed() { + when(repository.findHistoricalForOriginalTuple(request(false).originalPostAuthorizationTuple())) + .thenReturn(Optional.empty()); + assertCode( + Status.Code.FAILED_PRECONDITION, () -> authorized(() -> service.read(request(false)))); + assertThat(transactions.commits).isZero(); + assertThat(transactions.rollbacks).isEqualTo(1); + + TransactionSynchronizationManager.clear(); + transactions.resetCounts(); + when(repository.findHistoricalForOriginalTuple(request(false).originalPostAuthorizationTuple())) + .thenReturn( + Optional.of( + participation(false, "other-runtime", PARTICIPATION_ID, PARTICIPATION_FENCE))); + assertCode( + Status.Code.FAILED_PRECONDITION, () -> authorized(() -> service.read(request(false)))); + assertThat(transactions.commits).isEqualTo(1); + + assertCode( + Status.Code.PERMISSION_DENIED, + () -> + authorized( + () -> + service.read( + new AccountStartSessionWorldParticipationHistoricalReadRequest( + READ_ID, + "other-runtime", + originalTuple("other-runtime", false).canonicalBytes())))); + verify(repository, org.mockito.Mockito.times(2)) + .findHistoricalForOriginalTuple(request(false).originalPostAuthorizationTuple()); + } + + private AccountStartSessionWorldParticipationHistoricalReadRequest request(boolean expired) { + return new AccountStartSessionWorldParticipationHistoricalReadRequest( + READ_ID, NAMESPACE, originalTuple(NAMESPACE, expired).canonicalBytes()); + } + + private static StoredParticipation participation(boolean expired) { + return participation(expired, NAMESPACE, PARTICIPATION_ID, PARTICIPATION_FENCE); + } + + private static StoredParticipation participation( + boolean expired, String namespace, UUID participationId, long participationFence) { + StartSessionPostAuthorizationExecutionTuple tuple = originalTuple(namespace, expired); + return new StoredParticipation( + participationId, + participationFence, + tuple.controlPlaneRequestId(), + tuple.canonicalBytes(), + namespace, + TENANT, + GAME_INSTANCE_ID, + GAME_SESSION_ATTEMPT_ID, + GAME_SESSION_FENCE, + PREPARATION_INPUT, + digest(PREPARATION_INPUT), + 987L, + OffsetDateTime.parse("2026-10-09T00:00:00Z"), + List.of()); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple( + String namespace, boolean expired) { + UUID actor = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + UUID targetOwner = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + UUID reservationOwner = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + String requestId = "historical-participation-original-request"; + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + requestId, + actor, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, namespace), + new StartSessionOperatorAction.Target(91L, targetOwner), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "mocked historical Account read boundary")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + reservationOwner, + 19L, + authorityBundle(preTuple, expired), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle( + StartSessionPreAuthorizationReservationTuple tuple, boolean expired) { + return StartSessionAuthorityEvidenceBundleFixture.canonicalBytes( + tuple, + new Values( + uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"), + "sha256:" + "a".repeat(64), + "17", + "CURRENT", + Instant.parse(expired ? "2020-01-01T00:00:00Z" : "2026-10-09T00:00:00Z"), + Instant.parse(expired ? "2020-01-02T00:00:00Z" : "2026-10-10T00:00:00Z"), + 1L, + 2L, + 3L, + 4L, + 5L, + 23L, + uuid("a681bba7-c215-4cf1-a35b-14348912cbdc"), + "2", + "3")); + } + + private static T authorized(Supplier action) { + return peer(NAMESPACE, "world-management-service", action); + } + + private static T peer(String namespace, String workload, Supplier action) { + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var prior = context.attach(); + try { + return action.get(); + } finally { + context.detach(prior); + } + } + + private static void assertWritableReadCommittedTransaction() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + private static void assertNoSql() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } + + private static void assertCode(Status.Code code, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code)); + } + + private static String digest(String value) { + try { + return "sha256:" + + java.util.HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final UUID TENANT = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + + private static final class OwnerTransactions extends AbstractPlatformTransactionManager { + private int begins; + private int commits; + private int rollbacks; + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) { + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.isReadOnly()).isFalse(); + begins++; + } + + @Override + protected void doCommit(DefaultTransactionStatus status) { + commits++; + } + + @Override + protected void doRollback(DefaultTransactionStatus status) { + rollbacks++; + } + + void resetCounts() { + begins = 0; + commits = 0; + rollbacks = 0; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementServiceTest.java new file mode 100644 index 0000000000..731003e29a --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementServiceTest.java @@ -0,0 +1,510 @@ +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.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredSettlement; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture.Values; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminalReadClient; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminalReadRequest; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** Composition seams only: authenticated peer and exact owner terminal are stipulated here. */ +class AccountStartSessionWorldParticipationSettlementServiceTest { + private static final String NAMESPACE = "world-runtime"; + private static final UUID PARTICIPATION_ID = uuid("a8c1e8c8-f237-41b7-918d-ec2281bcac10"); + private static final UUID GAME_SESSION_ATTEMPT_ID = uuid("b9d2f9d9-0438-42c8-829e-fd3392cd9d21"); + private static final UUID GAME_INSTANCE_ID = uuid("c0e30aea-1549-43d9-93af-0e44a3deae32"); + private static final long PARTICIPATION_FENCE = 31L; + private static final long GAME_SESSION_FENCE = 37L; + private static final String PREPARATION_INPUT = + "{ \"selected\" : \"immutable source\", \"revision\": 3 }\n"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final AccountStartSessionWorldParticipationRepository repository = + mock(AccountStartSessionWorldParticipationRepository.class); + private final WorldStartSessionExecutionTerminalReadClient world = + mock(WorldStartSessionExecutionTerminalReadClient.class); + private final OwnerTransactions transactions = new OwnerTransactions(); + private final AccountStartSessionWorldParticipationSettlementService service = + new AccountStartSessionWorldParticipationSettlementService( + repository, world, transactions, NAMESPACE); + + @AfterEach + void clearThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesExactWorldPeerWithoutEndUserBeforeLookupIdentityOrOwnerAccess() { + assertCode(Status.Code.UNAUTHENTICATED, () -> service.settle(null, 0)); + for (String workload : List.of("account-service", "game-session-service")) { + assertCode( + Status.Code.PERMISSION_DENIED, + () -> peer(NAMESPACE, workload, () -> service.settle(null, 0))); + } + assertCode( + Status.Code.PERMISSION_DENIED, + () -> peer("other", "world-management-service", () -> service.settle(null, 0))); + SessionContext.setContext("123", List.of(), Map.of()); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> peer(NAMESPACE, "world-management-service", () -> service.settle(null, 0))); + verifyNoInteractions(repository, world); + assertThat(transactions.begins).isZero(); + } + + @Test + void deniesAmbientSqlOrSynchronizationBeforeIdentityValidation() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode(Status.Code.FAILED_PRECONDITION, () -> authorized(() -> service.settle(null, 0))); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertCode(Status.Code.FAILED_PRECONDITION, () -> authorized(() -> service.settle(null, 0))); + verifyNoInteractions(repository, world); + assertThat(transactions.begins).isZero(); + } + + @Test + void derivesExactReadFromRetainedParticipationAndCommitsThenReadsBackBothOutcomes() { + for (WorldStartSessionExecutionTerminal.Outcome outcome : + WorldStartSessionExecutionTerminal.Outcome.values()) { + reset(repository, world); + Fixture fixture = fixture(); + WorldStartSessionExecutionTerminal terminal = fixture.terminal(outcome); + StoredSettlement expected = fixture.settlement(terminal); + when(repository.findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn(Optional.of(fixture.participation)); + when(repository.findSettlementExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn(Optional.empty(), Optional.of(expected)); + when(world.read(any())) + .thenAnswer( + call -> { + assertNoSql(); + WorldStartSessionExecutionTerminalReadRequest request = call.getArgument(0); + assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(request.originalPostAuthorizationTuple()) + .containsExactly(fixture.participation.originalPostAuthorizationTuple()); + assertThat(request.accountWorldParticipationId()).isEqualTo(PARTICIPATION_ID); + assertThat(request.accountWorldParticipationFence()).isEqualTo(PARTICIPATION_FENCE); + assertThat(request.gameSessionOwnerAttemptId()).isEqualTo(GAME_SESSION_ATTEMPT_ID); + assertThat(request.gameSessionOwnerFence()).isEqualTo(GAME_SESSION_FENCE); + assertThat(request.canonicalGameInstanceId()).isEqualTo(GAME_INSTANCE_ID); + assertThat(request.preparationInputJson()).isEqualTo(PREPARATION_INPUT); + assertThat(request.preparationInputDigest()) + .isEqualTo(fixture.participation.preparationInputDigest()); + return terminal; + }); + when(repository.settleExact(any())) + .thenAnswer( + call -> { + assertWritableTransaction(); + assertThat(call.getArgument(0, WorldStartSessionExecutionTerminal.class).outcome()) + .isEqualTo(outcome); + return expected; + }); + + int priorCommits = transactions.commits; + StoredSettlement actual = + authorized(() -> service.settle(PARTICIPATION_ID, PARTICIPATION_FENCE)); + assertThat(actual.terminalBytes()).containsExactly(expected.terminalBytes()); + assertThat(actual.outcome()).isEqualTo(outcome); + assertThat(actual.worldExecutionFence()).isEqualTo(terminal.worldExecutionFence()); + assertThat(transactions.commits - priorCommits).isEqualTo(3); + assertThat(authorized(() -> service.settle(PARTICIPATION_ID, PARTICIPATION_FENCE))) + .isSameAs(expected); + assertThat(transactions.commits - priorCommits).isEqualTo(4); + ArgumentCaptor terminalCaptor = + ArgumentCaptor.forClass(WorldStartSessionExecutionTerminal.class); + verify(repository).settleExact(terminalCaptor.capture()); + assertThat(terminalCaptor.getValue().canonicalBytes()) + .containsExactly(terminal.canonicalBytes()); + verify(world).read(any()); + assertNoSql(); + } + } + + @Test + void alreadySettledHistoricalReceiptRecoversWithoutWorldOrCurrentActorChecks() { + Fixture fixture = fixture(); + var terminal = fixture.terminal(WorldStartSessionExecutionTerminal.Outcome.COMMITTED); + StoredSettlement receipt = fixture.settlement(terminal); + when(repository.findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn(Optional.of(fixture.participation)); + when(repository.findSettlementExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn(Optional.of(receipt)); + + assertThat(authorized(() -> service.settle(PARTICIPATION_ID, PARTICIPATION_FENCE))) + .isSameAs(receipt); + verifyNoInteractions(world); + assertThat(transactions.begins).isEqualTo(1); + assertThat(transactions.commits).isEqualTo(1); + } + + @Test + void absentOrUnavailableWorldTerminalNeverSettlesParticipation() { + Fixture fixture = fixture(); + when(repository.findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn(Optional.of(fixture.participation)); + when(repository.findSettlementExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn(Optional.empty()); + when(world.read(any())).thenReturn(null); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> service.settle(PARTICIPATION_ID, PARTICIPATION_FENCE))); + verify(repository, org.mockito.Mockito.never()).settleExact(any()); + assertThat(transactions.commits).isEqualTo(1); + + doThrow(Status.UNAVAILABLE.asRuntimeException()).when(world).read(any()); + assertCode( + Status.Code.UNAVAILABLE, + () -> authorized(() -> service.settle(PARTICIPATION_ID, PARTICIPATION_FENCE))); + verify(repository, org.mockito.Mockito.never()).settleExact(any()); + assertThat(transactions.commits).isEqualTo(2); + } + + @Test + void exactCodecRejectsSubstitutedWorldTerminalAndNoSqlOccursAcrossNetwork() { + Fixture fixture = fixture(); + when(repository.findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn(Optional.of(fixture.participation)); + when(repository.findSettlementExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn(Optional.empty()); + var substituted = + new WorldStartSessionExecutionTerminal( + fixture.participation.originalPostAuthorizationTuple(), + PARTICIPATION_ID, + PARTICIPATION_FENCE, + GAME_SESSION_ATTEMPT_ID, + GAME_SESSION_FENCE, + NAMESPACE, + fixture.participation.canonicalTenantId(), + fixture.participation.controlPlaneRequestId(), + GAME_INSTANCE_ID, + digest("substituted preparation"), + "substituted preparation", + 41L, + WorldStartSessionExecutionTerminal.Outcome.COMMITTED); + when(world.read(any())) + .thenAnswer( + call -> { + assertNoSql(); + return substituted; + }); + assertThatThrownBy( + () -> authorized(() -> service.settle(PARTICIPATION_ID, PARTICIPATION_FENCE))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("complete original StartSession identity"); + verify(repository, org.mockito.Mockito.never()).settleExact(any()); + assertThat(transactions.commits).isEqualTo(1); + } + + @Test + void targetNamespaceMismatchFailsBeforeWorldCallAndExpiredOriginalEvidenceDoesNotGateHistory() { + Fixture fixture = fixture(); + StoredParticipation otherNamespace = + new StoredParticipation( + fixture.participation.participationId(), + fixture.participation.participationFence(), + fixture.participation.controlPlaneRequestId(), + fixture.participation.originalPostAuthorizationTuple(), + "other-runtime", + fixture.participation.canonicalTenantId(), + fixture.participation.canonicalGameInstanceId(), + fixture.participation.gameSessionOwnerAttemptId(), + fixture.participation.gameSessionOwnerFence(), + fixture.participation.preparationInputJson(), + fixture.participation.preparationInputDigest(), + fixture.participation.producerXid(), + fixture.participation.createdAt(), + fixture.participation.sources()); + when(repository.findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn(Optional.of(otherNamespace)); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> authorized(() -> service.settle(PARTICIPATION_ID, PARTICIPATION_FENCE))); + verifyNoInteractions(world); + assertThat(transactions.commits).isEqualTo(0); + + // The persisted tuple's bundle is intentionally expired. Historical exact settlement + // depends on immutable owner readback and must not invoke current actor/JTI or expiry checks. + Fixture expired = fixture(true); + var terminal = expired.terminal(WorldStartSessionExecutionTerminal.Outcome.ABORTED); + StoredSettlement receipt = expired.settlement(terminal); + when(repository.findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn(Optional.of(expired.participation)); + when(repository.findSettlementExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn(Optional.empty(), Optional.of(receipt)); + when(world.read(any())).thenReturn(terminal); + when(repository.settleExact(any())).thenReturn(receipt); + assertThat(authorized(() -> service.settle(PARTICIPATION_ID, PARTICIPATION_FENCE))) + .isSameAs(receipt); + } + + @Test + void readbackMismatchAndSettlementCommitFailureDoNotReturnSuccess() { + Fixture fixture = fixture(); + var terminal = fixture.terminal(WorldStartSessionExecutionTerminal.Outcome.COMMITTED); + StoredSettlement first = fixture.settlement(terminal); + StoredSettlement changed = + new StoredSettlement( + first.participationId(), + first.outcome(), + first.worldExecutionFence() + 1, + first.terminalBytes(), + first.terminalDigest(), + first.settledAt()); + when(repository.findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn(Optional.of(fixture.participation)); + when(repository.findSettlementExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn(Optional.empty(), Optional.of(changed)); + when(world.read(any())).thenReturn(terminal); + when(repository.settleExact(any())).thenReturn(first); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> service.settle(PARTICIPATION_ID, PARTICIPATION_FENCE))); + assertThat(transactions.commits).isEqualTo(3); + + reset(repository, world); + when(repository.findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn(Optional.of(fixture.participation)); + when(repository.findSettlementExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn(Optional.empty()); + when(world.read(any())).thenReturn(terminal); + when(repository.settleExact(any())).thenReturn(first); + transactions.failCommitAt = transactions.commits + 2; + assertThatThrownBy( + () -> authorized(() -> service.settle(PARTICIPATION_ID, PARTICIPATION_FENCE))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("synthetic commit failure"); + assertThat(transactions.begins).isEqualTo(5); + } + + private static void assertWritableTransaction() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(java.sql.Connection.TRANSACTION_READ_COMMITTED); + } + + private static void assertNoSql() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } + + private static T authorized(Supplier action) { + return peer(NAMESPACE, "world-management-service", action); + } + + private static T peer(String namespace, String workload, Supplier action) { + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var prior = context.attach(); + try { + return action.get(); + } finally { + context.detach(prior); + } + } + + private static void assertCode(Status.Code code, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code)); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static String digest(String value) { + try { + return "sha256:" + + java.util.HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static Fixture fixture() { + return fixture(false); + } + + private static Fixture fixture(boolean expiredBundle) { + UUID tenantId = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + UUID actorId = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + UUID targetOwner = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + UUID reservationOwner = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + String requestId = "world-participation-settlement-original-request"; + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + requestId, + actorId, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(tenantId, NAMESPACE), + new StartSessionOperatorAction.Target(91L, targetOwner), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "StartSession terminal settlement test")); + var reference = + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "23", "18446744073709551615"); + StartSessionPostAuthorizationExecutionTuple original = + StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + reservationOwner, + 19L, + authorityBundle(preTuple, expiredBundle), + reference); + byte[] tupleBytes = original.canonicalBytes(); + StoredParticipation participation = + new StoredParticipation( + PARTICIPATION_ID, + PARTICIPATION_FENCE, + requestId, + tupleBytes, + NAMESPACE, + tenantId, + GAME_INSTANCE_ID, + GAME_SESSION_ATTEMPT_ID, + GAME_SESSION_FENCE, + PREPARATION_INPUT, + digest(PREPARATION_INPUT), + 987L, + OffsetDateTime.parse("2026-10-09T00:00:00Z"), + List.of()); + return new Fixture(participation); + } + + private static byte[] authorityBundle( + StartSessionPreAuthorizationReservationTuple tuple, boolean expired) { + return StartSessionAuthorityEvidenceBundleFixture.canonicalBytes( + tuple, + new Values( + uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"), + "sha256:" + "a".repeat(64), + "17", + "CURRENT", + Instant.parse(expired ? "2020-01-01T00:00:00Z" : "2026-10-09T00:00:00Z"), + Instant.parse(expired ? "2020-01-02T00:00:00Z" : "2026-10-10T00:00:00Z"), + 1L, + 2L, + 3L, + 4L, + 5L, + 23L, + uuid("a681bba7-c215-4cf1-a35b-14348912cbdc"), + "2", + "3")); + } + + private record Fixture(StoredParticipation participation) { + WorldStartSessionExecutionTerminal terminal( + WorldStartSessionExecutionTerminal.Outcome outcome) { + return new WorldStartSessionExecutionTerminal( + participation.originalPostAuthorizationTuple(), + PARTICIPATION_ID, + PARTICIPATION_FENCE, + GAME_SESSION_ATTEMPT_ID, + GAME_SESSION_FENCE, + NAMESPACE, + participation.canonicalTenantId(), + participation.controlPlaneRequestId(), + GAME_INSTANCE_ID, + participation.preparationInputDigest(), + PREPARATION_INPUT, + 41L, + outcome); + } + + StoredSettlement settlement(WorldStartSessionExecutionTerminal terminal) { + return new StoredSettlement( + PARTICIPATION_ID, + terminal.outcome(), + terminal.worldExecutionFence(), + terminal.canonicalBytes(), + terminal.digest(), + OffsetDateTime.parse("2026-10-09T00:01:00Z")); + } + } + + private static final class OwnerTransactions extends AbstractPlatformTransactionManager { + private static final long serialVersionUID = 1L; + int begins; + int commits; + int failCommitAt = -1; + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) { + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.isReadOnly()).isFalse(); + begins++; + } + + @Override + protected void doCommit(DefaultTransactionStatus status) { + commits++; + if (commits == failCommitAt) throw new IllegalStateException("synthetic commit failure"); + } + + @Override + protected void doRollback(DefaultTransactionStatus status) {} + } +} 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 new file mode 100644 index 0000000000..d3affece22 --- /dev/null +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java @@ -0,0 +1,290 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.codec.ByteArrayCodec; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Clock; +import java.util.Base64; +import java.util.Collection; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; + +/** + * Genuine Account owner mutations. Fresh creator/legal sources and signer platform evidence are + * explicitly test-only upstream inputs; this fixture is not production activation or settlement. + */ +public final class AccountControlUiOriginalOrderFixture implements AutoCloseable { + private final AccountControlUiOwnerSourcesFixture f; + private final AccountControlUiActorService actors; + private final AccountControlUiIssuanceService issuance; + private final AccountControlUiCoordination coordination; + private final RedisClient accountClient; + private final Path temporary; + private IssuedCreator originalCreator; + + public AccountControlUiOriginalOrderFixture( + String jdbcUrl, + String username, + String password, + String redisHost, + int redisPort, + Path temporary) + throws Exception { + this(jdbcUrl, username, password, redisHost, redisPort, temporary, UUID.randomUUID()); + } + + public AccountControlUiOriginalOrderFixture( + String jdbcUrl, + String username, + String password, + String redisHost, + int redisPort, + Path temporary, + UUID gameDesignTenant) + throws Exception { + this( + jdbcUrl, + username, + password, + redisHost, + redisPort, + temporary, + gameDesignTenant, + Clock.systemUTC()); + } + + /** Actor clock is injectable for genuine signed-credential expiry recovery proof. */ + public AccountControlUiOriginalOrderFixture( + String jdbcUrl, + String username, + String password, + String redisHost, + int redisPort, + Path temporary, + UUID gameDesignTenant, + Clock actorClock) + throws Exception { + this.temporary = temporary; + f = + new AccountControlUiOwnerSourcesFixture( + jdbcUrl, username, password, temporary, false, gameDesignTenant); + var lifecycle = new AccountControlUiSignerFixture(f, temporary); + lifecycle.commit(); + var originalSigner = f.tx(lifecycle.signer::captureCurrent); + assertThat(f.tx(() -> lifecycle.signer.requireOriginal(originalSigner.receipt())).receipt()) + .isEqualTo(originalSigner.receipt()); + custody("encryption", "enc1", 11); + 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()); + accountClient.setOptions(ClientOptions.builder().autoReconnect(false).build()); + try (var connection = admin.connect(ByteArrayCodec.INSTANCE)) { + connection + .sync() + .aclSetuser( + "account_coord_app", + new io.lettuce.core.AclSetuserArgs() + .reset() + .on() + .addPassword(PASSWORD) + .keyPattern("session:auth:token:*") + .addCommand(io.lettuce.core.protocol.CommandType.HELLO) + .addCommand(io.lettuce.core.protocol.CommandType.PING) + .addCommand( + io.lettuce.core.protocol.CommandType.CLIENT, + io.lettuce.core.protocol.CommandKeyword.SETINFO) + .addCommand( + io.lettuce.core.protocol.CommandType.ACL, + io.lettuce.core.protocol.CommandKeyword.WHOAMI) + .addCommand( + io.lettuce.core.protocol.CommandType.SCRIPT, + io.lettuce.core.protocol.CommandKeyword.LOAD) + .addCommand(io.lettuce.core.protocol.CommandType.EVALSHA) + .addCommand(io.lettuce.core.protocol.CommandType.GET) + .addCommand(io.lettuce.core.protocol.CommandType.SET) + .addCommand(io.lettuce.core.protocol.CommandType.PEXPIRETIME) + .addCommand(io.lettuce.core.protocol.CommandType.TIME)); + connection + .sync() + .dispatch( + TestAclCommand.INSTANCE, + new io.lettuce.core.output.StatusOutput<>(ByteArrayCodec.INSTANCE), + new io.lettuce.core.protocol.CommandArgs<>(ByteArrayCodec.INSTANCE) + .add("SETUSER") + .add("account_coord_app") + .add("+waitaof")); + awaitLocalAndReplicaAof(connection.sync()); + + } finally { + admin.shutdown(); + } + coordination = + new AccountControlUiCoordination( + () -> accountClient.connect(ByteArrayCodec.INSTANCE), + new AcknowledgementRequirements(1, 1, 5000), + testCatalog()); + var operations = new AccountControlUiIssuanceRepository(f.dsl); + var publicSource = + new AccountJwtJwksTrustedSource( + lifecycle.client, lifecycle.trust, lifecycle.desired, lifecycle.publication, f.manager); + actors = + new AccountControlUiActorService( + operations, + f.authority, + lifecycle.signer, + coordination, + publicSource, + f.fences, + f.manager, + actorClock); + issuance = + new AccountControlUiIssuanceService( + f.primary, + operations, + f.authority, + f.fences, + lifecycle.signer, + new AccountControlUiResponseCryptography( + new AccountControlUiKeyring(temporary.resolve("custody")), Clock.systemUTC()), + coordination, + actors, + f.manager, + Clock.systemUTC(), + 300_000L, + AccountControlUiOwnerSourcesFixture.CALLER); + } + + public UUID tenantId() { + return f.tenant; + } + + /** + * Real Account control-UI creator retained for composition with the original StartSession proof. + */ + IssuedCreator preparedOriginalCreator() { + if (originalCreator == null) originalCreator = issueCreator(); + return originalCreator; + } + + /** Same-package proof reuse; returns only an actual owner-issued and authenticated credential. */ + IssuedCreator issueCreator() { + var environment = f.terms.captureCurrentEnvironmentBoundary(); + String compact; + try (var peer = + AccountControlUiOwnerSourcesFixture.withPeer( + AccountControlUiOwnerSourcesFixture.CALLER); + var issued = + issuance.issue(f.request(AccountControlUiOwnerSourcesFixture.OTP), environment)) { + compact = new String(issued.compactBytes(), StandardCharsets.US_ASCII); + } + assertThat(f.challenges.findByAccountId(f.account.getId())).isEmpty(); + assertThat(actors.authenticate(compact, f.tenant, environment).accountId()) + .isEqualTo(f.account.getAccountUuid()); + return new IssuedCreator(compact, actors, environment, f); + } + + record IssuedCreator( + String compact, + AccountControlUiActorService actors, + CapturedEnvironmentBoundary environment, + AccountControlUiOwnerSourcesFixture sources) {} + + @Override + public void close() { + accountClient.shutdown(); + } + + private static RedisScriptCatalog testCatalog() { + return RedisScriptCatalog.fromContributions( + List.of( + new RedisScriptContribution() { + @Override + public String ownerId() { + return "account-service"; + } + + @Override + public Collection descriptors() { + return List.of(AccountControlUiRegistryContract.descriptor()); + } + })); + } + + private void custody(String purpose, String id, int value) throws Exception { + byte[] key = new byte[32]; + java.util.Arrays.fill(key, (byte) value); + var directory = Files.createDirectories(temporary.resolve("custody").resolve(purpose)); + Files.writeString( + directory.resolve("keyring"), + "firemud-account-response-envelope-keyring-v1\nactive " + + id + + " " + + Base64.getUrlEncoder().withoutPadding().encodeToString(key) + + "\n"); + } + + private record PublicJwk(String json, String jsonWithoutKeyOps, String fingerprint) {} + + private static void awaitLocalAndReplicaAof( + io.lettuce.core.api.sync.RedisCommands commands) throws InterruptedException { + byte[] probeKey = + ("test-only:positive-account-coordination-aof-probe:" + UUID.randomUUID()) + .getBytes(StandardCharsets.US_ASCII); + commands.set(probeKey, "test-only-replication-probe".getBytes(StandardCharsets.US_ASCII)); + long deadline = System.nanoTime() + java.time.Duration.ofSeconds(30).toNanos(); + while (System.nanoTime() < deadline) { + List counts = + commands.dispatch( + TestWaitAof.INSTANCE, + new io.lettuce.core.output.ArrayOutput<>(ByteArrayCodec.INSTANCE), + new io.lettuce.core.protocol.CommandArgs<>(ByteArrayCodec.INSTANCE) + .add(1) + .add(1) + .add(500)); + if (counts != null + && counts.size() == 2 + && counts.get(0) instanceof Long local + && counts.get(1) instanceof Long replicas + && local >= 1 + && replicas >= 1) { + return; + } + Thread.sleep(50); + } + throw new IllegalStateException("Test Coordination Redis replica did not acknowledge AOF"); + } + + private enum TestWaitAof implements io.lettuce.core.protocol.ProtocolKeyword { + INSTANCE; + + @Override + public byte[] getBytes() { + return "WAITAOF".getBytes(StandardCharsets.US_ASCII); + } + } + + private enum TestAclCommand implements io.lettuce.core.protocol.ProtocolKeyword { + INSTANCE; + + @Override + public byte[] getBytes() { + return "ACL".getBytes(StandardCharsets.US_ASCII); + } + } +} diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java new file mode 100644 index 0000000000..46bdcc8370 --- /dev/null +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java @@ -0,0 +1,614 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.grpc.BindableService; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.Callable; +import javax.crypto.spec.SecretKeySpec; +import net.firedevops.firemud.accountservice.client.StartSessionReservationEvidenceClient; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository; +import net.firedevops.firemud.accountservice.service.impl.StartSessionOperatorAuthorizationGrpcService; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptClient; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; +import org.jooq.DSLContext; +import org.jooq.Record; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.json.JsonMapper; + +/** + * Test-only proof fixture for Account's original human StartSession issuer, one-time redemption, + * and real World participation acquisition composition. + * + *

Logging's current-claim read response remains stipulated in the default constructor; a + * composed proof may inject its actual authenticated claim reader explicitly. The Account actor, + * source capture, issuance, reference custody, redemption, and later projection read use the real + * Account owners and retained PostgreSQL rows. A test may supply a Game Session owner-attempt + * lifecycle so it can reserve the exact issued tuple before redemption and attach the redeemed + * projection after redemption, without introducing Game Session classes into this fixture artifact. + * The peer scopes around issue and redemption are in-process test stipulations, not authenticated + * producer or mTLS proof. + */ +public final class AccountOriginalStartSessionAuthorizationProofFixture { + private static final Duration REFERENCE_LIFETIME = Duration.ofMinutes(5); + private static final Duration RESPONSE_RECOVERY_WINDOW = Duration.ofSeconds(30); + private static final String LOGGING_SERVICE = "logging-admin-service"; + private static final String GAME_SESSION_SERVICE = "game-session-service"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final Set attemptedControlPlaneRequestIds = new HashSet<>(); + private final AccountControlUiOwnerSourcesFixture accountSources; + private final AccountControlUiOriginalOrderFixture.IssuedCreator creator; + private final String namespace; + private final String loggingPeerUri; + private final String gameSessionPeerUri; + private final AccountStartSessionOperatorAuthorizationRepository repository; + private final AccountStartSessionAuthorityCaptureRepository captureRepository; + private final AccountStartSessionOperatorAuthorizationService authorizationService; + private final StartSessionOperatorAuthorizationGrpcService grpcService; + + public AccountOriginalStartSessionAuthorizationProofFixture( + AccountControlUiOriginalOrderFixture controlUi, Path temporary, String namespace) + throws Exception { + this(controlUi, temporary, namespace, stipulatedLoggingClaimClient()); + } + + /** + * Supplies the actual authenticated Logging claim reader for a composed owner proof. Existing + * callers retain their explicitly stipulated default; this overload adds no production bypass. + */ + public AccountOriginalStartSessionAuthorizationProofFixture( + AccountControlUiOriginalOrderFixture controlUi, + Path temporary, + String namespace, + StartSessionReservationEvidenceClient claimClient) + throws Exception { + Objects.requireNonNull(controlUi, "Account control-ui fixture is required"); + Objects.requireNonNull(temporary, "temporary test directory is required"); + this.namespace = requireNamespace(namespace); + creator = controlUi.preparedOriginalCreator(); + accountSources = creator.sources(); + + loggingPeerUri = peerUri(namespace, LOGGING_SERVICE); + gameSessionPeerUri = peerUri(namespace, GAME_SESSION_SERVICE); + Objects.requireNonNull(claimClient, "exact Logging claim client is required"); + repository = new AccountStartSessionOperatorAuthorizationRepository(accountSources.dsl); + captureRepository = new AccountStartSessionAuthorityCaptureRepository(accountSources.dsl); + authorizationService = + new AccountStartSessionOperatorAuthorizationService( + creator.actors(), + new AccountControlUiIssuanceRepository(accountSources.dsl), + captureRepository, + claimClient, + repository, + fingerprintKeys(), + responseCryptography(temporary), + accountSources.terms, + accountSources.manager, + Clock.systemUTC(), + new SecureRandom(), + loggingPeerUri, + gameSessionPeerUri, + REFERENCE_LIFETIME, + RESPONSE_RECOVERY_WINDOW); + grpcService = new StartSessionOperatorAuthorizationGrpcService(authorizationService, namespace); + } + + /** + * Performs one real Account issue and one real Account redemption for a supplied typed action. + * + *

The action's tenant and namespace must match this retained Account fixture, and its target + * owner account must be the authenticated creator. The reservation owner/fence identify the + * stipulated Logging claim; the Game Session attempt/fence are also stipulated. This method + * returns the exact original post-authorization tuple and durable owner identities, never the + * opaque authorization reference or key material. + */ + public synchronized OriginalStartSession issueAndRedeemOriginal( + String controlPlaneRequestId, + StartSessionOperatorAction action, + UUID reservationOwnerId, + long reservationClaimFence, + UUID gameSessionOwnerAttemptId, + long gameSessionOwnerFence) { + requireOwner(gameSessionOwnerAttemptId, "gameSessionOwnerAttemptId"); + requirePositive(gameSessionOwnerFence, "gameSessionOwnerFence"); + return issueAndRedeemOriginal( + controlPlaneRequestId, + action, + reservationOwnerId, + reservationClaimFence, + new OwnerAttemptLifecycle() { + @Override + public OwnerClaim reserve(StartSessionPostAuthorizationExecutionTuple originalTuple) { + return new OwnerClaim( + gameSessionOwnerAttemptId, UUID.randomUUID(), gameSessionOwnerFence); + } + + @Override + public void attachAccountRedemptionProjection( + OwnerClaim ownerClaim, StartSessionPostAuthorizationExecutionTuple originalTuple) { + // Existing callers may continue to use this fixture with a stipulated owner attempt. + } + }); + } + + /** + * Performs real Account issue and redemption around a test-supplied Game Session owner attempt. + * + *

The callback reserves the exact post-authorization tuple after issue and before Account + * redemption. Once redemption succeeds, the callback receives that same claim and tuple so the + * owning Game Session repository can attach the exact Account projection. Logging claim evidence + * remains stipulated unless the actual reader is injected; the issue/redemption peer identities + * remain stipulated by this Account fixture. + */ + public synchronized OriginalStartSession issueAndRedeemOriginal( + String controlPlaneRequestId, + StartSessionOperatorAction action, + UUID reservationOwnerId, + long reservationClaimFence, + OwnerAttemptLifecycle ownerAttemptLifecycle) { + Objects.requireNonNull(action, "canonical StartSession action is required"); + Objects.requireNonNull(ownerAttemptLifecycle, "Game Session owner attempt lifecycle required"); + requireActionBinding(action); + requireOwner(reservationOwnerId, "reservationOwnerId"); + requirePositive(reservationClaimFence, "reservationClaimFence"); + + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + controlPlaneRequestId, accountSources.account.getAccountUuid(), action); + if (!attemptedControlPlaneRequestIds.add(preTuple.controlPlaneRequestId())) { + throw new IllegalStateException( + "This proof fixture already attempted the original StartSession request"); + } + byte[] preTupleBytes = preTuple.canonicalJson().getBytes(StandardCharsets.UTF_8); + var authorization = + withPeer( + loggingPeerUri, + () -> + authorizationService.issue( + new AccountStartSessionOperatorAuthorizationService.IssueRequest( + creator.compact(), + preTupleBytes, + reservationOwnerId, + reservationClaimFence, + reservationOwnerId, + reservationClaimFence))); + + var sharedReference = + new StartSessionAuthorityEvidenceBundle.BundleReference( + authorization.bundleReference().bundleVersion(), + authorization.bundleReference().sourceVersion(), + authorization.bundleReference().sourceFence(), + authorization.bundleReference().linearization()); + var originalTuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + loggingPeerUri, + authorization.authorizationReferenceFingerprint(), + reservationOwnerId, + reservationClaimFence, + authorization.authorityEvidenceBundle(), + sharedReference); + + OwnerClaim ownerClaim = + Objects.requireNonNull( + ownerAttemptLifecycle.reserve(originalTuple), + "Game Session owner attempt reservation returned no claim"); + + var redemption = + withPeer( + gameSessionPeerUri, + () -> + authorizationService.redeem( + new AccountStartSessionOperatorAuthorizationService.RedeemRequest( + preTupleBytes, + authorization.operatorAuthorizationReference(), + authorization.authorizationReferenceFingerprint(), + reservationOwnerId, + reservationClaimFence, + ownerClaim.ownerAttemptId(), + ownerClaim.ownerFence()))); + assertThat(redemption.replay()).isFalse(); + ownerAttemptLifecycle.attachAccountRedemptionProjection(ownerClaim, originalTuple); + + var retained = + accountSources.tx( + () -> repository.findByControlPlaneRequestId(controlPlaneRequestId).orElseThrow()); + assertThat(retained.status()) + .isEqualTo(AccountStartSessionOperatorAuthorizationRepository.Status.REDEEMED); + assertThat(retained.preAuthorizationTuple()).containsExactly(preTupleBytes); + assertThat(retained.reservationOwnerId()).isEqualTo(reservationOwnerId); + assertThat(retained.reservationClaimFence()).isEqualTo(reservationClaimFence); + assertThat(retained.redemptionRedeemerWorkloadUri()).isEqualTo(gameSessionPeerUri); + assertThat(retained.redemptionOwnerAttemptId()).isEqualTo(ownerClaim.ownerAttemptId()); + assertThat(retained.redemptionOwnerFence()).isEqualTo(ownerClaim.ownerFence()); + assertThat(retained.redemptionReferenceFingerprint()) + .isEqualTo(authorization.authorizationReferenceFingerprint()); + assertThat(retained.issuanceOperationId()).isNotNull(); + assertThat(retained.issuanceFence()).isPositive(); + assertThat(retained.bundleReference().bundleVersion()) + .isEqualTo(authorization.bundleReference().bundleVersion()); + assertThat(retained.bundleReference().sourceVersion()) + .isEqualTo(authorization.bundleReference().sourceVersion()); + assertThat(retained.bundleReference().sourceFence()) + .isEqualTo(authorization.bundleReference().sourceFence()); + assertThat(retained.bundleReference().linearization()) + .isEqualTo(authorization.bundleReference().linearization()); + assertThat(retained.authorityEvidenceBundle()) + .containsExactly(authorization.authorityEvidenceBundle()); + assertThat(retained.authorityEvidenceBundle()) + .containsExactly(originalTuple.authorityEvidenceBundleBytes()); + assertThat(retained.authorizationReferenceFingerprint()) + .isEqualTo(originalTuple.authorizationReferenceFingerprint()); + assertThat(retained.redemptionAuthorityEvidenceBundle()) + .containsExactly(authorization.authorityEvidenceBundle()); + assertPersistedCapture( + preTuple, + reservationOwnerId, + reservationClaimFence, + authorization, + originalTuple, + retained); + + return new OriginalStartSession( + preTuple, + originalTuple, + reservationOwnerId, + reservationClaimFence, + ownerClaim.ownerAttemptId(), + ownerClaim.ownerFence(), + retained.issuanceOperationId(), + retained.issuanceFence(), + retained.referenceExpiresAt()); + } + + /** Creates the actual Account acquisition owner over this fixture's existing issuer and SQL. */ + public AccountStartSessionWorldParticipationAcquisitionService + worldParticipationAcquisitionService( + OriginalStartSessionCurrentAttemptClient gameSessionClient) { + Objects.requireNonNull( + gameSessionClient, "Game Session current-attempt observation client required"); + return new AccountStartSessionWorldParticipationAcquisitionService( + authorizationService, + new AccountStartSessionWorldParticipationRepository(accountSources.dsl), + new AccountStartSessionWorldOriginalAttemptEvidenceRepository(accountSources.dsl), + gameSessionClient, + accountSources.manager, + namespace); + } + + /** Existing fixture SQL context for independent test-only retained-row inspection. */ + public DSLContext sourceDsl() { + return accountSources.dsl; + } + + /** The real Account receiver for the retained redeemed-operation projection. */ + public BindableService grpcService() { + return grpcService; + } + + /** The actual Account UUID for the prepared creator used by this fixture. */ + public UUID creatorAccountId() { + return accountSources.account.getAccountUuid(); + } + + /** Test-only lifecycle for an owner attempt without a dependency on the Game Session artifact. */ + public interface OwnerAttemptLifecycle { + OwnerClaim reserve(StartSessionPostAuthorizationExecutionTuple originalTuple); + + void attachAccountRedemptionProjection( + OwnerClaim ownerClaim, StartSessionPostAuthorizationExecutionTuple originalTuple); + } + + /** Non-secret owner identities needed by Account redemption and acquisition. */ + public record OwnerClaim(UUID ownerAttemptId, UUID ownerMutationId, long ownerFence) { + public OwnerClaim { + requireOwner(ownerAttemptId, "ownerAttemptId"); + requireOwner(ownerMutationId, "ownerMutationId"); + requirePositive(ownerFence, "ownerFence"); + } + } + + private void assertPersistedCapture( + StartSessionPreAuthorizationReservationTuple preTuple, + UUID reservationOwnerId, + long reservationClaimFence, + AccountStartSessionOperatorAuthorizationService.AuthorizationResponse authorization, + StartSessionPostAuthorizationExecutionTuple originalTuple, + AccountStartSessionOperatorAuthorizationRepository.IssuanceRecord retained) { + AccountStartSessionAuthorityCapture capture = + withPeer( + loggingPeerUri, + () -> + creator + .actors() + .withCurrent( + creator.compact(), + accountSources.tenant, + creator.environment(), + current -> + captureRepository.lockReadExactCurrent( + current, + preTuple, + loggingPeerUri, + reservationOwnerId, + reservationClaimFence))); + + assertThat(capture.controlPlaneRequestId()).isEqualTo(preTuple.controlPlaneRequestId()); + assertThat(capture.bundleReference().bundleVersion()) + .isEqualTo(originalTuple.bundleReference().bundleVersion()); + assertThat(capture.bundleReference().sourceVersion()) + .isEqualTo(originalTuple.bundleReference().sourceVersion()); + assertThat(capture.bundleReference().sourceFence()) + .isEqualTo(originalTuple.bundleReference().sourceFence()); + assertThat(capture.bundleReference().linearization()) + .isEqualTo(originalTuple.bundleReference().linearization()); + assertThat(capture.sourceVersion()) + .isEqualTo(Long.parseLong(authorization.bundleReference().sourceVersion())); + assertThat(capture.sourceFence()) + .isEqualTo(Long.parseLong(authorization.bundleReference().sourceFence())); + assertThat(capture.linearization()).isEqualTo(authorization.bundleReference().linearization()); + assertThat(authorization.bundleReference().sourceVersion()) + .isEqualTo(originalTuple.bundleReference().sourceVersion()); + assertThat(authorization.bundleReference().sourceFence()) + .isEqualTo(originalTuple.bundleReference().sourceFence()); + assertThat(authorization.bundleReference().linearization()) + .isEqualTo(originalTuple.bundleReference().linearization()); + + var authorityBundle = + AccountStartSessionOperatorAuthorityBundle.decode(retained.authorityEvidenceBundle()); + authorityBundle.requireCaptureBinding( + capture, + preTuple, + AccountStartSessionOperatorAuthorityBundle.fromSharedReference( + originalTuple.bundleReference())); + assertThat(authorityBundle.issuanceOperationId()).isEqualTo(retained.issuanceOperationId()); + assertThat(authorityBundle.issuanceFence()).isEqualTo(retained.issuanceFence()); + assertThat(authorization.authorityEvidenceBundle()) + .containsExactly(authorityBundle.canonicalBytes()); + + Map snapshot = captureSnapshot(capture); + byte[] preTupleBytes = preTuple.canonicalJson().getBytes(StandardCharsets.UTF_8); + assertThat(snapshot.get("schema")).isEqualTo("account-start-session-authority-snapshot/v1"); + assertThat(snapshot.get("controlPlaneRequestId")).isEqualTo(preTuple.controlPlaneRequestId()); + assertThat(snapshot.get("preAuthorizationTuple")) + .isEqualTo(Base64.getEncoder().encodeToString(preTupleBytes)); + assertThat(snapshot.get("mutationDigest")).isEqualTo(preTuple.mutationDigest()); + assertThat(snapshot.get("accountId")).isEqualTo(preTuple.actor().accountId().toString()); + assertThat(snapshot.get("tenantId")).isEqualTo(preTuple.action().scope().tenantId().toString()); + assertThat(preTuple.action().scope().targetNamespace()).isEqualTo(namespace); + assertThat(snapshot.get("targetOwner")).isEqualTo(GAME_SESSION_SERVICE); + assertThat(snapshot.get("loggingWorkloadUri")).isEqualTo(loggingPeerUri); + assertThat(snapshot.get("reservationOwnerId")).isEqualTo(reservationOwnerId.toString()); + assertThat(snapshot.get("reservationClaimFence")) + .isEqualTo(Long.toString(reservationClaimFence)); + + Record captureRow = + accountSources.dsl.fetchOne( + "SELECT account_uuid, tenant_uuid, target_owner, logging_workload_uri, " + + "reservation_owner_id, reservation_claim_fence, pre_authorization_tuple, " + + "mutation_digest, issuance_fence, issuance_fence_source_version, " + + "canonical_snapshot_bytes, canonical_capture_bytes, source_version, " + + "source_fence, linearization " + + "FROM account_start_session_authority_captures " + + "WHERE control_plane_request_id = ?", + preTuple.controlPlaneRequestId()); + assertThat(captureRow).as("Account's genuine StartSession source capture").isNotNull(); + assertThat(capture.canonicalBytes()) + .containsExactly(captureRow.get("canonical_capture_bytes", byte[].class)); + assertThat(capture.snapshotBytes()) + .containsExactly(captureRow.get("canonical_snapshot_bytes", byte[].class)); + assertThat(captureRow.get("source_version", Long.class)).isEqualTo(capture.sourceVersion()); + assertThat(captureRow.get("source_fence", Long.class)).isEqualTo(capture.sourceFence()); + assertThat(captureRow.get("linearization", String.class)).isEqualTo(capture.linearization()); + assertThat(captureRow.get("account_uuid", UUID.class)).isEqualTo(preTuple.actor().accountId()); + assertThat(captureRow.get("tenant_uuid", UUID.class)) + .isEqualTo(preTuple.action().scope().tenantId()); + assertThat(captureRow.get("target_owner", String.class)).isEqualTo(GAME_SESSION_SERVICE); + assertThat(captureRow.get("logging_workload_uri", String.class)).isEqualTo(loggingPeerUri); + assertThat(captureRow.get("reservation_owner_id", UUID.class)).isEqualTo(reservationOwnerId); + assertThat(captureRow.get("reservation_claim_fence", Long.class)) + .isEqualTo(reservationClaimFence); + assertThat(captureRow.get("pre_authorization_tuple", byte[].class)) + .containsExactly(preTupleBytes); + assertThat(captureRow.get("mutation_digest", String.class)) + .isEqualTo(preTuple.mutationDigest()); + assertThat(snapshot.get("issuanceFence")) + .isEqualTo(Long.toString(captureRow.get("issuance_fence", Long.class))); + assertThat(snapshot.get("issuanceFence")).isEqualTo(Long.toString(retained.issuanceFence())); + assertThat(snapshot.get("issuanceFenceSourceVersion")) + .isEqualTo(Long.toString(captureRow.get("issuance_fence_source_version", Long.class))); + assertThat(retained.issuanceFence()).isEqualTo(authorityBundle.issuanceFence()); + } + + private static Map captureSnapshot(AccountStartSessionAuthorityCapture capture) { + try { + return JSON.readValue(capture.snapshotBytes(), new TypeReference<>() {}); + } catch (Exception malformed) { + throw new IllegalStateException("Account source snapshot is not readable", malformed); + } + } + + private static StartSessionReservationEvidenceClient stipulatedLoggingClaimClient() { + var client = mock(StartSessionReservationEvidenceClient.class); + when(client.readCurrentClaimEvidence( + any(StartSessionPreAuthorizationReservationTuple.class), + any(UUID.class), + anyLong(), + any(UUID.class), + anyLong(), + eq(StartSessionReservationEvidenceClient.Purpose.ISSUE))) + .thenAnswer( + invocation -> { + var tuple = + invocation.getArgument(0, StartSessionPreAuthorizationReservationTuple.class); + UUID reservationOwnerId = invocation.getArgument(1, UUID.class); + long reservationClaimFence = invocation.getArgument(2, Long.class); + UUID claimOwnerId = invocation.getArgument(3, UUID.class); + long claimFence = invocation.getArgument(4, Long.class); + if (!reservationOwnerId.equals(claimOwnerId) || reservationClaimFence != claimFence) { + throw new IllegalArgumentException( + "Stipulated ISSUE claim must retain the original owner and fence"); + } + return stipulatedClaim( + tuple, reservationOwnerId, reservationClaimFence, Instant.now()); + }); + return client; + } + + private void requireActionBinding(StartSessionOperatorAction action) { + if (!namespace.equals(action.scope().targetNamespace()) + || !accountSources.tenant.equals(action.scope().tenantId()) + || !accountSources.account.getAccountUuid().equals(action.target().ownerAccountId())) { + throw new IllegalArgumentException( + "StartSession action must bind the retained creator, tenant, and workload namespace"); + } + } + + private static ReadCurrentClaimEvidenceResponse stipulatedClaim( + StartSessionPreAuthorizationReservationTuple tuple, + UUID reservationOwnerId, + long reservationClaimFence, + Instant now) { + return ReadCurrentClaimEvidenceResponse.newBuilder() + .setControlPlaneRequestId(tuple.controlPlaneRequestId()) + .setPreAuthorizationTupleJson( + com.google.protobuf.ByteString.copyFrom( + tuple.canonicalJson().getBytes(StandardCharsets.UTF_8))) + .setMutationDigest(tuple.mutationDigest()) + .setReservationOwnerId(reservationOwnerId.toString()) + .setReservationClaimFence(reservationClaimFence) + .setClaimOwnerId(reservationOwnerId.toString()) + .setClaimFence(reservationClaimFence) + .setObservedAtEpochMillis(now.minusSeconds(1).toEpochMilli()) + .setClaimExpiresAtEpochMillis(now.plus(Duration.ofMinutes(5)).toEpochMilli()) + .setPurpose( + StartSessionReservationEvidencePurpose.START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE) + .build(); + } + + private static AccountOperatorAuthorizationFingerprintKeyring fingerprintKeys() { + byte[] key = new byte[32]; + Arrays.fill(key, (byte) 0x51); + return new AccountOperatorAuthorizationFingerprintKeyring( + () -> + new AccountOperatorAuthorizationFingerprintKeyring.Snapshot( + new AccountOperatorAuthorizationFingerprintKeyring.KeyMaterial( + "test-active", new SecretKeySpec(key, "HmacSHA256")), + List.of()), + Clock.systemUTC(), + Duration.ofMinutes(2)); + } + + private static AccountResponseEnvelopeCryptography responseCryptography(Path temporary) + throws Exception { + Files.createDirectories(temporary); + Path root = Files.createTempDirectory(temporary, "account-start-session-response-envelope-"); + byte[] key = new byte[32]; + Arrays.fill(key, (byte) 0x26); + Files.writeString( + root.resolve("keyring"), + "firemud-account-response-envelope-keyring-v1\nactive test-response " + + Base64.getUrlEncoder().withoutPadding().encodeToString(key) + + "\n", + StandardOpenOption.CREATE_NEW, + StandardOpenOption.WRITE); + return new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring(root.toString()), Clock.systemUTC(), new SecureRandom()); + } + + private static T withPeer(String peerUri, Callable action) { + try (var ignored = AccountControlUiOwnerSourcesFixture.withPeer(peerUri)) { + return action.call(); + } catch (RuntimeException failure) { + throw failure; + } catch (Exception failure) { + throw new IllegalStateException("Stipulated Account owner peer action failed", failure); + } + } + + private static String requireNamespace(String namespace) { + Objects.requireNonNull(namespace, "workload namespace is required"); + new StartSessionOperatorAction.Scope( + UUID.fromString("11111111-1111-4111-8111-111111111111"), namespace); + return namespace; + } + + private static String peerUri(String namespace, String service) { + return "spiffe://firemud/ns/" + namespace + "/sa/" + service; + } + + private static void requireOwner(UUID owner, String field) { + Objects.requireNonNull(owner, field + " is required"); + if (new UUID(0L, 0L).equals(owner)) { + throw new IllegalArgumentException(field + " must not be nil"); + } + } + + private static void requirePositive(long value, String field) { + if (value <= 0L) throw new IllegalArgumentException(field + " must be positive"); + } + + /** Exact non-secret identities retained by the original Account issue/redemption. */ + public record OriginalStartSession( + StartSessionPreAuthorizationReservationTuple preAuthorizationTuple, + StartSessionPostAuthorizationExecutionTuple originalTuple, + UUID reservationOwnerId, + long reservationClaimFence, + UUID gameSessionOwnerAttemptId, + long gameSessionOwnerFence, + UUID issuanceOperationId, + long issuanceFence, + Instant accountReferenceExpiresAt) { + public OriginalStartSession { + Objects.requireNonNull(preAuthorizationTuple, "original pre-authorization tuple required"); + Objects.requireNonNull(originalTuple, "original post-authorization tuple required"); + requireOwner(reservationOwnerId, "reservationOwnerId"); + requirePositive(reservationClaimFence, "reservationClaimFence"); + requireOwner(gameSessionOwnerAttemptId, "gameSessionOwnerAttemptId"); + requirePositive(gameSessionOwnerFence, "gameSessionOwnerFence"); + requireOwner(issuanceOperationId, "issuanceOperationId"); + requirePositive(issuanceFence, "issuanceFence"); + Objects.requireNonNull( + accountReferenceExpiresAt, "original Account reference expiry required"); + } + + @Override + public String toString() { + return "OriginalStartSession[controlPlaneRequestId=" + + preAuthorizationTuple.controlPlaneRequestId() + + ", issuanceOperationId=" + + issuanceOperationId + + ", issuanceFence=" + + issuanceFence + + ", original tuple evidence redacted]"; + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadClient.java new file mode 100644 index 0000000000..568f7ca3b0 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadClient.java @@ -0,0 +1,172 @@ +package net.firedevops.firemud.common.account.startsession; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountStartSessionWorldParticipationHistoricalReadServiceGrpc; +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; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Explicit file-backed mTLS client for Account's unregistered historical World participation lookup + * by the complete unchanged original StartSession tuple. + */ +public final class AccountStartSessionWorldParticipationHistoricalReadClient + extends AbstractReloadingBlockingGrpcClient< + AccountStartSessionWorldParticipationHistoricalReadServiceGrpc + .AccountStartSessionWorldParticipationHistoricalReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public AccountStartSessionWorldParticipationHistoricalReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + AccountStartSessionWorldParticipationHistoricalReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when an owning World component explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Account historical participation client is closed"); + } + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Account historical participation client has no gRPC stub"); + } + initialized = true; + } + + /** + * Resolves retained participation coordinates from the exact original tuple; this does not admit + * or renew World execution. + */ + public AccountStartSessionWorldParticipationHistoricalReadEvidence read( + AccountStartSessionWorldParticipationHistoricalReadRequest request) { + Objects.requireNonNull(request, "historical participation request is required"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Account historical participation request must use the configured workload namespace"); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Account historical participation read must start outside an ambient transaction"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .withMaxInboundMessageSize( + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec + .MAX_RESPONSE_WIRE_BYTES) + .readHistoricalStartSessionWorldParticipation( + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.toRequest(request)); + try { + return AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromResponse( + request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Account returned invalid historical World participation evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountStartSessionWorldParticipationHistoricalReadServiceGrpc + .AccountStartSessionWorldParticipationHistoricalReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return AccountStartSessionWorldParticipationHistoricalReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withMaxInboundMessageSize( + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.MAX_RESPONSE_WIRE_BYTES) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private AccountStartSessionWorldParticipationHistoricalReadServiceGrpc + .AccountStartSessionWorldParticipationHistoricalReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Account historical participation client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "Account historical participation read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Account historical participation read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Account historical participation read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Account historical participation read " + label + " must be a readable file-backed path", + invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Account historical participation read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadEvidence.java new file mode 100644 index 0000000000..200500dd34 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadEvidence.java @@ -0,0 +1,123 @@ +package net.firedevops.firemud.common.account.startsession; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminalReadRequest; + +/** Account-derived immutable historical participation fields for exact World reconciliation. */ +public final class AccountStartSessionWorldParticipationHistoricalReadEvidence { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final AccountStartSessionWorldParticipationHistoricalReadRequest request; + private final UUID accountWorldParticipationId; + private final long accountWorldParticipationFence; + private final UUID gameSessionOwnerAttemptId; + private final long gameSessionOwnerFence; + private final UUID canonicalGameInstanceId; + private final String preparationInputJson; + private final String preparationInputDigest; + + public AccountStartSessionWorldParticipationHistoricalReadEvidence( + AccountStartSessionWorldParticipationHistoricalReadRequest request, + UUID accountWorldParticipationId, + long accountWorldParticipationFence, + UUID gameSessionOwnerAttemptId, + long gameSessionOwnerFence, + UUID canonicalGameInstanceId, + String preparationInputJson, + String preparationInputDigest) { + this.request = Objects.requireNonNull(request, "historical participation request is required"); + this.accountWorldParticipationId = + requireNonNil(accountWorldParticipationId, "accountWorldParticipationId"); + if (accountWorldParticipationFence <= 0L) { + throw new IllegalArgumentException("Account World participation fence must be positive"); + } + this.accountWorldParticipationFence = accountWorldParticipationFence; + this.gameSessionOwnerAttemptId = + requireNonNil(gameSessionOwnerAttemptId, "gameSessionOwnerAttemptId"); + if (gameSessionOwnerFence <= 0L) { + throw new IllegalArgumentException("Game Session owner fence must be positive"); + } + this.gameSessionOwnerFence = gameSessionOwnerFence; + this.canonicalGameInstanceId = + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + this.preparationInputJson = + Objects.requireNonNull(preparationInputJson, "exact preparation input is required"); + this.preparationInputDigest = + Objects.requireNonNull(preparationInputDigest, "preparation input digest is required"); + + // Reuse the existing closed World identity validator without aliasing its terminal-read wire + // type or claiming that this historical evidence admits a World execution. + WorldStartSessionExecutionTerminalReadRequest exactIdentity = + new WorldStartSessionExecutionTerminalReadRequest( + request.readRequestId(), + request.targetNamespace(), + request.originalPostAuthorizationTuple(), + this.accountWorldParticipationId, + this.accountWorldParticipationFence, + this.gameSessionOwnerAttemptId, + this.gameSessionOwnerFence, + this.canonicalGameInstanceId, + this.preparationInputJson); + if (!exactIdentity.preparationInputDigest().equals(this.preparationInputDigest)) { + throw new IllegalArgumentException( + "preparationInputDigest differs from the exact retained preparation input"); + } + if (this.preparationInputJson.getBytes(java.nio.charset.StandardCharsets.UTF_8).length + > WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES) { + throw new IllegalArgumentException( + "Historical World preparation input exceeds its byte limit"); + } + } + + public AccountStartSessionWorldParticipationHistoricalReadRequest request() { + return request; + } + + public UUID accountWorldParticipationId() { + return accountWorldParticipationId; + } + + public long accountWorldParticipationFence() { + return accountWorldParticipationFence; + } + + public UUID gameSessionOwnerAttemptId() { + return gameSessionOwnerAttemptId; + } + + public long gameSessionOwnerFence() { + return gameSessionOwnerFence; + } + + public UUID canonicalGameInstanceId() { + return canonicalGameInstanceId; + } + + /** Returns the retained input byte-for-byte as text; it is never rewritten during recovery. */ + public String preparationInputJson() { + return preparationInputJson; + } + + public String preparationInputDigest() { + return preparationInputDigest; + } + + @Override + public String toString() { + return "AccountStartSessionWorldParticipationHistoricalReadEvidence[request=" + + request + + ", accountWorldParticipationId=" + + accountWorldParticipationId + + ", preparationInput=]"; + } + + private static UUID requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); + } + return value; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.java new file mode 100644 index 0000000000..e8677558c1 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.java @@ -0,0 +1,137 @@ +package net.firedevops.firemud.common.account.startsession; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ReadHistoricalStartSessionWorldParticipationRequest; +import net.firedevops.firemud.account.v1.ReadHistoricalStartSessionWorldParticipationResponse; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; + +/** Closed protobuf adapter for Account's historical World participation read. */ +public final class AccountStartSessionWorldParticipationHistoricalReadGrpcCodec { + public static final int MAX_REQUEST_WIRE_BYTES = + StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + 1024; + public static final int MAX_RESPONSE_WIRE_BYTES = + WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES + + StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + + 1024; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private AccountStartSessionWorldParticipationHistoricalReadGrpcCodec() {} + + public static ReadHistoricalStartSessionWorldParticipationRequest toRequest( + AccountStartSessionWorldParticipationHistoricalReadRequest request) { + Objects.requireNonNull(request, "historical participation request is required"); + var result = + ReadHistoricalStartSessionWorldParticipationRequest.newBuilder() + .setSchemaVersion( + AccountStartSessionWorldParticipationHistoricalReadRequest.SCHEMA_VERSION) + .setReadRequestId(request.readRequestId().toString()) + .setTargetNamespace(request.targetNamespace()) + .setOriginalPostAuthorizationTuple( + ByteString.copyFrom(request.originalPostAuthorizationTuple())) + .build(); + if (result.getSerializedSize() > MAX_REQUEST_WIRE_BYTES) { + throw new IllegalArgumentException("Historical participation request exceeds its wire limit"); + } + return result; + } + + public static AccountStartSessionWorldParticipationHistoricalReadRequest fromRequest( + ReadHistoricalStartSessionWorldParticipationRequest request) { + Objects.requireNonNull(request, "historical participation request is required"); + requireClosedMessage(request, "request"); + if (request.getSerializedSize() > MAX_REQUEST_WIRE_BYTES + || request.getSchemaVersion() + != AccountStartSessionWorldParticipationHistoricalReadRequest.SCHEMA_VERSION) { + throw new IllegalArgumentException( + "Unsupported or oversized historical participation request"); + } + return new AccountStartSessionWorldParticipationHistoricalReadRequest( + canonicalUuid(request.getReadRequestId(), "readRequestId"), + request.getTargetNamespace(), + request.getOriginalPostAuthorizationTuple().toByteArray()); + } + + public static ReadHistoricalStartSessionWorldParticipationResponse toResponse( + AccountStartSessionWorldParticipationHistoricalReadRequest request, + AccountStartSessionWorldParticipationHistoricalReadEvidence evidence) { + Objects.requireNonNull(evidence, "historical participation evidence is required"); + requireSameRequest(request, evidence.request()); + var response = + ReadHistoricalStartSessionWorldParticipationResponse.newBuilder() + .setRequest(toRequest(request)) + .setGameSessionOwnerAttemptId(evidence.gameSessionOwnerAttemptId().toString()) + .setGameSessionOwnerFence(evidence.gameSessionOwnerFence()) + .setCanonicalGameInstanceId(evidence.canonicalGameInstanceId().toString()) + .setPreparationInputJson(evidence.preparationInputJson()) + .setPreparationInputDigest(evidence.preparationInputDigest()) + .setAccountWorldParticipationId(evidence.accountWorldParticipationId().toString()) + .setAccountWorldParticipationFence(evidence.accountWorldParticipationFence()) + .build(); + if (response.getSerializedSize() > MAX_RESPONSE_WIRE_BYTES) { + throw new IllegalArgumentException( + "Historical participation response exceeds its wire limit"); + } + return response; + } + + public static AccountStartSessionWorldParticipationHistoricalReadEvidence fromResponse( + AccountStartSessionWorldParticipationHistoricalReadRequest request, + ReadHistoricalStartSessionWorldParticipationResponse response) { + Objects.requireNonNull(request, "historical participation request is required"); + Objects.requireNonNull(response, "historical participation response is required"); + requireClosedMessage(response, "response"); + if (response.getSerializedSize() > MAX_RESPONSE_WIRE_BYTES || !response.hasRequest()) { + throw new IllegalArgumentException("Missing or oversized historical participation response"); + } + AccountStartSessionWorldParticipationHistoricalReadRequest echoedRequest = + fromRequest(response.getRequest()); + requireSameRequest(request, echoedRequest); + if (response.getPreparationInputJson().getBytes(java.nio.charset.StandardCharsets.UTF_8).length + > WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES) { + throw new IllegalArgumentException("Historical preparation input exceeds its byte limit"); + } + return new AccountStartSessionWorldParticipationHistoricalReadEvidence( + echoedRequest, + canonicalUuid(response.getAccountWorldParticipationId(), "accountWorldParticipationId"), + response.getAccountWorldParticipationFence(), + canonicalUuid(response.getGameSessionOwnerAttemptId(), "gameSessionOwnerAttemptId"), + response.getGameSessionOwnerFence(), + canonicalUuid(response.getCanonicalGameInstanceId(), "canonicalGameInstanceId"), + response.getPreparationInputJson(), + response.getPreparationInputDigest()); + } + + private static void requireSameRequest( + AccountStartSessionWorldParticipationHistoricalReadRequest expected, + AccountStartSessionWorldParticipationHistoricalReadRequest actual) { + Objects.requireNonNull(expected, "historical participation request is required"); + if (!expected.equals(actual)) { + throw new IllegalArgumentException( + "Account changed the exact historical participation request"); + } + } + + private static UUID canonicalUuid(String value, String field) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || NIL_UUID.equals(parsed)) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID", malformed); + } + } + + private static void requireClosedMessage(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException( + "Account historical participation " + label + " contains unsupported fields"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadRequest.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadRequest.java new file mode 100644 index 0000000000..b281971b9f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadRequest.java @@ -0,0 +1,105 @@ +package net.firedevops.firemud.common.account.startsession; + +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; + +/** Exact original-operation identity for one historical Account World participation lookup. */ +public final class AccountStartSessionWorldParticipationHistoricalReadRequest { + public static final int SCHEMA_VERSION = 1; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final UUID readRequestId; + private final String targetNamespace; + private final byte[] originalPostAuthorizationTuple; + private final StartSessionPostAuthorizationExecutionTuple decodedOriginalTuple; + + public AccountStartSessionWorldParticipationHistoricalReadRequest( + UUID readRequestId, String targetNamespace, byte[] originalPostAuthorizationTuple) { + this.readRequestId = requireNonNil(readRequestId, "readRequestId"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + this.targetNamespace = targetNamespace; + Objects.requireNonNull(originalPostAuthorizationTuple, "original tuple is required"); + if (originalPostAuthorizationTuple.length == 0 + || originalPostAuthorizationTuple.length + > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES) { + throw new IllegalArgumentException( + "Complete original StartSession tuple is empty or oversized"); + } + this.originalPostAuthorizationTuple = originalPostAuthorizationTuple.clone(); + this.decodedOriginalTuple = + StartSessionPostAuthorizationExecutionTuple.decode(this.originalPostAuthorizationTuple); + if (!Arrays.equals( + this.originalPostAuthorizationTuple, this.decodedOriginalTuple.canonicalBytes()) + || !StartSessionOperatorAction.ACTION_FAMILY.equals( + this.decodedOriginalTuple.preAuthorizationTuple().actionFamily()) + || !StartSessionOperatorAction.OWNER_SERVICE.equals( + this.decodedOriginalTuple.preAuthorizationTuple().targetOwner()) + || !targetNamespace.equals( + this.decodedOriginalTuple.preAuthorizationTuple().action().scope().targetNamespace())) { + throw new IllegalArgumentException( + "Complete canonical tuple must identify the original StartSession for this namespace"); + } + + if (this.readRequestId.equals(this.decodedOriginalTuple.reservationOwnerId())) { + throw new IllegalArgumentException( + "readRequestId must be fresh and distinct from the reservation owner"); + } + } + + public UUID readRequestId() { + return readRequestId; + } + + public String targetNamespace() { + return targetNamespace; + } + + public byte[] originalPostAuthorizationTuple() { + return originalPostAuthorizationTuple.clone(); + } + + public StartSessionPostAuthorizationExecutionTuple decodedOriginalTuple() { + return decodedOriginalTuple; + } + + @Override + public boolean equals(Object other) { + if (this == other) return true; + if (!(other instanceof AccountStartSessionWorldParticipationHistoricalReadRequest that)) { + return false; + } + return readRequestId.equals(that.readRequestId) + && targetNamespace.equals(that.targetNamespace) + && Arrays.equals(originalPostAuthorizationTuple, that.originalPostAuthorizationTuple); + } + + @Override + public int hashCode() { + return 31 * Objects.hash(readRequestId, targetNamespace) + + Arrays.hashCode(originalPostAuthorizationTuple); + } + + @Override + public String toString() { + return "AccountStartSessionWorldParticipationHistoricalReadRequest[readRequestId=" + + readRequestId + + ", targetNamespace=" + + targetNamespace + + ", originalTuple=]"; + } + + private static UUID requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); + } + return value; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/StartSessionAccountRedemptionProjection.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/StartSessionAccountRedemptionProjection.java new file mode 100644 index 0000000000..5c6f4335f1 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/StartSessionAccountRedemptionProjection.java @@ -0,0 +1,59 @@ +package net.firedevops.firemud.common.account.startsession; + +import java.io.IOException; +import java.util.Map; +import java.util.Objects; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import tools.jackson.databind.json.JsonMapper; + +/** Canonical full Account projection used by original StartSession redemption. */ +public final class StartSessionAccountRedemptionProjection { + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private StartSessionAccountRedemptionProjection() {} + + /** + * Derives the complete canonical Account redemption projection from the original tuple. + * + *

The issuance fence remains a JSON number, matching the original projection bytes. This value + * proves integrity and tuple binding only; it does not establish Account authentication, + * currentness, or a live reservation claim. + */ + public static byte[] fromOriginalTuple( + StartSessionPostAuthorizationExecutionTuple originalTuple) { + Objects.requireNonNull(originalTuple, "originalTuple is required"); + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(originalTuple.authorityEvidenceBundleBytes()); + long issuanceFence; + try { + issuanceFence = Long.parseLong(originalTuple.issuanceFence()); + } catch (NumberFormatException malformed) { + throw new IllegalArgumentException("Original Account issuance fence is malformed", malformed); + } + if (issuanceFence <= 0L) { + throw new IllegalArgumentException("Original Account issuance fence is not positive"); + } + Map projection = + Map.of( + "projectionSchemaId", + "accountStartSessionRedemptionProjection", + "projectionSchemaVersion", + "1", + "authorizationReferenceFingerprint", + originalTuple.authorizationReferenceFingerprint(), + "authorityEvidenceBundle", + bundle.jsonValue(), + "issuanceOperationId", + bundle.issuanceOperationId().toString(), + "issuanceFence", + issuanceFence); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(projection)); + } catch (IOException malformed) { + throw new IllegalStateException( + "Could not encode the original Account redemption projection", malformed); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundle.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundle.java index f5806f916c..7b8446dc58 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundle.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundle.java @@ -28,9 +28,8 @@ * authorityEvidenceBundle/v1} contract. * *

This value proves only that supplied bytes are canonical and structurally bound to a typed - * StartSession tuple and selected fields from the separate Account bundle reference. It does not - * perform Account's full source/reference validation or establish current Account authority, source - * freshness, a live reservation claim, or permission to dispatch. + * StartSession tuple and the separate Account source reference. It does not establish current + * Account authority, source freshness, a live reservation claim, or permission to dispatch. */ public final class StartSessionAuthorityEvidenceBundle { public static final String BUNDLE_VERSION = "authorityEvidenceBundle/v1"; @@ -206,17 +205,17 @@ public void requireTupleBinding(StartSessionPreAuthorizationReservationTuple tup } /** - * Compares the bundle version, source version, and source fence with the corresponding bundle - * fields. This structural comparison is not Account's full source/reference validation, snapshot - * check, or redemption; it does not prove source freshness. + * Checks the bundle schema and capture source version against the separate Account reference. The + * source fence and Account issuance fence are independent owner identities; Account must match + * the complete reference to the exact owner-stored capture and issuance evidence. This integrity + * check is not authentication, freshness, a live reservation claim, or permission to dispatch. */ public void requireReferenceBinding(BundleReference reference) { Objects.requireNonNull(reference, "Account bundle reference is required"); Map projection = object(value.get("accountProjectionEvidence"), "accountProjectionEvidence"); if (!BUNDLE_VERSION.equals(reference.bundleVersion()) - || !reference.sourceVersion().equals(projection.get("sourceEvidenceVersion")) - || !reference.sourceFence().equals(value.get("issuanceFence"))) { + || !reference.sourceVersion().equals(projection.get("sourceEvidenceVersion"))) { throw denied("Account bundle reference differs from immutable authority evidence"); } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminal.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminal.java new file mode 100644 index 0000000000..8bf6437567 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminal.java @@ -0,0 +1,515 @@ +package net.firedevops.firemud.common.world; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Immutable integrity carrier for one durable World StartSession execution outcome. + * + *

This value binds the original post-authorization tuple to the exact World execution scope, + * independent source fences, retained preparation input, and one durable terminal outcome. It does + * not authenticate a producer, admit execution, or settle or release Account participation. + */ +public final class WorldStartSessionExecutionTerminal { + public static final String SCHEMA = "world-start-session-execution-terminal/v1"; + public static final int MAX_CANONICAL_BYTES = 24 * 1_024 * 1_024; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern CANONICAL_POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*"); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final int MAX_TUPLE_BASE64_CHARS = + ((StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + 2) / 3) * 4; + private static final Set FIELDS = + Set.of( + "schema", + "originalPostAuthorizationTupleBase64", + "accountWorldParticipationId", + "accountWorldParticipationFence", + "gameSessionOwnerAttemptId", + "gameSessionOwnerFence", + "targetNamespace", + "canonicalTenantId", + "controlPlaneRequestId", + "canonicalGameInstanceId", + "preparationInputDigest", + "preparationInputJson", + "worldExecutionFence", + "outcome"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .build(); + + private final byte[] originalPostAuthorizationTuple; + private final String originalPostAuthorizationTupleBase64; + private final UUID accountWorldParticipationId; + private final long accountWorldParticipationFence; + private final UUID gameSessionOwnerAttemptId; + private final long gameSessionOwnerFence; + private final String targetNamespace; + private final UUID canonicalTenantId; + private final String controlPlaneRequestId; + private final UUID canonicalGameInstanceId; + private final String preparationInputDigest; + private final String preparationInputJson; + private final long worldExecutionFence; + private final Outcome outcome; + private final byte[] canonicalBytes; + private final String digest; + + public WorldStartSessionExecutionTerminal( + byte[] originalPostAuthorizationTuple, + UUID accountWorldParticipationId, + long accountWorldParticipationFence, + UUID gameSessionOwnerAttemptId, + long gameSessionOwnerFence, + String targetNamespace, + UUID canonicalTenantId, + String controlPlaneRequestId, + UUID canonicalGameInstanceId, + String preparationInputDigest, + String preparationInputJson, + long worldExecutionFence, + Outcome outcome) { + this.preparationInputJson = requirePreparationInput(preparationInputJson); + jsonStringValueUtf8Length(this.preparationInputJson); + Objects.requireNonNull(originalPostAuthorizationTuple, "originalPostAuthorizationTuple"); + if (originalPostAuthorizationTuple.length == 0 + || originalPostAuthorizationTuple.length + > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES) { + throw invalid("Original post-authorization tuple exceeds its byte limit"); + } + this.originalPostAuthorizationTuple = originalPostAuthorizationTuple.clone(); + StartSessionPostAuthorizationExecutionTuple originalTuple = + StartSessionPostAuthorizationExecutionTuple.decode(this.originalPostAuthorizationTuple); + requireStartSessionGameSessionTarget(originalTuple); + + this.accountWorldParticipationId = + requireNonNil(accountWorldParticipationId, "accountWorldParticipationId"); + this.accountWorldParticipationFence = + requirePositive(accountWorldParticipationFence, "accountWorldParticipationFence"); + this.gameSessionOwnerAttemptId = + requireNonNil(gameSessionOwnerAttemptId, "gameSessionOwnerAttemptId"); + this.gameSessionOwnerFence = requirePositive(gameSessionOwnerFence, "gameSessionOwnerFence"); + this.worldExecutionFence = requirePositive(worldExecutionFence, "worldExecutionFence"); + + this.targetNamespace = requireNamespace(targetNamespace); + this.canonicalTenantId = requireNonNil(canonicalTenantId, "canonicalTenantId"); + this.controlPlaneRequestId = + Objects.requireNonNull(controlPlaneRequestId, "controlPlaneRequestId"); + this.canonicalGameInstanceId = + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + this.preparationInputDigest = requireDigest(preparationInputDigest); + this.outcome = Objects.requireNonNull(outcome, "outcome"); + this.originalPostAuthorizationTupleBase64 = + Base64.getEncoder().encodeToString(this.originalPostAuthorizationTuple); + + var original = originalTuple.preAuthorizationTuple(); + if (!this.targetNamespace.equals(original.action().scope().targetNamespace()) + || !this.canonicalTenantId.equals(original.action().scope().tenantId()) + || !this.controlPlaneRequestId.equals(originalTuple.controlPlaneRequestId())) { + throw invalid("World terminal scope differs from the original StartSession tuple"); + } + + requireCanonicalSize(); + byte[] preparationBytes = strictUtf8Bytes(this.preparationInputJson); + if (!sha256Prefixed(preparationBytes).equals(this.preparationInputDigest)) { + throw invalid("preparationInputDigest does not match the exact retained preparation input"); + } + this.canonicalBytes = encodeCanonicalBytes(); + this.digest = sha256Prefixed(this.canonicalBytes); + } + + /** Returns a defensive copy of the exact original post-authorization tuple bytes. */ + public byte[] originalPostAuthorizationTuple() { + return originalPostAuthorizationTuple.clone(); + } + + public String originalPostAuthorizationTupleBase64() { + return originalPostAuthorizationTupleBase64; + } + + public UUID accountWorldParticipationId() { + return accountWorldParticipationId; + } + + public long accountWorldParticipationFence() { + return accountWorldParticipationFence; + } + + public UUID gameSessionOwnerAttemptId() { + return gameSessionOwnerAttemptId; + } + + public long gameSessionOwnerFence() { + return gameSessionOwnerFence; + } + + public String targetNamespace() { + return targetNamespace; + } + + public UUID canonicalTenantId() { + return canonicalTenantId; + } + + public String controlPlaneRequestId() { + return controlPlaneRequestId; + } + + public UUID canonicalGameInstanceId() { + return canonicalGameInstanceId; + } + + public String preparationInputDigest() { + return preparationInputDigest; + } + + /** Returns the original preparation-input string without parsing or reformatting it. */ + public String preparationInputJson() { + return preparationInputJson; + } + + public long worldExecutionFence() { + return worldExecutionFence; + } + + public Outcome outcome() { + return outcome; + } + + /** Returns a defensive copy of the closed RFC 8785 UTF-8 representation. */ + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + /** SHA-256 digest of the complete canonical terminal, in the shared prefixed form. */ + public String digest() { + return digest; + } + + /** Strictly decodes one complete, closed, canonical World terminal value. */ + public static WorldStartSessionExecutionTerminal fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + if (stored.length == 0 || stored.length > MAX_CANONICAL_BYTES) { + throw invalid("Canonical World StartSession terminal exceeds its byte limit"); + } + try { + String json = strictUtf8(stored); + byte[] canonicalInput = Rfc8785CanonicalJson.canonicalizeUtf8(json); + if (!Arrays.equals(stored, canonicalInput)) { + throw invalid("Canonical World StartSession terminal is not RFC 8785 JSON"); + } + + JsonNode root = JSON.readTree(json); + requireExactFields(root); + if (!SCHEMA.equals(text(root, "schema"))) { + throw invalid("Unsupported World StartSession terminal schema"); + } + + WorldStartSessionExecutionTerminal terminal = + new WorldStartSessionExecutionTerminal( + decodeTuple(root), + canonicalUuid(root, "accountWorldParticipationId"), + positiveLong(root, "accountWorldParticipationFence"), + canonicalUuid(root, "gameSessionOwnerAttemptId"), + positiveLong(root, "gameSessionOwnerFence"), + text(root, "targetNamespace"), + canonicalUuid(root, "canonicalTenantId"), + text(root, "controlPlaneRequestId"), + canonicalUuid(root, "canonicalGameInstanceId"), + text(root, "preparationInputDigest"), + text(root, "preparationInputJson"), + positiveLong(root, "worldExecutionFence"), + parseOutcome(text(root, "outcome"))); + if (!Arrays.equals(stored, terminal.canonicalBytes)) { + throw invalid("Canonical World StartSession terminal has a noncanonical re-encoding"); + } + return terminal; + } catch (IllegalArgumentException invalid) { + throw invalid; + } catch (IOException | RuntimeException malformed) { + throw invalid("Canonical World StartSession terminal is invalid", malformed); + } + } + + private byte[] encodeCanonicalBytes() { + byte[] encoded = encodeCanonical(canonicalValue(preparationInputJson)); + if (encoded.length > MAX_CANONICAL_BYTES) { + throw invalid("Canonical World StartSession terminal exceeds its byte limit"); + } + return encoded; + } + + private void requireCanonicalSize() { + byte[] emptyStringPreimage = encodeCanonical(canonicalValue("")); + long expectedLength = + emptyStringPreimage.length + jsonStringValueUtf8Length(preparationInputJson); + if (expectedLength > MAX_CANONICAL_BYTES) { + throw invalid("Canonical World StartSession terminal exceeds its byte limit"); + } + } + + private Map canonicalValue(String exactPreparationInputJson) { + Map value = new LinkedHashMap<>(); + value.put("schema", SCHEMA); + value.put("originalPostAuthorizationTupleBase64", originalPostAuthorizationTupleBase64); + value.put("accountWorldParticipationId", accountWorldParticipationId.toString()); + value.put("accountWorldParticipationFence", Long.toString(accountWorldParticipationFence)); + value.put("gameSessionOwnerAttemptId", gameSessionOwnerAttemptId.toString()); + value.put("gameSessionOwnerFence", Long.toString(gameSessionOwnerFence)); + value.put("targetNamespace", targetNamespace); + value.put("canonicalTenantId", canonicalTenantId.toString()); + value.put("controlPlaneRequestId", controlPlaneRequestId); + value.put("canonicalGameInstanceId", canonicalGameInstanceId.toString()); + value.put("preparationInputDigest", preparationInputDigest); + value.put("preparationInputJson", exactPreparationInputJson); + value.put("worldExecutionFence", Long.toString(worldExecutionFence)); + value.put("outcome", outcome.name()); + return value; + } + + private static byte[] encodeCanonical(Map value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException impossible) { + throw new IllegalStateException("World StartSession terminal cannot be encoded", impossible); + } + } + + private static long jsonStringValueUtf8Length(String value) { + long length = 0L; + for (int index = 0; index < value.length(); index++) { + char current = value.charAt(index); + if (current == '\b' + || current == '\t' + || current == '\n' + || current == '\f' + || current == '\r' + || current == '"' + || current == '\\') { + length += 2L; + } else if (current <= 0x1f) { + length += 6L; + } else if (current <= 0x7f) { + length++; + } else if (current <= 0x7ff) { + length += 2L; + } else if (Character.isHighSurrogate(current)) { + if (index + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(index + 1))) { + throw invalid("preparationInputJson is not valid Unicode"); + } + length += 4L; + index++; + } else if (Character.isLowSurrogate(current)) { + throw invalid("preparationInputJson is not valid Unicode"); + } else { + length += 3L; + } + if (length > MAX_CANONICAL_BYTES) { + throw invalid("Canonical World StartSession terminal exceeds its byte limit"); + } + } + return length; + } + + private static byte[] strictUtf8Bytes(String value) { + jsonStringValueUtf8Length(value); + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(java.nio.CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (java.nio.charset.CharacterCodingException malformed) { + throw invalid("preparationInputJson is not valid UTF-8", malformed); + } + } + + private static byte[] decodeTuple(JsonNode root) { + String encoded = text(root, "originalPostAuthorizationTupleBase64"); + if (encoded.isEmpty() || encoded.length() > MAX_TUPLE_BASE64_CHARS) { + throw invalid("Original post-authorization tuple exceeds its byte limit"); + } + try { + byte[] decoded = Base64.getDecoder().decode(encoded); + if (decoded.length == 0 + || decoded.length > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + || !Base64.getEncoder().encodeToString(decoded).equals(encoded)) { + throw invalid("Original post-authorization tuple must use canonical base64"); + } + return decoded; + } catch (IllegalArgumentException malformed) { + throw invalid("Original post-authorization tuple must use canonical base64", malformed); + } + } + + private static void requireStartSessionGameSessionTarget( + StartSessionPostAuthorizationExecutionTuple tuple) { + var original = tuple.preAuthorizationTuple(); + if (!StartSessionOperatorAction.ACTION_FAMILY.equals(original.actionFamily()) + || !StartSessionOperatorAction.OWNER_SERVICE.equals(original.targetOwner())) { + throw invalid("World terminal requires the original Game Session StartSession tuple"); + } + } + + private static String requireNamespace(String value) { + Objects.requireNonNull(value, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(value)) { + throw invalid("targetNamespace must be one canonical DNS label"); + } + return value; + } + + private static UUID requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field); + if (NIL_UUID.equals(value)) { + throw invalid(field + " must not be nil"); + } + return value; + } + + private static long requirePositive(long value, String field) { + if (value <= 0L) { + throw invalid(field + " must be a positive signed 64-bit integer"); + } + return value; + } + + private static String requireDigest(String value) { + Objects.requireNonNull(value, "preparationInputDigest"); + if (!SHA256.matcher(value).matches()) { + throw invalid("preparationInputDigest must be sha256: followed by lowercase hexadecimal"); + } + return value; + } + + private static String requirePreparationInput(String value) { + Objects.requireNonNull(value, "preparationInputJson"); + if (value.isBlank()) { + throw invalid("preparationInputJson must retain a nonblank exact input"); + } + if (value.length() > MAX_CANONICAL_BYTES) { + throw invalid("preparationInputJson exceeds the terminal byte limit"); + } + return value; + } + + private static String strictUtf8(byte[] value) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(value)) + .toString(); + } catch (java.nio.charset.CharacterCodingException malformed) { + throw invalid("Canonical World StartSession terminal is not strict UTF-8", malformed); + } + } + + private static void requireExactFields(JsonNode root) { + if (root == null || !root.isObject()) { + throw invalid("Canonical World StartSession terminal must be a JSON object"); + } + Set actual = new HashSet<>(); + root.propertyNames().forEach(actual::add); + if (!FIELDS.equals(actual)) { + throw invalid("Canonical World StartSession terminal has missing or unsupported fields"); + } + } + + private static String text(JsonNode root, String field) { + JsonNode value = root == null ? null : root.get(field); + if (value == null || !value.isTextual()) { + throw invalid(field + " must be a string"); + } + return value.textValue(); + } + + private static UUID canonicalUuid(JsonNode root, String field) { + String value = text(root, field); + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(NIL_UUID)) { + throw invalid(field + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw invalid(field + " must be a canonical non-nil UUID", malformed); + } + } + + private static long positiveLong(JsonNode root, String field) { + String value = text(root, field); + if (!CANONICAL_POSITIVE_DECIMAL.matcher(value).matches()) { + throw invalid(field + " must be a canonical positive ASCII decimal string"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException overflow) { + throw invalid(field + " exceeds the positive signed 64-bit range", overflow); + } + } + + private static Outcome parseOutcome(String value) { + try { + return Outcome.valueOf(value); + } catch (IllegalArgumentException unsupported) { + throw invalid( + "World StartSession terminal outcome must be COMMITTED or ABORTED", unsupported); + } + } + + private static String sha256Prefixed(byte[] bytes) { + return "sha256:" + sha256(bytes); + } + + private static String sha256(byte[] bytes) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + private static IllegalArgumentException invalid(String message, Throwable cause) { + return new IllegalArgumentException(message, cause); + } + + public enum Outcome { + COMMITTED, + ABORTED + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClient.java new file mode 100644 index 0000000000..8023bac9c4 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClient.java @@ -0,0 +1,164 @@ +package net.firedevops.firemud.common.world; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +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; +import net.firedevops.firemud.worldmanagement.v1.WorldStartSessionExecutionTerminalReadServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit file-backed mTLS client for the unregistered Account-authenticated World read. */ +public final class WorldStartSessionExecutionTerminalReadClient + extends AbstractReloadingBlockingGrpcClient< + WorldStartSessionExecutionTerminalReadServiceGrpc + .WorldStartSessionExecutionTerminalReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public WorldStartSessionExecutionTerminalReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + WorldStartSessionExecutionTerminalReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when an owning service explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("World StartSession terminal read client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("World StartSession terminal read client has no gRPC stub"); + } + initialized = true; + } + + /** Reads one exact historical terminal without renewing or settling its source participation. */ + public WorldStartSessionExecutionTerminal read( + WorldStartSessionExecutionTerminalReadRequest request) { + Objects.requireNonNull(request, "World StartSession terminal read request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "World StartSession terminal request must use the configured workload namespace"); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "World StartSession terminal read must start outside an ambient transaction"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readWorldStartSessionExecutionTerminal( + WorldStartSessionExecutionTerminalReadGrpcCodec.toRequest(request)); + try { + return WorldStartSessionExecutionTerminalReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "World returned invalid original StartSession terminal evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected WorldStartSessionExecutionTerminalReadServiceGrpc + .WorldStartSessionExecutionTerminalReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + return WorldStartSessionExecutionTerminalReadServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize( + WorldStartSessionExecutionTerminalReadGrpcCodec.MAX_RESPONSE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private WorldStartSessionExecutionTerminalReadServiceGrpc + .WorldStartSessionExecutionTerminalReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "World StartSession terminal read client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("World StartSession terminal read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "World StartSession terminal read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "World StartSession terminal read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "World StartSession terminal read " + label + " must be a readable file-backed path", + invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "World StartSession terminal read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadGrpcCodec.java new file mode 100644 index 0000000000..d4f36ac9ff --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadGrpcCodec.java @@ -0,0 +1,134 @@ +package net.firedevops.firemud.common.world; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldStartSessionExecutionTerminalRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldStartSessionExecutionTerminalResponse; + +/** Closed protobuf adapter for exact historical StartSession terminal readback. */ +public final class WorldStartSessionExecutionTerminalReadGrpcCodec { + /** Canonical terminal plus bounded protobuf framing and the fresh read UUID. */ + public static final int MAX_RESPONSE_BYTES = + WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES + 1_024; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private WorldStartSessionExecutionTerminalReadGrpcCodec() {} + + public static WorldStartSessionExecutionTerminalReadRequest fromRequest( + ReadWorldStartSessionExecutionTerminalRequest request) { + Objects.requireNonNull(request, "World StartSession terminal read request"); + requireNoUnknownFields(request, "request"); + return new WorldStartSessionExecutionTerminalReadRequest( + canonicalUuid(request.getReadRequestId(), "readRequestId"), + request.getTargetNamespace(), + request.getOriginalPostAuthorizationTuple().toByteArray(), + canonicalUuid(request.getAccountWorldParticipationId(), "accountWorldParticipationId"), + request.getAccountWorldParticipationFence(), + canonicalUuid(request.getGameSessionOwnerAttemptId(), "gameSessionOwnerAttemptId"), + request.getGameSessionOwnerFence(), + canonicalUuid(request.getCanonicalGameInstanceId(), "canonicalGameInstanceId"), + request.getPreparationInputJson()); + } + + public static ReadWorldStartSessionExecutionTerminalRequest toRequest( + WorldStartSessionExecutionTerminalReadRequest request) { + Objects.requireNonNull(request, "World StartSession terminal read request"); + return ReadWorldStartSessionExecutionTerminalRequest.newBuilder() + .setReadRequestId(request.readRequestId().toString()) + .setTargetNamespace(request.targetNamespace()) + .setOriginalPostAuthorizationTuple( + ByteString.copyFrom(request.originalPostAuthorizationTuple())) + .setAccountWorldParticipationId(request.accountWorldParticipationId().toString()) + .setAccountWorldParticipationFence(request.accountWorldParticipationFence()) + .setGameSessionOwnerAttemptId(request.gameSessionOwnerAttemptId().toString()) + .setGameSessionOwnerFence(request.gameSessionOwnerFence()) + .setCanonicalGameInstanceId(request.canonicalGameInstanceId().toString()) + .setPreparationInputJson(request.preparationInputJson()) + .build(); + } + + public static ReadWorldStartSessionExecutionTerminalResponse toResponse( + WorldStartSessionExecutionTerminalReadRequest request, + WorldStartSessionExecutionTerminal terminal) { + requireSameIdentity(request, terminal); + return ReadWorldStartSessionExecutionTerminalResponse.newBuilder() + .setReadRequestId(request.readRequestId().toString()) + .setCanonicalTerminalBytes(ByteString.copyFrom(terminal.canonicalBytes())) + .build(); + } + + public static WorldStartSessionExecutionTerminal fromResponse( + WorldStartSessionExecutionTerminalReadRequest request, + ReadWorldStartSessionExecutionTerminalResponse response) { + Objects.requireNonNull(request, "World StartSession terminal read request"); + Objects.requireNonNull(response, "World StartSession terminal response"); + if (response.getSerializedSize() > MAX_RESPONSE_BYTES) { + throw invalid("World StartSession terminal response exceeds its wire limit"); + } + requireNoUnknownFields(response, "response"); + UUID readRequestId = canonicalUuid(response.getReadRequestId(), "readRequestId"); + if (!request.readRequestId().equals(readRequestId)) { + throw invalid("World changed the exact StartSession terminal read correlation"); + } + byte[] bytes = response.getCanonicalTerminalBytes().toByteArray(); + if (bytes.length == 0 + || bytes.length > WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES) { + throw invalid("World StartSession terminal bytes are missing or exceed their limit"); + } + WorldStartSessionExecutionTerminal terminal = + WorldStartSessionExecutionTerminal.fromStored(bytes); + requireSameIdentity(request, terminal); + return terminal; + } + + private static void requireSameIdentity( + WorldStartSessionExecutionTerminalReadRequest request, + WorldStartSessionExecutionTerminal terminal) { + Objects.requireNonNull(request, "World StartSession terminal read request"); + Objects.requireNonNull(terminal, "World StartSession terminal"); + if (!Arrays.equals( + request.originalPostAuthorizationTuple(), terminal.originalPostAuthorizationTuple()) + || !request.accountWorldParticipationId().equals(terminal.accountWorldParticipationId()) + || request.accountWorldParticipationFence() != terminal.accountWorldParticipationFence() + || !request.gameSessionOwnerAttemptId().equals(terminal.gameSessionOwnerAttemptId()) + || request.gameSessionOwnerFence() != terminal.gameSessionOwnerFence() + || !request.targetNamespace().equals(terminal.targetNamespace()) + || !request.canonicalTenantId().equals(terminal.canonicalTenantId()) + || !request.controlPlaneRequestId().equals(terminal.controlPlaneRequestId()) + || !request.canonicalGameInstanceId().equals(terminal.canonicalGameInstanceId()) + || !request.preparationInputDigest().equals(terminal.preparationInputDigest()) + || !request.preparationInputJson().equals(terminal.preparationInputJson())) { + throw invalid("World terminal differs from the complete original StartSession identity"); + } + } + + private static UUID canonicalUuid(String value, String field) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || NIL_UUID.equals(parsed)) { + throw invalid(field + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw invalid(field + " must be a canonical non-nil UUID", malformed); + } + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw invalid("World StartSession terminal " + label + " contains unsupported fields"); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + private static IllegalArgumentException invalid(String message, Throwable cause) { + return new IllegalArgumentException(message, cause); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadRequest.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadRequest.java new file mode 100644 index 0000000000..0ce227095a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadRequest.java @@ -0,0 +1,195 @@ +package net.firedevops.firemud.common.world; + +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.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; + +/** Exact immutable identity and fresh correlation for one historical World terminal read. */ +public final class WorldStartSessionExecutionTerminalReadRequest { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final UUID readRequestId; + private final String targetNamespace; + private final byte[] originalPostAuthorizationTuple; + private final StartSessionPostAuthorizationExecutionTuple decodedOriginalTuple; + private final UUID accountWorldParticipationId; + private final long accountWorldParticipationFence; + private final UUID gameSessionOwnerAttemptId; + private final long gameSessionOwnerFence; + private final UUID canonicalGameInstanceId; + private final String preparationInputJson; + private final String preparationInputDigest; + + public WorldStartSessionExecutionTerminalReadRequest( + UUID readRequestId, + String targetNamespace, + byte[] originalPostAuthorizationTuple, + UUID accountWorldParticipationId, + long accountWorldParticipationFence, + UUID gameSessionOwnerAttemptId, + long gameSessionOwnerFence, + UUID canonicalGameInstanceId, + String preparationInputJson) { + this.readRequestId = requireNonNil(readRequestId, "readRequestId"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw invalid("targetNamespace must be one canonical DNS label"); + } + this.targetNamespace = targetNamespace; + if (originalPostAuthorizationTuple == null + || originalPostAuthorizationTuple.length == 0 + || originalPostAuthorizationTuple.length + > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES) { + throw invalid("Exact original StartSession post-authorization tuple is required"); + } + this.originalPostAuthorizationTuple = originalPostAuthorizationTuple.clone(); + this.decodedOriginalTuple = + StartSessionPostAuthorizationExecutionTuple.decode(this.originalPostAuthorizationTuple); + var original = decodedOriginalTuple.preAuthorizationTuple(); + if (!StartSessionOperatorAction.ACTION_FAMILY.equals(original.actionFamily()) + || !StartSessionOperatorAction.OWNER_SERVICE.equals(original.targetOwner())) { + throw invalid("Original tuple must identify the Game Session StartSession operation"); + } + if (!targetNamespace.equals(original.action().scope().targetNamespace())) { + throw invalid("targetNamespace differs from the exact original StartSession tuple"); + } + + this.accountWorldParticipationId = + requireNonNil(accountWorldParticipationId, "accountWorldParticipationId"); + this.accountWorldParticipationFence = + requirePositive(accountWorldParticipationFence, "accountWorldParticipationFence"); + this.gameSessionOwnerAttemptId = + requireNonNil(gameSessionOwnerAttemptId, "gameSessionOwnerAttemptId"); + this.gameSessionOwnerFence = requirePositive(gameSessionOwnerFence, "gameSessionOwnerFence"); + this.canonicalGameInstanceId = + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + if (this.readRequestId.equals(this.accountWorldParticipationId) + || this.readRequestId.equals(this.gameSessionOwnerAttemptId) + || this.readRequestId.equals(this.canonicalGameInstanceId) + || this.readRequestId.equals(decodedOriginalTuple.reservationOwnerId())) { + throw invalid("readRequestId must be fresh and distinct from retained operation identities"); + } + this.preparationInputJson = requirePreparationInput(preparationInputJson); + this.preparationInputDigest = digest(strictUtf8(this.preparationInputJson)); + } + + public UUID readRequestId() { + return readRequestId; + } + + public String targetNamespace() { + return targetNamespace; + } + + public byte[] originalPostAuthorizationTuple() { + return originalPostAuthorizationTuple.clone(); + } + + public StartSessionPostAuthorizationExecutionTuple decodedOriginalTuple() { + return decodedOriginalTuple; + } + + public UUID accountWorldParticipationId() { + return accountWorldParticipationId; + } + + public long accountWorldParticipationFence() { + return accountWorldParticipationFence; + } + + public UUID gameSessionOwnerAttemptId() { + return gameSessionOwnerAttemptId; + } + + public long gameSessionOwnerFence() { + return gameSessionOwnerFence; + } + + public UUID canonicalGameInstanceId() { + return canonicalGameInstanceId; + } + + public UUID canonicalTenantId() { + return decodedOriginalTuple.preAuthorizationTuple().action().scope().tenantId(); + } + + public String controlPlaneRequestId() { + return decodedOriginalTuple.controlPlaneRequestId(); + } + + public String preparationInputJson() { + return preparationInputJson; + } + + /** Derived from the exact input string; it is never a separate request authority field. */ + public String preparationInputDigest() { + return preparationInputDigest; + } + + private static UUID requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field); + if (NIL_UUID.equals(value)) { + throw invalid(field + " must be a canonical non-nil UUID"); + } + return value; + } + + private static long requirePositive(long value, String field) { + if (value <= 0L) { + throw invalid(field + " must be a positive signed 64-bit integer"); + } + return value; + } + + private static String requirePreparationInput(String value) { + Objects.requireNonNull(value, "preparationInputJson"); + if (value.isBlank()) { + throw invalid("preparationInputJson must retain the exact original input"); + } + if (strictUtf8(value).length > WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES) { + throw invalid("preparationInputJson exceeds the terminal byte limit"); + } + return value; + } + + private static byte[] strictUtf8(String value) { + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] result = new byte[encoded.remaining()]; + encoded.get(result); + return result; + } catch (CharacterCodingException malformed) { + throw invalid("preparationInputJson must be valid Unicode", malformed); + } + } + + private static String digest(byte[] value) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + private static IllegalArgumentException invalid(String message, Throwable cause) { + return new IllegalArgumentException(message, cause); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadClientTest.java new file mode 100644 index 0000000000..af82ce8558 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadClientTest.java @@ -0,0 +1,169 @@ +package net.firedevops.firemud.common.account.startsession; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; +import java.util.UUID; +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.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture.Values; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Configuration and call-boundary proof only; this is not socket or peer-authentication proof. */ +class AccountStartSessionWorldParticipationHistoricalReadClientTest { + @Test + void requiresFileBackedMtlsAndConfiguredNamespace(@TempDir Path directory) throws Exception { + var plaintext = fileBacked(directory); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new AccountStartSessionWorldParticipationHistoricalReadClient( + new ServiceEndpointsProperties(), + plaintext, + new GrpcChannelFactory(), + "world-runtime")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + var classpath = fileBacked(directory); + classpath.setPrivateKey("classpath:private.key"); + assertThatThrownBy( + () -> + new AccountStartSessionWorldParticipationHistoricalReadClient( + new ServiceEndpointsProperties(), + classpath, + new GrpcChannelFactory(), + "world-runtime")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + var client = + new AccountStartSessionWorldParticipationHistoricalReadClient( + new ServiceEndpointsProperties(), + fileBacked(directory), + new GrpcChannelFactory(), + "world-runtime"); + try { + assertThatThrownBy( + () -> + new AccountStartSessionWorldParticipationHistoricalReadClient( + new ServiceEndpointsProperties(), + fileBacked(directory), + new GrpcChannelFactory(), + "not a namespace")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("namespace"); + assertThatThrownBy(() -> client.read(request("other-runtime"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + } finally { + client.close(); + } + } + + @Test + void requiresInitializedClientAndNoAmbientSqlOrSynchronization(@TempDir Path directory) + throws Exception { + var client = + new AccountStartSessionWorldParticipationHistoricalReadClient( + new ServiceEndpointsProperties(), + fileBacked(directory), + new GrpcChannelFactory(), + "world-runtime"); + try { + assertThatThrownBy(() -> client.read(request("world-runtime"))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.read(request("world-runtime"))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction"); + TransactionSynchronizationManager.setActualTransactionActive(false); + + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> client.read(request("world-runtime"))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction"); + } finally { + TransactionSynchronizationManager.clear(); + client.close(); + } + } + + private static AccountStartSessionWorldParticipationHistoricalReadRequest request( + String namespace) { + return new AccountStartSessionWorldParticipationHistoricalReadRequest( + UUID.fromString("d1f41bfb-265a-4f3b-8b2a-124cba20ce43"), + namespace, + originalTuple(namespace).canonicalBytes()); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple(String namespace) { + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "historical-client-original-request", + UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"), + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope( + UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"), namespace), + new StartSessionOperatorAction.Target( + 91L, UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a")), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "synthetic historical client boundary test")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + UUID.fromString("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"), + 19L, + StartSessionAuthorityEvidenceBundleFixture.canonicalBytes( + preTuple, + new Values( + UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"), + "sha256:" + "a".repeat(64), + "17", + "CURRENT", + Instant.parse("2020-01-01T00:00:00Z"), + Instant.parse("2020-01-02T00:00:00Z"), + 1L, + 2L, + 3L, + 4L, + 5L, + 23L, + UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"), + "2", + "3")), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static CommonGrpcClientProperties fileBacked(Path directory) throws Exception { + var properties = new CommonGrpcClientProperties(); + properties.setCertChain( + Files.writeString(directory.resolve("client.crt"), "certificate").toString()); + properties.setPrivateKey( + Files.writeString(directory.resolve("client.key"), "private key").toString()); + properties.setCaCert( + Files.writeString(directory.resolve("ca.crt"), "CA certificate").toString()); + return properties; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadGrpcCodecTest.java new file mode 100644 index 0000000000..cd5c2aba44 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadGrpcCodecTest.java @@ -0,0 +1,309 @@ +package net.firedevops.firemud.common.account.startsession; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture.Values; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; +import org.junit.jupiter.api.Test; + +class AccountStartSessionWorldParticipationHistoricalReadGrpcCodecTest { + private static final String NAMESPACE = "world-runtime"; + private static final UUID TENANT = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID PARTICIPATION_ID = uuid("a8c1e8c8-f237-41b7-918d-ec2281bcac10"); + private static final UUID GAME_SESSION_ATTEMPT_ID = uuid("b9d2f9d9-0438-42c8-829e-fd3392cd9d21"); + private static final UUID GAME_INSTANCE_ID = uuid("c0e30aea-1549-43d9-93af-0e44a3deae32"); + private static final UUID READ_ID = uuid("d1f41bfb-265a-4f3b-8b2a-124cba20ce43"); + private static final String PREPARATION_INPUT = + "{ \"identity\" : \"retained original input\", \"revision\": 3 }\n"; + + @Test + void roundTripsTheCompleteOriginalTupleAndResolvedHistoricalCoordinates() { + var request = request(); + var evidence = evidence(request); + + var wireRequest = + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.toRequest(request); + var decodedRequest = + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromRequest(wireRequest); + assertThat(decodedRequest).isEqualTo(request); + + var response = + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.toResponse(request, evidence); + assertThat(response.getAllFields()).hasSize(8); + var decoded = + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromResponse( + request, response); + assertThat(decoded.request()).isEqualTo(request); + assertThat(decoded.request().originalPostAuthorizationTuple()) + .containsExactly(request.originalPostAuthorizationTuple()); + assertThat(decoded.accountWorldParticipationId()).isEqualTo(PARTICIPATION_ID); + assertThat(decoded.accountWorldParticipationFence()).isEqualTo(31L); + assertThat(decoded.gameSessionOwnerAttemptId()).isEqualTo(GAME_SESSION_ATTEMPT_ID); + assertThat(decoded.gameSessionOwnerFence()).isEqualTo(37L); + assertThat(decoded.canonicalGameInstanceId()).isEqualTo(GAME_INSTANCE_ID); + assertThat(decoded.preparationInputJson()).isEqualTo(PREPARATION_INPUT); + assertThat(decoded.preparationInputDigest()).isEqualTo(digest(PREPARATION_INPUT)); + } + + @Test + void rejectsUnknownFieldsUnsupportedVersionMalformedReadIdAndIncompleteTuple() { + var request = request(); + UnknownFieldSet unknown = unknown(); + var wire = AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.toRequest(request); + + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromRequest( + wire.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromRequest( + wire.toBuilder().setSchemaVersion(2).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unsupported"); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromRequest( + wire.toBuilder().setReadRequestId(READ_ID + " ").build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical non-nil UUID"); + assertThatThrownBy( + () -> + new AccountStartSessionWorldParticipationHistoricalReadRequest( + READ_ID, NAMESPACE, new byte[0])) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("empty or oversized"); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromRequest( + wire.toBuilder() + .setOriginalPostAuthorizationTuple(com.google.protobuf.ByteString.EMPTY) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("empty or oversized"); + } + + @Test + void rejectsOnlyReservationOwnerCollisionAtRequestBoundary() { + var original = originalTuple(NAMESPACE); + assertThatThrownBy( + () -> + new AccountStartSessionWorldParticipationHistoricalReadRequest( + original.reservationOwnerId(), NAMESPACE, original.canonicalBytes())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("distinct from the reservation owner"); + + for (UUID requestId : + new UUID[] { + original.preAuthorizationTuple().actor().accountId(), + TENANT, + uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f") + }) { + assertThat( + new AccountStartSessionWorldParticipationHistoricalReadRequest( + requestId, NAMESPACE, original.canonicalBytes()) + .readRequestId()) + .isEqualTo(requestId); + } + } + + @Test + void rejectsChangedRequestEchoUnknownResponseAndInconsistentRetainedIdentity() { + var request = request(); + var response = + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.toResponse( + request, evidence(request)); + + var changedEcho = + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setReadRequestId("0fd3d542-a9f8-4b8f-b1df-79413650126c") + .build()) + .build(); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromResponse( + request, changedEcho)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed the exact"); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromResponse( + request, response.toBuilder().setUnknownFields(unknown()).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setPreparationInputDigest("sha256:" + "0".repeat(64)) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("differs from the exact retained"); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.toResponse( + request, + evidence( + new AccountStartSessionWorldParticipationHistoricalReadRequest( + READ_ID, NAMESPACE, originalTuple(NAMESPACE, 20L).canonicalBytes())))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed the exact"); + } + + @Test + void rejectsOversizedPreparationInputAndTupleAtClosedCarrierBoundary() { + var request = request(); + String oversized = "x".repeat(WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES + 1); + assertThatThrownBy( + () -> + new AccountStartSessionWorldParticipationHistoricalReadEvidence( + request, + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L, + GAME_INSTANCE_ID, + oversized, + digest(oversized))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("byte limit"); + assertThatThrownBy( + () -> + new AccountStartSessionWorldParticipationHistoricalReadRequest( + READ_ID, + NAMESPACE, + new byte + [StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + + 1])) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("empty or oversized"); + assertThatThrownBy( + () -> + new AccountStartSessionWorldParticipationHistoricalReadEvidence( + request, + PARTICIPATION_ID, + 0L, + GAME_SESSION_ATTEMPT_ID, + 37L, + GAME_INSTANCE_ID, + PREPARATION_INPUT, + digest(PREPARATION_INPUT))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("fence must be positive"); + } + + private static AccountStartSessionWorldParticipationHistoricalReadRequest request() { + return new AccountStartSessionWorldParticipationHistoricalReadRequest( + READ_ID, NAMESPACE, originalTuple(NAMESPACE).canonicalBytes()); + } + + private static AccountStartSessionWorldParticipationHistoricalReadEvidence evidence( + AccountStartSessionWorldParticipationHistoricalReadRequest request) { + return new AccountStartSessionWorldParticipationHistoricalReadEvidence( + request, + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L, + GAME_INSTANCE_ID, + PREPARATION_INPUT, + digest(PREPARATION_INPUT)); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple(String namespace) { + return originalTuple(namespace, 19L); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple( + String namespace, long reservationClaimFence) { + UUID actor = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + UUID targetOwner = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + UUID reservationOwner = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + String requestId = "historical-participation-original-request"; + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + requestId, + actor, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, namespace), + new StartSessionOperatorAction.Target(91L, targetOwner), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "synthetic historical Account evidence carrier test")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + reservationOwner, + reservationClaimFence, + authorityBundle(preTuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + return StartSessionAuthorityEvidenceBundleFixture.canonicalBytes( + tuple, + new Values( + uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"), + "sha256:" + "a".repeat(64), + "17", + "CURRENT", + Instant.parse("2020-01-01T00:00:00Z"), + Instant.parse("2020-01-02T00:00:00Z"), + 1L, + 2L, + 3L, + 4L, + 5L, + 23L, + uuid("a681bba7-c215-4cf1-a35b-14348912cbdc"), + "2", + "3")); + } + + private static UnknownFieldSet unknown() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } + + private static String digest(String value) { + try { + return "sha256:" + + java.util.HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClientTest.java new file mode 100644 index 0000000000..d7b806d289 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClientTest.java @@ -0,0 +1,98 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.ManagedChannelBuilder; +import java.nio.file.Files; +import java.nio.file.Path; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldStartSessionExecutionTerminalReadClientTest { + @Test + void clientReceiveLimitIncludesTheCompleteCanonicalTerminalEnvelope(@TempDir Path directory) + throws Exception { + var client = + new WorldStartSessionExecutionTerminalReadClient( + new ServiceEndpointsProperties(), + fileBacked(directory), + new GrpcChannelFactory(), + "world-runtime"); + // No connection is made: this verifies stub configuration, not authenticated socket proof. + var channel = ManagedChannelBuilder.forTarget("localhost:1").usePlaintext().build(); + try { + assertThat(client.buildStub(channel).getCallOptions().getMaxInboundMessageSize()) + .isEqualTo(WorldStartSessionExecutionTerminalReadGrpcCodec.MAX_RESPONSE_BYTES) + .isGreaterThan(WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES); + } finally { + channel.shutdownNow(); + client.close(); + } + } + + @Test + void requiresFileBackedMtlsInitializationAndAnIndependentCallerTransaction( + @TempDir Path directory) throws Exception { + var plaintext = fileBacked(directory); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new WorldStartSessionExecutionTerminalReadClient( + new ServiceEndpointsProperties(), + plaintext, + new GrpcChannelFactory(), + "world-runtime")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + var classpath = fileBacked(directory); + classpath.setCaCert("classpath:ca.crt"); + assertThatThrownBy( + () -> + new WorldStartSessionExecutionTerminalReadClient( + new ServiceEndpointsProperties(), + classpath, + new GrpcChannelFactory(), + "world-runtime")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + var client = + new WorldStartSessionExecutionTerminalReadClient( + new ServiceEndpointsProperties(), + fileBacked(directory), + new GrpcChannelFactory(), + "world-runtime"); + try { + assertThatThrownBy(() -> client.read(null)).isInstanceOf(NullPointerException.class); + var request = WorldStartSessionExecutionTerminalReadGrpcCodecTest.request(); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction"); + } finally { + TransactionSynchronizationManager.clear(); + client.close(); + } + } + + private static CommonGrpcClientProperties fileBacked(Path directory) throws Exception { + var properties = new CommonGrpcClientProperties(); + properties.setCertChain( + Files.writeString(directory.resolve("client.crt"), "certificate").toString()); + properties.setPrivateKey( + Files.writeString(directory.resolve("client.key"), "private key").toString()); + properties.setCaCert( + Files.writeString(directory.resolve("ca.crt"), "CA certificate").toString()); + return properties; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadGrpcCodecTest.java new file mode 100644 index 0000000000..ffe9ba7080 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadGrpcCodecTest.java @@ -0,0 +1,251 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture.Values; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal.Outcome; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldStartSessionExecutionTerminalResponse; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class WorldStartSessionExecutionTerminalReadGrpcCodecTest { + private static final UUID TENANT = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID RESERVATION_OWNER = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID PARTICIPATION_ID = uuid("a8c1e8c8-f237-41b7-918d-ec2281bcac10"); + private static final UUID GAME_SESSION_ATTEMPT_ID = uuid("b9d2f9d9-0438-42c8-829e-fd3392cd9d21"); + private static final UUID GAME_INSTANCE_ID = uuid("c0e30aea-1549-43d9-93af-0e44a3deae32"); + private static final UUID READ_ID = uuid("d1f41bfb-265a-4f3b-8b2a-124cba20ce43"); + private static final String CONTROL_PLANE_REQUEST_ID = "terminal-read-original-request"; + private static final String NAMESPACE = "world-runtime"; + private static final String PREPARATION_INPUT = + "{ \"selected\" : \"immutable source\", \"revision\": 3 }\n"; + private static final String WORKLOAD = + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void rejectsAnOverboundWireEnvelopeBeforeDecodingItsTerminal() { + var response = + ReadWorldStartSessionExecutionTerminalResponse.newBuilder() + .setReadRequestId(READ_ID.toString()) + .setCanonicalTerminalBytes( + com.google.protobuf.ByteString.copyFrom( + new byte[WorldStartSessionExecutionTerminalReadGrpcCodec.MAX_RESPONSE_BYTES])) + .build(); + assertThatThrownBy( + () -> WorldStartSessionExecutionTerminalReadGrpcCodec.fromResponse(request(), response)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("wire limit"); + } + + @Test + void roundTripsFreshReadAndOnlyCanonicalTerminalResult() { + var request = request(); + var wireRequest = WorldStartSessionExecutionTerminalReadGrpcCodec.toRequest(request); + var decoded = WorldStartSessionExecutionTerminalReadGrpcCodec.fromRequest(wireRequest); + assertThat(decoded.readRequestId()).isEqualTo(READ_ID); + assertThat(decoded.originalPostAuthorizationTuple()) + .containsExactly(request.originalPostAuthorizationTuple()); + assertThat(decoded.accountWorldParticipationFence()).isEqualTo(31L); + assertThat(decoded.gameSessionOwnerFence()).isEqualTo(37L); + assertThat(decoded.preparationInputJson()).isEqualTo(PREPARATION_INPUT); + + var terminal = terminal(request, PARTICIPATION_ID, 31L, GAME_SESSION_ATTEMPT_ID, 37L); + var response = WorldStartSessionExecutionTerminalReadGrpcCodec.toResponse(request, terminal); + assertThat(response.getAllFields()).hasSize(2); + var recovered = WorldStartSessionExecutionTerminalReadGrpcCodec.fromResponse(request, response); + assertThat(recovered.canonicalBytes()).containsExactly(terminal.canonicalBytes()); + assertThat(recovered.outcome()).isEqualTo(Outcome.COMMITTED); + } + + @Test + void rejectsUnknownFieldsMalformedIdentityAndMixedNamespaceBeforeUse() { + var request = request(); + UnknownFieldSet unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + + assertThatThrownBy( + () -> + WorldStartSessionExecutionTerminalReadGrpcCodec.fromRequest( + WorldStartSessionExecutionTerminalReadGrpcCodec.toRequest(request).toBuilder() + .setUnknownFields(unknown) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + WorldStartSessionExecutionTerminalReadGrpcCodec.fromRequest( + WorldStartSessionExecutionTerminalReadGrpcCodec.toRequest(request).toBuilder() + .setReadRequestId("d1f41bfb-265a-4f3b-8b2a-124cba20ce43 ") + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical non-nil UUID"); + assertThatThrownBy( + () -> + WorldStartSessionExecutionTerminalReadGrpcCodec.fromRequest( + WorldStartSessionExecutionTerminalReadGrpcCodec.toRequest(request).toBuilder() + .setAccountWorldParticipationFence(0L) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("positive"); + assertThatThrownBy( + () -> + WorldStartSessionExecutionTerminalReadGrpcCodec.fromRequest( + WorldStartSessionExecutionTerminalReadGrpcCodec.toRequest(request).toBuilder() + .setTargetNamespace("other-runtime") + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("differs from the exact original"); + } + + @Test + void rejectsSubstitutedTerminalIdentityOrReadCorrelation() { + var request = request(); + var substituted = + terminal( + request, + uuid("e2a52c0c-c71f-4900-b1f2-c78f8b512a63"), + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L); + var response = + ReadWorldStartSessionExecutionTerminalResponse.newBuilder() + .setReadRequestId(READ_ID.toString()) + .setCanonicalTerminalBytes( + com.google.protobuf.ByteString.copyFrom(substituted.canonicalBytes())) + .build(); + assertThatThrownBy( + () -> WorldStartSessionExecutionTerminalReadGrpcCodec.fromResponse(request, response)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("complete original StartSession identity"); + + var valid = terminal(request, PARTICIPATION_ID, 31L, GAME_SESSION_ATTEMPT_ID, 37L); + var changedCorrelation = + ReadWorldStartSessionExecutionTerminalResponse.newBuilder() + .setReadRequestId("e2a52c0c-c71f-4900-b1f2-c78f8b512a63") + .setCanonicalTerminalBytes( + com.google.protobuf.ByteString.copyFrom(valid.canonicalBytes())) + .build(); + assertThatThrownBy( + () -> + WorldStartSessionExecutionTerminalReadGrpcCodec.fromResponse( + request, changedCorrelation)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed the exact"); + + assertThatThrownBy( + () -> + WorldStartSessionExecutionTerminalReadGrpcCodec.fromResponse( + request, changedCorrelation.toBuilder().setUnknownFields(unknown()).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + } + + static WorldStartSessionExecutionTerminalReadRequest request() { + return new WorldStartSessionExecutionTerminalReadRequest( + READ_ID, + NAMESPACE, + originalTuple().canonicalBytes(), + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L, + GAME_INSTANCE_ID, + PREPARATION_INPUT); + } + + private static WorldStartSessionExecutionTerminal terminal( + WorldStartSessionExecutionTerminalReadRequest request, + UUID participationId, + long participationFence, + UUID attemptId, + long attemptFence) { + return new WorldStartSessionExecutionTerminal( + request.originalPostAuthorizationTuple(), + participationId, + participationFence, + attemptId, + attemptFence, + request.targetNamespace(), + request.canonicalTenantId(), + request.controlPlaneRequestId(), + request.canonicalGameInstanceId(), + request.preparationInputDigest(), + request.preparationInputJson(), + 41L, + Outcome.COMMITTED); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple() { + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + CONTROL_PLANE_REQUEST_ID, + ACTOR, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, NAMESPACE), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "canonical StartSession owner attempt")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + WORKLOAD, + FINGERPRINT, + RESERVATION_OWNER, + 19L, + bundle(preTuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] bundle(StartSessionPreAuthorizationReservationTuple tuple) { + return StartSessionAuthorityEvidenceBundleFixture.canonicalBytes( + tuple, + new Values( + uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"), + "sha256:" + "a".repeat(64), + "17", + "CURRENT", + Instant.parse("2026-10-09T00:00:00Z"), + Instant.parse("2026-10-09T00:05:00Z"), + 1L, + 2L, + 3L, + 4L, + 5L, + 23L, + uuid("a681bba7-c215-4cf1-a35b-14348912cbdc"), + "2", + "3")); + } + + private static UnknownFieldSet unknown() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalTest.java new file mode 100644 index 0000000000..9ae8b909ce --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalTest.java @@ -0,0 +1,618 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture.Values; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal.Outcome; +import org.junit.jupiter.api.Test; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.json.JsonMapper; + +class WorldStartSessionExecutionTerminalTest { + private static final UUID TENANT = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID RESERVATION_OWNER = + UUID.fromString("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID ISSUANCE_ID = UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final UUID PARTICIPATION_ID = + UUID.fromString("a8c1e8c8-f237-41b7-918d-ec2281bcac10"); + private static final UUID GAME_SESSION_ATTEMPT_ID = + UUID.fromString("b9d2f9d9-0438-42c8-829e-fd3392cd9d21"); + private static final UUID GAME_INSTANCE_ID = + UUID.fromString("c0e30aea-1549-43d9-93af-0e44a3deae32"); + private static final String REQUEST_ID = "start-world-terminal-vector"; + private static final String NAMESPACE = "world-runtime"; + private static final String PREPARATION_INPUT = + "{ \"selected\" : \"immutable source\", \"revision\": 3 }\n"; + private static final String WORKLOAD = + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private static final String EXPECTED_PREPARATION_INPUT_DIGEST = + "sha256:0b98b4ce717296fdaaeece6709c7c7d7b1b4c149ed1dc5b0c1afc43c91fe2bb1"; + private static final String EXPECTED_ORIGINAL_TUPLE_BASE64 = + String.join( + "", + "eyJhY3Rpb25GYW1pbHkiOiJTdGFydFNlc3Npb24iLCJhY3Rpb25GYW1pbHlSZXF1ZXN0SWRlbnRpdHkiOnsicmVxdWVzdElkIjoi", + "c3RhcnQtd29ybGQtdGVybWluYWwtdmVjdG9yIiwicmVxdWVzdElkZW50aXR5S2luZCI6ImNvbnRyb2xQbGFuZVJlcXVlc3RJZCJ9", + "LCJhY3Rpb25GYW1pbHlTY2hlbWFJZCI6ImZpcmVtdWQuZ2FtZS1zZXNzaW9uLnN0YXJ0LXNlc3Npb24iLCJhY3Rpb25GYW1pbHlT", + "Y2hlbWFWZXJzaW9uIjoiMSIsImFjdG9yIjp7ImFjY291bnRJZCI6ImE0ZjVmNGViLTgyNDMtNGQ0Mi05MDNhLTMzNDk1NDU2YTYy", + "MiIsImtpbmQiOiJIVU1BTiJ9LCJhdWRpdFJlYXNvbiI6ImNhbm9uaWNhbCBTdGFydFNlc3Npb24gb3duZXIgYXR0ZW1wdCIsImF1", + "dGhlbnRpY2F0ZWRXb3JrbG9hZElkZW50aXR5Ijp7ImlkZW50aXR5S2luZCI6Ik1VVFVBTF9UTFNfU1BJRkZFIiwidXJpIjoic3Bp", + "ZmZlOi8vZmlyZW11ZC9ucy93b3JsZC1ydW50aW1lL3NhL2xvZ2dpbmctYWRtaW4tc2VydmljZSJ9LCJhdXRob3JpdHlFdmlkZW5j", + "ZUJ1bmRsZSI6eyJhY2NvdW50UHJvamVjdGlvbkV2aWRlbmNlIjp7ImV2YWx1YXRlZEF0IjoiMjAyNi0xMC0wOVQwMDowMDowMFoi", + "LCJleHBpcmVzQXQiOiIyMDI2LTEwLTA5VDAwOjA1OjAwWiIsInByb2plY3Rpb25TdGF0dXMiOiJDVVJSRU5UIiwic291cmNlRXZp", + "ZGVuY2VJZCI6InNoYTI1NjphYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh", + "YWFhYWFhIiwic291cmNlRXZpZGVuY2VWZXJzaW9uIjoiMTciLCJzb3VyY2VUeXBlIjoiQUNDT1VOVCJ9LCJhdXRob3JpdHlTY29w", + "ZSI6eyJhY3Rpb25GYW1pbHkiOiJTdGFydFNlc3Npb24iLCJhcHBsaWNhYmxlQWNjb3VudElkIjoiYTRmNWY0ZWItODI0My00ZDQy", + "LTkwM2EtMzM0OTU0NTZhNjIyIiwiYXBwbGljYWJsZVRlbmFudElkIjoiOWY4ZjA2YjQtMzZlNS00ZDExLTljMmEtNWFkZmQ3ZjQx", + "NTMxIiwic2NvcGUiOnsidGFyZ2V0TmFtZXNwYWNlIjoid29ybGQtcnVudGltZSIsInRlbmFudElkIjoiOWY4ZjA2YjQtMzZlNS00", + "ZDExLTljMmEtNWFkZmQ3ZjQxNTMxIn19LCJhdXRob3JpdHlUdXBsZSI6eyJhY2NvdW50QXV0aG9yaXR5R2VuZXJhdGlvbiI6Miwi", + "aXNzdWVyQXV0aEdlbmVyYXRpb24iOjEsIm1lbWJlcnNoaXBBdXRob3JpdHlHZW5lcmF0aW9uIjp7IjlmOGYwNmI0LTM2ZTUtNGQx", + "MS05YzJhLTVhZGZkN2Y0MTUzMSI6NH0sInByaXZhdGVSZWFsbUdyYW50VmVyc2lvbnMiOltdLCJ0ZW5hbnRBdXRob3JpdHlHZW5l", + "cmF0aW9uIjp7IjlmOGYwNmI0LTM2ZTUtNGQxMS05YzJhLTVhZGZkN2Y0MTUzMSI6M319LCJidW5kbGVWZXJzaW9uIjoiYXV0aG9y", + "aXR5RXZpZGVuY2VCdW5kbGUvdjEiLCJpc3N1YW5jZUV2aWRlbmNlIjp7ImFjY291bnRHZW5lcmF0aW9uIjoiMiIsImFjdG9yQWNj", + "b3VudElkIjoiYTRmNWY0ZWItODI0My00ZDQyLTkwM2EtMzM0OTU0NTZhNjIyIiwiY29udHJvbFVpVG9rZW5KdGkiOiJhNjgxYmJh", + "Ny1jMjE1LTRjZjEtYTM1Yi0xNDM0ODkxMmNiZGMiLCJldmlkZW5jZVR5cGUiOiJIdW1hbkF1dGhvcml0eUV2aWRlbmNlL3YxIiwi", + "cm9sZSI6InRlbmFudEFkbWluIiwidGVuYW50R2VuZXJhdGlvbiI6IjMifSwiaXNzdWFuY2VGZW5jZSI6IjIzIiwiaXNzdWFuY2VL", + "aW5kIjoiaHVtYW5fb3BlcmF0b3IiLCJpc3N1YW5jZU9wZXJhdGlvbklkZW50aXR5Ijp7ImFjdGlvbkZhbWlseVJlcXVlc3RJZGVu", + "dGl0eSI6eyJyZXF1ZXN0SWQiOiJzdGFydC13b3JsZC10ZXJtaW5hbC12ZWN0b3IiLCJyZXF1ZXN0SWRlbnRpdHlLaW5kIjoiY29u", + "dHJvbFBsYW5lUmVxdWVzdElkIn0sImNvbnRyb2xQbGFuZVJlcXVlc3RJZCI6InN0YXJ0LXdvcmxkLXRlcm1pbmFsLXZlY3RvciIs", + "Imlzc3VhbmNlT3BlcmF0aW9uSWQiOiJmNWQwNDRiZC03ZTVmLTRlMmQtOTg1OS05MDI1Y2JkY2M2MGYiLCJtdXRhdGlvbkRpZ2Vz", + "dCI6ImQyMGY5MDVkYjdiNmUzOTVjODAwOGY2ZjZlNDk4NjY0MWM1NTk1ZTEzNWRjZDkwN2E0YzQ2NGZmNjQyMDEwZTAifSwibWVt", + "YmVyc2hpcFZlcnNpb24iOnsiOWY4ZjA2YjQtMzZlNS00ZDExLTljMmEtNWFkZmQ3ZjQxNTMxIjo1fX0sImF1dGhvcml0eUV2aWRl", + "bmNlQnVuZGxlUmVmZXJlbmNlIjp7ImJ1bmRsZVZlcnNpb24iOiJhdXRob3JpdHlFdmlkZW5jZUJ1bmRsZS92MSIsImxpbmVhcml6", + "YXRpb24iOiIxODQ0Njc0NDA3MzcwOTU1MTYxNSIsInNvdXJjZUZlbmNlIjoiMjMiLCJzb3VyY2VWZXJzaW9uIjoiMTcifSwiYXV0", + "aG9yaXR5VHVwbGUiOnsiYWNjb3VudEF1dGhvcml0eUdlbmVyYXRpb24iOjIsImlzc3VlckF1dGhHZW5lcmF0aW9uIjoxLCJtZW1i", + "ZXJzaGlwQXV0aG9yaXR5R2VuZXJhdGlvbiI6eyI5ZjhmMDZiNC0zNmU1LTRkMTEtOWMyYS01YWRmZDdmNDE1MzEiOjR9LCJwcml2", + "YXRlUmVhbG1HcmFudFZlcnNpb25zIjpbXSwidGVuYW50QXV0aG9yaXR5R2VuZXJhdGlvbiI6eyI5ZjhmMDZiNC0zNmU1LTRkMTEt", + "OWMyYS01YWRmZDdmNDE1MzEiOjN9fSwiYXV0aG9yaXphdGlvblJlZmVyZW5jZUZpbmdlcnByaW50IjoiYXJmcC92MS90ZXN0LWtl", + "eS9iYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiIiwiYXV0b21h", + "dGlvblBvbGljeSI6eyJwcmVzZW5jZSI6IkFCU0VOVCJ9LCJjb250cm9sUGxhbmVSZXF1ZXN0SWQiOiJzdGFydC13b3JsZC10ZXJt", + "aW5hbC12ZWN0b3IiLCJleHBlY3RlZFZlcnNpb24iOnsicHJlc2VuY2UiOiJBQlNFTlQifSwiaXNzdWFuY2VGZW5jZSI6IjIzIiwi", + "aXNzdWFuY2VLaW5kIjoiaHVtYW5fb3BlcmF0b3IiLCJtZW1iZXJzaGlwVmVyc2lvbiI6eyI5ZjhmMDZiNC0zNmU1LTRkMTEtOWMy", + "YS01YWRmZDdmNDE1MzEiOjV9LCJtdXRhdGlvbiI6eyJjbGllbnRJcCI6eyJwcmVzZW5jZSI6IkFCU0VOVCJ9fSwibXV0YXRpb25E", + "aWdlc3QiOiJkMjBmOTA1ZGI3YjZlMzk1YzgwMDhmNmY2ZTQ5ODY2NDFjNTU5NWUxMzVkY2Q5MDdhNGM0NjRmZjY0MjAxMGUwIiwi", + "cHJlQXV0aG9yaXphdGlvblJlc2VydmF0aW9uVHVwbGUiOnsiYWN0aW9uRmFtaWx5IjoiU3RhcnRTZXNzaW9uIiwiYWN0aW9uRmFt", + "aWx5UmVxdWVzdElkZW50aXR5Ijp7InJlcXVlc3RJZCI6InN0YXJ0LXdvcmxkLXRlcm1pbmFsLXZlY3RvciIsInJlcXVlc3RJZGVu", + "dGl0eUtpbmQiOiJjb250cm9sUGxhbmVSZXF1ZXN0SWQifSwiYWN0aW9uRmFtaWx5U2NoZW1hSWQiOiJmaXJlbXVkLmdhbWUtc2Vz", + "c2lvbi5zdGFydC1zZXNzaW9uIiwiYWN0aW9uRmFtaWx5U2NoZW1hVmVyc2lvbiI6IjEiLCJhY3RvciI6eyJhY2NvdW50SWQiOiJh", + "NGY1ZjRlYi04MjQzLTRkNDItOTAzYS0zMzQ5NTQ1NmE2MjIiLCJraW5kIjoiSFVNQU4ifSwiYXVkaXRSZWFzb24iOiJjYW5vbmlj", + "YWwgU3RhcnRTZXNzaW9uIG93bmVyIGF0dGVtcHQiLCJhdXRvbWF0aW9uUG9saWN5Ijp7InByZXNlbmNlIjoiQUJTRU5UIn0sImV4", + "cGVjdGVkVmVyc2lvbiI6eyJwcmVzZW5jZSI6IkFCU0VOVCJ9LCJtdXRhdGlvbiI6eyJjbGllbnRJcCI6eyJwcmVzZW5jZSI6IkFC", + "U0VOVCJ9fSwic2NvcGUiOnsidGFyZ2V0TmFtZXNwYWNlIjoid29ybGQtcnVudGltZSIsInRlbmFudElkIjoiOWY4ZjA2YjQtMzZl", + "NS00ZDExLTljMmEtNWFkZmQ3ZjQxNTMxIn0sInRhcmdldCI6eyJnYW1lVGVtcGxhdGVJZCI6IjkxIiwib3duZXJBY2NvdW50SWQi", + "OiIzNmFhOWNlNS0wZWJjLTRjMTQtOWY2Yi1kMTYwZWRjNjA1OWEifSwidGFyZ2V0T3duZXIiOnsib3duZXJTZXJ2aWNlIjoiZ2Ft", + "ZS1zZXNzaW9uLXNlcnZpY2UifSwidHVwbGVTY2hlbWFJZCI6InByZUF1dGhvcml6YXRpb25SZXNlcnZhdGlvblR1cGxlIiwidHVw", + "bGVTY2hlbWFWZXJzaW9uIjoiMSJ9LCJyZXNlcnZhdGlvbkNsYWltRmVuY2UiOjE5LCJyZXNlcnZhdGlvbk93bmVySWQiOiI3YzAw", + "NWI2NS1mY2IxLTRhYzktYTcxNC1mM2QwZjQ0OWVkY2YiLCJzY29wZSI6eyJ0YXJnZXROYW1lc3BhY2UiOiJ3b3JsZC1ydW50aW1l", + "IiwidGVuYW50SWQiOiI5ZjhmMDZiNC0zNmU1LTRkMTEtOWMyYS01YWRmZDdmNDE1MzEifSwidGFyZ2V0Ijp7ImdhbWVUZW1wbGF0", + "ZUlkIjoiOTEiLCJvd25lckFjY291bnRJZCI6IjM2YWE5Y2U1LTBlYmMtNGMxNC05ZjZiLWQxNjBlZGM2MDU5YSJ9LCJ0YXJnZXRP", + "d25lciI6eyJvd25lclNlcnZpY2UiOiJnYW1lLXNlc3Npb24tc2VydmljZSJ9LCJ0dXBsZVNjaGVtYUlkIjoicG9zdEF1dGhvcml6", + "YXRpb25FeGVjdXRpb25UdXBsZSIsInR1cGxlU2NoZW1hVmVyc2lvbiI6IjEifQ=="); + private static final String EXPECTED_DIGEST = + "sha256:a3304a2e145bd7eec557cd87d233e9dd399d5c3a5c658438f2039eb7e0898eb1"; + private static final String EXPECTED_CANONICAL_PREIMAGE = + "{\"accountWorldParticipationFence\":\"31\"," + + "\"accountWorldParticipationId\":\"a8c1e8c8-f237-41b7-918d-ec2281bcac10\"," + + "\"canonicalGameInstanceId\":\"c0e30aea-1549-43d9-93af-0e44a3deae32\"," + + "\"canonicalTenantId\":\"9f8f06b4-36e5-4d11-9c2a-5adfd7f41531\"," + + "\"controlPlaneRequestId\":\"start-world-terminal-vector\"," + + "\"gameSessionOwnerAttemptId\":\"b9d2f9d9-0438-42c8-829e-fd3392cd9d21\"," + + "\"gameSessionOwnerFence\":\"37\"," + + "\"originalPostAuthorizationTupleBase64\":\"" + + EXPECTED_ORIGINAL_TUPLE_BASE64 + + "\",\"outcome\":\"COMMITTED\"," + + "\"preparationInputDigest\":\"" + + EXPECTED_PREPARATION_INPUT_DIGEST + + "\",\"preparationInputJson\":\"{ \\\"selected\\\" : \\\"immutable source\\\", \\\"revision\\\": 3 }\\n\"," + + "\"schema\":\"world-start-session-execution-terminal/v1\"," + + "\"targetNamespace\":\"world-runtime\",\"worldExecutionFence\":\"41\"}"; + + @Test + void committedTerminalMatchesFrozenCanonicalVectorAndPreservesExactTupleAndInput() + throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = originalTuple(); + byte[] originalTupleBytes = tuple.canonicalBytes(); + WorldStartSessionExecutionTerminal terminal = terminal(tuple, Outcome.COMMITTED); + + assertThat(new String(terminal.canonicalBytes(), StandardCharsets.UTF_8)) + .isEqualTo(EXPECTED_CANONICAL_PREIMAGE); + assertThat(terminal.digest()).isEqualTo(EXPECTED_DIGEST); + assertThat(terminal.originalPostAuthorizationTupleBase64()) + .isEqualTo(EXPECTED_ORIGINAL_TUPLE_BASE64); + assertThat(terminal.originalPostAuthorizationTuple()).containsExactly(originalTupleBytes); + assertThat(terminal.preparationInputJson()).isEqualTo(PREPARATION_INPUT); + + WorldStartSessionExecutionTerminal decoded = + WorldStartSessionExecutionTerminal.fromStored(terminal.canonicalBytes()); + assertThat(decoded.canonicalBytes()).containsExactly(terminal.canonicalBytes()); + assertThat(decoded.digest()).isEqualTo(terminal.digest()); + assertThat(decoded.originalPostAuthorizationTuple()).containsExactly(originalTupleBytes); + assertThat(decoded.originalPostAuthorizationTupleBase64()) + .isEqualTo(Base64.getEncoder().encodeToString(originalTupleBytes)); + assertThat(decoded.preparationInputJson()).isEqualTo(PREPARATION_INPUT); + assertThat(decoded.accountWorldParticipationFence()).isEqualTo(31L); + assertThat(decoded.gameSessionOwnerFence()).isEqualTo(37L); + assertThat(decoded.worldExecutionFence()).isEqualTo(41L); + } + + @Test + void abortedAndCommittedOutcomesAreStableExactReadbacksWithoutObservationFields() + throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = originalTuple(); + WorldStartSessionExecutionTerminal committed = terminal(tuple, Outcome.COMMITTED); + WorldStartSessionExecutionTerminal aborted = terminal(tuple, Outcome.ABORTED); + + assertThat(committed.canonicalBytes()).isNotEqualTo(aborted.canonicalBytes()); + assertThat(committed.digest()).isNotEqualTo(aborted.digest()); + for (WorldStartSessionExecutionTerminal expected : List.of(committed, aborted)) { + byte[] firstRead = expected.canonicalBytes(); + WorldStartSessionExecutionTerminal firstDecoded = + WorldStartSessionExecutionTerminal.fromStored(firstRead); + WorldStartSessionExecutionTerminal secondDecoded = + WorldStartSessionExecutionTerminal.fromStored(firstDecoded.canonicalBytes()); + assertThat(secondDecoded.canonicalBytes()).containsExactly(firstRead); + assertThat(secondDecoded.digest()).isEqualTo(expected.digest()); + } + + assertInvalid( + withField(committed.canonicalBytes(), "currentReadCorrelationId", "later-read-id")); + assertInvalid( + withField(committed.canonicalBytes(), "authorizationExpiry", "2099-01-01T00:00:00Z")); + assertInvalid(withField(committed.canonicalBytes(), "outcome", "PENDING")); + assertInvalid(withField(committed.canonicalBytes(), "outcome", "TIMEOUT")); + } + + @Test + void retainsEveryBindingAndFenceAndRejectsScopeSubstitution() throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = originalTuple(); + WorldStartSessionExecutionTerminal baseline = terminal(tuple, Outcome.COMMITTED); + byte[] original = baseline.canonicalBytes(); + + assertChanged( + new WorldStartSessionExecutionTerminal( + tuple.canonicalBytes(), + uuid("d1e40bfb-265a-44ea-84b0-1f55b4efbf43"), + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L, + NAMESPACE, + TENANT, + REQUEST_ID, + GAME_INSTANCE_ID, + digest(PREPARATION_INPUT), + PREPARATION_INPUT, + 41L, + Outcome.COMMITTED), + original); + assertChanged(terminal(originalTuple(92L), Outcome.COMMITTED), original); + assertChanged( + new WorldStartSessionExecutionTerminal( + tuple.canonicalBytes(), + PARTICIPATION_ID, + 43L, + GAME_SESSION_ATTEMPT_ID, + 37L, + NAMESPACE, + TENANT, + REQUEST_ID, + GAME_INSTANCE_ID, + digest(PREPARATION_INPUT), + PREPARATION_INPUT, + 41L, + Outcome.COMMITTED), + original); + assertChanged( + new WorldStartSessionExecutionTerminal( + tuple.canonicalBytes(), + PARTICIPATION_ID, + 31L, + uuid("e2f51c0c-376b-45fb-95b1-2066c5f0c054"), + 37L, + NAMESPACE, + TENANT, + REQUEST_ID, + GAME_INSTANCE_ID, + digest(PREPARATION_INPUT), + PREPARATION_INPUT, + 41L, + Outcome.COMMITTED), + original); + assertChanged( + new WorldStartSessionExecutionTerminal( + tuple.canonicalBytes(), + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 47L, + NAMESPACE, + TENANT, + REQUEST_ID, + GAME_INSTANCE_ID, + digest(PREPARATION_INPUT), + PREPARATION_INPUT, + 41L, + Outcome.COMMITTED), + original); + assertChanged( + new WorldStartSessionExecutionTerminal( + tuple.canonicalBytes(), + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L, + NAMESPACE, + TENANT, + REQUEST_ID, + uuid("f3042d1d-487c-46ac-a6c2-3177d6f1d165"), + digest(PREPARATION_INPUT), + PREPARATION_INPUT, + 41L, + Outcome.COMMITTED), + original); + assertChanged( + new WorldStartSessionExecutionTerminal( + tuple.canonicalBytes(), + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L, + NAMESPACE, + TENANT, + REQUEST_ID, + GAME_INSTANCE_ID, + digest(PREPARATION_INPUT), + PREPARATION_INPUT, + 43L, + Outcome.COMMITTED), + original); + + assertThatThrownBy( + () -> + new WorldStartSessionExecutionTerminal( + tuple.canonicalBytes(), + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L, + "another-runtime", + TENANT, + REQUEST_ID, + GAME_INSTANCE_ID, + digest(PREPARATION_INPUT), + PREPARATION_INPUT, + 41L, + Outcome.COMMITTED)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("scope"); + assertThatThrownBy( + () -> + new WorldStartSessionExecutionTerminal( + tuple.canonicalBytes(), + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L, + NAMESPACE, + uuid("d4053e2e-598d-47bd-b7d3-4288e702e276"), + REQUEST_ID, + GAME_INSTANCE_ID, + digest(PREPARATION_INPUT), + PREPARATION_INPUT, + 41L, + Outcome.COMMITTED)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("scope"); + assertThatThrownBy( + () -> + new WorldStartSessionExecutionTerminal( + tuple.canonicalBytes(), + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L, + NAMESPACE, + TENANT, + "substituted-request-id", + GAME_INSTANCE_ID, + digest(PREPARATION_INPUT), + PREPARATION_INPUT, + 41L, + Outcome.COMMITTED)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("scope"); + + WorldStartSessionExecutionTerminal equalFenceValues = + new WorldStartSessionExecutionTerminal( + tuple.canonicalBytes(), + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 31L, + NAMESPACE, + TENANT, + REQUEST_ID, + GAME_INSTANCE_ID, + digest(PREPARATION_INPUT), + PREPARATION_INPUT, + 31L, + Outcome.COMMITTED); + WorldStartSessionExecutionTerminal equalFenceReadback = + WorldStartSessionExecutionTerminal.fromStored(equalFenceValues.canonicalBytes()); + assertThat(equalFenceReadback.accountWorldParticipationFence()).isEqualTo(31L); + assertThat(equalFenceReadback.gameSessionOwnerFence()).isEqualTo(31L); + assertThat(equalFenceReadback.worldExecutionFence()).isEqualTo(31L); + assertThat(new String(equalFenceReadback.canonicalBytes(), StandardCharsets.UTF_8)) + .contains( + "\"accountWorldParticipationFence\":\"31\"", + "\"gameSessionOwnerFence\":\"31\"", + "\"worldExecutionFence\":\"31\""); + } + + @Test + void rejectsMalformedDuplicateUnknownTrailingAndNoncanonicalStoredValues() throws Exception { + WorldStartSessionExecutionTerminal terminal = terminal(originalTuple(), Outcome.COMMITTED); + String canonical = new String(terminal.canonicalBytes(), StandardCharsets.UTF_8); + + assertInvalid(canonical + " "); + assertInvalid(canonical + "{}"); + assertInvalid(canonical.replace("\"schema\":", "\"extra\":true,\"schema\":")); + assertInvalid( + canonical.replace( + "\"schema\":\"" + WorldStartSessionExecutionTerminal.SCHEMA + "\"", + "\"schema\":\"" + + WorldStartSessionExecutionTerminal.SCHEMA + + "\",\"schema\":\"" + + WorldStartSessionExecutionTerminal.SCHEMA + + "\"")); + assertInvalid( + canonical.replace( + "\"schema\":\"world-start-session-execution-terminal/v1\"", "\"schema\":\"v2\"")); + assertInvalid( + new StringBuilder(canonical).insert(canonical.indexOf("\"schema\""), " ").toString()); + assertThatThrownBy( + () -> WorldStartSessionExecutionTerminal.fromStored(new byte[] {(byte) 0xc3, 0x28})) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("strict UTF-8"); + assertThatThrownBy( + () -> + WorldStartSessionExecutionTerminal.fromStored( + new byte[WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES + 1])) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("byte limit"); + + byte[] tupleReencodedWithoutPadding = + withField( + terminal.canonicalBytes(), + "originalPostAuthorizationTupleBase64", + terminal.originalPostAuthorizationTupleBase64().replaceAll("=+$", "")); + if (!terminal.originalPostAuthorizationTupleBase64().endsWith("=")) { + String padded = terminal.originalPostAuthorizationTupleBase64() + "="; + tupleReencodedWithoutPadding = + withField(terminal.canonicalBytes(), "originalPostAuthorizationTupleBase64", padded); + } + assertInvalid(tupleReencodedWithoutPadding); + } + + @Test + void requiresCanonicalPositiveBigintStringsNonNilUuidsAndExactInputDigest() throws Exception { + WorldStartSessionExecutionTerminal terminal = terminal(originalTuple(), Outcome.COMMITTED); + for (String field : + List.of("accountWorldParticipationFence", "gameSessionOwnerFence", "worldExecutionFence")) { + for (String invalidCounter : List.of("0", "01", "-1", "9223372036854775808", "٣")) { + assertInvalid(withField(terminal.canonicalBytes(), field, invalidCounter)); + } + } + assertInvalid(withField(terminal.canonicalBytes(), "worldExecutionFence", 41)); + assertInvalid( + withField( + terminal.canonicalBytes(), + "accountWorldParticipationId", + "00000000-0000-0000-0000-000000000000")); + + assertThat( + new WorldStartSessionExecutionTerminal( + originalTuple().canonicalBytes(), + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L, + NAMESPACE, + TENANT, + REQUEST_ID, + GAME_INSTANCE_ID, + digest(PREPARATION_INPUT), + PREPARATION_INPUT, + Long.MAX_VALUE, + Outcome.ABORTED) + .worldExecutionFence()) + .isEqualTo(Long.MAX_VALUE); + + assertThatThrownBy( + () -> + new WorldStartSessionExecutionTerminal( + originalTuple().canonicalBytes(), + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L, + NAMESPACE, + TENANT, + REQUEST_ID, + GAME_INSTANCE_ID, + digest("changed input"), + PREPARATION_INPUT, + 41L, + Outcome.COMMITTED)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("preparationInputDigest"); + assertThatThrownBy( + () -> + new WorldStartSessionExecutionTerminal( + originalTuple().canonicalBytes(), + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L, + NAMESPACE, + TENANT, + REQUEST_ID, + GAME_INSTANCE_ID, + digest(PREPARATION_INPUT), + "{ \"selected\" : \"different exact bytes\" }", + 41L, + Outcome.COMMITTED)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("preparationInputDigest"); + } + + @Test + void defensivelyCopiesTupleAndCanonicalBytesAndKeepsPreparationStringUnchanged() { + StartSessionPostAuthorizationExecutionTuple tuple = originalTuple(); + byte[] suppliedTuple = tuple.canonicalBytes(); + WorldStartSessionExecutionTerminal terminal = terminal(tuple, Outcome.COMMITTED); + byte[] stored = terminal.canonicalBytes(); + byte[] exposedTuple = terminal.originalPostAuthorizationTuple(); + suppliedTuple[0] = (byte) '!'; + stored[0] = (byte) '!'; + exposedTuple[0] = (byte) '!'; + + assertThat(terminal.canonicalBytes()[0]).isNotEqualTo((byte) '!'); + assertThat(terminal.originalPostAuthorizationTuple()[0]).isNotEqualTo((byte) '!'); + assertThat(terminal.preparationInputJson()).isEqualTo(PREPARATION_INPUT); + } + + private static WorldStartSessionExecutionTerminal terminal( + StartSessionPostAuthorizationExecutionTuple tuple, Outcome outcome) { + return new WorldStartSessionExecutionTerminal( + tuple.canonicalBytes(), + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L, + NAMESPACE, + TENANT, + REQUEST_ID, + GAME_INSTANCE_ID, + digest(PREPARATION_INPUT), + PREPARATION_INPUT, + 41L, + outcome); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple() { + return originalTuple(91L); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple(long gameTemplateId) { + StartSessionPreAuthorizationReservationTuple preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + REQUEST_ID, + ACTOR, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, NAMESPACE), + new StartSessionOperatorAction.Target(gameTemplateId, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "canonical StartSession owner attempt")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, WORKLOAD, FINGERPRINT, RESERVATION_OWNER, 19L, bundle(preTuple), reference()); + } + + private static byte[] bundle(StartSessionPreAuthorizationReservationTuple tuple) { + return StartSessionAuthorityEvidenceBundleFixture.canonicalBytes( + tuple, + new Values( + ISSUANCE_ID, + "sha256:" + "a".repeat(64), + "17", + "CURRENT", + Instant.parse("2026-10-09T00:00:00Z"), + Instant.parse("2026-10-09T00:05:00Z"), + 1L, + 2L, + 3L, + 4L, + 5L, + 23L, + TOKEN_JTI, + "2", + "3")); + } + + private static StartSessionAuthorityEvidenceBundle.BundleReference reference() { + return new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "23", "18446744073709551615"); + } + + private static byte[] withField(byte[] source, String field, Object replacement) + throws IOException { + Map value = + JSON.readValue(source, new TypeReference>() {}); + value.put(field, replacement); + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private static void assertInvalid(String value) { + assertThatThrownBy( + () -> + WorldStartSessionExecutionTerminal.fromStored( + value.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static void assertInvalid(byte[] value) { + assertThatThrownBy(() -> WorldStartSessionExecutionTerminal.fromStored(value)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static void assertChanged( + WorldStartSessionExecutionTerminal changed, byte[] baselineCanonical) { + assertThat(changed.canonicalBytes()).isNotEqualTo(baselineCanonical); + assertThat(changed.digest()).isNotEqualTo("sha256:" + digestBytes(baselineCanonical)); + assertThat( + WorldStartSessionExecutionTerminal.fromStored(changed.canonicalBytes()) + .canonicalBytes()) + .containsExactly(changed.canonicalBytes()); + } + + private static String digest(String value) { + return "sha256:" + digestBytes(value.getBytes(StandardCharsets.UTF_8)); + } + + private static String digestBytes(byte[] value) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundleTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundleTest.java index 458f7004fb..892c733258 100644 --- a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundleTest.java +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundleTest.java @@ -201,12 +201,13 @@ void rejectsInvalidExpiryAndReferenceOverflowOrMismatch() throws Exception { new StartSessionAuthorityEvidenceBundle.BundleReference( StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "18", "23", "17"))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - decoded.requireReferenceBinding( - new StartSessionAuthorityEvidenceBundle.BundleReference( - StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "24", "17"))) - .isInstanceOf(IllegalArgumentException.class); + assertThat( + org.assertj.core.api.Assertions.catchThrowable( + () -> + decoded.requireReferenceBinding( + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "24", "17")))) + .isNull(); assertThatThrownBy( () -> new StartSessionAuthorityEvidenceBundle.BundleReference( diff --git a/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundleFixture.java b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundleFixture.java new file mode 100644 index 0000000000..2bbc707a18 --- /dev/null +++ b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundleFixture.java @@ -0,0 +1,139 @@ +package net.firedevops.firemud.common.operator; + +import java.io.IOException; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.json.JsonMapper; + +/** Test data builder for canonical human StartSession authority evidence bundles. */ +public final class StartSessionAuthorityEvidenceBundleFixture { + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private StartSessionAuthorityEvidenceBundleFixture() {} + + /** Values which vary across synthetic authority-bundle scenarios. */ + public record Values( + UUID issuanceOperationId, + String sourceEvidenceId, + String sourceEvidenceVersion, + String projectionStatus, + Instant evaluatedAt, + Instant expiresAt, + long issuerAuthGeneration, + long accountAuthorityGeneration, + long tenantAuthorityGeneration, + long membershipAuthorityGeneration, + long membershipVersion, + long issuanceFence, + UUID controlUiTokenJti, + String accountGeneration, + String tenantGeneration) { + public Values { + Objects.requireNonNull(issuanceOperationId); + Objects.requireNonNull(sourceEvidenceId); + Objects.requireNonNull(sourceEvidenceVersion); + Objects.requireNonNull(projectionStatus); + Objects.requireNonNull(evaluatedAt); + Objects.requireNonNull(expiresAt); + Objects.requireNonNull(controlUiTokenJti); + Objects.requireNonNull(accountGeneration); + Objects.requireNonNull(tenantGeneration); + } + } + + /** Builds canonical bytes without invoking the production decoder or its validation rules. */ + public static byte[] canonicalBytes( + StartSessionPreAuthorizationReservationTuple tuple, Values values) { + Objects.requireNonNull(tuple); + Objects.requireNonNull(values); + String actorId = tuple.actor().accountId().toString(); + String tenantId = tuple.action().scope().tenantId().toString(); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", + Map.of( + "tenantId", + tenantId, + "targetNamespace", + tuple.action().scope().targetNamespace()), + "actionFamily", + tuple.actionFamily(), + "applicableAccountId", + actorId, + "applicableTenantId", + tenantId), + "accountProjectionEvidence", + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + values.sourceEvidenceId(), + "sourceEvidenceVersion", + values.sourceEvidenceVersion(), + "projectionStatus", + values.projectionStatus(), + "evaluatedAt", + values.evaluatedAt().toString(), + "expiresAt", + values.expiresAt().toString()), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", + values.issuanceOperationId().toString(), + "controlPlaneRequestId", + tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", + tuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", + values.issuerAuthGeneration(), + "accountAuthorityGeneration", + values.accountAuthorityGeneration(), + "tenantAuthorityGeneration", + Map.of(tenantId, values.tenantAuthorityGeneration()), + "membershipAuthorityGeneration", + Map.of(tenantId, values.membershipAuthorityGeneration()), + "privateRealmGrantVersions", + List.of()), + "membershipVersion", + Map.of(tenantId, values.membershipVersion()), + "issuanceFence", + Long.toString(values.issuanceFence()), + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + actorId, + "controlUiTokenJti", + values.controlUiTokenJti().toString(), + "role", + "tenantAdmin", + "accountGeneration", + values.accountGeneration(), + "tenantGeneration", + values.tenantGeneration())); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException impossible) { + throw new IllegalStateException(impossible); + } + } +} diff --git a/services/common-security/build.gradle.kts b/services/common-security/build.gradle.kts index 4109423d1f..ae0af42f53 100644 --- a/services/common-security/build.gradle.kts +++ b/services/common-security/build.gradle.kts @@ -9,6 +9,7 @@ dependencies { implementation(libs.jjwt.api) implementation(libs.spring.aop) implementation(libs.spring.boot.starter) + implementation("org.springframework:spring-tx") compileOnly(libs.spring.boot.starter.web) implementation(libs.aspectjweaver) compileOnly(libs.grpc.spring.boot.starter) @@ -17,4 +18,5 @@ dependencies { runtimeOnly(libs.jjwt.jackson) testImplementation(libs.spring.boot.starter.test) + testImplementation(testFixtures(project(":common-platform-core"))) } diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationAcquisitionClient.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationAcquisitionClient.java new file mode 100644 index 0000000000..6a1f01cf5b --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationAcquisitionClient.java @@ -0,0 +1,349 @@ +package net.firedevops.firemud.common.account.startsession; + +import com.google.protobuf.Message; +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountStartSessionWorldParticipationAcquisitionServiceGrpc; +import net.firedevops.firemud.account.v1.AcquireStartSessionWorldParticipationRequest; +import net.firedevops.firemud.account.v1.AcquireStartSessionWorldParticipationResponse; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +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; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** File-backed mTLS client for Account's unregistered World-participation acquisition. */ +public final class AccountStartSessionWorldParticipationAcquisitionClient + extends AbstractReloadingBlockingGrpcClient< + AccountStartSessionWorldParticipationAcquisitionServiceGrpc + .AccountStartSessionWorldParticipationAcquisitionServiceBlockingStub> { + private static final int MAX_REQUEST_BYTES = + WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES + + StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + + 2 * 1024; + private static final int MAX_RESPONSE_BYTES = + MAX_REQUEST_BYTES + + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.MAX_RESPONSE_BYTES + + 2 * 1024; + private static final long CALL_DEADLINE_SECONDS = 5L; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public AccountStartSessionWorldParticipationAcquisitionClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + AccountStartSessionWorldParticipationAcquisitionClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when an owning World component explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Account World-participation client is closed"); + } + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Account World-participation stub is unavailable"); + } + initialized = true; + } + + /** Acquires and validates the exact original participation response outside ambient SQL. */ + public AcquireStartSessionWorldParticipationResponse acquire( + AcquireStartSessionWorldParticipationRequest request) { + requireWorkloadOnlyContext(); + validateRequest(request, workloadNamespace); + try { + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .acquireStartSessionWorldParticipation(request); + validateResponse(request, workloadNamespace, response); + return response; + } catch (StatusRuntimeException failure) { + throw Status.fromCode(failure.getStatus().getCode()).asRuntimeException(); + } catch (IllegalArgumentException malformed) { + throw new IllegalStateException( + "Account returned invalid original StartSession World participation evidence", malformed); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountStartSessionWorldParticipationAcquisitionServiceGrpc + .AccountStartSessionWorldParticipationAcquisitionServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return AccountStartSessionWorldParticipationAcquisitionServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(MAX_RESPONSE_BYTES) + .withMaxOutboundMessageSize(MAX_REQUEST_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private AccountStartSessionWorldParticipationAcquisitionServiceGrpc + .AccountStartSessionWorldParticipationAcquisitionServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Account World-participation client is not initialized and available"); + } + return currentStub; + } + + private static void requireWorkloadOnlyContext() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Account World-participation acquisition requires no ambient SQL or synchronization"); + } + if (SessionContext.hasAuthenticatedCallerContext()) { + throw new IllegalStateException( + "Account World-participation acquisition requires a workload-only caller context"); + } + } + + private static void validateRequest( + AcquireStartSessionWorldParticipationRequest request, String expectedNamespace) { + Objects.requireNonNull(request, "World-participation acquisition request is required"); + requireClosed(request, "request"); + if (request.getSerializedSize() > MAX_REQUEST_BYTES + || request.getSchemaVersion() != 1 + || !GrpcPeerIdentity.isValidNamespace(expectedNamespace) + || !expectedNamespace.equals(request.getTargetNamespace())) { + throw new IllegalArgumentException("Unsupported or oversized World-participation request"); + } + UUID acquisitionId = canonicalUuid(request.getAcquisitionRequestId(), "acquisitionRequestId"); + UUID mutationId = canonicalUuid(request.getGameSessionOwnerMutationId(), "ownerMutationId"); + UUID attemptId = canonicalUuid(request.getGameSessionOwnerAttemptId(), "ownerAttemptId"); + UUID instanceId = canonicalUuid(request.getCanonicalGameInstanceId(), "gameInstanceId"); + if (request.getGameSessionOwnerFence() <= 0L) { + throw new IllegalArgumentException("Game Session owner fence must be positive"); + } + byte[] tupleBytes = request.getOriginalPostAuthorizationTuple().toByteArray(); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(tupleBytes); + if (tupleBytes.length == 0 + || tupleBytes.length > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + || !MessageDigest.isEqual(tupleBytes, tuple.canonicalBytes()) + || !StartSessionOperatorAction.ACTION_FAMILY.equals( + tuple.preAuthorizationTuple().actionFamily()) + || !StartSessionOperatorAction.OWNER_SERVICE.equals( + tuple.preAuthorizationTuple().targetOwner()) + || !expectedNamespace.equals( + tuple.preAuthorizationTuple().action().scope().targetNamespace())) { + throw new IllegalArgumentException("Exact canonical original StartSession tuple required"); + } + Set occupied = new HashSet<>(); + occupied.add(mutationId); + occupied.add(attemptId); + occupied.add(instanceId); + occupied.add(tuple.reservationOwnerId()); + occupied.add(tuple.preAuthorizationTuple().actor().accountId()); + occupied.add(tuple.preAuthorizationTuple().action().scope().tenantId()); + occupied.add( + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()) + .issuanceOperationId()); + if (tuple.controlPlaneRequestId().equals(acquisitionId.toString()) + || occupied.contains(acquisitionId)) { + throw new IllegalArgumentException( + "Acquisition correlation must be independent of retained operation identities"); + } + String preparation = request.getPreparationInputJson(); + if (preparation.isBlank() + || !StandardCharsets.UTF_8.newEncoder().canEncode(preparation) + || preparation.getBytes(StandardCharsets.UTF_8).length + > WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES + || !SHA256.matcher(request.getPreparationInputDigest()).matches() + || !request + .getPreparationInputDigest() + .equals(digestPrefixed(preparation.getBytes(StandardCharsets.UTF_8)))) { + throw new IllegalArgumentException( + "Exact bounded World preparation input and digest required"); + } + var canonical = + AcquireStartSessionWorldParticipationRequest.newBuilder() + .setSchemaVersion(1) + .setAcquisitionRequestId(acquisitionId.toString()) + .setTargetNamespace(expectedNamespace) + .setOriginalPostAuthorizationTuple(request.getOriginalPostAuthorizationTuple()) + .setGameSessionOwnerMutationId(mutationId.toString()) + .setGameSessionOwnerAttemptId(attemptId.toString()) + .setGameSessionOwnerFence(request.getGameSessionOwnerFence()) + .setCanonicalGameInstanceId(instanceId.toString()) + .setPreparationInputJson(preparation) + .setPreparationInputDigest(request.getPreparationInputDigest()) + .build(); + if (!canonical.equals(request)) { + throw new IllegalArgumentException("World-participation request is not canonical"); + } + } + + private static void validateResponse( + AcquireStartSessionWorldParticipationRequest expected, + String expectedNamespace, + AcquireStartSessionWorldParticipationResponse response) { + Objects.requireNonNull(response, "Account World-participation response is required"); + requireClosed(response, "response"); + if (response.getSerializedSize() > MAX_RESPONSE_BYTES + || !response.hasRequest() + || !response.hasOriginalAttemptEvidence()) { + throw new IllegalArgumentException("Missing or oversized World-participation response"); + } + requireClosed(response.getRequest(), "request echo"); + if (!expected.equals(response.getRequest()) + || !expectedNamespace.equals(response.getRequest().getTargetNamespace())) { + throw new IllegalArgumentException("Account changed the exact acquisition request"); + } + canonicalUuid(response.getAccountWorldParticipationId(), "accountWorldParticipationId"); + if (response.getAccountWorldParticipationFence() <= 0L) { + throw new IllegalArgumentException("Account World participation fence must be positive"); + } + var original = + StartSessionPostAuthorizationExecutionTuple.decode( + expected.getOriginalPostAuthorizationTuple().toByteArray()); + var observation = response.getOriginalAttemptEvidence(); + requireClosed(observation, "original attempt evidence"); + var observedRequest = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromRequest(observation.getRequest()); + var exactObservation = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + observedRequest, observation); + if (!OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE.equals( + exactObservation.phaseState()) + || !expectedNamespace.equals(observedRequest.targetNamespace()) + || !MessageDigest.isEqual( + expected.getOriginalPostAuthorizationTuple().toByteArray(), + observedRequest.canonicalPostAuthorizationTuple()) + || !canonicalUuid(expected.getGameSessionOwnerMutationId(), "ownerMutationId") + .equals(observedRequest.expectedOwnerMutationId()) + || !canonicalUuid(expected.getGameSessionOwnerAttemptId(), "ownerAttemptId") + .equals(observedRequest.expectedOwnerAttemptId()) + || expected.getGameSessionOwnerFence() != observedRequest.expectedOwnerFence() + || !MessageDigest.isEqual( + StartSessionAccountRedemptionProjection.fromOriginalTuple(original), + exactObservation.accountRedemptionProjection()) + || !observation.equals( + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(exactObservation))) { + throw new IllegalArgumentException( + "Account changed the original tuple, Game Session attempt, or full redemption projection"); + } + } + + private static void requireClosed(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException( + "World-participation " + label + " contains unknown fields"); + } + } + + private static UUID canonicalUuid(String value, String field) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || NIL_UUID.equals(parsed)) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (RuntimeException malformed) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID", malformed); + } + } + + private static String digestPrefixed(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "Account World-participation acquisition requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null + || configuredPath.isBlank() + || configuredPath.trim().startsWith("classpath:")) { + throw new IllegalArgumentException( + "Account World-participation acquisition requires file-backed mTLS material"); + } + Path path; + try { + path = Path.of(configuredPath.trim()); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Account World-participation " + label + " must be file-backed", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Account World-participation " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationAcquisitionClientMtlsTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationAcquisitionClientMtlsTest.java new file mode 100644 index 0000000000..beebb31c6e --- /dev/null +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationAcquisitionClientMtlsTest.java @@ -0,0 +1,723 @@ +package net.firedevops.firemud.common.account.startsession; + +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.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import io.grpc.ForwardingServerCall; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +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.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.UnaryOperator; +import net.firedevops.firemud.account.v1.AccountStartSessionWorldParticipationAcquisitionServiceGrpc; +import net.firedevops.firemud.account.v1.AcquireStartSessionWorldParticipationRequest; +import net.firedevops.firemud.account.v1.AcquireStartSessionWorldParticipationResponse; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +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.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture.Values; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +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.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** Socket mTLS client proof with a synthetic mocked Account acquisition backend, not PostgreSQL. */ +class AccountStartSessionWorldParticipationAcquisitionClientMtlsTest { + private static final String NAMESPACE = "world-runtime"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/world-runtime/sa/account-service"; + private static final String WORLD_URI = + "spiffe://firemud/ns/world-runtime/sa/world-management-service"; + private static final String STORE_PASSWORD = "synthetic-world-participation-test-password"; + private static final UUID ACCOUNT_ID = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TENANT_ID = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID MUTATION_ID = uuid("b9d2f9d9-0438-42c8-829e-fd3392cd9d21"); + private static final UUID ATTEMPT_ID = uuid("4a3fc69f-a18a-4b94-b1d1-2e8b4c3f0e4b"); + private static final UUID GAME_INSTANCE_ID = uuid("c0e30aea-1549-43d9-93af-0e44a3deae32"); + private static final UUID PARTICIPATION_ID = uuid("a8c1e8c8-f237-41b7-918d-ec2281bcac10"); + private static final String PREPARATION_JSON = + "{\"selected\":\"immutable source\",\"revision\":3}"; + private static final Instant ORIGINAL_LEASE_EXPIRY = Instant.parse("2026-10-12T00:00:00Z"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @TempDir static Path temporaryDirectory; + private static TestPki pki; + private Server server; + private AccountStartSessionWorldParticipationAcquisitionClient client; + + @BeforeAll + static void createSyntheticWorkloadCertificates() throws Exception { + pki = TestPki.create(temporaryDirectory); + } + + @AfterEach + void stopTransportAndClearThreadState() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void loopbackMtlsReturnsExactBoundParticipationAndCompleteObservation() throws Exception { + var wireRequest = request(NAMESPACE); + var expected = response(wireRequest); + var backend = mock(WorldParticipationAcquisitionBackend.class); + when(backend.acquire(any())).thenReturn(expected); + AtomicInteger handlers = startServer(backend, UnaryOperator.identity()); + client = newClient(server.getPort(), pki.worldClient()); + client.init(); + + var actual = client.acquire(wireRequest); + + assertThat(actual.getRequest()).isEqualTo(wireRequest); + assertThat(actual.getAccountWorldParticipationId()).isEqualTo(PARTICIPATION_ID.toString()); + assertThat(actual.getAccountWorldParticipationFence()).isEqualTo(31L); + assertThat(actual.getOriginalAttemptEvidence()) + .isEqualTo(expected.getOriginalAttemptEvidence()); + assertThat(handlers).hasValue(1); + ArgumentCaptor captured = + ArgumentCaptor.forClass(AcquireStartSessionWorldParticipationRequest.class); + verify(backend).acquire(captured.capture()); + assertThat(captured.getValue()).isEqualTo(wireRequest); + } + + @Test + void rejectsEchoAndOriginalEvidenceSubstitutionFromTheRemotePeer() throws Exception { + var wireRequest = request(NAMESPACE); + var backend = mock(WorldParticipationAcquisitionBackend.class); + when(backend.acquire(any())).thenReturn(response(wireRequest)); + AtomicInteger handlers = + startServer( + backend, + response -> + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setAcquisitionRequestId("11111111-1111-4111-8111-111111111111")) + .build()); + client = newClient(server.getPort(), pki.worldClient()); + client.init(); + assertThatThrownBy(() -> client.acquire(wireRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid original StartSession World participation evidence"); + assertThat(handlers).hasValue(1); + + stopCurrentTransport(); + when(backend.acquire(any())).thenReturn(response(wireRequest)); + handlers = + startServer( + backend, + response -> { + var observation = response.getOriginalAttemptEvidence(); + var changed = + observation.toBuilder() + .setRequest( + observation.getRequest().toBuilder() + .setExpectedOwnerFence( + observation.getRequest().getExpectedOwnerFence() + 1)) + .build(); + return response.toBuilder().setOriginalAttemptEvidence(changed).build(); + }); + client = newClient(server.getPort(), pki.worldClient()); + client.init(); + assertThatThrownBy(() -> client.acquire(wireRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid original StartSession World participation evidence"); + assertThat(handlers).hasValue(1); + } + + @Test + void wrongAuthenticatedWorkloadsAndLocalNamespaceMismatchAreRejected() throws Exception { + var wireRequest = request(NAMESPACE); + var backend = mock(WorldParticipationAcquisitionBackend.class); + AtomicInteger handlers = startServer(backend, UnaryOperator.identity()); + for (TestIdentity identity : List.of(pki.wrongServiceClient(), pki.otherNamespaceClient())) { + client = newClient(server.getPort(), identity); + client.init(); + assertThatThrownBy(() -> client.acquire(wireRequest)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + client.close(); + client = null; + } + assertThat(handlers).hasValue(2); + verifyNoInteractions(backend); + + var validPeerClient = newClient(server.getPort(), pki.worldClient()); + client = validPeerClient; + client.init(); + assertThatThrownBy(() -> client.acquire(request("default"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unsupported or oversized World-participation request"); + assertThat(handlers).hasValue(2); + verifyNoInteractions(backend); + } + + @Test + void wrongAccountServerWorkloadIsRejectedBeforeSendingTheRequest() throws Exception { + var backend = mock(WorldParticipationAcquisitionBackend.class); + AtomicInteger handlers = startServer(backend, UnaryOperator.identity(), pki.wrongServer()); + client = newClient(server.getPort(), pki.worldClient()); + client.init(); + + assertThatThrownBy(() -> client.acquire(request(NAMESPACE))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(handlers).hasValue(0); + verifyNoInteractions(backend); + } + + @Test + void rejectsAmbientSqlAndEndUserContextBeforeSending() throws Exception { + var backend = mock(WorldParticipationAcquisitionBackend.class); + AtomicInteger handlers = startServer(backend, UnaryOperator.identity()); + client = newClient(server.getPort(), pki.worldClient()); + client.init(); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.acquire(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient SQL"); + TransactionSynchronizationManager.clear(); + SessionContext.setContext("123", List.of(), Map.of()); + assertThatThrownBy(() -> client.acquire(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("workload-only"); + assertThat(handlers).hasValue(0); + verifyNoInteractions(backend); + } + + private AtomicInteger startServer( + WorldParticipationAcquisitionBackend backend, + UnaryOperator responseMutation) + throws Exception { + return startServer(backend, responseMutation, pki.accountServer()); + } + + private AtomicInteger startServer( + WorldParticipationAcquisitionBackend backend, + UnaryOperator responseMutation, + TestIdentity serverIdentity) + throws Exception { + AtomicInteger handlers = new AtomicInteger(); + var service = + new AccountStartSessionWorldParticipationAcquisitionServiceGrpc + .AccountStartSessionWorldParticipationAcquisitionServiceImplBase() { + @Override + public void acquireStartSessionWorldParticipation( + AcquireStartSessionWorldParticipationRequest request, + StreamObserver observer) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + observer.onError(Status.UNAUTHENTICATED.asRuntimeException()); + return; + } + if (!WORLD_URI.equals(peer.uri()) + || !NAMESPACE.equals(peer.namespace()) + || SessionContext.hasAuthenticatedCallerContext()) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + try { + observer.onNext(backend.acquire(request)); + observer.onCompleted(); + } catch (RuntimeException failure) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + } + }; + ServerInterceptor countHandlers = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + handlers.incrementAndGet(); + return next.startCall(call, metadata); + } + }; + ServerInterceptor mutateResponse = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + var transformedCall = + new ForwardingServerCall.SimpleForwardingServerCall(call) { + @Override + @SuppressWarnings("unchecked") + public void sendMessage(RespT message) { + if (message instanceof AcquireStartSessionWorldParticipationResponse response) { + super.sendMessage((RespT) responseMutation.apply(response)); + } else { + super.sendMessage(message); + } + } + }; + return next.startCall(transformedCall, metadata); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize(32 * 1024 * 1024) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverIdentity.privateKey(), serverIdentity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, countHandlers, new GrpcPeerIdentityInterceptor(), mutateResponse)) + .build() + .start(); + return handlers; + } + + private AccountStartSessionWorldParticipationAcquisitionClient newClient( + int port, TestIdentity identity) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + port); + return new AccountStartSessionWorldParticipationAcquisitionClient( + endpoints, + pki.clientProperties(temporaryDirectory, identity), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static AcquireStartSessionWorldParticipationRequest request(String namespace) { + return AcquireStartSessionWorldParticipationRequest.newBuilder() + .setSchemaVersion(1) + .setAcquisitionRequestId("263a218e-1752-47f2-97c3-6273b2ea9f15") + .setTargetNamespace(namespace) + .setOriginalPostAuthorizationTuple(ByteString.copyFrom(originalTuple().canonicalBytes())) + .setGameSessionOwnerMutationId(MUTATION_ID.toString()) + .setGameSessionOwnerAttemptId(ATTEMPT_ID.toString()) + .setGameSessionOwnerFence(37L) + .setCanonicalGameInstanceId(GAME_INSTANCE_ID.toString()) + .setPreparationInputJson(PREPARATION_JSON) + .setPreparationInputDigest(digest(PREPARATION_JSON)) + .build(); + } + + private static AcquireStartSessionWorldParticipationResponse response( + AcquireStartSessionWorldParticipationRequest wire) { + var tuple = + StartSessionPostAuthorizationExecutionTuple.decode( + wire.getOriginalPostAuthorizationTuple().toByteArray()); + var observationRequest = + new Request( + uuid("4d66578e-a7cd-4a37-8cfb-30aa4c0c23b3"), + NAMESPACE, + tuple.canonicalBytes(), + ATTEMPT_ID, + MUTATION_ID, + 37L); + var observation = + new Result( + observationRequest, + ORIGINAL_LEASE_EXPIRY, + StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple)); + return AcquireStartSessionWorldParticipationResponse.newBuilder() + .setRequest(wire) + .setAccountWorldParticipationId(PARTICIPATION_ID.toString()) + .setAccountWorldParticipationFence(31L) + .setOriginalAttemptEvidence( + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(observation)) + .build(); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple() { + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "world-participation-mtls-test", + ACCOUNT_ID, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, NAMESPACE), + new StartSessionOperatorAction.Target( + 91L, uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a")), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "synthetic World participation mTLS proof")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"), + 19L, + authorityBundle(preTuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + return StartSessionAuthorityEvidenceBundleFixture.canonicalBytes( + tuple, + new Values( + uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"), + "sha256:" + "a".repeat(64), + "17", + "CURRENT", + Instant.parse("2026-10-09T00:00:00Z"), + Instant.parse("2026-10-10T00:00:00Z"), + 1L, + 2L, + 3L, + 4L, + 5L, + 23L, + uuid("a681bba7-c215-4cf1-a35b-14348912cbdc"), + "2", + "3")); + } + + private static String digest(String value) { + return digest(value.getBytes(StandardCharsets.UTF_8)); + } + + private static String digest(byte[] value) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private void stopCurrentTransport() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + private interface WorldParticipationAcquisitionBackend { + AcquireStartSessionWorldParticipationResponse acquire( + AcquireStartSessionWorldParticipationRequest request); + } + + private record TestPki( + X509Certificate caCertificate, + TestIdentity accountServer, + TestIdentity wrongServer, + TestIdentity worldClient, + TestIdentity wrongServiceClient, + TestIdentity otherNamespaceClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("world-participation-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD World participation test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("world-participation-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + X509Certificate ca = readCertificate(caFile); + return new TestPki( + ca, + issueIdentity(directory, caStore, caFile, "account-server", ACCOUNT_URI, true), + issueIdentity( + directory, + caStore, + caFile, + "wrong-account-server", + "spiffe://firemud/ns/world-runtime/sa/account-other", + true), + issueIdentity(directory, caStore, caFile, "world-client", WORLD_URI, false), + issueIdentity( + directory, + caStore, + caFile, + "wrong-service-client", + "spiffe://firemud/ns/world-runtime/sa/game-session-service", + false), + issueIdentity( + directory, + caStore, + caFile, + "other-namespace-client", + "spiffe://firemud/ns/other-runtime/sa/world-management-service", + false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + var properties = new CommonGrpcClientProperties(); + properties.setPlaintext(false); + properties.setCertChain( + writePem( + directory.resolve("client-" + identity.certificate().getSerialNumber() + ".crt"), + "CERTIFICATE", + identity.certificate().getEncoded()) + .toString()); + properties.setPrivateKey( + writePem( + directory.resolve("client-" + identity.certificate().getSerialNumber() + ".key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()) + .toString()); + properties.setCaCert( + writePem( + directory.resolve("trusted-test-ca.crt"), + "CERTIFICATE", + caCertificate.getEncoded()) + .toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java index a3cc8ef137..22eca3e89a 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java @@ -29,6 +29,7 @@ import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; import net.firedevops.firemud.common.grpc.GrpcTlsMaterialResolver; import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; /** @@ -146,6 +147,9 @@ public AuthorizationReference issueHuman( response.getBundleReference(), response.getUnknownFields().asMap().isEmpty(), response.getAuthenticatedLoggingWorkloadIdentity(), + response.getOriginalAccountPostAuthorizationTuple().toByteArray(), + reservationOwnerId, + reservationClaimFence, tuple); } @@ -181,6 +185,9 @@ public AuthorizationReference recover( response.getBundleReference(), response.getUnknownFields().asMap().isEmpty(), response.getAuthenticatedLoggingWorkloadIdentity(), + response.getOriginalAccountPostAuthorizationTuple().toByteArray(), + reservationOwnerId, + reservationClaimFence, tuple); } @@ -229,6 +236,9 @@ private AuthorizationReference validateResponse( AuthorityEvidenceBundleReference wireReference, boolean hasNoUnknownFields, String authenticatedLoggingWorkloadIdentity, + byte[] originalAccountPostAuthorizationTuple, + UUID reservationOwnerId, + long reservationClaimFence, StartSessionPreAuthorizationReservationTuple tuple) { try { if (!hasNoUnknownFields || !hasExpiry || !hasBundleReference) { @@ -264,6 +274,21 @@ private AuthorizationReference validateResponse( if (!wireReference.getUnknownFields().asMap().isEmpty()) { throw malformedResponse(); } + StartSessionPostAuthorizationExecutionTuple expectedTuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + tuple, + authenticatedLoggingWorkloadIdentity, + fingerprint, + reservationOwnerId, + reservationClaimFence, + authorityEvidenceBundle, + reference); + StartSessionPostAuthorizationExecutionTuple accountTuple = + StartSessionPostAuthorizationExecutionTuple.decode(originalAccountPostAuthorizationTuple); + if (!java.security.MessageDigest.isEqual( + expectedTuple.canonicalBytes(), accountTuple.canonicalBytes())) { + throw malformedResponse(); + } return new AuthorizationReference( opaqueReference, fingerprint, @@ -271,7 +296,8 @@ private AuthorizationReference validateResponse( authorityEvidenceBundle, reference, authenticatedLoggingWorkloadIdentity, - bundle); + bundle, + accountTuple); } catch (IllegalStateException expected) { throw expected; } catch (RuntimeException malformed) { @@ -342,6 +368,7 @@ public static final class AuthorizationReference { private final StartSessionAuthorityEvidenceBundle.BundleReference bundleReference; private final String authenticatedLoggingWorkloadIdentity; private final StartSessionAuthorityEvidenceBundle decodedBundle; + private final StartSessionPostAuthorizationExecutionTuple postAuthorizationTuple; private AuthorizationReference( String operatorAuthorizationReference, @@ -350,7 +377,8 @@ private AuthorizationReference( byte[] authorityEvidenceBundle, StartSessionAuthorityEvidenceBundle.BundleReference bundleReference, String authenticatedLoggingWorkloadIdentity, - StartSessionAuthorityEvidenceBundle decodedBundle) { + StartSessionAuthorityEvidenceBundle decodedBundle, + StartSessionPostAuthorizationExecutionTuple postAuthorizationTuple) { this.operatorAuthorizationReference = operatorAuthorizationReference; this.authorizationReferenceFingerprint = authorizationReferenceFingerprint; this.expiresAt = expiresAt; @@ -358,6 +386,7 @@ private AuthorizationReference( this.bundleReference = bundleReference; this.authenticatedLoggingWorkloadIdentity = authenticatedLoggingWorkloadIdentity; this.decodedBundle = decodedBundle; + this.postAuthorizationTuple = postAuthorizationTuple; } public String operatorAuthorizationReference() { @@ -389,6 +418,11 @@ public StartSessionAuthorityEvidenceBundle decodedBundle() { return decodedBundle; } + /** Exact canonical tuple authored by Account from its retained original issuance evidence. */ + public StartSessionPostAuthorizationExecutionTuple postAuthorizationTuple() { + return postAuthorizationTuple; + } + @Override public String toString() { return "AuthorizationReference[operatorAuthorizationReference=, " @@ -398,6 +432,7 @@ public String toString() { + bundleReference + ", authenticatedLoggingWorkloadIdentity=" + authenticatedLoggingWorkloadIdentity + + ", postAuthorizationTuple=" + "]"; } } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java index 17ea2e6784..51a4282ad7 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.loggingadmin.operator; +import java.security.MessageDigest; import java.util.Objects; import java.util.Optional; import java.util.UUID; @@ -120,14 +121,22 @@ private Result persistExactAccountResponse( AuthorizationReference accountResponse) { Objects.requireNonNull(accountResponse, "validated Account response is required"); StartSessionPostAuthorizationExecutionTuple postAuthorizationTuple = + accountResponse.postAuthorizationTuple(); + ClaimEvidence claimEvidence = claim.claimEvidence(); + StartSessionPostAuthorizationExecutionTuple expectedTuple = StartSessionPostAuthorizationExecutionTuple.createHuman( sharedTuple(tuple), accountResponse.authenticatedLoggingWorkloadIdentity(), accountResponse.authorizationReferenceFingerprint(), - claim.claimEvidence().reservationOwnerId(), - claim.claimEvidence().reservationClaimFence(), + claimEvidence.reservationOwnerId(), + claimEvidence.reservationClaimFence(), accountResponse.authorityEvidenceBundle(), accountResponse.bundleReference()); + if (!MessageDigest.isEqual( + expectedTuple.canonicalBytes(), postAuthorizationTuple.canonicalBytes())) { + throw new IllegalArgumentException( + "Account post-authorization tuple differs from its authorization response"); + } AuthorizationCompletion completion = reservations.completeAuthorization(claim, postAuthorizationTuple); if (!completion.transitioned()) { diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java index a397195770..d84515884e 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java @@ -45,6 +45,7 @@ import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -102,8 +103,14 @@ void issueAndRecoverUseExactTupleAndClaimIdentityAndReturnValidatedOriginalBytes assertThat(issued.authenticatedLoggingWorkloadIdentity()) .isEqualTo(LOGGING_WORKLOAD_IDENTITY); assertThat(issued.decodedBundle().controlPlaneRequestId()).isEqualTo("client-βeta"); + assertThat(issued.postAuthorizationTuple().canonicalBytes()) + .containsExactly( + ownerTupleBytes( + tuple, bundle, reference(), RESERVATION_OWNER, 9L, LOGGING_WORKLOAD_IDENTITY)); assertThat(recovered.authorityEvidenceBundle()).containsExactly(bundle); assertThat(recovered.operatorAuthorizationReference()).isEqualTo(OPAQUE_REFERENCE); + assertThat(recovered.postAuthorizationTuple().canonicalBytes()) + .containsExactly(issued.postAuthorizationTuple().canonicalBytes()); assertThat(recovered.authenticatedLoggingWorkloadIdentity()) .isEqualTo(LOGGING_WORKLOAD_IDENTITY); @@ -212,6 +219,7 @@ void rejectsMalformedUnknownChangedOrExpiredAccountResponses() throws Exception assertRejected(tuple, valid.toBuilder().setUnknownFields(unknownFields()).build()); assertRejected(tuple, valid.toBuilder().clearExpiresAt().build()); assertRejected(tuple, valid.toBuilder().clearBundleReference().build()); + assertRejected(tuple, valid.toBuilder().clearOriginalAccountPostAuthorizationTuple().build()); assertRejected( tuple, valid.toBuilder() @@ -220,10 +228,95 @@ void rejectsMalformedUnknownChangedOrExpiredAccountResponses() throws Exception .setUnknownFields(unknownFields()) .build()) .build()); + IssueHumanOperatorAuthorizationReferenceResponse distinctSourceAndIssuanceFences = + valid.toBuilder() + .setBundleReference(valid.getBundleReference().toBuilder().setSourceFence("24").build()) + .build(); + assertRejected(tuple, distinctSourceAndIssuanceFences); + byte[] distinctTuple = + ownerTupleBytes( + tuple, + validBundle, + valid.getBundleReference().toBuilder().setSourceFence("24").build(), + RESERVATION_OWNER, + 9L, + LOGGING_WORKLOAD_IDENTITY); + IssueHumanOperatorAuthorizationReferenceResponse independentSourceFence = + valid.toBuilder() + .setBundleReference(valid.getBundleReference().toBuilder().setSourceFence("24").build()) + .setOriginalAccountPostAuthorizationTuple(ByteString.copyFrom(distinctTuple)) + .build(); + StartSessionOperatorAuthorizationClient.AuthorizationReference accepted = + assertAccepted(tuple, independentSourceFence); + assertThat(accepted.bundleReference().sourceFence()).isEqualTo("24"); + assertThat(accepted.decodedBundle().issuanceFence()).isEqualTo("23"); + assertThat(accepted.postAuthorizationTuple().bundleReference().sourceFence()).isEqualTo("24"); assertRejected( tuple, valid.toBuilder() - .setBundleReference(valid.getBundleReference().toBuilder().setSourceFence("24").build()) + .setBundleReference( + valid.getBundleReference().toBuilder().setSourceVersion("18").build()) + .build()); + assertRejected( + tuple, + valid.toBuilder() + .setBundleReference( + valid.getBundleReference().toBuilder().setBundleVersion("unsupported").build()) + .build()); + assertRejected( + tuple, + valid.toBuilder() + .setBundleReference( + valid.getBundleReference().toBuilder().setLinearization("4").build()) + .build()); + assertRejected( + tuple, + valid.toBuilder() + .setOriginalAccountPostAuthorizationTuple( + ByteString.copyFrom( + ownerTupleBytes( + tuple, + validBundle, + valid.getBundleReference().toBuilder().setSourceFence("24").build(), + RESERVATION_OWNER, + 9L, + LOGGING_WORKLOAD_IDENTITY))) + .build()); + String originalTupleJson = + new String( + valid.getOriginalAccountPostAuthorizationTuple().toByteArray(), StandardCharsets.UTF_8); + assertRejected( + tuple, + valid.toBuilder() + .setOriginalAccountPostAuthorizationTuple( + ByteString.copyFrom( + originalTupleJson + .replace("\"sourceVersion\":\"17\"", "\"sourceVersion\":\"18\"") + .getBytes(StandardCharsets.UTF_8))) + .build()); + assertRejected( + tuple, + valid.toBuilder() + .setOriginalAccountPostAuthorizationTuple( + ByteString.copyFrom( + originalTupleJson + .replace( + "\"bundleVersion\":\"authorityEvidenceBundle/v1\"", + "\"bundleVersion\":\"authorityEvidenceBundle/v2\"") + .getBytes(StandardCharsets.UTF_8))) + .build()); + assertRejected( + tuple, + valid.toBuilder() + .setOriginalAccountPostAuthorizationTuple( + ByteString.copyFrom( + ownerTupleBytes( + tuple, + validBundle, + valid.getBundleReference().toBuilder().setLinearization("4").build(), + RESERVATION_OWNER, + 9L, + LOGGING_WORKLOAD_IDENTITY))) .build()); assertRejected( tuple, @@ -361,6 +454,21 @@ private void assertRejected( } } + private StartSessionOperatorAuthorizationClient.AuthorizationReference assertAccepted( + StartSessionPreAuthorizationReservationTuple tuple, + IssueHumanOperatorAuthorizationReferenceResponse response) + throws Exception { + var stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.issueHumanOperatorAuthorizationReference(any())).thenReturn(response); + try (TestClient client = new TestClient(stub, fileBackedTlsProperties())) { + return client.issueHuman(tuple, CONTROL_UI_TOKEN, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L); + } + } + private void assertRecoverRejected( StartSessionPreAuthorizationReservationTuple tuple, RecoverOperatorAuthorizationReferenceResponse response) @@ -386,6 +494,10 @@ private static IssueHumanOperatorAuthorizationReferenceResponse issueResponse( .setAuthorityEvidenceBundle(ByteString.copyFrom(bundle)) .setBundleReference(reference()) .setAuthenticatedLoggingWorkloadIdentity(LOGGING_WORKLOAD_IDENTITY) + .setOriginalAccountPostAuthorizationTuple( + ByteString.copyFrom( + ownerTupleBytes( + tuple, bundle, reference(), RESERVATION_OWNER, 9L, LOGGING_WORKLOAD_IDENTITY))) .build(); } @@ -398,9 +510,35 @@ private static RecoverOperatorAuthorizationReferenceResponse recoverResponse( .setAuthorityEvidenceBundle(ByteString.copyFrom(bundle)) .setBundleReference(reference()) .setAuthenticatedLoggingWorkloadIdentity(LOGGING_WORKLOAD_IDENTITY) + .setOriginalAccountPostAuthorizationTuple( + ByteString.copyFrom( + ownerTupleBytes( + tuple, bundle, reference(), RESERVATION_OWNER, 9L, LOGGING_WORKLOAD_IDENTITY))) .build(); } + private static byte[] ownerTupleBytes( + StartSessionPreAuthorizationReservationTuple tuple, + byte[] bundle, + AuthorityEvidenceBundleReference wireReference, + UUID reservationOwner, + long reservationClaimFence, + String loggingIdentity) { + return StartSessionPostAuthorizationExecutionTuple.createHuman( + tuple, + loggingIdentity, + FINGERPRINT, + reservationOwner, + reservationClaimFence, + bundle, + new StartSessionAuthorityEvidenceBundle.BundleReference( + wireReference.getBundleVersion(), + wireReference.getSourceVersion(), + wireReference.getSourceFence(), + wireReference.getLinearization())) + .canonicalBytes(); + } + private static Timestamp timestamp(Instant instant) { return Timestamp.newBuilder() .setSeconds(instant.getEpochSecond()) diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java index 7c77d6e25e..6409516c44 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java @@ -107,7 +107,6 @@ void onlyReservationWinnerIssuesAndOnlyDurableOwnerPendingReturnsTransientRefere eq(NOW_MILLIS))) .thenReturn( new StartSessionPreAuthorizationReservationRepository.TransitionResult(pending, true)); - AuthorizationReference response = authorizationReference(tuple); when(accountClient.issueHuman( eq(shared(tuple)), eq(CONTROL_UI_TOKEN), @@ -115,7 +114,12 @@ void onlyReservationWinnerIssuesAndOnlyDurableOwnerPendingReturnsTransientRefere eq(1L), any(UUID.class), eq(1L))) - .thenReturn(response); + .thenAnswer( + invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue())); stubAuthorizationEnrichment(tuple, true, true); Result first = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); @@ -170,6 +174,8 @@ void onlyReservationWinnerIssuesAndOnlyDurableOwnerPendingReturnsTransientRefere .contains(LOGGING_IDENTITY) .doesNotContain(OPAQUE_REFERENCE) .doesNotContain(CONTROL_UI_TOKEN); + assertThat(persistedTuple.getValue()) + .isEqualTo(first.handoff().postAuthorizationTuple().canonicalJson()); persistenceOrder .verify(repository) .beginOwnerExecution( @@ -195,10 +201,9 @@ void recoveryUsesOriginalOwnerAndFreshFenceAndNeverCallsIssue() throws Exception Optional.of( new StartSessionPreAuthorizationReservationRepository.RecoveryClaimResult( pending, ORIGINAL_OWNER))); - AuthorizationReference response = authorizationReference(tuple); when(accountClient.recover( eq(shared(tuple)), eq(ORIGINAL_OWNER), eq(1L), any(UUID.class), eq(3L))) - .thenReturn(response); + .thenAnswer(invocation -> authorizationReference(tuple, ORIGINAL_OWNER, 1L)); stubAuthorizationEnrichment(tuple, true, true); Result result = coordinator.recover(tuple); @@ -206,10 +211,23 @@ void recoveryUsesOriginalOwnerAndFreshFenceAndNeverCallsIssue() throws Exception assertThat(result.progress()).isEqualTo(Progress.OWNER_EXECUTION_PENDING); assertThat(result.handoff().postAuthorizationTuple().reservationOwnerId()) .isEqualTo(ORIGINAL_OWNER); + ArgumentCaptor persistedTuple = ArgumentCaptor.forClass(String.class); ArgumentCaptor currentOwner = ArgumentCaptor.forClass(UUID.class); verify(accountClient) .recover(eq(shared(tuple)), eq(ORIGINAL_OWNER), eq(1L), currentOwner.capture(), eq(3L)); assertThat(currentOwner.getValue()).isNotEqualTo(ORIGINAL_OWNER); + verify(repository) + .completeAuthorization( + eq(tuple), + eq(tuple.mutationDigest()), + eq(ORIGINAL_OWNER), + eq(1L), + eq(currentOwner.getValue()), + eq(3L), + persistedTuple.capture(), + eq(NOW_MILLIS)); + assertThat(persistedTuple.getValue()) + .isEqualTo(result.handoff().postAuthorizationTuple().canonicalJson()); verify(accountClient, never()) .issueHuman(any(), anyString(), any(), anyLong(), any(), anyLong()); } @@ -235,7 +253,6 @@ void issueHumanAndDispatchForwardsOnlyAfterDurableOwnerPendingAndOnlyOnce() thro .thenReturn( new StartSessionPreAuthorizationReservationRepository.TransitionResult( alreadyPending, true)); - AuthorizationReference response = authorizationReference(tuple); when(accountClient.issueHuman( eq(shared(tuple)), eq(CONTROL_UI_TOKEN), @@ -243,7 +260,12 @@ void issueHumanAndDispatchForwardsOnlyAfterDurableOwnerPendingAndOnlyOnce() thro eq(1L), any(UUID.class), eq(1L))) - .thenReturn(response); + .thenAnswer( + invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue())); stubAuthorizationEnrichment(tuple, true, true); GameSessionClient ownerClient = mock(GameSessionClient.class); StartSessionOwnerHandoffResult ownerEcho = ownerEcho(tuple); @@ -317,10 +339,9 @@ void recoverAndDispatchForwardsTheOriginalRecoveredOperationOnce() throws Except Optional.of( new StartSessionPreAuthorizationReservationRepository.RecoveryClaimResult( pending, ORIGINAL_OWNER))); - AuthorizationReference response = authorizationReference(tuple); when(accountClient.recover( eq(shared(tuple)), eq(ORIGINAL_OWNER), eq(1L), any(UUID.class), eq(3L))) - .thenReturn(response); + .thenAnswer(invocation -> authorizationReference(tuple, ORIGINAL_OWNER, 1L)); stubAuthorizationEnrichment(tuple, true, true); GameSessionClient ownerClient = mock(GameSessionClient.class); StartSessionOwnerHandoffResult ownerEcho = ownerEcho(tuple); @@ -412,10 +433,14 @@ void ambiguousOwnerDispatchPropagatesAndExactDuplicateDoesNotRedeliver() throws .thenReturn( new StartSessionPreAuthorizationReservationRepository.TransitionResult( alreadyPending, true)); - AuthorizationReference response = authorizationReference(tuple); when(accountClient.issueHuman( eq(shared(tuple)), anyString(), any(UUID.class), eq(1L), any(UUID.class), eq(1L))) - .thenReturn(response); + .thenAnswer( + invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue())); stubAuthorizationEnrichment(tuple, true, true); GameSessionClient ownerClient = mock(GameSessionClient.class); io.grpc.StatusRuntimeException ambiguous = Status.UNAVAILABLE.asRuntimeException(); @@ -439,10 +464,14 @@ void ambiguousOwnerDispatchPropagatesAndExactDuplicateDoesNotRedeliver() throws void ownerPendingDuplicateCasDoesNotReturnTransientHandoff() throws Exception { StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-owner-duplicate"); stubInitialReservation(tuple); - AuthorizationReference response = authorizationReference(tuple); when(accountClient.issueHuman( eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong())) - .thenReturn(response); + .thenAnswer( + invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue())); stubAuthorizationEnrichment(tuple, true, false); Result result = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); @@ -470,10 +499,12 @@ void ownerPendingDuplicateCasDoesNotReturnTransientHandoff() throws Exception { void ownerPendingTransitionFailureNeverReturnsTransientPayload() throws Exception { StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-owner-stale"); stubInitialReservation(tuple); - AuthorizationReference response = authorizationReference(tuple); when(accountClient.issueHuman( eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong())) - .thenReturn(response); + .thenAnswer( + invocation -> + authorizationReference( + tuple, invocation.getArgument(2), invocation.getArgument(3))); stubAuthorizationEnrichment(tuple, true, true); when(repository.beginOwnerExecution( eq(tuple), @@ -554,10 +585,14 @@ void mismatchedResponseTupleAndStaleClaimAfterAccountReturnAreNotForwarded() thr StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-mismatch"); StartSessionPreAuthorizationReservationTuple substituted = tuple("coordinator-substituted"); stubInitialReservation(tuple); - AuthorizationReference substitutedResponse = authorizationReference(substituted); when(accountClient.issueHuman( eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong())) - .thenReturn(substitutedResponse); + .thenAnswer( + invocation -> + authorizationReference( + substituted, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue())); assertThatThrownBy(() -> coordinator.issueHuman(tuple, CONTROL_UI_TOKEN)) .isInstanceOf(IllegalArgumentException.class); @@ -570,7 +605,6 @@ void mismatchedResponseTupleAndStaleClaimAfterAccountReturnAreNotForwarded() thr StartSessionPreAuthorizationReservationTuple staleTuple = tuple("coordinator-stale-return"); stubInitialReservation(staleTuple); - AuthorizationReference staleResponse = authorizationReference(staleTuple); when(accountClient.issueHuman( eq(shared(staleTuple)), anyString(), @@ -578,7 +612,12 @@ void mismatchedResponseTupleAndStaleClaimAfterAccountReturnAreNotForwarded() thr anyLong(), any(UUID.class), anyLong())) - .thenReturn(staleResponse); + .thenAnswer( + invocation -> + authorizationReference( + staleTuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue())); when(repository.completeAuthorization( eq(staleTuple), eq(staleTuple.mutationDigest()), @@ -707,7 +746,8 @@ private void stubAuthorizationEnrichment( } private static AuthorizationReference authorizationReference( - StartSessionPreAuthorizationReservationTuple tuple) throws Exception { + StartSessionPreAuthorizationReservationTuple tuple, UUID reservationOwner, long claimFence) + throws Exception { AuthorizationReference response = mock(AuthorizationReference.class); when(response.operatorAuthorizationReference()).thenReturn(OPAQUE_REFERENCE); when(response.authorizationReferenceFingerprint()).thenReturn(FINGERPRINT); @@ -715,6 +755,16 @@ private static AuthorizationReference authorizationReference( when(response.authorityEvidenceBundle()).thenReturn(bundleBytes(tuple, NOW.plusSeconds(300))); when(response.bundleReference()).thenReturn(bundleReference()); when(response.authenticatedLoggingWorkloadIdentity()).thenReturn(LOGGING_IDENTITY); + when(response.postAuthorizationTuple()) + .thenReturn( + StartSessionPostAuthorizationExecutionTuple.createHuman( + shared(tuple), + LOGGING_IDENTITY, + FINGERPRINT, + reservationOwner, + claimFence, + bundleBytes(tuple, NOW.plusSeconds(300)), + bundleReference())); return response; }