diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index fe7306cdbf..3610bd373d 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -54,6 +54,8 @@ This target contract is not complete in the current service. The existing `secur ## Implementation Status +Passive original StartSession admission/activation protection storage adds no callable acquisition, read or settlement API. SQL terminal integrity is not authenticated Game Session/World terminal authority, and no protection grants runtime admission or activation. The [Account storage consequence](./runtime-and-data.md#original-startsession-source-protection-storage) and [focused proof tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage) retain the exact boundary and open producer/consumer gates. + The initial private gameplay LOGIN owner, signer, registry, and response-recovery code is present as unregistered Account source, with focused proof sources. Before its final Account transaction, the commit source publishes the current issuer and Account projections and requires an exact matching observation; publication or observation failure denies the commit. Caller currentness and response recovery may use an older committed signer generation only while the exact original public-key fingerprint remains in the current trusted JWKS and current owner evidence, including the original issuance JTI, still matches; the applicable authority, API, source, expiry, and compromise fences remain required. This does not add or activate an API, proto method, or Spring composition; the source has no caller-selected profile or property override. See the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake) for exact proof scope; deployed ACL/TLS, signer-key custody, caller authentication, gameplay admission, and runtime activation remain unproved. Account UUID generation currently has three established provenances: `ACCOUNT_REPOSITORY_INSERT` uses `AccountRepository` and `UUID.randomUUID()`; `ACCOUNT_V29_MIGRATION` uses `gen_random_uuid()` for retained rows; and `ACCOUNT_DATABASE_INSERT` uses the `gen_random_uuid()` database default. These current producer outputs are RFC 4122 version 4 UUIDs. This records generator provenance and does not claim that database constraints reject custom UUID versions. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index fa969a4388..de4a6995d6 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,6 +8,8 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ## Implementation Status +The additive [V165 source-protection storage](../../../../services/account-service/src/main/resources/db/migration/V165__original_start_session_source_protections.sql) provides passive original StartSession admission and activation protection relations and source-writer exclusions. It adds no registered producer or transport. Qualification and remaining composition gates are recorded in the [source-protection tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage). + Account has an unregistered initial private gameplay LOGIN source slice for request-bound credential digests, signer and JWKS trust, pending and committed registry ownership, authority projection reads, and encrypted response recovery. Before its final Account transaction, the commit source publishes the current issuer and Account projections and requires an exact matching observation; publication or observation failure denies the commit. Caller currentness and response recovery may use an older committed signer generation only while the exact original public-key fingerprint remains in the current trusted JWKS and current owner evidence, including the original issuance JTI, still matches; the applicable authority, API, source, expiry, and compromise fences remain required. The source fixes the explicitly approved `game-session-account-delegation` profile and has no caller-selected profile or property bypass. It adds no endpoint or runtime registration; deployed ACL/TLS, signer-key custody, caller authentication, consumer authorization, gameplay admission, and runtime activation remain unproved. See the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake) for exact unit and physical fixture proof scope. Account's unregistered original-ACK storage seam requires PostgreSQL 18 for fresh operations: the original executor performs a writable SERIALIZABLE physical COMMIT on its enlisted connection and returns an opaque acknowledgement only after observing the database clock before unchanged expiry; a separate transaction commits the exact receipt. Receiving V146 changes only the fresh receipt-insert guard, preserving the donor V122 SQL unchanged as receiving V144. Its historical durable reader remains PostgreSQL 16-only, so lost-acknowledgement recovery and retained-receipt retries remain denied on PostgreSQL 18. This storage evidence does not authenticate a caller, establish current Account ownership or admission, authorize gameplay, or register runtime behavior. Migration provenance and pending receiving proof are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-fresh-original-ack-storage-preparation). @@ -329,3 +331,11 @@ Account owns the sole supported v1 Stripe integration for FireMUD hosting-plan b This service sends verification and password reset emails using a configured SMTP provider. 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 a known-account post-commit SMTP send throws; those exceptions are caught and logged, while unknown requests create no token and schedule no email. **Current gap:** these sends still run synchronously after commit, so SMTP latency remains a timing oracle; durable asynchronous delivery is absent. Focused service tests prove exception containment, not timing resistance, HTTP-level timing parity, or durable delivery, so this is not full account-enumeration resistance. Public email-verification initiation no longer accepts a numeric account selector, while the internal gRPC method remains account-ID based. Notifications for suspicious logins or account events are queued for asynchronous delivery via a gRPC `NotificationService`. Sample templates live under `resources/templates/` and environment variables configure `spring.mail.*` along with `firemud.mail.from`, `firemud.mail.verification-url`, and `firemud.mail.reset-url`. The Account-owned trusted-source context, distributed candidate/source throttles, and limiter-outage behavior from [ADR 0034](../../decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md) remain unimplemented, so neutral responses do not by themselves complete the abuse-control boundary. The gRPC API is defined in [`notification_service.proto`](../../../../protos/account/v1/notification_service.proto). The configured default verification URL is a `GET /auth/verify-email` link while Account exposes verification as `POST /auth/verify-email`; the default reset URL points to `/reset-password`, for which no Account route exists. The canonical Gateway forwards Account auth under `/api/account/auth/**` ([Gateway client behavior](../spring-cloud-gateway/client-behavior.md)). The shipped defaults therefore do not route users to the canonical POST APIs ([Account API Contracts](./api-contracts.md#rest-apis)); deployment must provide an explicit web-client/edge handoff or matching handler, with link reachability proof, before recovery and verification are treated as end-to-end live. + +## Original StartSession Source-Protection Storage + +Account retains admission and activation protection separately from the original World participation. Each protection stores the complete original tuple and redemption projection, capture, ordered source-child evidence, actual Game Session owner mutation/attempt/fence, and unchanged original lease expiry. Admission additionally binds the complete World admission hold; activation binds the canonical World PREPARING evidence and its separate activation request. Database checks validate the nested original issuance-operation identity rather than accepting a matching projection hash alone. Identity/fence allocation, exact current lookup and append-only guards preserve the first protection without renewing authority. + +The existing Account source-lock order remains canonical: source-key locks precede protection-row locks, and NOWAIT refuses a reversed or unavailable acquisition. Pending admission or activation blocks the existing source-hold, source-change and hosted-terms disclosure paths until the distinct protection has its exact immutable terminal settlement. Expiry, World receiving settlement, absence and an asserted outcome cannot release another protection. Settlement stores the complete original protection and exact terminal binding; these SQL checks validate integrity and do not authenticate the terminal producer. The owner obligations remain defined by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md). + +V165 preserves canonical predecessor SQL and retained owner rows; it never backfills protection, adopts missing historical evidence, fabricates owner proof or registers runtime authority. Its scoped PostgreSQL fixtures explicitly stipulate upstream capture/redemption/World rows with upstream producer triggers disabled while leaving the protection and source-writer guards under test enabled. Such execution establishes storage integrity, exclusion and retained-history behavior only. Genuine current-owner acquisition, authenticated terminal reads/settlement, continuously protected admission, activation and the separate selected-owner source-reservation obligation remain unproved. 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 1973b6f4de..4914bb1660 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,12 @@ Game Session now carries a default-off source path for current route and publish The Account source-currentness/first-JOIN persistence stage builds on the tested V30–V39 storage and retention-safety prerequisite. It preserves V40 fresh source-baseline hooks, canonical source/event proof, and the complete owner-local first-JOIN coordinator rather than dropping them to reduce scope. Earlier source-stage checkpoints have reported unit and integration-source proof; physical PostgreSQL proof for the current reconciled cut remains unavailable. The parent's 493 unit tests and 13 targeted physical PostgreSQL cases across separate runs cover only storage/currentness. These primitives do not supply authenticated public JOIN, the cross-service target-through-commit gate, Game Session text JOIN, or playable proof. Existing #2898/#2848 gaps and capability statuses remain unchanged. +### Original StartSession source-protection storage + +The bounded V165 receiving cut adds passive Account admission and activation protection storage and immutable terminal-settlement integrity, while preserving every canonical parent migration and original owner evidence. Its existing source-writer hooks retain World participation and other published owner guards. The source-only V130 selected-owner reservation hook is outside this cut and remains a separate receiving obligation. AA-1.3 stays `partial` / `drift-found`; all genuine Gameplay handoffs remain open and broader Unit 1B remains paused. + +Fresh qualification on the receiving cut based on published Entity parent `6d93e3466b51079cb132d103b80b07dc1d3d0794` passes all 13 focused PostgreSQL cases with zero failures, errors or skips. The canonical gate also passes actual jOOQ generation, integration-source compilation, formatting, Checkstyle, SpotBugs, link checking and Markdown lint (2m47s; 86 tasks, 77 executed and 9 from cache). Only the two selected storage suites executed; this is not a full Account integration run or rebuilt packaged-runtime proof. The focused [admission storage suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java) defines eleven PostgreSQL cases, including unchanged retained rows/OIDs/checksums, complete original tuple and nested issuance binding, exact current replay, precision-sensitive expiry, source-writer exclusion, immutable rows and failed terminal release. The [activation storage suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java) defines two cases covering identity, pending exclusion, currentness and exact terminal integrity. These fixtures explicitly stipulate upstream Account/World/Game Session data with upstream producer triggers disabled; the protection and writer guards under test stay enabled. The fresh execution qualifies these storage fixtures only; historic whole-carrier results do not qualify additional cut behavior. Genuine source currentness, authenticated owner production and terminal settlement, continuous admission protection, activation, actor placement and region delivery remain unproved. Canonical obligations remain in [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md), with local storage consequences in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#original-startsession-source-protection-storage). + ### Entity character-creation denial 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). diff --git a/services/account-service/src/main/resources/db/migration/V165__original_start_session_source_protections.sql b/services/account-service/src/main/resources/db/migration/V165__original_start_session_source_protections.sql new file mode 100644 index 0000000000..1529026b92 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V165__original_start_session_source_protections.sql @@ -0,0 +1,1460 @@ +-- Additive receiving Account admission and activation source protections after the canonical +-- capture (V158), World participation (V159), original attempt (V160), and independent source +-- fence (V160.1) owners. No predecessor, retained row, checksum, or owner identity is rewritten. +-- Complete original tuple projection and the independent nested issuance-operation identity +-- are installed directly; this migration never installs the superseded scalar projection guard. +-- These storage/integrity boundaries do not register runtime authority or authenticate producers. + +-- Distinct Account source protection through original Game Session admission. World +-- settlement and original-attempt observation expiry never settle this participation. +-- These integrity guards do not authenticate a producer or Game Session terminal RPC. +CREATE TABLE account_start_session_admission_protections ( + protection_id UUID PRIMARY KEY CHECK (protection_id <> '00000000-0000-0000-0000-000000000000'::UUID), + protection_fence BIGINT GENERATED ALWAYS AS IDENTITY UNIQUE CHECK (protection_fence > 0), + control_plane_request_id VARCHAR(128) NOT NULL UNIQUE + REFERENCES account_start_session_authority_captures(control_plane_request_id) ON DELETE RESTRICT, + original_post_authorization_tuple BYTEA NOT NULL CHECK (octet_length(original_post_authorization_tuple) BETWEEN 1 AND 262144), + account_redemption_projection BYTEA NOT NULL CHECK (octet_length(account_redemption_projection) BETWEEN 1 AND 262144), + game_session_owner_mutation_id UUID NOT NULL UNIQUE CHECK (game_session_owner_mutation_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), + original_lease_expires_at TIMESTAMPTZ NOT NULL CHECK (isfinite(original_lease_expires_at)), + account_world_participation_id UUID NOT NULL UNIQUE + REFERENCES account_start_session_world_participations(participation_id) ON DELETE RESTRICT, + account_world_participation_fence BIGINT NOT NULL CHECK (account_world_participation_fence > 0), + 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, + canonical_game_instance_id UUID NOT NULL CHECK (canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::UUID), + capture_source_version BIGINT NOT NULL CHECK (capture_source_version > 0), + capture_source_fence BIGINT NOT NULL CHECK (capture_source_fence > 0), + capture_sha256 VARCHAR(64) NOT NULL CHECK (capture_sha256 ~ '^[0-9a-f]{64}$'), + world_admission_hold_identity_bytes BYTEA NOT NULL CHECK (octet_length(world_admission_hold_identity_bytes) BETWEEN 1 AND 262144), + request_binding_bytes BYTEA NOT NULL CHECK (octet_length(request_binding_bytes) BETWEEN 1 AND 1048576), + request_binding_digest VARCHAR(71) NOT NULL + CHECK (request_binding_digest = 'sha256:' || encode(sha256(request_binding_bytes), 'hex')), + producer_xid BIGINT NOT NULL DEFAULT txid_current(), + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() +); + +CREATE TABLE account_start_session_admission_protection_sources ( + protection_id UUID NOT NULL REFERENCES account_start_session_admission_protections(protection_id) ON DELETE RESTRICT, + source_key VARCHAR(2048) NOT NULL REFERENCES account_draft_authorization_source_locks(source_key), + source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) BETWEEN 1 AND 131072), + PRIMARY KEY (protection_id, source_key) +); +CREATE INDEX account_ss_admission_sources_by_key + ON account_start_session_admission_protection_sources(source_key, protection_id); + +CREATE TABLE account_start_session_admission_protection_settlements ( + protection_id UUID PRIMARY KEY REFERENCES account_start_session_admission_protections(protection_id) ON DELETE RESTRICT, + outcome VARCHAR(16) NOT NULL CHECK (outcome IN ('COMMITTED', 'ABORTED')), + terminal_bytes BYTEA NOT NULL CHECK (octet_length(terminal_bytes) BETWEEN 1 AND 25165824), + terminal_digest VARCHAR(71) NOT NULL CHECK (terminal_digest = 'sha256:' || encode(sha256(terminal_bytes), 'hex')), + settled_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() +); + +-- [jooq ignore start] +CREATE FUNCTION account_ss_admission_is_settled(protection_value UUID) +RETURNS BOOLEAN LANGUAGE SQL STABLE STRICT AS $$ + SELECT EXISTS (SELECT 1 FROM account_start_session_admission_protection_settlements + WHERE protection_id = protection_value) +$$; + +-- Called only after the owning writer has locked its canonical source-key set. This +-- shared addition preserves the independently assembled World and other owner guards. +CREATE FUNCTION account_ss_admission_assert_no_pending(source_keys TEXT[]) +RETURNS VOID LANGUAGE plpgsql VOLATILE STRICT AS $$ +BEGIN + PERFORM protection.protection_id + FROM account_start_session_admission_protections protection + JOIN account_start_session_admission_protection_sources source + ON source.protection_id = protection.protection_id + WHERE source.source_key = ANY(source_keys) + AND NOT account_ss_admission_is_settled(protection.protection_id) + ORDER BY protection.protection_id FOR UPDATE OF protection NOWAIT; + IF FOUND THEN + RAISE EXCEPTION 'Original StartSession admission protection remains pending for a required source' + USING ERRCODE = '55P03'; + END IF; +END; +$$; + +-- Account currentness must independently reconstruct the exact live original actor, +-- registry, signer and source capture before invoking this integrity boundary. SQL +-- validates retained bindings; neither a capture nor a historical observation grants +-- admission, and a gap requires the producer's fresh unchanged-source validation. +CREATE FUNCTION account_ss_admission_assert_current( + original account_start_session_admission_protections, + require_complete BOOLEAN +) RETURNS VOID LANGUAGE plpgsql VOLATILE STRICT AS $$ +DECLARE + capture account_start_session_authority_captures%ROWTYPE; + world_parent account_start_session_world_participations%ROWTYPE; + observation account_start_session_world_original_attempt_evidence%ROWTYPE; + authorization_row account_start_session_operator_authorizations%ROWTYPE; + snapshot_value JSONB; + tuple_value JSONB; + request_value JSONB; + hold_value JSONB; + hold_request JSONB; + projection_value JSONB; + source_value JSONB; + source_bytes BYTEA; + source_key_value TEXT; + keys TEXT[]; +BEGIN + 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; + IF snapshot_value->>'schema' IS DISTINCT FROM 'account-start-session-authority-snapshot/v1' + OR snapshot_value->>'controlPlaneRequestId' IS DISTINCT FROM original.control_plane_request_id THEN + RAISE EXCEPTION 'Admission protection requires the exact original source snapshot' USING ERRCODE = '23514'; + END IF; + keys := account_start_session_world_participation_lock_sources(snapshot_value); + PERFORM account_start_session_world_participation_assert_exclusive(keys, snapshot_value); + SELECT * INTO STRICT capture FROM account_start_session_authority_captures + WHERE control_plane_request_id = original.control_plane_request_id FOR UPDATE NOWAIT; + SELECT * INTO STRICT world_parent FROM account_start_session_world_participations + WHERE participation_id = original.account_world_participation_id FOR UPDATE NOWAIT; + SELECT * INTO STRICT observation FROM account_start_session_world_original_attempt_evidence + WHERE participation_id = original.account_world_participation_id FOR UPDATE NOWAIT; + SELECT * INTO STRICT authorization_row FROM account_start_session_operator_authorizations + WHERE control_plane_request_id = original.control_plane_request_id FOR UPDATE NOWAIT; + PERFORM protection_id FROM account_start_session_admission_protections + WHERE protection_id = original.protection_id FOR UPDATE NOWAIT; + -- Always check actual database time after every lock, including exact recovery. + IF original.original_lease_expires_at <= clock_timestamp() + OR authorization_row.reference_expires_at <= clock_timestamp() + OR account_ss_admission_is_settled(original.protection_id) THEN + RAISE EXCEPTION 'Original StartSession admission protection is not current' + USING ERRCODE = '23514'; + END IF; + IF capture.source_version IS DISTINCT FROM original.capture_source_version + OR capture.source_fence IS DISTINCT FROM original.capture_source_fence + OR capture.canonical_sha256 IS DISTINCT FROM original.capture_sha256 + OR world_parent.participation_fence IS DISTINCT FROM original.account_world_participation_fence + OR world_parent.control_plane_request_id IS DISTINCT FROM original.control_plane_request_id + OR world_parent.original_post_authorization_tuple IS DISTINCT FROM original.original_post_authorization_tuple + OR world_parent.game_session_owner_attempt_id IS DISTINCT FROM original.game_session_owner_attempt_id + OR world_parent.game_session_owner_fence IS DISTINCT FROM original.game_session_owner_fence + OR world_parent.target_namespace IS DISTINCT FROM original.target_namespace + OR world_parent.canonical_tenant_id IS DISTINCT FROM original.canonical_tenant_id + OR world_parent.canonical_game_instance_id IS DISTINCT FROM original.canonical_game_instance_id + OR observation.target_namespace IS DISTINCT FROM original.target_namespace + OR observation.game_session_owner_mutation_id IS DISTINCT FROM original.game_session_owner_mutation_id + OR observation.game_session_owner_attempt_id IS DISTINCT FROM original.game_session_owner_attempt_id + OR observation.game_session_owner_fence IS DISTINCT FROM original.game_session_owner_fence + OR observation.original_lease_expires_at IS DISTINCT FROM original.original_lease_expires_at + OR authorization_row.status IS DISTINCT FROM 'REDEEMED' + OR authorization_row.redemption_owner_attempt_id IS DISTINCT FROM original.game_session_owner_attempt_id + OR authorization_row.redemption_owner_fence IS DISTINCT FROM original.game_session_owner_fence + 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.issuance_fence IS DISTINCT FROM authorization_row.issuance_fence THEN + RAISE EXCEPTION 'Original StartSession admission protection differs from its retained owner bindings' + USING ERRCODE = '23514'; + END IF; + tuple_value := convert_from(original.original_post_authorization_tuple, 'UTF8')::JSONB; + IF tuple_value->'preAuthorizationReservationTuple' IS DISTINCT FROM convert_from(authorization_row.pre_authorization_tuple, 'UTF8')::JSONB + 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->'authorityEvidenceBundle' IS DISTINCT FROM convert_from(authorization_row.authority_evidence_bundle, 'UTF8')::JSONB THEN + RAISE EXCEPTION 'Admission tuple differs from original Account issuance' USING ERRCODE = '23514'; + END IF; + projection_value := convert_from(original.account_redemption_projection, 'UTF8')::JSONB; + IF original.account_redemption_projection IS DISTINCT FROM original.original_post_authorization_tuple + OR projection_value #>> '{authorityEvidenceBundle,issuanceOperationIdentity,issuanceOperationId}' + IS DISTINCT FROM authorization_row.issuance_operation_id::TEXT THEN + RAISE EXCEPTION 'Admission projection differs from complete original Account redemption' USING ERRCODE = '23514'; + END IF; + request_value := convert_from(original.request_binding_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(request_value) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'Admission request binding is not an object' USING ERRCODE = '23514'; + END IF; + IF (SELECT count(*) FROM jsonb_object_keys(request_value)) <> 10 + OR EXISTS (SELECT 1 FROM jsonb_each(request_value) field WHERE jsonb_typeof(field.value) <> 'string') + OR request_value->>'schema' IS DISTINCT FROM 'account-start-session-admission-protection-request/v1' + OR request_value->>'originalPostAuthorizationTupleBytesBase64' IS DISTINCT FROM regexp_replace(encode(original.original_post_authorization_tuple, 'base64'), E'[\n\r]', '', 'g') + OR request_value->>'accountRedemptionProjectionBytesBase64' IS DISTINCT FROM regexp_replace(encode(original.account_redemption_projection, 'base64'), E'[\n\r]', '', 'g') + OR request_value->>'gameSessionOwnerMutationId' IS DISTINCT FROM original.game_session_owner_mutation_id::TEXT + OR request_value->>'gameSessionOwnerAttemptId' IS DISTINCT FROM original.game_session_owner_attempt_id::TEXT + OR request_value->>'gameSessionOwnerFence' IS DISTINCT FROM original.game_session_owner_fence::TEXT + OR request_value->>'originalLeaseExpiresAt' IS DISTINCT FROM + to_char(original.original_lease_expires_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') + OR request_value->>'accountWorldParticipationId' IS DISTINCT FROM original.account_world_participation_id::TEXT + OR request_value->>'accountWorldParticipationFence' IS DISTINCT FROM original.account_world_participation_fence::TEXT + OR request_value->>'worldAdmissionHoldIdentityBytesBase64' IS DISTINCT FROM regexp_replace(encode(original.world_admission_hold_identity_bytes, 'base64'), E'[\n\r]', '', 'g') THEN + RAISE EXCEPTION 'Admission request binding differs from exact immutable selectors' USING ERRCODE = '23514'; + END IF; + hold_value := convert_from(original.world_admission_hold_identity_bytes, 'UTF8')::JSONB; + hold_request := convert_from(decode(hold_value->>'requestBytesBase64', 'base64'), 'UTF8')::JSONB; + IF hold_value->>'schema' IS DISTINCT FROM 'world-canonical-initial-admission-hold-identity/v1' + OR (SELECT count(*) FROM jsonb_object_keys(hold_value)) <> 5 + OR NOT (hold_value ?& ARRAY['schema', 'holdId', 'holdFence', 'holdBindingDigest', 'requestBytesBase64']) + OR EXISTS (SELECT 1 FROM jsonb_each(hold_value) field WHERE jsonb_typeof(field.value) <> 'string') + OR (hold_value->>'holdId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR (hold_value->>'holdFence')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR hold_value->>'holdBindingDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(decode(hold_value->>'requestBytesBase64', 'base64')), 'hex') + OR hold_request->>'schema' IS DISTINCT FROM 'world-canonical-initial-admission-hold-request/v1' + OR hold_request->'request'->>'targetNamespace' IS DISTINCT FROM original.target_namespace + OR hold_request->'request'->>'canonicalTenantId' IS DISTINCT FROM original.canonical_tenant_id::TEXT + OR hold_request->'request'->>'canonicalGameInstanceId' IS DISTINCT FROM original.canonical_game_instance_id::TEXT THEN + RAISE EXCEPTION 'Admission hold identity differs from original instance and request' USING ERRCODE = '23514'; + END IF; + -- Original World source children remain immutable even when World has settled. + PERFORM account_start_session_world_participation_assert_sources(world_parent.participation_id, snapshot_value); + IF require_complete THEN + IF (SELECT count(*) FROM account_start_session_admission_protection_sources + WHERE protection_id = original.protection_id) <> jsonb_array_length(snapshot_value->'sourceVector') THEN + RAISE EXCEPTION 'Admission protection 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 + source_bytes := decode(source_value #>> '{}', 'base64'); + source_key_value := account_start_session_world_participation_source_key(source_bytes); + IF NOT EXISTS (SELECT 1 FROM account_start_session_admission_protection_sources + WHERE protection_id = original.protection_id AND source_key = source_key_value + AND source_evidence = source_bytes) THEN + RAISE EXCEPTION 'Admission source child differs from complete original capture' USING ERRCODE = '23514'; + END IF; + END LOOP; + END IF; + IF original.original_lease_expires_at <= clock_timestamp() + OR authorization_row.reference_expires_at <= clock_timestamp() THEN + RAISE EXCEPTION 'Original StartSession admission expiry elapsed during integrity validation' USING ERRCODE = '23514'; + END IF; +END; +$$; + +CREATE FUNCTION account_ss_admission_read_current_exact(protection_value UUID, fence_value BIGINT, request_value BYTEA) +RETURNS SETOF account_start_session_admission_protections LANGUAGE plpgsql VOLATILE STRICT AS $$ +DECLARE original account_start_session_admission_protections%ROWTYPE; +BEGIN + SELECT * INTO STRICT original FROM account_start_session_admission_protections + WHERE protection_id = protection_value AND protection_fence = fence_value; + IF original.request_binding_bytes IS DISTINCT FROM request_value THEN + RAISE EXCEPTION 'Original admission recovery binding differs' USING ERRCODE = '23514'; + END IF; + PERFORM account_ss_admission_assert_current(original, TRUE); + RETURN NEXT original; +END; +$$; + +CREATE FUNCTION account_ss_admission_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.producer_xid IS DISTINCT FROM txid_current() THEN + RAISE EXCEPTION 'Admission protection must be created by its producer transaction' USING ERRCODE = '23514'; + END IF; + PERFORM account_ss_admission_assert_current(NEW::account_start_session_admission_protections, FALSE); + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_ss_admission_source_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE producer BIGINT; +BEGIN + SELECT producer_xid INTO STRICT producer FROM account_start_session_admission_protections + WHERE protection_id = NEW.protection_id; + IF producer 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 'Admission sources must be exact same-producer children' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_ss_admission_complete_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE original account_start_session_admission_protections%ROWTYPE; +BEGIN + SELECT * INTO STRICT original FROM account_start_session_admission_protections + WHERE protection_id = NEW.protection_id; + PERFORM account_ss_admission_assert_current(original, TRUE); + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_ss_admission_no_mutation() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Original StartSession admission evidence is append-only' USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_ss_admission_validate BEFORE INSERT ON account_start_session_admission_protections + FOR EACH ROW EXECUTE FUNCTION account_ss_admission_insert_guard(); +CREATE TRIGGER account_ss_admission_immutable BEFORE UPDATE OR DELETE ON account_start_session_admission_protections + FOR EACH ROW EXECUTE FUNCTION account_ss_admission_no_mutation(); +CREATE TRIGGER account_ss_admission_no_truncate BEFORE TRUNCATE ON account_start_session_admission_protections + FOR EACH STATEMENT EXECUTE FUNCTION account_ss_admission_no_mutation(); +CREATE TRIGGER account_ss_admission_sources_validate BEFORE INSERT ON account_start_session_admission_protection_sources + FOR EACH ROW EXECUTE FUNCTION account_ss_admission_source_insert_guard(); +CREATE TRIGGER account_ss_admission_sources_immutable BEFORE UPDATE OR DELETE ON account_start_session_admission_protection_sources + FOR EACH ROW EXECUTE FUNCTION account_ss_admission_no_mutation(); +CREATE TRIGGER account_ss_admission_sources_no_truncate BEFORE TRUNCATE ON account_start_session_admission_protection_sources + FOR EACH STATEMENT EXECUTE FUNCTION account_ss_admission_no_mutation(); +CREATE CONSTRAINT TRIGGER account_ss_admission_complete AFTER INSERT ON account_start_session_admission_protections + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_ss_admission_complete_guard(); +CREATE TRIGGER account_ss_admission_settlements_immutable BEFORE UPDATE OR DELETE ON account_start_session_admission_protection_settlements + FOR EACH ROW EXECUTE FUNCTION account_ss_admission_no_mutation(); +-- The authenticated exact Game Session terminal API is not yet composed. Reject every +-- settlement insertion until its sealed complete terminal binding guard replaces this +-- unpublished gate. An outcome assertion alone can never release source protection. +CREATE TRIGGER account_ss_admission_settlements_disabled BEFORE INSERT ON account_start_session_admission_protection_settlements + FOR EACH ROW EXECUTE FUNCTION account_ss_admission_no_mutation(); +CREATE TRIGGER account_ss_admission_settlements_no_truncate BEFORE TRUNCATE ON account_start_session_admission_protection_settlements + FOR EACH STATEMENT EXECUTE FUNCTION account_ss_admission_no_mutation(); + +DO $migration$ +DECLARE original TEXT; + anchor TEXT := $anchor$ FOR operation_value IN SELECT DISTINCT s.operation_id + FROM account_draft_authorization_sources s$anchor$; +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 admission source-writer anchor'; + END IF; + EXECUTE replace(original, anchor, + E' PERFORM account_ss_admission_assert_no_pending(source_keys);\n' || anchor); +END; +$migration$; + +DO $migration$ +DECLARE original TEXT; + anchor TEXT := $anchor$ FOR operation IN SELECT DISTINCT source.operation_id + FROM account_draft_authorization_changed_scopes changed$anchor$; +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 assembled admission source-change anchor'; + END IF; + EXECUTE replace(original, anchor, $guard$ PERFORM account_ss_admission_assert_no_pending( + ARRAY(SELECT source_key FROM account_draft_authorization_changed_scopes + WHERE change_id = OLD.change_id)); +$guard$ || anchor); +END; +$migration$; + +DO $migration$ +DECLARE original TEXT; + anchor TEXT := $anchor$ IF OLD.status = 'PREPARED' AND NEW.status = 'DISPATCH_AUTHORIZED'$anchor$; +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 assembled admission disclosure anchor'; + END IF; + EXECUTE replace(original, anchor, $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 source_key FROM account_hosted_terms_disclosure_sources + WHERE 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; + PERFORM account_ss_admission_assert_no_pending(ARRAY( + SELECT OLD.source_key UNION SELECT source_key FROM account_hosted_terms_disclosure_sources + WHERE handoff_id = OLD.handoff_id)); + END IF; +$guard$ || anchor); +END; +$migration$; +-- [jooq ignore end] + + +-- Immutable Account settlement for the exact original Game Session admission proof. +-- This guard validates retained structure and integrity only. It does not authenticate +-- the remote producer; the internal Game Session client owns that provenance boundary. +-- [jooq ignore start] +CREATE FUNCTION account_ss_admission_settlement_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_start_session_admission_protections%ROWTYPE; + capture account_start_session_authority_captures%ROWTYPE; + existing account_start_session_admission_protection_settlements%ROWTYPE; + terminal_json JSONB; + evidence_json JSONB; + hold_json JSONB; + hold_request_json JSONB; + snapshot_json JSONB; + evidence_bytes BYTEA; + owner_proof_bytes BYTEA; + canonical_outer TEXT; + canonical_evidence TEXT; + canonical_request TEXT; + canonical_hold TEXT; + canonical_hold_request TEXT; + source_vector TEXT; + source_count BIGINT; + source_bytes_total BIGINT; + source_value JSONB; + source_bytes BYTEA; + source_key_value TEXT; + previous_sort_key INTEGER[]; + current_sort_key INTEGER[]; + position_value INTEGER := 1; + frame_next_position INTEGER; + parsed BYTEA; + marker TEXT; + proof_schema TEXT; + proof_hold_bytes BYTEA; + proof_outcome TEXT; + pointer_marker TEXT; + pointer_text TEXT; + audit_marker TEXT; + audit_text TEXT; + digest_marker TEXT; + proof_digest TEXT; + abort_value TEXT; + terminal_marker TEXT; + terminal_at_text TEXT; + terminal_stem TEXT; + expected_pointer NUMERIC; + prior_pointer NUMERIC; + original_request JSONB; +BEGIN + SELECT * INTO STRICT original + FROM account_start_session_admission_protections + WHERE protection_id = NEW.protection_id; + + IF NEW.outcome NOT IN ('COMMITTED', 'ABORTED') + OR NEW.terminal_bytes IS NULL + OR octet_length(NEW.terminal_bytes) NOT BETWEEN 1 AND 25165824 + OR NEW.terminal_digest IS DISTINCT FROM + 'sha256:' || encode(sha256(NEW.terminal_bytes), 'hex') THEN + RAISE EXCEPTION 'Malformed original StartSession admission settlement' + USING ERRCODE = '23514'; + END IF; + + -- Reconstructing the complete outer object makes duplicate keys, alternate escaping, + -- trailing input, and non-RFC8785 ordering fail byte-for-byte. + terminal_json := convert_from(NEW.terminal_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(terminal_json) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(terminal_json)) <> 3 + OR NOT (terminal_json ?& ARRAY[ + 'schema', 'canonicalAccountProtectionEvidenceBytesBase64', + 'canonicalGameSessionOwnerProofBytesBase64']) + OR EXISTS (SELECT 1 FROM jsonb_each(terminal_json) field + WHERE jsonb_typeof(field.value) IS DISTINCT FROM 'string') + OR terminal_json->>'schema' IS DISTINCT FROM + 'account-start-session-admission-protection-settlement/v1' THEN + RAISE EXCEPTION 'Original StartSession admission settlement is not the closed envelope' + USING ERRCODE = '23514'; + END IF; + evidence_bytes := decode(terminal_json->>'canonicalAccountProtectionEvidenceBytesBase64', 'base64'); + owner_proof_bytes := decode(terminal_json->>'canonicalGameSessionOwnerProofBytesBase64', 'base64'); + IF octet_length(evidence_bytes) NOT BETWEEN 1 AND 8388608 + OR octet_length(owner_proof_bytes) NOT BETWEEN 1 AND 66048 + OR regexp_replace(encode(evidence_bytes, 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM terminal_json->>'canonicalAccountProtectionEvidenceBytesBase64' + OR regexp_replace(encode(owner_proof_bytes, 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM terminal_json->>'canonicalGameSessionOwnerProofBytesBase64' THEN + RAISE EXCEPTION 'Original StartSession admission settlement has invalid canonical Base64' + USING ERRCODE = '23514'; + END IF; + canonical_outer := '{"canonicalAccountProtectionEvidenceBytesBase64":"' + || (terminal_json->>'canonicalAccountProtectionEvidenceBytesBase64') + || '","canonicalGameSessionOwnerProofBytesBase64":"' + || (terminal_json->>'canonicalGameSessionOwnerProofBytesBase64') + || '","schema":"account-start-session-admission-protection-settlement/v1"}'; + IF convert_to(canonical_outer, 'UTF8') IS DISTINCT FROM NEW.terminal_bytes THEN + RAISE EXCEPTION 'Original StartSession admission settlement is not canonical JSON' + 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; + IF capture.source_version IS DISTINCT FROM original.capture_source_version + OR capture.source_fence IS DISTINCT FROM original.capture_source_fence + OR capture.canonical_sha256 IS DISTINCT FROM original.capture_sha256 + OR octet_length(capture.canonical_capture_bytes) NOT BETWEEN 1 AND 262144 + OR octet_length(capture.canonical_snapshot_bytes) NOT BETWEEN 1 AND 245760 + OR capture.canonical_sha256 IS DISTINCT FROM + encode(sha256(capture.canonical_capture_bytes), 'hex') + OR capture.snapshot_sha256 IS DISTINCT FROM + encode(sha256(capture.canonical_snapshot_bytes), 'hex') THEN + RAISE EXCEPTION 'Original StartSession admission capture differs from retained protection' + USING ERRCODE = '23514'; + END IF; + + -- The immutable Account request is a closed ten-string object. Rebuild its canonical + -- representation from the retained parent so the settlement cannot bind a projection. + canonical_request := '{"accountRedemptionProjectionBytesBase64":"' + || regexp_replace(encode(original.account_redemption_projection, 'base64'), E'[\n\r]', '', 'g') + || '","accountWorldParticipationFence":"' + || original.account_world_participation_fence::TEXT + || '","accountWorldParticipationId":"' + || original.account_world_participation_id::TEXT + || '","gameSessionOwnerAttemptId":"' + || original.game_session_owner_attempt_id::TEXT + || '","gameSessionOwnerFence":"' + || original.game_session_owner_fence::TEXT + || '","gameSessionOwnerMutationId":"' + || original.game_session_owner_mutation_id::TEXT + || '","originalLeaseExpiresAt":"' + || to_char(original.original_lease_expires_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') + || '","originalPostAuthorizationTupleBytesBase64":"' + || regexp_replace(encode(original.original_post_authorization_tuple, 'base64'), E'[\n\r]', '', 'g') + || '","schema":"account-start-session-admission-protection-request/v1"' + || ',"worldAdmissionHoldIdentityBytesBase64":"' + || regexp_replace(encode(original.world_admission_hold_identity_bytes, 'base64'), E'[\n\r]', '', 'g') + || '"}'; + IF octet_length(original.request_binding_bytes) NOT BETWEEN 1 AND 786432 + OR octet_length(original.world_admission_hold_identity_bytes) NOT BETWEEN 1 AND 65536 + OR convert_to(canonical_request, 'UTF8') IS DISTINCT FROM original.request_binding_bytes + OR original.request_binding_digest IS DISTINCT FROM + 'sha256:' || encode(sha256(original.request_binding_bytes), 'hex') THEN + RAISE EXCEPTION 'Original StartSession admission request is not its exact canonical binding' + USING ERRCODE = '23514'; + END IF; + + snapshot_json := convert_from(capture.canonical_snapshot_bytes, 'UTF8')::JSONB; + IF snapshot_json->>'schema' IS DISTINCT FROM 'account-start-session-authority-snapshot/v1' + OR snapshot_json->>'controlPlaneRequestId' IS DISTINCT FROM original.control_plane_request_id + OR jsonb_typeof(snapshot_json->'sourceVector') IS DISTINCT FROM 'array' + OR jsonb_array_length(snapshot_json->'sourceVector') NOT BETWEEN 1 AND 256 THEN + RAISE EXCEPTION 'Original StartSession admission source capture is incomplete' + USING ERRCODE = '23514'; + END IF; + SELECT count(*) INTO source_count + FROM account_start_session_admission_protection_sources + WHERE protection_id = original.protection_id; + SELECT COALESCE(sum(octet_length(source_evidence)), 0) INTO source_bytes_total + FROM account_start_session_admission_protection_sources + WHERE protection_id = original.protection_id; + IF source_count IS DISTINCT FROM jsonb_array_length(snapshot_json->'sourceVector')::BIGINT + OR source_bytes_total > 4194304 THEN + RAISE EXCEPTION 'Original StartSession admission source children are incomplete' + USING ERRCODE = '23514'; + END IF; + FOR source_value IN SELECT value FROM jsonb_array_elements(snapshot_json->'sourceVector') LOOP + IF jsonb_typeof(source_value) IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'Original StartSession source vector has a non-string member' + USING ERRCODE = '23514'; + END IF; + source_bytes := decode(source_value #>> '{}', 'base64'); + IF octet_length(source_bytes) NOT BETWEEN 1 AND 131072 + OR regexp_replace(encode(source_bytes, 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM source_value #>> '{}' THEN + RAISE EXCEPTION 'Original StartSession source vector has noncanonical bytes' + USING ERRCODE = '23514'; + END IF; + source_key_value := account_start_session_world_participation_source_key(source_bytes); + current_sort_key := account_publication_authorization_source_sort_key(source_key_value); + IF previous_sort_key IS NOT NULL AND current_sort_key <= previous_sort_key THEN + RAISE EXCEPTION 'Original StartSession source vector is duplicated or out of order' + USING ERRCODE = '23514'; + END IF; + previous_sort_key := current_sort_key; + IF NOT EXISTS ( + SELECT 1 FROM account_start_session_admission_protection_sources source + WHERE source.protection_id = original.protection_id + AND source.source_key = source_key_value + AND source.source_evidence = source_bytes) THEN + RAISE EXCEPTION 'Original StartSession source child differs from its immutable capture' + USING ERRCODE = '23514'; + END IF; + END LOOP; + + SELECT string_agg( + '"' || regexp_replace(encode(source.source_evidence, 'base64'), E'[\n\r]', '', 'g') || '"', + ',' ORDER BY account_publication_authorization_source_sort_key(source.source_key)) + INTO source_vector + FROM account_start_session_admission_protection_sources source + WHERE source.protection_id = original.protection_id; + canonical_evidence := '{"accountProtectionFence":"' || original.protection_fence::TEXT + || '","accountProtectionId":"' || original.protection_id::TEXT + || '","originalSourceCaptureReferenceBytesBase64":"' + || regexp_replace(encode(capture.canonical_capture_bytes, 'base64'), E'[\n\r]', '', 'g') + || '","originalSourceCaptureReferenceSha256":"' || capture.canonical_sha256 + || '","requestBytesBase64":"' + || regexp_replace(encode(original.request_binding_bytes, 'base64'), E'[\n\r]', '', 'g') + || '","schema":"account-start-session-admission-protection-evidence/v1"' + || ',"sourceEvidenceVector":[' || source_vector || ']}'; + IF convert_to(canonical_evidence, 'UTF8') IS DISTINCT FROM evidence_bytes THEN + RAISE EXCEPTION 'Original StartSession admission evidence differs from its full retained binding' + USING ERRCODE = '23514'; + END IF; + + -- Validate the exact retained World hold identity and request, including the original + -- target and the pointer precondition used to derive a committed next pointer. + hold_json := convert_from(original.world_admission_hold_identity_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(hold_json) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(hold_json)) <> 5 + OR NOT (hold_json ?& ARRAY['schema', 'holdId', 'holdFence', 'holdBindingDigest', 'requestBytesBase64']) + OR EXISTS (SELECT 1 FROM jsonb_each(hold_json) field + WHERE jsonb_typeof(field.value) IS DISTINCT FROM 'string') + OR hold_json->>'schema' IS DISTINCT FROM 'world-canonical-initial-admission-hold-identity/v1' THEN + RAISE EXCEPTION 'Original StartSession admission hold identity is malformed' + USING ERRCODE = '23514'; + END IF; + IF (hold_json->>'holdId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR (hold_json->>'holdFence')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR hold_json->>'holdId' IS DISTINCT FROM (hold_json->>'holdId')::UUID::TEXT + OR hold_json->>'holdFence' IS DISTINCT FROM (hold_json->>'holdFence')::UUID::TEXT THEN + RAISE EXCEPTION 'Original StartSession admission hold identity is nil' + USING ERRCODE = '23514'; + END IF; + hold_request_json := convert_from(decode(hold_json->>'requestBytesBase64', 'base64'), 'UTF8')::JSONB; + IF regexp_replace(encode(decode(hold_json->>'requestBytesBase64', 'base64'), 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM hold_json->>'requestBytesBase64' + OR hold_json->>'holdBindingDigest' IS DISTINCT FROM + 'sha256:' || encode(sha256(decode(hold_json->>'requestBytesBase64', 'base64')), 'hex') + OR jsonb_typeof(hold_request_json) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(hold_request_json)) <> 2 + OR NOT (hold_request_json ?& ARRAY['schema', 'request']) + OR hold_request_json->>'schema' IS DISTINCT FROM 'world-canonical-initial-admission-hold-request/v1' + OR jsonb_typeof(hold_request_json->'request') IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(hold_request_json->'request')) <> 14 + OR NOT (hold_request_json->'request' ?& ARRAY[ + 'activeLifecycleEpoch', 'canonicalGameInstanceId', 'canonicalTenantId', + 'canonicalVersionId', 'expectedCatalogRevision', 'expectedPriorPointerVersion', + 'initialAdmissionOrigin', 'initialAdmissionRequestDigest', + 'initialAdmissionRequestId', 'playableStateNamespaceId', 'playableStateScope', + 'realmId', 'targetNamespace', 'worldSlug']) + OR hold_request_json->'request'->>'targetNamespace' IS DISTINCT FROM original.target_namespace + OR hold_request_json->'request'->>'canonicalTenantId' IS DISTINCT FROM original.canonical_tenant_id::TEXT + OR hold_request_json->'request'->>'canonicalGameInstanceId' IS DISTINCT FROM original.canonical_game_instance_id::TEXT THEN + RAISE EXCEPTION 'Original StartSession admission hold request differs from retained protection' + USING ERRCODE = '23514'; + END IF; + IF EXISTS ( + SELECT 1 FROM jsonb_each(hold_request_json->'request') field + WHERE field.key <> 'expectedPriorPointerVersion' + AND jsonb_typeof(field.value) IS DISTINCT FROM 'string') + OR jsonb_typeof(hold_request_json->'request'->'expectedPriorPointerVersion') NOT IN ('string', 'null') THEN + RAISE EXCEPTION 'Original StartSession hold request fields have invalid JSON types' + USING ERRCODE = '23514'; + END IF; + canonical_hold_request := '{"request":{"activeLifecycleEpoch":' + || to_json(hold_request_json->'request'->>'activeLifecycleEpoch')::TEXT + || ',"canonicalGameInstanceId":' + || to_json(hold_request_json->'request'->>'canonicalGameInstanceId')::TEXT + || ',"canonicalTenantId":' + || to_json(hold_request_json->'request'->>'canonicalTenantId')::TEXT + || ',"canonicalVersionId":' + || to_json(hold_request_json->'request'->>'canonicalVersionId')::TEXT + || ',"expectedCatalogRevision":' + || to_json(hold_request_json->'request'->>'expectedCatalogRevision')::TEXT + || ',"expectedPriorPointerVersion":' + || CASE + WHEN jsonb_typeof(hold_request_json->'request'->'expectedPriorPointerVersion') = 'null' + THEN 'null' + ELSE to_json(hold_request_json->'request'->>'expectedPriorPointerVersion')::TEXT + END + || ',"initialAdmissionOrigin":' + || to_json(hold_request_json->'request'->>'initialAdmissionOrigin')::TEXT + || ',"initialAdmissionRequestDigest":' + || to_json(hold_request_json->'request'->>'initialAdmissionRequestDigest')::TEXT + || ',"initialAdmissionRequestId":' + || to_json(hold_request_json->'request'->>'initialAdmissionRequestId')::TEXT + || ',"playableStateNamespaceId":' + || to_json(hold_request_json->'request'->>'playableStateNamespaceId')::TEXT + || ',"playableStateScope":' + || to_json(hold_request_json->'request'->>'playableStateScope')::TEXT + || ',"realmId":' + || to_json(hold_request_json->'request'->>'realmId')::TEXT + || ',"targetNamespace":' + || to_json(hold_request_json->'request'->>'targetNamespace')::TEXT + || ',"worldSlug":' + || to_json(hold_request_json->'request'->>'worldSlug')::TEXT + || '},"schema":"world-canonical-initial-admission-hold-request/v1"}'; + IF convert_to(canonical_hold_request, 'UTF8') IS DISTINCT FROM + decode(hold_json->>'requestBytesBase64', 'base64') THEN + RAISE EXCEPTION 'Original StartSession hold request is not canonical JSON' + USING ERRCODE = '23514'; + END IF; + canonical_hold := '{"holdBindingDigest":"' || (hold_json->>'holdBindingDigest') + || '","holdFence":"' || (hold_json->>'holdFence') + || '","holdId":"' || (hold_json->>'holdId') + || '","requestBytesBase64":"' || (hold_json->>'requestBytesBase64') + || '","schema":"world-canonical-initial-admission-hold-identity/v1"}'; + IF convert_to(canonical_hold, 'UTF8') IS DISTINCT FROM original.world_admission_hold_identity_bytes THEN + RAISE EXCEPTION 'Original StartSession admission hold identity is not canonical' + USING ERRCODE = '23514'; + END IF; + + -- The actual Game Session codec frames the hold and seven terminal fields. Do not treat + -- its opaque terminal proof digest as permission; only the exact COMMITTED/ABORTED shape + -- below may settle this immutable Account binding. + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + proof_schema := convert_from(parsed, 'UTF8'); + position_value := frame_next_position; + SELECT frame.frame_value, frame.next_position INTO proof_hold_bytes, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + proof_outcome := convert_from(parsed, 'UTF8'); + + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + pointer_marker := convert_from(parsed, 'UTF8'); + IF pointer_marker = 'PRESENT' THEN + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + pointer_text := convert_from(parsed, 'UTF8'); + ELSIF pointer_marker IS DISTINCT FROM 'ABSENT' THEN + RAISE EXCEPTION 'Original StartSession terminal pointer frame is malformed' USING ERRCODE = '23514'; + END IF; + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + audit_marker := convert_from(parsed, 'UTF8'); + IF audit_marker = 'PRESENT' THEN + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + audit_text := convert_from(parsed, 'UTF8'); + ELSIF audit_marker IS DISTINCT FROM 'ABSENT' THEN + RAISE EXCEPTION 'Original StartSession terminal audit frame is malformed' USING ERRCODE = '23514'; + END IF; + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + digest_marker := convert_from(parsed, 'UTF8'); + IF digest_marker = 'PRESENT' THEN + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + proof_digest := convert_from(parsed, 'UTF8'); + ELSIF digest_marker IS DISTINCT FROM 'ABSENT' THEN + RAISE EXCEPTION 'Original StartSession terminal digest frame is malformed' USING ERRCODE = '23514'; + END IF; + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + abort_value := convert_from(parsed, 'UTF8'); + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + terminal_marker := convert_from(parsed, 'UTF8'); + IF terminal_marker = 'PRESENT' THEN + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + terminal_at_text := convert_from(parsed, 'UTF8'); + ELSIF terminal_marker IS DISTINCT FROM 'ABSENT' THEN + RAISE EXCEPTION 'Original StartSession terminal timestamp frame is malformed' USING ERRCODE = '23514'; + END IF; + IF position_value <> octet_length(owner_proof_bytes) + 1 + OR proof_schema IS DISTINCT FROM 'game-session-canonical-initial-admission-owner-proof/v1' + OR proof_hold_bytes IS DISTINCT FROM original.world_admission_hold_identity_bytes + OR proof_digest IS NULL OR proof_digest !~ '^sha256:[0-9a-f]{64}$' + OR terminal_at_text IS NULL + OR terminal_at_text !~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]{3}|\.[0-9]{6}|\.[0-9]{9})?Z$' + OR terminal_at_text ~ '\.000Z$' + OR terminal_at_text ~ '\.[0-9]{3}000Z$' + OR terminal_at_text ~ '\.[0-9]{6}000Z$' + OR abort_value NOT IN ('true', 'false') THEN + RAISE EXCEPTION 'Original StartSession owner proof is malformed or differs from its hold' + USING ERRCODE = '23514'; + END IF; + -- Validate the calendar/time stem separately. Casting the complete fraction to + -- TIMESTAMPTZ would round nanoseconds to PostgreSQL microseconds and could silently + -- accept noncanonical Java Instant text; the exact frame bytes remain authoritative. + terminal_stem := to_char( + substring(terminal_at_text FROM 1 FOR 19)::TIMESTAMP WITHOUT TIME ZONE, + 'YYYY-MM-DD"T"HH24:MI:SS'); + IF terminal_stem IS DISTINCT FROM substring(terminal_at_text FROM 1 FOR 19) THEN + RAISE EXCEPTION 'Original StartSession owner proof timestamp stem is not normalized' + USING ERRCODE = '23514'; + END IF; + original_request := hold_request_json->'request'; + IF proof_outcome = 'COMMITTED' THEN + IF pointer_marker IS DISTINCT FROM 'PRESENT' + OR pointer_text IS NULL OR pointer_text !~ '^[1-9][0-9]{0,18}$' + OR audit_marker IS DISTINCT FROM 'PRESENT' + OR audit_text IS NULL OR audit_text !~ '^[1-9][0-9]{0,18}$' + OR abort_value IS DISTINCT FROM 'false' THEN + RAISE EXCEPTION 'Committed Game Session terminal proof has invalid outcome fields' + USING ERRCODE = '23514'; + END IF; + IF original_request->>'initialAdmissionOrigin' = 'NO_PRIOR_POINTER' + AND original_request->'expectedPriorPointerVersion' = 'null'::JSONB THEN + expected_pointer := 1; + ELSIF original_request->>'initialAdmissionOrigin' = 'EXPECT_CLOSED' + AND jsonb_typeof(original_request->'expectedPriorPointerVersion') = 'string' + AND original_request->>'expectedPriorPointerVersion' ~ '^[1-9][0-9]{0,18}$' THEN + prior_pointer := (original_request->>'expectedPriorPointerVersion')::NUMERIC; + IF prior_pointer >= 9223372036854775807 THEN + RAISE EXCEPTION 'Original StartSession pointer version cannot advance without overflow' + USING ERRCODE = '23514'; + END IF; + expected_pointer := prior_pointer + 1; + ELSE + RAISE EXCEPTION 'Original StartSession hold has an invalid pointer precondition' + USING ERRCODE = '23514'; + END IF; + IF pointer_text::NUMERIC IS DISTINCT FROM expected_pointer THEN + RAISE EXCEPTION 'Committed Game Session terminal proof does not name the exact next pointer' + USING ERRCODE = '23514'; + END IF; + PERFORM audit_text::BIGINT; + IF NEW.outcome IS DISTINCT FROM 'COMMITTED' THEN + RAISE EXCEPTION 'Account settlement outcome differs from Game Session owner proof' + USING ERRCODE = '23514'; + END IF; + ELSIF proof_outcome = 'ABORTED' THEN + IF pointer_marker IS DISTINCT FROM 'ABSENT' + OR audit_marker IS DISTINCT FROM 'ABSENT' + OR abort_value IS DISTINCT FROM 'true' + OR NEW.outcome IS DISTINCT FROM 'ABORTED' THEN + RAISE EXCEPTION 'Aborted Game Session terminal proof lacks positive durable exclusion' + USING ERRCODE = '23514'; + END IF; + ELSE + RAISE EXCEPTION 'Pending or unsupported Game Session owner proof cannot settle protection' + USING ERRCODE = '23514'; + END IF; + + SELECT * INTO existing + FROM account_start_session_admission_protection_settlements + WHERE protection_id = NEW.protection_id; + IF FOUND AND (existing.outcome IS DISTINCT FROM NEW.outcome + OR existing.terminal_bytes IS DISTINCT FROM NEW.terminal_bytes + OR existing.terminal_digest IS DISTINCT FROM NEW.terminal_digest) THEN + RAISE EXCEPTION 'Original StartSession admission terminal settlement conflicts with its first receipt' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +DROP TRIGGER account_ss_admission_settlements_disabled + ON account_start_session_admission_protection_settlements; +CREATE TRIGGER account_ss_admission_settlements_validate + BEFORE INSERT ON account_start_session_admission_protection_settlements + FOR EACH ROW EXECUTE FUNCTION account_ss_admission_settlement_insert_guard(); +-- [jooq ignore end] + + +-- Distinct Account-owned source protection through the exact original World activation. +-- This is immutable storage only: it authenticates no owner and has no release or +-- settlement path. A future exact ACTIVE/ABORTED terminal contract must add that separately. +CREATE TABLE account_start_session_activation_protections ( + activation_protection_id UUID PRIMARY KEY DEFAULT gen_random_uuid() + CHECK (activation_protection_id <> '00000000-0000-0000-0000-000000000000'::UUID), + activation_protection_fence BIGINT GENERATED ALWAYS AS IDENTITY UNIQUE + CHECK (activation_protection_fence > 0), + control_plane_request_id VARCHAR(128) NOT NULL UNIQUE + REFERENCES account_start_session_authority_captures(control_plane_request_id) ON DELETE RESTRICT, + account_world_participation_id UUID NOT NULL UNIQUE + REFERENCES account_start_session_world_participations(participation_id) ON DELETE RESTRICT, + account_world_participation_fence BIGINT NOT NULL CHECK (account_world_participation_fence > 0), + original_post_authorization_tuple BYTEA NOT NULL + CHECK (octet_length(original_post_authorization_tuple) BETWEEN 1 AND 262144), + account_redemption_projection BYTEA NOT NULL + CHECK (octet_length(account_redemption_projection) BETWEEN 1 AND 135168), + game_session_owner_mutation_id UUID NOT NULL UNIQUE + CHECK (game_session_owner_mutation_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), + original_lease_expires_at TIMESTAMPTZ NOT NULL CHECK (isfinite(original_lease_expires_at)), + 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, + canonical_game_instance_id UUID NOT NULL + CHECK (canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::UUID), + world_activation_request_id UUID NOT NULL + CHECK (world_activation_request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + game_session_launch_read_evidence BYTEA NOT NULL + CHECK (octet_length(game_session_launch_read_evidence) BETWEEN 1 AND 42991616), + world_preparing_evidence BYTEA NOT NULL + CHECK (octet_length(world_preparing_evidence) BETWEEN 1 AND 67108864), + capture_source_version BIGINT NOT NULL CHECK (capture_source_version > 0), + capture_source_fence BIGINT NOT NULL CHECK (capture_source_fence > 0), + capture_sha256 VARCHAR(64) NOT NULL CHECK (capture_sha256 ~ '^[0-9a-f]{64}$'), + capture_reference_bytes BYTEA NOT NULL + CHECK (octet_length(capture_reference_bytes) BETWEEN 1 AND 262144), + capture_reference_sha256 VARCHAR(64) NOT NULL + CHECK (capture_reference_sha256 ~ '^[0-9a-f]{64}$'), + operation_identity_bytes BYTEA NOT NULL + CHECK (octet_length(operation_identity_bytes) BETWEEN 1 AND 150994944), + operation_identity_digest VARCHAR(71) NOT NULL UNIQUE + CHECK (operation_identity_digest = 'sha256:' || encode(sha256(operation_identity_bytes), 'hex')), + request_binding_bytes BYTEA NOT NULL + CHECK (octet_length(request_binding_bytes) BETWEEN 1 AND 150994944), + request_binding_digest VARCHAR(71) NOT NULL + CHECK (request_binding_digest = 'sha256:' || encode(sha256(request_binding_bytes), 'hex')), + producer_xid BIGINT NOT NULL DEFAULT txid_current(), + acquired_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + CHECK (isfinite(acquired_at) AND acquired_at < original_lease_expires_at), + CHECK (capture_sha256 = capture_reference_sha256) +); + +CREATE TABLE account_start_session_activation_protection_sources ( + activation_protection_id UUID NOT NULL + REFERENCES account_start_session_activation_protections(activation_protection_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 (activation_protection_id, source_key) +); +CREATE INDEX account_ss_activation_sources_by_key + ON account_start_session_activation_protection_sources(source_key, activation_protection_id); + +-- [jooq ignore start] +CREATE FUNCTION account_ss_activation_assert_current( + request_bytes BYTEA, + operation_bytes BYTEA, + operation_digest TEXT, + require_complete BOOLEAN +) RETURNS VOID LANGUAGE plpgsql VOLATILE STRICT AS $$ +DECLARE + capture account_start_session_authority_captures%ROWTYPE; + world_parent account_start_session_world_participations%ROWTYPE; + observation account_start_session_world_original_attempt_evidence%ROWTYPE; + authorization_row account_start_session_operator_authorizations%ROWTYPE; + retained account_start_session_activation_protections%ROWTYPE; + snapshot_value JSONB; + request_value JSONB; + tuple_value JSONB; + projection_value JSONB; + preparing_value JSONB; + preparing_request JSONB; + source_value JSONB; + source_bytes BYTEA; + source_key_value TEXT; + tuple_bytes BYTEA; + projection_bytes BYTEA; + preparing_bytes BYTEA; + control_request_id TEXT; + requested_participation_id UUID; + keys TEXT[]; + retained_found BOOLEAN := FALSE; +BEGIN + IF octet_length(request_bytes) NOT BETWEEN 1 AND 150994944 + OR octet_length(operation_bytes) NOT BETWEEN 1 AND 150994944 + OR operation_digest IS DISTINCT FROM 'sha256:' || encode(sha256(operation_bytes), 'hex') THEN + RAISE EXCEPTION 'Original StartSession activation request or operation identity is invalid' + USING ERRCODE = '23514'; + END IF; + request_value := convert_from(request_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(request_value) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(request_value)) <> 12 + OR NOT (request_value ?& ARRAY[ + 'schema', 'originalPostAuthorizationTupleBytesBase64', + 'accountRedemptionProjectionBytesBase64', 'gameSessionOwnerMutationId', + 'gameSessionOwnerAttemptId', 'gameSessionOwnerFence', 'originalLeaseExpiresAt', + 'accountWorldParticipationId', 'accountWorldParticipationFence', + 'gameSessionLaunchReadEvidenceBytesBase64', 'worldActivationRequestId', + 'preparingEvidenceBytesBase64']) + OR EXISTS (SELECT 1 FROM jsonb_each(request_value) field WHERE jsonb_typeof(field.value) <> 'string') + OR request_value->>'schema' IS DISTINCT FROM 'account-start-session-activation-protection-request/v1' THEN + RAISE EXCEPTION 'Original StartSession activation request has an unsupported shape' + USING ERRCODE = '23514'; + END IF; + tuple_bytes := decode(request_value->>'originalPostAuthorizationTupleBytesBase64', 'base64'); + projection_bytes := decode(request_value->>'accountRedemptionProjectionBytesBase64', 'base64'); + preparing_bytes := decode(request_value->>'preparingEvidenceBytesBase64', 'base64'); + tuple_value := convert_from(tuple_bytes, 'UTF8')::JSONB; + control_request_id := tuple_value->>'controlPlaneRequestId'; + requested_participation_id := (request_value->>'accountWorldParticipationId')::UUID; + + -- Source-key locks are acquired in the canonical V129 order before any retained owner, + -- World or activation-protection row is locked. + SELECT * INTO STRICT capture FROM account_start_session_authority_captures + WHERE control_plane_request_id = control_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 control_request_id THEN + RAISE EXCEPTION 'Activation protection requires the exact original Account source snapshot' + USING ERRCODE = '23514'; + END IF; + keys := account_start_session_world_participation_lock_sources(snapshot_value); + PERFORM account_start_session_world_participation_assert_exclusive(keys, snapshot_value); + + SELECT * INTO STRICT capture FROM account_start_session_authority_captures + WHERE control_plane_request_id = control_request_id FOR UPDATE NOWAIT; + SELECT * INTO STRICT world_parent FROM account_start_session_world_participations + WHERE account_start_session_world_participations.participation_id = requested_participation_id + FOR UPDATE NOWAIT; + SELECT * INTO STRICT observation FROM account_start_session_world_original_attempt_evidence + WHERE participation_id = world_parent.participation_id FOR UPDATE NOWAIT; + SELECT * INTO STRICT authorization_row FROM account_start_session_operator_authorizations + WHERE control_plane_request_id = control_request_id FOR UPDATE NOWAIT; + SELECT * INTO retained FROM account_start_session_activation_protections + WHERE account_start_session_activation_protections.control_plane_request_id = control_request_id + FOR UPDATE NOWAIT; + retained_found := FOUND; + + preparing_value := convert_from(preparing_bytes, 'UTF8')::JSONB; + preparing_request := preparing_value->'request'; + projection_value := convert_from(projection_bytes, 'UTF8')::JSONB; + IF request_value->>'gameSessionOwnerMutationId' IS DISTINCT FROM observation.game_session_owner_mutation_id::TEXT + OR request_value->>'gameSessionOwnerAttemptId' IS DISTINCT FROM observation.game_session_owner_attempt_id::TEXT + OR request_value->>'gameSessionOwnerFence' IS DISTINCT FROM observation.game_session_owner_fence::TEXT + OR request_value->>'originalLeaseExpiresAt' IS DISTINCT FROM + to_char(observation.original_lease_expires_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') + OR request_value->>'accountWorldParticipationId' IS DISTINCT FROM world_parent.participation_id::TEXT + OR request_value->>'accountWorldParticipationFence' IS DISTINCT FROM world_parent.participation_fence::TEXT + OR world_parent.control_plane_request_id IS DISTINCT FROM control_request_id + OR world_parent.original_post_authorization_tuple IS DISTINCT FROM tuple_bytes + OR world_parent.game_session_owner_attempt_id IS DISTINCT FROM observation.game_session_owner_attempt_id + OR world_parent.game_session_owner_fence IS DISTINCT FROM observation.game_session_owner_fence + OR observation.target_namespace IS DISTINCT FROM world_parent.target_namespace + OR NOT EXISTS ( + SELECT 1 FROM account_start_session_world_participation_settlements settlement + WHERE settlement.participation_id = world_parent.participation_id + AND settlement.outcome = 'COMMITTED') + OR preparing_value->>'schema' IS DISTINCT FROM 'world-canonical-instance-lifecycle-evidence/v1' + OR preparing_value->>'lifecycleStatus' IS DISTINCT FROM 'PREPARING' + OR preparing_request->>'controlPlaneRequestId' IS DISTINCT FROM control_request_id + OR preparing_request->>'targetNamespace' IS DISTINCT FROM world_parent.target_namespace + OR preparing_request->>'canonicalTenantId' IS DISTINCT FROM world_parent.canonical_tenant_id::TEXT + OR preparing_request->>'canonicalGameInstanceId' IS DISTINCT FROM world_parent.canonical_game_instance_id::TEXT + OR capture.source_version <= 0 OR capture.source_fence <= 0 THEN + RAISE EXCEPTION 'Activation protection differs from committed original World preparation or attempt' + USING ERRCODE = '23514'; + END IF; + + -- Retain the original Account issuance/redemption tuple and complete projection exactly. + IF capture.canonical_sha256 IS DISTINCT FROM encode(sha256(capture.canonical_capture_bytes), 'hex') + OR capture.snapshot_sha256 IS DISTINCT FROM encode(sha256(capture.canonical_snapshot_bytes), 'hex') + OR capture.pre_authorization_tuple IS DISTINCT FROM authorization_row.pre_authorization_tuple + OR capture.issuance_fence IS DISTINCT FROM authorization_row.issuance_fence + OR authorization_row.status IS DISTINCT FROM 'REDEEMED' + OR authorization_row.redemption_owner_attempt_id IS DISTINCT FROM observation.game_session_owner_attempt_id + OR authorization_row.redemption_owner_fence IS DISTINCT FROM observation.game_session_owner_fence + 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 tuple_value->'preAuthorizationReservationTuple' IS DISTINCT FROM convert_from(authorization_row.pre_authorization_tuple, 'UTF8')::JSONB + 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->'authorityEvidenceBundle' IS DISTINCT FROM convert_from(authorization_row.authority_evidence_bundle, 'UTF8')::JSONB + OR projection_bytes IS DISTINCT FROM tuple_bytes + OR projection_value #>> '{authorityEvidenceBundle,issuanceOperationIdentity,issuanceOperationId}' + IS DISTINCT FROM authorization_row.issuance_operation_id::TEXT + OR capture.canonical_sha256 IS DISTINCT FROM encode(sha256(capture.canonical_capture_bytes), 'hex') THEN + RAISE EXCEPTION 'Activation protection differs from original Account redemption or capture' + USING ERRCODE = '23514'; + END IF; + + IF retained_found AND ( + retained.operation_identity_bytes IS DISTINCT FROM operation_bytes + OR retained.operation_identity_digest IS DISTINCT FROM operation_digest + OR retained.account_world_participation_id IS DISTINCT FROM world_parent.participation_id + OR retained.account_world_participation_fence IS DISTINCT FROM world_parent.participation_fence) THEN + RAISE EXCEPTION 'Original StartSession activation protection conflicts with its immutable binding' + USING ERRCODE = '23514'; + END IF; + + -- The typed Common carrier validates the closed Game Session STARTING result and exact + -- World PREPARING evidence. SQL independently checks finite original authority only after + -- all canonical source and owner/protection row locks have completed. + IF observation.original_lease_expires_at IS DISTINCT FROM + (request_value->>'originalLeaseExpiresAt')::TIMESTAMPTZ + OR observation.original_lease_expires_at <= clock_timestamp() + OR authorization_row.reference_expires_at <= clock_timestamp() THEN + RAISE EXCEPTION 'Original StartSession activation protection lease is stale or expired' + USING ERRCODE = '23514'; + END IF; + + PERFORM account_start_session_world_participation_assert_sources(world_parent.participation_id, snapshot_value); + IF require_complete THEN + IF (SELECT count(*) FROM account_start_session_activation_protection_sources + WHERE activation_protection_id = retained.activation_protection_id) + <> jsonb_array_length(snapshot_value->'sourceVector') THEN + RAISE EXCEPTION 'Activation protection 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 + source_bytes := decode(source_value #>> '{}', 'base64'); + source_key_value := account_start_session_world_participation_source_key(source_bytes); + IF NOT EXISTS (SELECT 1 FROM account_start_session_activation_protection_sources + WHERE activation_protection_id = retained.activation_protection_id + AND source_key = source_key_value AND source_evidence = source_bytes) THEN + RAISE EXCEPTION 'Activation protection source child differs from original capture' + USING ERRCODE = '23514'; + END IF; + END LOOP; + END IF; +END; +$$; + +CREATE FUNCTION account_ss_activation_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + request_value JSONB; + tuple_bytes BYTEA; + projection_bytes BYTEA; + launch_bytes BYTEA; + preparing_bytes BYTEA; +BEGIN + IF NEW.producer_xid IS DISTINCT FROM txid_current() + OR NEW.capture_sha256 IS DISTINCT FROM encode(sha256(NEW.capture_reference_bytes), 'hex') THEN + RAISE EXCEPTION 'Activation protection must retain its producer capture transaction and digest' + USING ERRCODE = '23514'; + END IF; + request_value := convert_from(NEW.request_binding_bytes, 'UTF8')::JSONB; + tuple_bytes := decode(request_value->>'originalPostAuthorizationTupleBytesBase64', 'base64'); + projection_bytes := decode(request_value->>'accountRedemptionProjectionBytesBase64', 'base64'); + launch_bytes := decode(request_value->>'gameSessionLaunchReadEvidenceBytesBase64', 'base64'); + preparing_bytes := decode(request_value->>'preparingEvidenceBytesBase64', 'base64'); + IF NEW.control_plane_request_id IS DISTINCT FROM + (convert_from(tuple_bytes, 'UTF8')::JSONB->>'controlPlaneRequestId') + OR NEW.original_post_authorization_tuple IS DISTINCT FROM tuple_bytes + OR NEW.account_redemption_projection IS DISTINCT FROM projection_bytes + OR NEW.game_session_owner_mutation_id IS DISTINCT FROM (request_value->>'gameSessionOwnerMutationId')::UUID + OR NEW.game_session_owner_attempt_id IS DISTINCT FROM (request_value->>'gameSessionOwnerAttemptId')::UUID + OR NEW.game_session_owner_fence IS DISTINCT FROM (request_value->>'gameSessionOwnerFence')::BIGINT + OR NEW.original_lease_expires_at IS DISTINCT FROM (request_value->>'originalLeaseExpiresAt')::TIMESTAMPTZ + OR NEW.account_world_participation_id IS DISTINCT FROM (request_value->>'accountWorldParticipationId')::UUID + OR NEW.account_world_participation_fence IS DISTINCT FROM (request_value->>'accountWorldParticipationFence')::BIGINT + OR NEW.world_activation_request_id IS DISTINCT FROM (request_value->>'worldActivationRequestId')::UUID + OR NEW.game_session_launch_read_evidence IS DISTINCT FROM launch_bytes + OR NEW.world_preparing_evidence IS DISTINCT FROM preparing_bytes + OR NEW.request_binding_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.request_binding_bytes), 'hex') + OR NEW.operation_identity_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.operation_identity_bytes), 'hex') THEN + RAISE EXCEPTION 'Activation protection does not retain its exact canonical request fields' + USING ERRCODE = '23514'; + END IF; + PERFORM account_ss_activation_assert_current( + NEW.request_binding_bytes, NEW.operation_identity_bytes, NEW.operation_identity_digest, FALSE); + IF NOT EXISTS ( + SELECT 1 FROM account_start_session_authority_captures capture + WHERE capture.control_plane_request_id = NEW.control_plane_request_id + AND capture.source_version = NEW.capture_source_version + AND capture.source_fence = NEW.capture_source_fence + AND capture.canonical_sha256 = NEW.capture_sha256 + AND capture.canonical_capture_bytes = NEW.capture_reference_bytes + AND NEW.target_namespace = (convert_from(tuple_bytes, 'UTF8')::JSONB + ->'preAuthorizationReservationTuple'->'scope'->>'targetNamespace') + AND NEW.canonical_tenant_id = (convert_from(tuple_bytes, 'UTF8')::JSONB + ->'preAuthorizationReservationTuple'->'scope'->>'tenantId')::UUID + AND NEW.canonical_game_instance_id = (convert_from(preparing_bytes, 'UTF8')::JSONB + ->'request'->>'canonicalGameInstanceId')::UUID + AND NEW.capture_reference_sha256 = encode(sha256(NEW.capture_reference_bytes), 'hex')) THEN + RAISE EXCEPTION 'Activation protection capture or target differs from the exact current request' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_ss_activation_source_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE producer BIGINT; +BEGIN + SELECT producer_xid INTO STRICT producer FROM account_start_session_activation_protections + WHERE activation_protection_id = NEW.activation_protection_id; + IF producer 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 'Activation protection sources must be exact same-producer children' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_ss_activation_complete_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE original account_start_session_activation_protections%ROWTYPE; +BEGIN + SELECT * INTO STRICT original FROM account_start_session_activation_protections + WHERE activation_protection_id = NEW.activation_protection_id; + PERFORM account_ss_activation_assert_current( + original.request_binding_bytes, original.operation_identity_bytes, + original.operation_identity_digest, TRUE); + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_ss_activation_no_mutation() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Original StartSession activation protection is immutable and has no settlement path' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_ss_activation_validate BEFORE INSERT ON account_start_session_activation_protections + FOR EACH ROW EXECUTE FUNCTION account_ss_activation_insert_guard(); +CREATE TRIGGER account_ss_activation_immutable BEFORE UPDATE OR DELETE ON account_start_session_activation_protections + FOR EACH ROW EXECUTE FUNCTION account_ss_activation_no_mutation(); +CREATE TRIGGER account_ss_activation_no_truncate BEFORE TRUNCATE ON account_start_session_activation_protections + FOR EACH STATEMENT EXECUTE FUNCTION account_ss_activation_no_mutation(); +CREATE TRIGGER account_ss_activation_sources_validate BEFORE INSERT ON account_start_session_activation_protection_sources + FOR EACH ROW EXECUTE FUNCTION account_ss_activation_source_insert_guard(); +CREATE TRIGGER account_ss_activation_sources_immutable BEFORE UPDATE OR DELETE ON account_start_session_activation_protection_sources + FOR EACH ROW EXECUTE FUNCTION account_ss_activation_no_mutation(); +CREATE TRIGGER account_ss_activation_sources_no_truncate BEFORE TRUNCATE ON account_start_session_activation_protection_sources + FOR EACH STATEMENT EXECUTE FUNCTION account_ss_activation_no_mutation(); +CREATE CONSTRAINT TRIGGER account_ss_activation_complete AFTER INSERT ON account_start_session_activation_protections + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_ss_activation_complete_guard(); + +-- Existing assembled source-writer guards call this helper after locking their canonical +-- source keys. Keep every admission check installed above and add the permanently pending activation rows. +CREATE OR REPLACE FUNCTION account_ss_admission_assert_no_pending(source_keys TEXT[]) +RETURNS VOID LANGUAGE plpgsql VOLATILE STRICT AS $$ +BEGIN + PERFORM protection.protection_id + FROM account_start_session_admission_protections protection + JOIN account_start_session_admission_protection_sources source + ON source.protection_id = protection.protection_id + WHERE source.source_key = ANY(source_keys) + AND NOT account_ss_admission_is_settled(protection.protection_id) + ORDER BY protection.protection_id FOR UPDATE OF protection NOWAIT; + IF FOUND THEN + RAISE EXCEPTION 'Original StartSession admission protection remains pending for a required source' + USING ERRCODE = '55P03'; + END IF; + PERFORM protection.activation_protection_id + FROM account_start_session_activation_protections protection + JOIN account_start_session_activation_protection_sources source + ON source.activation_protection_id = protection.activation_protection_id + WHERE source.source_key = ANY(source_keys) + ORDER BY protection.activation_protection_id FOR UPDATE OF protection NOWAIT; + IF FOUND THEN + RAISE EXCEPTION 'Original StartSession activation protection remains pending for a required source' + USING ERRCODE = '55P03'; + END IF; +END; +$$; +-- [jooq ignore end] + + +-- Append-only resolution of the distinct original StartSession activation source protection. +-- Only an exact authenticated World ACTIVE or fenced ABORTED terminal receipt may be recorded; +-- expiry, missing World state, timeout, generic close, and absence are not terminal outcomes. +CREATE TABLE account_start_session_activation_protection_settlements ( + activation_protection_id UUID PRIMARY KEY + REFERENCES account_start_session_activation_protections(activation_protection_id) ON DELETE RESTRICT, + activation_protection_fence BIGINT NOT NULL CHECK (activation_protection_fence > 0), + world_activation_request_id UUID NOT NULL + CHECK (world_activation_request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + world_activation_fence BIGINT NOT NULL CHECK (world_activation_fence > 0), + outcome VARCHAR(16) NOT NULL CHECK (outcome IN ('COMMITTED', 'ABORTED')), + account_protection_evidence_bytes BYTEA NOT NULL + CHECK (octet_length(account_protection_evidence_bytes) BETWEEN 1 AND 209715264), + terminal_bytes BYTEA NOT NULL + CHECK (octet_length(terminal_bytes) BETWEEN 1 AND 805306368), + terminal_digest VARCHAR(71) NOT NULL + CHECK (terminal_digest = 'sha256:' || encode(sha256(terminal_bytes), 'hex')), + settled_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() + CHECK (isfinite(settled_at)) +); + +-- [jooq ignore start] +CREATE FUNCTION account_ss_activation_settlement_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_start_session_activation_protections%ROWTYPE; + terminal JSONB; + protection_evidence JSONB; + protection_request JSONB; + protection_request_bytes BYTEA; + result_value JSONB; + result_bytes BYTEA; + result_request_bytes BYTEA; + preparing_bytes BYTEA; + preparing_value JSONB; + preparing_request JSONB; + expected_preparing JSONB; + expected_activation_request JSONB; + expected_source_vector JSONB; + source_count BIGINT; + evidence_base64 TEXT; +BEGIN + SELECT * INTO STRICT original FROM account_start_session_activation_protections + WHERE activation_protection_id = NEW.activation_protection_id; + terminal := convert_from(NEW.terminal_bytes, 'UTF8')::JSONB; + evidence_base64 := replace(replace(encode(NEW.account_protection_evidence_bytes, 'base64'), E'\n', ''), E'\r', ''); + protection_evidence := convert_from(NEW.account_protection_evidence_bytes, 'UTF8')::JSONB; + protection_request_bytes := decode(protection_evidence->>'requestBytesBase64', 'base64'); + protection_request := convert_from(protection_request_bytes, 'UTF8')::JSONB; + preparing_bytes := decode(protection_request->>'preparingEvidenceBytesBase64', 'base64'); + preparing_value := convert_from(preparing_bytes, 'UTF8')::JSONB; + preparing_request := preparing_value->'request'; + expected_preparing := jsonb_set( + preparing_value, '{request}', preparing_request - 'readRequestId', FALSE); + expected_activation_request := jsonb_build_object( + 'schema', 'world-canonical-instance-activation-request/v1', + 'activationRequestId', original.world_activation_request_id::TEXT, + 'preparingEvidence', expected_preparing); + result_bytes := decode(terminal->>'activationResultBytesBase64', 'base64'); + result_value := convert_from(result_bytes, 'UTF8')::JSONB; + result_request_bytes := decode(result_value->>'requestBytesBase64', 'base64'); + SELECT count(*) INTO source_count + FROM account_start_session_activation_protection_sources + WHERE activation_protection_id = original.activation_protection_id; + SELECT COALESCE( + jsonb_agg( + to_jsonb(replace(replace(encode(source.source_evidence, 'base64'), E'\n', ''), E'\r', '')) + ORDER BY source.source_key), + '[]'::JSONB) + INTO expected_source_vector + FROM account_start_session_activation_protection_sources source + WHERE source.activation_protection_id = original.activation_protection_id; + IF NEW.activation_protection_fence IS DISTINCT FROM original.activation_protection_fence + OR NEW.world_activation_request_id IS DISTINCT FROM original.world_activation_request_id + OR NEW.terminal_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.terminal_bytes), 'hex') + OR jsonb_typeof(protection_evidence) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(protection_evidence)) <> 8 + OR NOT (protection_evidence ?& ARRAY[ + 'schema', 'requestBytesBase64', 'accountProtectionId', 'accountProtectionFence', + 'acquiredAt', 'originalSourceCaptureReferenceBytesBase64', + 'originalSourceCaptureReferenceSha256', 'sourceEvidenceVector']) + OR protection_evidence->>'schema' IS DISTINCT FROM 'account-start-session-activation-protection-evidence/v1' + OR protection_evidence->>'accountProtectionId' IS DISTINCT FROM original.activation_protection_id::TEXT + OR protection_evidence->>'accountProtectionFence' IS DISTINCT FROM original.activation_protection_fence::TEXT + OR protection_evidence->>'acquiredAt' IS DISTINCT FROM + to_char(original.acquired_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') + OR protection_evidence->>'requestBytesBase64' IS DISTINCT FROM + replace(replace(encode(original.request_binding_bytes, 'base64'), E'\n', ''), E'\r', '') + OR protection_request_bytes IS DISTINCT FROM original.request_binding_bytes + OR jsonb_typeof(protection_request) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(protection_request)) <> 12 + OR NOT (protection_request ?& ARRAY[ + 'schema', 'originalPostAuthorizationTupleBytesBase64', + 'accountRedemptionProjectionBytesBase64', 'gameSessionOwnerMutationId', + 'gameSessionOwnerAttemptId', 'gameSessionOwnerFence', 'originalLeaseExpiresAt', + 'accountWorldParticipationId', 'accountWorldParticipationFence', + 'gameSessionLaunchReadEvidenceBytesBase64', 'worldActivationRequestId', + 'preparingEvidenceBytesBase64']) + OR protection_request->>'schema' IS DISTINCT FROM 'account-start-session-activation-protection-request/v1' + OR decode(protection_request->>'originalPostAuthorizationTupleBytesBase64', 'base64') + IS DISTINCT FROM original.original_post_authorization_tuple + OR decode(protection_request->>'accountRedemptionProjectionBytesBase64', 'base64') + IS DISTINCT FROM original.account_redemption_projection + OR protection_request->>'gameSessionOwnerMutationId' + IS DISTINCT FROM original.game_session_owner_mutation_id::TEXT + OR protection_request->>'gameSessionOwnerAttemptId' + IS DISTINCT FROM original.game_session_owner_attempt_id::TEXT + OR protection_request->>'gameSessionOwnerFence' + IS DISTINCT FROM original.game_session_owner_fence::TEXT + OR protection_request->>'originalLeaseExpiresAt' IS DISTINCT FROM + to_char(original.original_lease_expires_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') + OR protection_request->>'accountWorldParticipationId' + IS DISTINCT FROM original.account_world_participation_id::TEXT + OR protection_request->>'accountWorldParticipationFence' + IS DISTINCT FROM original.account_world_participation_fence::TEXT + OR decode(protection_request->>'gameSessionLaunchReadEvidenceBytesBase64', 'base64') + IS DISTINCT FROM original.game_session_launch_read_evidence + OR protection_request->>'worldActivationRequestId' IS DISTINCT FROM original.world_activation_request_id::TEXT + OR protection_request->>'preparingEvidenceBytesBase64' IS DISTINCT FROM + replace(replace(encode(original.world_preparing_evidence, 'base64'), E'\n', ''), E'\r', '') + OR protection_evidence->>'originalSourceCaptureReferenceBytesBase64' IS DISTINCT FROM + replace(replace(encode(original.capture_reference_bytes, 'base64'), E'\n', ''), E'\r', '') + OR protection_evidence->>'originalSourceCaptureReferenceSha256' IS DISTINCT FROM + encode(sha256(original.capture_reference_bytes), 'hex') + OR original.capture_reference_sha256 IS DISTINCT FROM + encode(sha256(original.capture_reference_bytes), 'hex') + OR jsonb_typeof(protection_evidence->'sourceEvidenceVector') IS DISTINCT FROM 'array' + OR source_count <= 0 + OR jsonb_array_length(protection_evidence->'sourceEvidenceVector') IS DISTINCT FROM source_count + OR protection_evidence->'sourceEvidenceVector' IS DISTINCT FROM expected_source_vector + OR EXISTS ( + SELECT 1 FROM account_start_session_activation_protection_sources source + WHERE source.activation_protection_id = original.activation_protection_id + AND account_start_session_world_participation_source_key(source.source_evidence) + IS DISTINCT FROM source.source_key) + OR jsonb_typeof(terminal) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(terminal)) <> 8 + OR NOT (terminal ?& ARRAY[ + 'schema', 'activationRequestId', 'accountProtectionId', 'accountProtectionFence', + 'worldActivationFence', 'accountProtectionEvidenceBytesBase64', + 'activationResultBytesBase64', 'activationResultSha256']) + OR terminal->>'schema' IS DISTINCT FROM 'world-original-start-session-activation-terminal-evidence/v1' + OR terminal->>'activationRequestId' IS DISTINCT FROM NEW.world_activation_request_id::TEXT + OR terminal->>'accountProtectionId' IS DISTINCT FROM NEW.activation_protection_id::TEXT + OR terminal->>'accountProtectionFence' IS DISTINCT FROM NEW.activation_protection_fence::TEXT + OR terminal->>'worldActivationFence' IS DISTINCT FROM NEW.world_activation_fence::TEXT + OR terminal->>'accountProtectionEvidenceBytesBase64' IS DISTINCT FROM evidence_base64 + OR terminal->>'activationResultSha256' IS DISTINCT FROM encode(sha256(result_bytes), 'hex') + OR result_value IS NULL + OR jsonb_typeof(result_value) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(result_value)) <> 8 + OR NOT (result_value ?& ARRAY[ + 'schema', 'activationRequestId', 'requestDigest', 'requestBytesBase64', + 'preparingEvidenceBytesBase64', 'outcome', 'terminalCode', + 'lifecycleEvidenceBytesBase64']) + OR result_value->>'schema' IS DISTINCT FROM 'world-canonical-instance-activation-result/v1' + OR result_value->>'activationRequestId' IS DISTINCT FROM NEW.world_activation_request_id::TEXT + OR result_value->>'requestDigest' IS DISTINCT FROM + 'sha256:' || encode(sha256(result_request_bytes), 'hex') + OR convert_from(result_request_bytes, 'UTF8')::JSONB IS DISTINCT FROM expected_activation_request + OR result_value->>'requestBytesBase64' IS DISTINCT FROM + replace(replace(encode(result_request_bytes, 'base64'), E'\n', ''), E'\r', '') + OR result_value->>'preparingEvidenceBytesBase64' IS DISTINCT FROM + replace(replace(encode(original.world_preparing_evidence, 'base64'), E'\n', ''), E'\r', '') + OR result_value->>'outcome' IS DISTINCT FROM NEW.outcome + OR (NEW.outcome = 'COMMITTED' AND result_value->'terminalCode' IS DISTINCT FROM 'null'::JSONB) + OR (NEW.outcome = 'ABORTED' + AND (jsonb_typeof(result_value->'terminalCode') IS DISTINCT FROM 'string' + OR length(result_value->>'terminalCode') = 0)) THEN + RAISE EXCEPTION 'Activation settlement must retain the exact terminal receipt for its protection' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_ss_activation_settlement_no_mutation() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Original StartSession activation settlement is immutable' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_ss_activation_settlement_validate + BEFORE INSERT ON account_start_session_activation_protection_settlements + FOR EACH ROW EXECUTE FUNCTION account_ss_activation_settlement_insert_guard(); +CREATE TRIGGER account_ss_activation_settlement_immutable + BEFORE UPDATE OR DELETE ON account_start_session_activation_protection_settlements + FOR EACH ROW EXECUTE FUNCTION account_ss_activation_settlement_no_mutation(); +CREATE TRIGGER account_ss_activation_settlement_no_truncate + BEFORE TRUNCATE ON account_start_session_activation_protection_settlements + FOR EACH STATEMENT EXECUTE FUNCTION account_ss_activation_settlement_no_mutation(); + +CREATE OR REPLACE FUNCTION account_ss_activation_no_mutation() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Original StartSession activation protection is immutable; terminal settlement is separate and append-only' + USING ERRCODE = '23514'; +END; +$$; + +-- Preserve the admission-protection branch and settle activation source guards only when an +-- exact terminal receipt exists. Existing V129 source writers already call this shared function. +CREATE OR REPLACE FUNCTION account_ss_admission_assert_no_pending(source_keys TEXT[]) +RETURNS VOID LANGUAGE plpgsql VOLATILE STRICT AS $$ +BEGIN + PERFORM protection.protection_id + FROM account_start_session_admission_protections protection + JOIN account_start_session_admission_protection_sources source + ON source.protection_id = protection.protection_id + WHERE source.source_key = ANY(source_keys) + AND NOT account_ss_admission_is_settled(protection.protection_id) + ORDER BY protection.protection_id FOR UPDATE OF protection NOWAIT; + IF FOUND THEN + RAISE EXCEPTION 'Original StartSession admission protection remains pending for a required source' + USING ERRCODE = '55P03'; + END IF; + + PERFORM protection.activation_protection_id + FROM account_start_session_activation_protections protection + JOIN account_start_session_activation_protection_sources source + ON source.activation_protection_id = protection.activation_protection_id + WHERE source.source_key = ANY(source_keys) + AND NOT EXISTS ( + SELECT 1 FROM account_start_session_activation_protection_settlements settlement + WHERE settlement.activation_protection_id = protection.activation_protection_id) + ORDER BY protection.activation_protection_id FOR UPDATE OF protection NOWAIT; + IF FOUND THEN + RAISE EXCEPTION 'Original StartSession activation protection remains pending for a required source' + USING ERRCODE = '55P03'; + END IF; +END; +$$; +-- [jooq ignore end] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java new file mode 100644 index 0000000000..11f3d490a8 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java @@ -0,0 +1,1041 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Field; +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; +import tools.jackson.databind.json.JsonMapper; + +/** + * Runs V165 against the actual Account PostgreSQL schema and assembled source-writer guard. The + * integrity and currentness fixtures seed related owner rows with producer triggers disabled; they + * prove SQL currentness/exclusion/immutability only, not authenticated activation-protection + * production. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountStartSessionActivationProtectionPostgresIntegrationTest { + @Container + static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void databaseOwnsProtectionIdentityAndPendingProtectionBlocksSourceWriters() throws Exception { + Fixture fixture = fixture(); + UUID participationId = UUID.randomUUID(); + UUID ownerMutationId = UUID.randomUUID(); + UUID ownerAttemptId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID gameInstanceId = UUID.randomUUID(); + UUID activationRequestId = UUID.randomUUID(); + byte[] captureReference = bytes("capture-reference"); + byte[] operationIdentity = bytes("{\"schema\":\"activation-operation-test/v1\"}"); + String captureDigest = hash(captureReference); + String operationDigest = "sha256:" + hash(operationIdentity); + OffsetDateTime expiry = + fixture + .dsl() + .fetchSingle("SELECT clock_timestamp() - INTERVAL '1 minute'") + .get(0, OffsetDateTime.class); + OffsetDateTime acquiredAt = expiry.minusMinutes(1); + String expiryText = timestamp(expiry); + SourceEvidence sourceEvidence = + new SourceEvidence( + SourceKind.ACCOUNT, + tenantId.toString(), + "2", + "17", + null, + null, + bytes("captured activation source")); + String sourceKey = sourceEvidence.key(); + byte[] sourceEvidenceBytes = sourceEvidence.canonicalBytes(); + byte[] tuple = bytes("synthetic original tuple"); + byte[] projection = bytes("synthetic Account redemption projection"); + byte[] launchRead = bytes("synthetic authenticated STARTING launch read"); + byte[] preparingEvidence = + jsonBytes( + Map.of( + "schema", + "world-canonical-instance-lifecycle-evidence/v1", + "request", + Map.of( + "readRequestId", + UUID.randomUUID().toString(), + "controlPlaneRequestId", + fixture.requestId(), + "targetNamespace", + "test", + "canonicalTenantId", + tenantId.toString(), + "canonicalGameInstanceId", + gameInstanceId.toString()), + "lifecycleStatus", + "PREPARING", + "lifecycleEpoch", + 12, + "rowVersion", + 19)); + byte[] requestBinding = + activationRequest( + tuple, + projection, + ownerMutationId, + ownerAttemptId, + 11L, + expiryText, + participationId, + 7L, + launchRead, + activationRequestId, + preparingEvidence); + String requestDigest = "sha256:" + hash(requestBinding); + + fixture + .transaction() + .executeWithoutResult( + status -> { + fixture + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?)", + sourceKey); + fixture.dsl().execute("SET LOCAL session_replication_role = replica"); + insert( + fixture.dsl(), + "account_start_session_activation_protections", + "control_plane_request_id", + fixture.requestId(), + "account_world_participation_id", + participationId, + "account_world_participation_fence", + 7L, + "original_post_authorization_tuple", + tuple, + "account_redemption_projection", + projection, + "game_session_owner_mutation_id", + ownerMutationId, + "game_session_owner_attempt_id", + ownerAttemptId, + "game_session_owner_fence", + 11L, + "original_lease_expires_at", + expiry, + "acquired_at", + acquiredAt, + "target_namespace", + "test", + "canonical_tenant_id", + tenantId, + "canonical_game_instance_id", + gameInstanceId, + "world_activation_request_id", + activationRequestId, + "game_session_launch_read_evidence", + launchRead, + "world_preparing_evidence", + preparingEvidence, + "capture_source_version", + 13L, + "capture_source_fence", + 17L, + "capture_sha256", + captureDigest, + "capture_reference_bytes", + captureReference, + "capture_reference_sha256", + captureDigest, + "operation_identity_bytes", + operationIdentity, + "operation_identity_digest", + operationDigest, + "request_binding_bytes", + requestBinding, + "request_binding_digest", + requestDigest); + var parent = + fixture + .dsl() + .fetchSingle( + "SELECT activation_protection_id, activation_protection_fence, " + + "acquired_at " + + "FROM account_start_session_activation_protections " + + "WHERE control_plane_request_id = ?", + fixture.requestId()); + UUID id = parent.get("activation_protection_id", UUID.class); + insert( + fixture.dsl(), + "account_start_session_activation_protection_sources", + "activation_protection_id", + id, + "source_key", + sourceKey, + "source_evidence", + sourceEvidenceBytes); + fixture.dsl().execute("SET LOCAL session_replication_role = origin"); + }); + + var stored = + fixture + .dsl() + .fetchSingle( + "SELECT activation_protection_id, activation_protection_fence, acquired_at " + + "FROM account_start_session_activation_protections " + + "WHERE operation_identity_digest = ?", + operationDigest); + UUID id = stored.get("activation_protection_id", UUID.class); + assertThat(id).isNotNull().isNotEqualTo(new UUID(0L, 0L)); + assertThat(stored.get("activation_protection_fence", Long.class)).isPositive(); + assertThat(stored.get("acquired_at", OffsetDateTime.class)).isNotNull(); + + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "UPDATE account_start_session_activation_protections " + + "SET acquired_at = acquired_at " + + "WHERE activation_protection_id = ?", + id))) + .hasMessageContaining("immutable; terminal settlement is separate"); + + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(" + + "ARRAY[?]::text[])", + sourceKey))) + .hasMessageContaining("Original StartSession activation protection remains pending"); + + // This synthetic SQL receipt proves only that V165 permits a source writer after an immutable + // terminal-shaped row is committed. It is not a typed receipt or authenticated World producer + // proof. The original Account lease is deliberately expired before this settlement insert. + OffsetDateTime retainedAcquiredAt = stored.get("acquired_at", OffsetDateTime.class); + long protectionFence = stored.get("activation_protection_fence", Long.class); + byte[] accountEvidenceBytes = + accountEvidence( + id, + protectionFence, + retainedAcquiredAt, + requestBinding, + captureReference, + sourceEvidenceBytes); + byte[] activationResultBytes = + activationResult(activationRequestId, preparingEvidence, "COMMITTED"); + + Map changedCapture = readJson(accountEvidenceBytes); + byte[] wrongCapture = bytes("substituted capture reference"); + changedCapture.put( + "originalSourceCaptureReferenceBytesBase64", + Base64.getEncoder().encodeToString(wrongCapture)); + changedCapture.put("originalSourceCaptureReferenceSha256", hash(wrongCapture)); + assertSettlementInsertRejected( + fixture, + id, + protectionFence, + activationRequestId, + accountEvidenceBytes(changedCapture), + activationResultBytes); + + Map changedRequest = readJson(accountEvidenceBytes); + changedRequest.put( + "requestBytesBase64", + Base64.getEncoder().encodeToString(bytes("{\"schema\":\"substituted-request/v1\"}"))); + assertSettlementInsertRejected( + fixture, + id, + protectionFence, + activationRequestId, + accountEvidenceBytes(changedRequest), + activationResultBytes); + + Map changedSources = readJson(accountEvidenceBytes); + changedSources.put( + "sourceEvidenceVector", + java.util.List.of(Base64.getEncoder().encodeToString(bytes("substituted source")))); + assertSettlementInsertRejected( + fixture, + id, + protectionFence, + activationRequestId, + accountEvidenceBytes(changedSources), + activationResultBytes); + + byte[] terminalBytes = + terminalBytes( + id, protectionFence, activationRequestId, accountEvidenceBytes, activationResultBytes); + fixture + .transaction() + .executeWithoutResult( + status -> + insert( + fixture.dsl(), + "account_start_session_activation_protection_settlements", + "activation_protection_id", + id, + "activation_protection_fence", + protectionFence, + "world_activation_request_id", + activationRequestId, + "world_activation_fence", + 29L, + "outcome", + "COMMITTED", + "account_protection_evidence_bytes", + accountEvidenceBytes, + "terminal_bytes", + terminalBytes, + "terminal_digest", + "sha256:" + hash(terminalBytes))); + + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey)); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "UPDATE account_start_session_activation_protection_settlements " + + "SET outcome = outcome WHERE activation_protection_id = ?", + id))) + .hasMessageContaining("activation settlement is immutable"); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "DELETE FROM account_start_session_activation_protection_settlements " + + "WHERE activation_protection_id = ?", + id))) + .hasMessageContaining("activation settlement is immutable"); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "TRUNCATE account_start_session_activation_protection_settlements"))) + .hasMessageContaining("activation settlement is immutable"); + + for (String guard : + new String[] { + "account_control_ui_hold_required_sources(text[])", + "account_draft_authorization_source_change_guard()", + "account_hosted_terms_disclosure_handoff_guard()" + }) { + String guardDefinition = + fixture + .dsl() + .fetchSingle("SELECT pg_get_functiondef(?::regprocedure)", guard) + .get(0, String.class); + assertThat(guardDefinition) + .contains("account_ss_admission_assert_no_pending") + .contains("account_start_session_world_participations"); + } + String pendingProtectionDefinition = + fixture + .dsl() + .fetchSingle( + "SELECT pg_get_functiondef('account_ss_admission_assert_no_pending(text[])'::regprocedure)") + .get(0, String.class); + assertThat(pendingProtectionDefinition) + .contains("account_start_session_admission_protection_sources") + .contains("account_ss_admission_is_settled") + .contains("account_start_session_activation_protection_settlements"); + } + + @Test + void currentnessRequiresCommittedPreparationExactAttemptAndUnexpiredLease() throws Exception { + Fixture fixture = fixture(); + CurrentnessCase valid = currentnessCase(fixture, Instant.now().plusSeconds(60)); + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_ss_activation_assert_current(?, ?, ?, FALSE)", + valid.requestBytes(), + valid.operationIdentityBytes(), + valid.operationIdentityDigest())); + + Map changedProjectionRequest = + JSON.readValue(valid.requestBytes(), new tools.jackson.core.type.TypeReference<>() {}); + byte[] originalTuple = + Base64.getDecoder() + .decode( + (String) changedProjectionRequest.get("originalPostAuthorizationTupleBytesBase64")); + byte[] differentSpelling = + (" " + new String(originalTuple, StandardCharsets.UTF_8)).getBytes(StandardCharsets.UTF_8); + changedProjectionRequest.put( + "accountRedemptionProjectionBytesBase64", + Base64.getEncoder().encodeToString(differentSpelling)); + byte[] changedProjection = jsonBytes(changedProjectionRequest); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_ss_activation_assert_current(?, ?, ?, FALSE)", + changedProjection, + valid.operationIdentityBytes(), + valid.operationIdentityDigest()))) + .hasMessageContaining( + "Activation protection differs from original Account redemption or capture"); + + byte[] changedAttempt = + activationRequest(valid, UUID.randomUUID().toString(), valid.expiryText(), "PREPARING"); + assertCurrentnessRejected(fixture, changedAttempt, valid.operationIdentityBytes()); + + byte[] changedWorldState = + activationRequest(valid, valid.ownerAttemptId().toString(), valid.expiryText(), "ACTIVE"); + assertCurrentnessRejected(fixture, changedWorldState, valid.operationIdentityBytes()); + + Fixture expiredFixture = fixture(); + CurrentnessCase expired = currentnessCase(expiredFixture, Instant.now().minusSeconds(1)); + assertCurrentnessRejected( + expiredFixture, expired.requestBytes(), expired.operationIdentityBytes()); + } + + private static void assertSettlementInsertRejected( + Fixture fixture, + UUID protectionId, + long protectionFence, + UUID activationRequestId, + byte[] protectionEvidenceBytes, + byte[] activationResultBytes) { + byte[] terminalBytes = + terminalBytes( + protectionId, + protectionFence, + activationRequestId, + protectionEvidenceBytes, + activationResultBytes); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + insert( + fixture.dsl(), + "account_start_session_activation_protection_settlements", + "activation_protection_id", + protectionId, + "activation_protection_fence", + protectionFence, + "world_activation_request_id", + activationRequestId, + "world_activation_fence", + 29L, + "outcome", + "COMMITTED", + "account_protection_evidence_bytes", + protectionEvidenceBytes, + "terminal_bytes", + terminalBytes, + "terminal_digest", + "sha256:" + hash(terminalBytes)))) + .isInstanceOf(RuntimeException.class) + .satisfies( + failure -> { + Throwable postgresFailure = failure; + while (postgresFailure.getCause() != null) { + postgresFailure = postgresFailure.getCause(); + } + assertThat(postgresFailure) + .isInstanceOfSatisfying( + org.postgresql.util.PSQLException.class, + sqlFailure -> assertThat(sqlFailure.getSQLState()).isEqualTo("23514")); + }); + } + + private static byte[] accountEvidence( + UUID protectionId, + long protectionFence, + OffsetDateTime acquiredAt, + byte[] requestBytes, + byte[] captureReference, + byte[] sourceEvidence) + throws Exception { + Map value = new LinkedHashMap<>(); + value.put("schema", "account-start-session-activation-protection-evidence/v1"); + value.put("requestBytesBase64", Base64.getEncoder().encodeToString(requestBytes)); + value.put("accountProtectionId", protectionId.toString()); + value.put("accountProtectionFence", Long.toString(protectionFence)); + value.put("acquiredAt", timestamp(acquiredAt)); + value.put( + "originalSourceCaptureReferenceBytesBase64", + Base64.getEncoder().encodeToString(captureReference)); + value.put("originalSourceCaptureReferenceSha256", hash(captureReference)); + value.put( + "sourceEvidenceVector", + java.util.List.of(Base64.getEncoder().encodeToString(sourceEvidence))); + return jsonBytes(value); + } + + private static byte[] accountEvidenceBytes(Map value) throws Exception { + return jsonBytes(value); + } + + private static byte[] activationResult( + UUID activationRequestId, byte[] preparingEvidence, String outcome) throws Exception { + Map preparing = readJson(preparingEvidence); + @SuppressWarnings("unchecked") + Map lifecycleRequest = (Map) preparing.get("request"); + lifecycleRequest.remove("readRequestId"); + Map activationRequest = new LinkedHashMap<>(); + activationRequest.put("schema", "world-canonical-instance-activation-request/v1"); + activationRequest.put("activationRequestId", activationRequestId.toString()); + activationRequest.put("preparingEvidence", preparing); + byte[] activationRequestBytes = jsonBytes(activationRequest); + + Map result = new LinkedHashMap<>(); + result.put("schema", "world-canonical-instance-activation-result/v1"); + result.put("activationRequestId", activationRequestId.toString()); + result.put("requestDigest", "sha256:" + hash(activationRequestBytes)); + result.put("requestBytesBase64", Base64.getEncoder().encodeToString(activationRequestBytes)); + result.put( + "preparingEvidenceBytesBase64", Base64.getEncoder().encodeToString(preparingEvidence)); + result.put("outcome", outcome); + result.put("terminalCode", "COMMITTED".equals(outcome) ? null : "FENCED_ABORT"); + result.put( + "lifecycleEvidenceBytesBase64", + Base64.getEncoder().encodeToString(bytes("synthetic ACTIVE"))); + return jsonBytes(result); + } + + private static byte[] terminalBytes( + UUID protectionId, + long protectionFence, + UUID activationRequestId, + byte[] protectionEvidenceBytes, + byte[] activationResultBytes) { + Map terminal = new LinkedHashMap<>(); + terminal.put("schema", "world-original-start-session-activation-terminal-evidence/v1"); + terminal.put("activationRequestId", activationRequestId.toString()); + terminal.put("accountProtectionId", protectionId.toString()); + terminal.put("accountProtectionFence", Long.toString(protectionFence)); + terminal.put("worldActivationFence", "29"); + terminal.put( + "accountProtectionEvidenceBytesBase64", + Base64.getEncoder().encodeToString(protectionEvidenceBytes)); + terminal.put( + "activationResultBytesBase64", Base64.getEncoder().encodeToString(activationResultBytes)); + terminal.put("activationResultSha256", hash(activationResultBytes)); + try { + return jsonBytes(terminal); + } catch (Exception impossible) { + throw new IllegalStateException("Synthetic terminal receipt must be canonical", impossible); + } + } + + private static Map readJson(byte[] bytes) throws Exception { + return JSON.readValue(bytes, new tools.jackson.core.type.TypeReference<>() {}); + } + + private static String timestamp(OffsetDateTime value) { + return DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS'Z'") + .withZone(ZoneOffset.UTC) + .format(value.toInstant()); + } + + private static void assertCurrentnessRejected( + Fixture fixture, byte[] requestBytes, byte[] operationIdentityBytes) { + String operationDigest = "sha256:" + hash(operationIdentityBytes); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_ss_activation_assert_current(?, ?, ?, FALSE)", + requestBytes, + operationIdentityBytes, + operationDigest))) + .isInstanceOf(RuntimeException.class) + .satisfies( + failure -> { + Throwable postgresFailure = failure; + while (postgresFailure.getCause() != null) { + postgresFailure = postgresFailure.getCause(); + } + assertThat(postgresFailure) + .isInstanceOfSatisfying( + org.postgresql.util.PSQLException.class, + sqlFailure -> assertThat(sqlFailure.getSQLState()).isEqualTo("23514")); + }); + } + + private static CurrentnessCase currentnessCase(Fixture fixture, Instant originalLease) + throws Exception { + UUID tenantId = UUID.randomUUID(); + UUID gameInstanceId = UUID.randomUUID(); + UUID participationId = UUID.randomUUID(); + UUID ownerMutationId = UUID.randomUUID(); + UUID ownerAttemptId = UUID.randomUUID(); + UUID activationRequestId = UUID.randomUUID(); + UUID accountId = UUID.randomUUID(); + UUID issuanceOperationId = UUID.randomUUID(); + long ownerFence = 11L; + long issuanceFence = 9L; + long sourceVersion = 13L; + long sourceFence = 17L; + String requestId = "original-activation/" + UUID.randomUUID(); + String fingerprint = "arfp/v1/activation-test/" + "a".repeat(64); + OffsetDateTime dbNow = + fixture.dsl().fetchSingle("SELECT clock_timestamp()").get(0, OffsetDateTime.class); + Instant normalizedNow = dbNow.toInstant().truncatedTo(ChronoUnit.MICROS); + Instant normalizedLease = originalLease.truncatedTo(ChronoUnit.MICROS); + Instant issuedAt = normalizedNow.minusSeconds(10); + Instant redeemedAt = normalizedNow.minusSeconds(5); + Instant referenceExpiry = normalizedNow.plusSeconds(180); + Instant responseExpiry = normalizedNow.plusSeconds(220); + String expiryText = + DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS'Z'") + .withZone(ZoneOffset.UTC) + .format(normalizedLease); + + byte[] preAuthorization = bytes("{}"); + Map bundleValue = + Map.of( + "issuanceOperationIdentity", + Map.of("issuanceOperationId", issuanceOperationId.toString())); + byte[] authorityBundle = jsonBytes(bundleValue); + byte[] tuple = + jsonBytes( + Map.of( + "controlPlaneRequestId", + requestId, + "preAuthorizationReservationTuple", + Map.of(), + "authorizationReferenceFingerprint", + fingerprint, + "issuanceFence", + Long.toString(issuanceFence), + "authorityEvidenceBundle", + bundleValue)); + // Current-use integrity preserves the complete stipulated original tuple without scalarizing + // it. + byte[] projection = tuple.clone(); + SourceEvidence sourceEvidence = + new SourceEvidence( + SourceKind.ACCOUNT, + tenantId.toString(), + "2", + "17", + null, + null, + bytes("activation-source")); + String sourceKey = sourceEvidence.key(); + byte[] snapshot = + jsonBytes( + Map.of( + "schema", + "account-start-session-authority-snapshot/v1", + "controlPlaneRequestId", + requestId, + "sourceVector", + java.util.List.of( + Base64.getEncoder().encodeToString(sourceEvidence.canonicalBytes())))); + byte[] captureReference = bytes("{}"); + String captureDigest = hash(captureReference); + String snapshotDigest = hash(snapshot); + byte[] attemptBytes = bytes("synthetic-current-original-attempt"); + String preparationInput = "{}"; + String preparationDigest = "sha256:" + hash(bytes(preparationInput)); + + byte[] worldPreparing = + jsonBytes( + Map.of( + "schema", + "world-canonical-instance-lifecycle-evidence/v1", + "request", + Map.of( + "controlPlaneRequestId", + requestId, + "targetNamespace", + "test", + "canonicalTenantId", + tenantId.toString(), + "canonicalGameInstanceId", + gameInstanceId.toString()), + "lifecycleStatus", + "PREPARING")); + byte[] launchRead = bytes("synthetic exact STARTING read"); + byte[] operationIdentity = bytes("activation operation identity"); + String operationDigest = "sha256:" + hash(operationIdentity); + fixture + .transaction() + .executeWithoutResult( + status -> { + fixture + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?)", + sourceKey); + fixture.dsl().execute("SET LOCAL session_replication_role = replica"); + insert( + fixture.dsl(), + "account_start_session_authority_captures", + "control_plane_request_id", + requestId, + "account_uuid", + accountId, + "tenant_uuid", + tenantId, + "target_owner", + "game-session-service", + "logging_workload_uri", + "spiffe://firemud/ns/test/sa/logging-admin-service", + "reservation_owner_id", + UUID.randomUUID(), + "reservation_claim_fence", + 7L, + "pre_authorization_tuple", + preAuthorization, + "mutation_digest", + "c".repeat(64), + "control_ui_operation_id", + UUID.randomUUID(), + "control_ui_token_jti", + UUID.randomUUID(), + "control_ui_token_hash", + "d".repeat(64), + "control_ui_signer_receipt_sha256", + "e".repeat(64), + "issuance_fence", + issuanceFence, + "issuance_fence_source_version", + sourceVersion, + "captured_at", + OffsetDateTime.ofInstant( + normalizedNow.truncatedTo(ChronoUnit.MILLIS), ZoneOffset.UTC), + "snapshot_sha256", + snapshotDigest, + "canonical_snapshot_bytes", + snapshot, + "source_version", + sourceVersion, + "source_fence", + sourceFence, + "linearization", + "19", + "canonical_sha256", + captureDigest, + "canonical_capture_bytes", + captureReference); + insert( + fixture.dsl(), + "account_start_session_operator_authorizations", + "control_plane_request_id", + requestId, + "pre_authorization_tuple", + preAuthorization, + "mutation_digest", + "c".repeat(64), + "issuance_workload_uri", + "spiffe://firemud/ns/test/sa/logging-admin-service", + "reservation_owner_id", + UUID.randomUUID(), + "reservation_claim_fence", + 7L, + "issuance_operation_id", + issuanceOperationId, + "issuance_fence", + issuanceFence, + "bundle_version", + "authorityEvidenceBundle/v1", + "bundle_source_version", + Long.toString(sourceVersion), + "bundle_source_fence", + Long.toString(sourceFence), + "bundle_linearization", + "19", + "authority_evidence_bundle", + authorityBundle, + "authorization_reference_fingerprint", + fingerprint, + "encrypted_response_envelope", + bytes("synthetic response"), + "issued_at", + OffsetDateTime.ofInstant(issuedAt, ZoneOffset.UTC), + "reference_expires_at", + OffsetDateTime.ofInstant(referenceExpiry, ZoneOffset.UTC), + "response_envelope_expires_at", + OffsetDateTime.ofInstant(responseExpiry, ZoneOffset.UTC), + "status", + "REDEEMED", + "redemption_redeemer_workload_uri", + "spiffe://firemud/ns/test/sa/game-session-service", + "redemption_owner_attempt_id", + ownerAttemptId, + "redemption_owner_fence", + ownerFence, + "redeemed_at", + OffsetDateTime.ofInstant(redeemedAt, ZoneOffset.UTC), + "redemption_reference_fingerprint", + fingerprint, + "redemption_authority_evidence_bundle", + authorityBundle); + insert( + fixture.dsl(), + "account_start_session_world_participations", + "participation_id", + participationId, + "control_plane_request_id", + requestId, + "original_post_authorization_tuple", + tuple, + "target_namespace", + "test", + "canonical_tenant_id", + tenantId, + "canonical_game_instance_id", + gameInstanceId, + "game_session_owner_attempt_id", + ownerAttemptId, + "game_session_owner_fence", + ownerFence, + "preparation_input_json", + preparationInput, + "preparation_input_digest", + preparationDigest); + insert( + fixture.dsl(), + "account_start_session_world_participation_sources", + "participation_id", + participationId, + "source_key", + sourceKey, + "source_evidence", + sourceEvidence.canonicalBytes()); + insert( + fixture.dsl(), + "account_start_session_world_original_attempt_evidence", + "participation_id", + participationId, + "target_namespace", + "test", + "game_session_owner_mutation_id", + ownerMutationId, + "game_session_owner_attempt_id", + ownerAttemptId, + "game_session_owner_fence", + ownerFence, + "original_lease_expires_at", + OffsetDateTime.ofInstant(normalizedLease, ZoneOffset.UTC), + "original_response_bytes", + attemptBytes, + "original_response_digest", + "sha256:" + hash(attemptBytes)); + insert( + fixture.dsl(), + "account_start_session_world_participation_settlements", + "participation_id", + participationId, + "outcome", + "COMMITTED", + "world_execution_fence", + 3L, + "terminal_bytes", + bytes("synthetic committed preparation"), + "terminal_digest", + "sha256:" + hash(bytes("synthetic committed preparation"))); + fixture.dsl().execute("SET LOCAL session_replication_role = origin"); + }); + byte[] requestBytes = + activationRequest( + tuple, + projection, + ownerMutationId, + ownerAttemptId, + ownerFence, + expiryText, + participationId, + fixture + .dsl() + .fetchSingle( + "SELECT participation_fence FROM account_start_session_world_participations " + + "WHERE participation_id = ?", + participationId) + .get("participation_fence", Long.class), + launchRead, + activationRequestId, + worldPreparing); + return new CurrentnessCase( + requestBytes, operationIdentity, operationDigest, ownerAttemptId, expiryText); + } + + private static byte[] activationRequest( + CurrentnessCase current, String ownerAttemptId, String expiry, String worldStatus) + throws Exception { + Map root = + JSON.readValue(current.requestBytes(), new tools.jackson.core.type.TypeReference<>() {}); + root.put("gameSessionOwnerAttemptId", ownerAttemptId); + root.put("originalLeaseExpiresAt", expiry); + byte[] preparing = + Base64.getDecoder().decode((String) root.get("preparingEvidenceBytesBase64")); + Map world = + JSON.readValue(preparing, new tools.jackson.core.type.TypeReference<>() {}); + world.put("lifecycleStatus", worldStatus); + root.put("preparingEvidenceBytesBase64", Base64.getEncoder().encodeToString(jsonBytes(world))); + return jsonBytes(root); + } + + private static byte[] activationRequest( + byte[] tuple, + byte[] projection, + UUID ownerMutationId, + UUID ownerAttemptId, + long ownerFence, + String expiry, + UUID participationId, + long participationFence, + byte[] launchRead, + UUID activationRequestId, + byte[] preparingEvidence) + throws Exception { + Map value = new LinkedHashMap<>(); + value.put("schema", "account-start-session-activation-protection-request/v1"); + value.put( + "originalPostAuthorizationTupleBytesBase64", Base64.getEncoder().encodeToString(tuple)); + value.put( + "accountRedemptionProjectionBytesBase64", Base64.getEncoder().encodeToString(projection)); + value.put("gameSessionOwnerMutationId", ownerMutationId.toString()); + value.put("gameSessionOwnerAttemptId", ownerAttemptId.toString()); + value.put("gameSessionOwnerFence", Long.toString(ownerFence)); + value.put("originalLeaseExpiresAt", expiry); + value.put("accountWorldParticipationId", participationId.toString()); + value.put("accountWorldParticipationFence", Long.toString(participationFence)); + value.put( + "gameSessionLaunchReadEvidenceBytesBase64", Base64.getEncoder().encodeToString(launchRead)); + value.put("worldActivationRequestId", activationRequestId.toString()); + value.put( + "preparingEvidenceBytesBase64", Base64.getEncoder().encodeToString(preparingEvidence)); + byte[] result = jsonBytes(value); + return result; + } + + private static byte[] jsonBytes(Object value) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private static Fixture fixture() { + String schema = "ss_activation_" + 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); + String requestId = "activation-test/" + UUID.randomUUID(); + return new Fixture(dsl, transaction, requestId); + } + + private static void insert(DSLContext dsl, String table, Object... fields) { + Map, Object> values = new java.util.LinkedHashMap<>(); + for (int index = 0; index < fields.length; index += 2) { + values.put(DSL.field(DSL.name((String) fields[index])), fields[index + 1]); + } + dsl.insertInto(DSL.table(DSL.name(table))).set(values).execute(); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static String hash(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private record Fixture(DSLContext dsl, TransactionTemplate transaction, String requestId) {} + + private record CurrentnessCase( + byte[] requestBytes, + byte[] operationIdentityBytes, + String operationIdentityDigest, + UUID ownerAttemptId, + String expiryText) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java new file mode 100644 index 0000000000..49da9e23a3 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java @@ -0,0 +1,1211 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.sql.Connection; +import java.sql.SQLException; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +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 net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.postgresql.util.PSQLException; +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; + +/** + * SQL integrity and source-writer definitions. Upstream Account capture, redeemed authorization, + * World settlement and Game Session observation are explicitly stipulated with upstream triggers + * disabled. Current admission guards remain enabled for acquisition and all assertions. These + * fixtures are not genuine authenticated Account/World/Game Session producer or consumer proof. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountStartSessionAdmissionProtectionPostgresIntegrationTest { + @Container + static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void v165AddsSourceProtectionsWithoutChangingRetainedCanonicalParentEvidence() { + Fixture parent = fixture(60_000L, "160.1", false); + // A passive non-authorizing signer baseline is explicitly stipulated, as are the upstream + // capture/World rows in this fixture. This does not establish authenticated producer proof. + parent + .transaction() + .executeWithoutResult( + status -> { + parent.dsl().execute("SET LOCAL session_replication_role = replica"); + parent + .dsl() + .execute( + "INSERT INTO account_jwt_signer_desired_states " + + "(environment_id, cluster_id, kubernetes_namespace, custody_mode) " + + "VALUES ('test', 'test-cluster', 'test', 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK')"); + parent.dsl().execute("SET LOCAL session_replication_role = origin"); + }); + List retainedTables = + List.of( + "account_jwt_signer_desired_states", + "account_draft_authorization_source_locks", + "account_start_session_authority_captures", + "account_start_session_operator_authorizations", + "account_start_session_world_participations", + "account_start_session_world_participation_sources", + "account_start_session_world_original_attempt_evidence", + "account_start_session_world_participation_settlements"); + Map beforeRows = new LinkedHashMap<>(); + Map beforeOids = new LinkedHashMap<>(); + for (String table : retainedTables) { + beforeRows.put(table, retainedPhysicalRows(parent, table)); + beforeOids.put( + table, + parent.dsl().fetchSingle("SELECT ?::regclass::oid::bigint", table).get(0, Long.class)); + } + List retainedFunctions = + List.of( + "account_start_session_world_participation_insert_guard()", + "account_start_session_operator_authorization_guard()", + "account_jwt_signer_promotion_insert_guard()"); + Map beforeDefinitions = new LinkedHashMap<>(); + for (String signature : retainedFunctions) { + beforeDefinitions.put( + signature, + parent + .dsl() + .fetchSingle("SELECT pg_get_functiondef(?::regprocedure)", signature) + .get(0, String.class)); + beforeOids.put( + signature, + parent + .dsl() + .fetchSingle("SELECT ?::regprocedure::oid::bigint", signature) + .get(0, Long.class)); + } + var checksums = + parent + .dsl() + .fetch( + "SELECT version, checksum FROM flyway_schema_history WHERE success AND version IS NOT NULL ORDER BY installed_rank"); + assertThat( + parent + .dsl() + .fetchSingle( + "SELECT to_regclass('account_start_session_admission_protections')::TEXT") + .get(0, String.class)) + .isNull(); + Flyway.configure() + .dataSource(parent.dataSource()) + .schemas(parent.dataSource().getSchema()) + .defaultSchema(parent.dataSource().getSchema()) + .placeholders(Map.of("serviceSchema", parent.dataSource().getSchema())) + .locations("classpath:db/migration") + .target(MigrationVersion.fromVersion("165")) + .load() + .migrate(); + for (String table : retainedTables) { + assertThat(retainedPhysicalRows(parent, table)).isEqualTo(beforeRows.get(table)); + assertThat( + parent.dsl().fetchSingle("SELECT ?::regclass::oid::bigint", table).get(0, Long.class)) + .isEqualTo(beforeOids.get(table)); + } + for (String signature : retainedFunctions) { + assertThat( + parent + .dsl() + .fetchSingle("SELECT pg_get_functiondef(?::regprocedure)", signature) + .get(0, String.class)) + .isEqualTo(beforeDefinitions.get(signature)); + assertThat( + parent + .dsl() + .fetchSingle("SELECT ?::regprocedure::oid::bigint", signature) + .get(0, Long.class)) + .isEqualTo(beforeOids.get(signature)); + } + for (var row : checksums) { + assertThat( + parent + .dsl() + .fetchSingle( + "SELECT checksum FROM flyway_schema_history WHERE success AND version = ?", + row.get("version", String.class)) + .get(0, Integer.class)) + .isEqualTo(row.get("checksum", Integer.class)); + } + for (String signature : + List.of( + "account_ss_admission_assert_current(account_start_session_admission_protections,boolean)", + "account_ss_activation_assert_current(bytea,bytea,text,boolean)")) { + String definition = + parent + .dsl() + .fetchSingle("SELECT pg_get_functiondef(?::regprocedure)", signature) + .get(0, String.class); + assertThat(definition) + .contains("issuanceOperationIdentity,issuanceOperationId") + .doesNotContain("'projectionSchemaId', 'accountStartSessionRedemptionProjection'"); + } + acquire(parent); + assertThat(parent.projection()).containsExactly(parent.tuple()); + assertThat( + parent + .dsl() + .fetchSingle( + "SELECT bundle_source_fence, issuance_fence FROM account_start_session_operator_authorizations WHERE control_plane_request_id = ?", + parent.requestId()) + .get("bundle_source_fence", String.class)) + .isEqualTo("13"); + assertThat( + parent + .dsl() + .fetchSingle( + "SELECT issuance_fence FROM account_start_session_operator_authorizations WHERE control_plane_request_id = ?", + parent.requestId()) + .get(0, Long.class)) + .isEqualTo(9L); + + Fixture scalar = fixture(60_000L, null, true); + assertThatThrownBy(() -> acquire(scalar)) + .hasMessageContaining( + "Admission projection differs from complete original Account redemption"); + } + + private static String retainedPhysicalRows(Fixture fixture, String table) { + return fixture + .dsl() + .fetchSingle( + "SELECT coalesce(jsonb_agg(value ORDER BY value::TEXT), '[]'::JSONB)::TEXT " + + "FROM (SELECT to_jsonb(original) || jsonb_build_object(" + + "'_xmin', original.xmin::TEXT, '_ctid', original.ctid::TEXT) AS value FROM " + + table + + " original) retained") + .get(0, String.class); + } + + @Test + void fullTupleDoesNotBypassIndependentOwnerIssuanceOperationBinding() { + Fixture fixture = fixture(); + // Stipulate a contradictory retained owner row to isolate this SQL integrity conjunct. + // The parent immutable writer remains enabled outside this deliberate corruption fixture. + fixture + .transaction() + .executeWithoutResult( + status -> { + fixture.dsl().execute("SET LOCAL session_replication_role = replica"); + fixture + .dsl() + .execute( + "UPDATE account_start_session_operator_authorizations SET issuance_operation_id = ? " + + "WHERE control_plane_request_id = ?", + UUID.randomUUID(), + fixture.requestId()); + fixture.dsl().execute("SET LOCAL session_replication_role = origin"); + }); + assertThat(fixture.projection()).containsExactly(fixture.tuple()); + assertThatThrownBy(() -> acquire(fixture)) + .hasMessageContaining( + "Admission projection differs from complete original Account redemption"); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT count(*) FROM account_start_session_admission_protections") + .get(0, Long.class)) + .isZero(); + } + + @Test + void installsAdditiveHooksWithoutRemovingExistingOwnerChecks() { + Fixture fixture = fixture(); + for (String function : + List.of( + "account_control_ui_hold_required_sources(text[])", + "account_draft_authorization_source_change_guard()", + "account_hosted_terms_disclosure_handoff_guard()")) { + String definition = + fixture + .dsl() + .fetchSingle("SELECT pg_get_functiondef(?::regprocedure)", function) + .get(0, String.class); + assertThat(definition) + .contains( + "account_ss_admission_assert_no_pending", + "account_start_session_world_participations") + // The actual published parent has the canonical World guard. Selected-owner source + // reservations remain a separate V130 receiving obligation, outside passive V165. + .doesNotContain("account_selected_owner_intake_source_read"); + } + String hold = + fixture + .dsl() + .fetchSingle( + "SELECT pg_get_functiondef('account_control_ui_hold_required_sources(text[])'::regprocedure)") + .get(0, String.class); + assertThat(hold) + .contains( + "account_draft_authorization_sources", + "account_selected_publication_sources", + "account_game_logic_intake_sources", + "account_game_logic_intake_source_read_sources"); + } + + @Test + void exactCurrentReadPreservesIdentityWithoutAllocatingAndWorldCommitCannotReleaseIt() { + Fixture fixture = fixture(); + assertThat(fixture.expiry().getNano() % 1_000_000).isNotZero(); + acquire(fixture); + Long sequence = sequenceValue(fixture); + for (int retry = 0; retry < 2; retry++) { + var current = + fixture + .transaction() + .execute( + status -> + fixture + .dsl() + .fetchSingle( + "SELECT * FROM account_ss_admission_read_current_exact(?, ?, ?)", + fixture.protectionId(), + 1L, + fixture.request())); + assertThat(current.get("protection_id", UUID.class)).isEqualTo(fixture.protectionId()); + assertThat(current.get("request_binding_bytes", byte[].class)) + .containsExactly(fixture.request()); + OffsetDateTime retainedExpiry = + current.get("original_lease_expires_at", OffsetDateTime.class); + assertThat(retainedExpiry).isNotNull(); + assertThat(retainedExpiry.toInstant()).isEqualTo(fixture.expiry().toInstant()); + } + assertThat(sequenceValue(fixture)).isEqualTo(sequence); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT account_start_session_world_participation_is_settled(?)", + fixture.worldId()) + .get(0, Boolean.class)) + .isTrue(); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + fixture.source().key()))) + .hasMessageContaining("Original StartSession admission protection remains pending"); + } + + @Test + void changedSubmillisecondOriginalExpiryCannotRecoverRetainedProtection() { + Fixture fixture = fixture(); + acquire(fixture); + var storedRowBefore = + fixture + .dsl() + .fetchSingle( + "SELECT * FROM account_start_session_admission_protections WHERE protection_id = ?", + fixture.protectionId()); + DateTimeFormatter expiryFormat = + DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS'Z'").withZone(ZoneOffset.UTC); + String originalExpiryText = expiryFormat.format(fixture.expiry().toInstant()); + String changedExpiryText = expiryFormat.format(fixture.expiry().plusNanos(1_000).toInstant()); + byte[] changedRequest = + new String(fixture.request(), StandardCharsets.UTF_8) + .replace(originalExpiryText, changedExpiryText) + .getBytes(StandardCharsets.UTF_8); + assertThat(changedRequest).isNotEqualTo(fixture.request()); + + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT * FROM account_ss_admission_read_current_exact(?, ?, ?)", + fixture.protectionId(), + 1L, + changedRequest))) + .hasMessageContaining("Original admission recovery binding differs"); + var storedRowAfter = + fixture + .dsl() + .fetchSingle( + "SELECT * FROM account_start_session_admission_protections WHERE protection_id = ?", + fixture.protectionId()); + assertThat(storedRowAfter).isEqualTo(storedRowBefore); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT account_ss_admission_is_settled(?)", fixture.protectionId()) + .get(0, Boolean.class)) + .isFalse(); + } + + @Test + void forgedWorldHoldDigestWithoutCanonicalPrefixCannotBecomeProtection() { + Fixture fixture = fixture(); + String holdText = new String(fixture.hold(), StandardCharsets.UTF_8); + String digestMarker = "\"holdBindingDigest\":\""; + int digestStart = holdText.indexOf(digestMarker) + digestMarker.length(); + int digestEnd = holdText.indexOf('"', digestStart); + String validDigest = holdText.substring(digestStart, digestEnd); + assertThat(validDigest).startsWith("sha256:"); + String forgedHoldText = + holdText.substring(0, digestStart) + + validDigest.substring("sha256:".length()) + + holdText.substring(digestEnd); + byte[] forgedHold = forgedHoldText.getBytes(StandardCharsets.UTF_8); + byte[] forgedRequest = + new String(fixture.request(), StandardCharsets.UTF_8) + .replace(base64(fixture.hold()), base64(forgedHold)) + .getBytes(StandardCharsets.UTF_8); + + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> insertProtection(fixture, 11L, forgedHold, forgedRequest))) + .hasMessageContaining("Admission hold identity differs from original instance and request"); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT count(*) FROM account_start_session_admission_protections") + .get(0, Long.class)) + .isZero(); + } + + @Test + void pendingAdmissionExcludesRealSourceChangeCompletionAndDisclosureDispatch() { + Fixture fixture = fixture(); + acquire(fixture); + UUID changeId = UUID.randomUUID(); + fixture + .transaction() + .executeWithoutResult( + status -> { + insert( + fixture.dsl(), + "account_draft_authorization_source_changes", + "change_id", + changeId, + "binding", + bytes("change"), + "status", + "WAITING"); + insert( + fixture.dsl(), + "account_draft_authorization_changed_scopes", + "change_id", + changeId, + "source_key", + fixture.source().key()); + }); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "UPDATE account_draft_authorization_source_changes SET status = 'SOURCE_COMMITTED', committed_at = clock_timestamp() WHERE change_id = ?", + changeId))) + .hasMessageContaining("Original StartSession admission protection remains pending"); + UUID handoffId = UUID.randomUUID(); + fixture + .transaction() + .executeWithoutResult( + status -> + insert( + fixture.dsl(), + "account_hosted_terms_disclosure_handoffs", + "handoff_id", + handoffId, + "request_id", + UUID.randomUUID(), + "kind", + "CATALOG", + "source_key", + fixture.source().key(), + "predecessor_digest", + "sha256:" + "a".repeat(64), + "candidate_digest", + "sha256:" + "b".repeat(64), + "effective_at", + OffsetDateTime.now().plusDays(1), + "binding", + bytes("disclosure"), + "binding_digest", + "sha256:" + hash(bytes("disclosure")), + "status", + "PREPARED")); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "UPDATE account_hosted_terms_disclosure_handoffs SET status = 'DISPATCH_AUTHORIZED', dispatch_attempts = 1 WHERE handoff_id = ?", + handoffId))) + .hasMessageContaining("Original StartSession admission protection remains pending"); + } + + @Test + void rawChangedCaptureAndIncompleteChildrenCannotBecomeProtection() { + Fixture changed = fixture(); + assertThatThrownBy( + () -> + changed + .transaction() + .executeWithoutResult(status -> insertProtection(changed, 99L))) + .hasMessageContaining("retained owner bindings"); + Fixture incomplete = fixture(); + assertThatThrownBy( + () -> + incomplete + .transaction() + .executeWithoutResult(status -> insertProtection(incomplete, 11L))) + .satisfies( + failure -> + assertDatabaseGuardFailure( + failure, + "Admission protection has incomplete or extra source children", + "23514")); + assertThat( + incomplete + .dsl() + .fetchSingle("SELECT count(*) FROM account_start_session_admission_protections") + .get(0, Long.class)) + .isZero(); + } + + @Test + void immutableRowsAndUnprovedTerminalCannotReleaseProtection() { + Fixture fixture = fixture(); + acquire(fixture); + for (String table : + List.of( + "account_start_session_admission_protections", + "account_start_session_admission_protection_sources")) { + assertThatThrownBy(() -> fixture.dsl().execute("DELETE FROM " + table)) + .hasMessageContaining("append-only"); + assertThatThrownBy(() -> fixture.dsl().execute("TRUNCATE " + table + " CASCADE")) + .hasMessageContaining("append-only"); + } + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE account_start_session_admission_protection_sources SET source_evidence = ?", + bytes("changed"))) + .hasMessageContaining("append-only"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "INSERT INTO account_start_session_admission_protection_settlements (protection_id, outcome, terminal_bytes, terminal_digest) VALUES (?, 'ABORTED', ?, ?)", + fixture.protectionId(), + malformedSettlementBytes(), + "sha256:" + hash(malformedSettlementBytes()))) + .hasMessageContaining("not the closed envelope"); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT account_ss_admission_is_settled(?)", fixture.protectionId()) + .get(0, Boolean.class)) + .isFalse(); + } + + @Test + void expiredOriginalCannotRecoverEvenWhenRetainedIdentityAndSourcesRemain() { + Fixture fixture = fixture(); + acquire(fixture); + // Stipulate passage of the immutable original expiry without changing protection: + // rewriting the fixture row requires disabling the immutable upstream/new triggers. + fixture + .transaction() + .executeWithoutResult( + status -> { + fixture.dsl().execute("SET LOCAL session_replication_role = replica"); + fixture + .dsl() + .execute( + "UPDATE account_start_session_admission_protections SET original_lease_expires_at = date_trunc('milliseconds', clock_timestamp() - INTERVAL '1 second') WHERE protection_id = ?", + fixture.protectionId()); + fixture.dsl().execute("SET LOCAL session_replication_role = origin"); + }); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT * FROM account_ss_admission_read_current_exact(?, ?, ?)", + fixture.protectionId(), + 1L, + fixture.request()))) + .hasMessageContaining("not current"); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT account_ss_admission_is_settled(?)", fixture.protectionId()) + .get(0, Boolean.class)) + .isFalse(); + } + + @Test + void currentRecoveryRechecksDatabaseExpiryAfterTheCallerWaitsForOriginalCaptureLock() + throws Exception { + Fixture fixture = fixture(3_000L); + acquire(fixture); + var executor = Executors.newSingleThreadExecutor(); + CountDownLatch entered = new CountDownLatch(1); + try (Connection lock = fixture.dataSource().getConnection()) { + lock.setAutoCommit(false); + DSL.using(lock, SQLDialect.POSTGRES) + .fetch( + "SELECT control_plane_request_id FROM account_start_session_authority_captures WHERE control_plane_request_id = ? FOR UPDATE", + fixture.requestId()); + var waiting = + executor.submit( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> { + entered.countDown(); + // The currentness producer's original-capture lock can wait before the + // V165 + // boundary. V165 itself uses NOWAIT to avoid reversing source lock + // order. + fixture + .dsl() + .fetch( + "SELECT control_plane_request_id FROM account_start_session_authority_captures WHERE control_plane_request_id = ? FOR UPDATE", + fixture.requestId()); + fixture + .dsl() + .execute( + "SELECT * FROM account_ss_admission_read_current_exact(?, ?, ?)", + fixture.protectionId(), + 1L, + fixture.request()); + })); + assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); + long expiryDeadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (fixture + .dsl() + .fetchSingle("SELECT clock_timestamp() >= ?::timestamptz", fixture.expiry()) + .get(0, Boolean.class) + .equals(false) + && System.nanoTime() < expiryDeadline) { + Thread.sleep(20L); + } + assertThat( + fixture + .dsl() + .fetchSingle("SELECT clock_timestamp() >= ?::timestamptz", fixture.expiry()) + .get(0, Boolean.class)) + .isTrue(); + assertThat(waiting.isDone()).isFalse(); + lock.commit(); + assertThatThrownBy(() -> waiting.get(5, TimeUnit.SECONDS)) + .isInstanceOf(ExecutionException.class) + .hasStackTraceContaining("not current"); + } finally { + executor.shutdownNow(); + assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + assertThat( + fixture + .dsl() + .fetchSingle("SELECT account_ss_admission_is_settled(?)", fixture.protectionId()) + .get(0, Boolean.class)) + .isFalse(); + } + + private static void acquire(Fixture fixture) { + fixture + .transaction() + .executeWithoutResult( + status -> { + insertProtection(fixture, 11L); + insert( + fixture.dsl(), + "account_start_session_admission_protection_sources", + "protection_id", + fixture.protectionId(), + "source_key", + fixture.source().key(), + "source_evidence", + fixture.source().canonicalBytes()); + }); + } + + private static void insertProtection(Fixture fixture, long version) { + insertProtection(fixture, version, fixture.hold(), fixture.request()); + } + + private static void insertProtection( + Fixture fixture, long version, byte[] holdIdentity, byte[] request) { + insert( + fixture.dsl(), + "account_start_session_admission_protections", + "protection_id", + fixture.protectionId(), + "control_plane_request_id", + fixture.requestId(), + "original_post_authorization_tuple", + fixture.tuple(), + "account_redemption_projection", + fixture.projection(), + "game_session_owner_mutation_id", + fixture.mutationId(), + "game_session_owner_attempt_id", + fixture.attemptId(), + "game_session_owner_fence", + 47L, + "original_lease_expires_at", + fixture.expiry(), + "account_world_participation_id", + fixture.worldId(), + "account_world_participation_fence", + 1L, + "target_namespace", + "test", + "canonical_tenant_id", + fixture.tenantId(), + "canonical_game_instance_id", + fixture.instanceId(), + "capture_source_version", + version, + "capture_source_fence", + 13L, + "capture_sha256", + hash(bytes("{}")), + "world_admission_hold_identity_bytes", + holdIdentity, + "request_binding_bytes", + request, + "request_binding_digest", + "sha256:" + hash(request)); + } + + private static Fixture fixture() { + return fixture(60_000L); + } + + private static Fixture fixture(long leaseMillis) { + return fixture(leaseMillis, null, false); + } + + private static Fixture fixture(long leaseMillis, String target, boolean scalarProjection) { + String schema = "ss_admission_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + var migration = + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (target != null) migration.target(MigrationVersion.fromVersion(target)); + 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); + OffsetDateTime now = + dsl.fetchSingle( + "SELECT date_trunc('milliseconds', clock_timestamp()) + INTERVAL '123 microseconds'") + .get(0, OffsetDateTime.class); + OffsetDateTime capturedAt = now.truncatedTo(ChronoUnit.MILLIS); + UUID tenant = UUID.randomUUID(); + UUID instance = UUID.randomUUID(); + UUID actor = UUID.randomUUID(); + UUID mutation = UUID.randomUUID(); + UUID attempt = UUID.randomUUID(); + UUID world = UUID.randomUUID(); + UUID issuance = UUID.randomUUID(); + String requestId = "original/" + UUID.randomUUID(); + SourceEvidence evidence = + new SourceEvidence( + SourceKind.HOSTED_TERMS, "test-terms", "1", "1", null, null, bytes("terms")); + Map authorityBundle = + Map.of("issuanceOperationIdentity", Map.of("issuanceOperationId", issuance.toString())); + byte[] tuple = + json( + Map.of( + "preAuthorizationReservationTuple", + Map.of(), + "authorizationReferenceFingerprint", + "arfp/v1/key-1/" + "a".repeat(64), + "issuanceFence", + "9", + "authorityEvidenceBundle", + authorityBundle)); + // Upstream authority is explicitly stipulated; current SQL still requires exact tuple bytes. + byte[] projection = + scalarProjection + ? json( + Map.of( + "projectionSchemaId", + "accountStartSessionRedemptionProjection", + "projectionSchemaVersion", + "1", + "authorizationReferenceFingerprint", + "arfp/v1/key-1/" + "a".repeat(64), + "authorityEvidenceBundle", + authorityBundle, + "issuanceOperationId", + issuance.toString(), + "issuanceFence", + 9L)) + : tuple.clone(); + var holdRequest = + new WorldCanonicalInitialAdmissionHold.Request( + "test", + tenant, + "test-world", + UUID.randomUUID(), + UUID.randomUUID(), + "SHARED", + instance, + UUID.randomUUID(), + 1L, + "separate-initial-admission-identity", + "b".repeat(64), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + 1L, + null); + byte[] hold = + new WorldCanonicalInitialAdmissionHold.HoldIdentity( + holdRequest, UUID.randomUUID(), UUID.randomUUID()) + .canonicalBytes(); + OffsetDateTime expiry = now.plusNanos(leaseMillis * 1_000_000L); + byte[] request = + json( + Map.of( + "schema", + "account-start-session-admission-protection-request/v1", + "originalPostAuthorizationTupleBytesBase64", + base64(tuple), + "accountRedemptionProjectionBytesBase64", + base64(projection), + "gameSessionOwnerMutationId", + mutation.toString(), + "gameSessionOwnerAttemptId", + attempt.toString(), + "gameSessionOwnerFence", + "47", + "originalLeaseExpiresAt", + DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS'Z'") + .withZone(ZoneOffset.UTC) + .format(expiry.toInstant()), + "accountWorldParticipationId", + world.toString(), + "accountWorldParticipationFence", + "1", + "worldAdmissionHoldIdentityBytesBase64", + base64(hold))); + Fixture fixture = + new Fixture( + dsl, + transaction, + source, + UUID.randomUUID(), + requestId, + tenant, + instance, + mutation, + attempt, + world, + expiry, + evidence, + tuple, + projection, + hold, + request); + byte[] snapshot = + json( + Map.of( + "schema", + "account-start-session-authority-snapshot/v1", + "controlPlaneRequestId", + requestId, + "sourceVector", + List.of(base64(evidence.canonicalBytes())))); + transaction.executeWithoutResult( + status -> { + dsl.execute("SET LOCAL session_replication_role = replica"); + insert( + dsl, + "account_canonical_tenant_identity_claims", + "canonical_tenant_id", + tenant, + "identity_kind", + "APPROVED_RETAINED", + "source_operation_id", + UUID.randomUUID(), + "source_account_legacy_tenant_id", + 1L, + "source_target_namespace", + "test", + "source_game_row_id", + 1L, + "source_game_tenant_key", + tenant.toString()); + insert(dsl, "account_draft_authorization_source_locks", "source_key", evidence.key()); + insert( + dsl, + "account_start_session_authority_captures", + "control_plane_request_id", + requestId, + "account_uuid", + actor, + "tenant_uuid", + tenant, + "target_owner", + "game-session-service", + "logging_workload_uri", + "spiffe://firemud/ns/test/sa/logging-admin-service", + "reservation_owner_id", + UUID.randomUUID(), + "reservation_claim_fence", + 7L, + "pre_authorization_tuple", + bytes("{}"), + "mutation_digest", + "c".repeat(64), + "control_ui_operation_id", + UUID.randomUUID(), + "control_ui_token_jti", + UUID.randomUUID(), + "control_ui_token_hash", + "d".repeat(64), + "control_ui_signer_receipt_sha256", + "e".repeat(64), + "issuance_fence", + 9L, + "issuance_fence_source_version", + 1L, + "captured_at", + capturedAt, + "snapshot_sha256", + hash(snapshot), + "canonical_snapshot_bytes", + snapshot, + "source_version", + 11L, + "source_fence", + 13L, + "linearization", + "17", + "canonical_sha256", + hash(bytes("{}")), + "canonical_capture_bytes", + bytes("{}")); + insert( + dsl, + "account_start_session_operator_authorizations", + "control_plane_request_id", + requestId, + "pre_authorization_tuple", + bytes("{}"), + "mutation_digest", + "c".repeat(64), + "issuance_workload_uri", + "spiffe://firemud/ns/test/sa/logging-admin-service", + "reservation_owner_id", + UUID.randomUUID(), + "reservation_claim_fence", + 7L, + "issuance_operation_id", + issuance, + "issuance_fence", + 9L, + "bundle_version", + "authorityEvidenceBundle/v1", + "bundle_source_version", + "11", + "bundle_source_fence", + "13", + "bundle_linearization", + "17", + "authority_evidence_bundle", + json(authorityBundle), + "authorization_reference_fingerprint", + "arfp/v1/key-1/" + "a".repeat(64), + "encrypted_response_envelope", + bytes("synthetic"), + "issued_at", + now.minusSeconds(10), + "reference_expires_at", + now.plusSeconds(90), + "response_envelope_expires_at", + now.plusSeconds(120), + "status", + "REDEEMED", + "redemption_redeemer_workload_uri", + "spiffe://firemud/ns/test/sa/game-session-service", + "redemption_owner_attempt_id", + attempt, + "redemption_owner_fence", + 47L, + "redeemed_at", + now.minusSeconds(5), + "redemption_reference_fingerprint", + "arfp/v1/key-1/" + "a".repeat(64), + "redemption_authority_evidence_bundle", + json(authorityBundle)); + insert( + dsl, + "account_start_session_world_participations", + "participation_id", + world, + "control_plane_request_id", + requestId, + "original_post_authorization_tuple", + tuple, + "target_namespace", + "test", + "canonical_tenant_id", + tenant, + "canonical_game_instance_id", + instance, + "game_session_owner_attempt_id", + attempt, + "game_session_owner_fence", + 47L, + "preparation_input_json", + "{}", + "preparation_input_digest", + "sha256:" + hash(bytes("{}"))); + insert( + dsl, + "account_start_session_world_participation_sources", + "participation_id", + world, + "source_key", + evidence.key(), + "source_evidence", + evidence.canonicalBytes()); + insert( + dsl, + "account_start_session_world_original_attempt_evidence", + "participation_id", + world, + "target_namespace", + "test", + "game_session_owner_mutation_id", + mutation, + "game_session_owner_attempt_id", + attempt, + "game_session_owner_fence", + 47L, + "original_lease_expires_at", + expiry, + "original_response_bytes", + bytes("synthetic-observation"), + "original_response_digest", + "sha256:" + hash(bytes("synthetic-observation"))); + insert( + dsl, + "account_start_session_world_participation_settlements", + "participation_id", + world, + "outcome", + "COMMITTED", + "world_execution_fence", + 1L, + "terminal_bytes", + bytes("synthetic-terminal"), + "terminal_digest", + "sha256:" + hash(bytes("synthetic-terminal"))); + dsl.execute("SET LOCAL session_replication_role = origin"); + }); + return fixture; + } + + private static void insert(DSLContext dsl, String table, Object... fields) { + Map, Object> values = new LinkedHashMap<>(); + for (int index = 0; index < fields.length; index += 2) + values.put(DSL.field(DSL.name((String) fields[index])), fields[index + 1]); + try { + dsl.insertInto(DSL.table(DSL.name(table))).set(values).execute(); + } catch (RuntimeException failure) { + String sqlState = "unavailable"; + String constraint = "unavailable"; + StringBuilder causeTypes = new StringBuilder(); + var visited = + java.util.Collections.newSetFromMap(new java.util.IdentityHashMap()); + Throwable cause = failure; + int causeCount = 0; + while (cause != null && causeCount < 32 && visited.add(cause)) { + if (causeTypes.length() > 0) causeTypes.append("->"); + causeTypes.append(diagnosticIdentifier(cause.getClass().getSimpleName())); + causeCount++; + if (cause instanceof SQLException sqlFailure && sqlFailure.getSQLState() != null) { + sqlState = sqlFailure.getSQLState(); + } + if (cause instanceof PSQLException postgresFailure) { + var serverError = postgresFailure.getServerErrorMessage(); + if (serverError != null && serverError.getConstraint() != null) { + constraint = serverError.getConstraint(); + } + } + cause = cause.getCause(); + } + if (cause != null) causeTypes.append("->truncated"); + System.err.printf( + "StartSession admission fixture insert failed: " + + "table=%s SQLSTATE=%s constraint=%s causeTypes=%s%n", + diagnosticIdentifier(table), + diagnosticIdentifier(sqlState), + diagnosticIdentifier(constraint), + causeTypes); + throw failure; + } + } + + private static String diagnosticIdentifier(String value) { + return value != null && value.matches("[A-Za-z0-9_]+") ? value : "unavailable"; + } + + private static Long sequenceValue(Fixture fixture) { + var sequence = + fixture + .dsl() + .fetchSingle( + "SELECT namespace.nspname AS schema_name, relation.relname AS sequence_name " + + "FROM pg_class relation " + + "JOIN pg_namespace namespace ON namespace.oid = relation.relnamespace " + + "WHERE relation.oid = pg_get_serial_sequence(" + + "format('%I.%I', current_schema(), ?), ?)::regclass", + "account_start_session_admission_protections", "protection_fence"); + return fixture + .dsl() + .select(DSL.field(DSL.name("last_value"), Long.class)) + .from( + DSL.table( + DSL.name( + sequence.get("schema_name", String.class), + sequence.get("sequence_name", String.class)))) + .fetchSingle(0, Long.class); + } + + private static void assertDatabaseGuardFailure( + Throwable failure, String expectedMessage, String expectedSqlState) { + var visited = + java.util.Collections.newSetFromMap(new java.util.IdentityHashMap()); + Throwable cause = failure; + PSQLException databaseFailure = null; + while (cause != null && visited.add(cause)) { + if (cause instanceof PSQLException postgresFailure) { + databaseFailure = postgresFailure; + break; + } + cause = cause.getCause(); + } + assertThat((Throwable) databaseFailure) + .as("the rejected fixture write must fail at PostgreSQL's database guard") + .isNotNull(); + assertThat(databaseFailure.getSQLState()).isEqualTo(expectedSqlState); + assertThat(databaseFailure.getServerErrorMessage()).isNotNull(); + assertThat(databaseFailure.getServerErrorMessage().getMessage()).contains(expectedMessage); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static byte[] malformedSettlementBytes() { + return bytes( + "{\"canonicalAccountProtectionEvidenceBytesBase64\":\"\"," + + "\"canonicalGameSessionOwnerProofBytesBase64\":\"\"," + + "\"schema\":\"account-start-session-admission-protection-settlement/v2\"}"); + } + + private static byte[] json(Map value) { + return AccountControlUiAuthority.canonical(value); + } + + private static String base64(byte[] value) { + return Base64.getEncoder().encodeToString(value); + } + + private static String hash(byte[] value) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private record Fixture( + DSLContext dsl, + TransactionTemplate transaction, + DriverManagerDataSource dataSource, + UUID protectionId, + String requestId, + UUID tenantId, + UUID instanceId, + UUID mutationId, + UUID attemptId, + UUID worldId, + OffsetDateTime expiry, + SourceEvidence source, + byte[] tuple, + byte[] projection, + byte[] hold, + byte[] request) {} +}