diff --git a/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md b/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md index 8620d0bbbc..60d0b6db7e 100644 --- a/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md +++ b/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md @@ -53,7 +53,7 @@ Unattended operator automation uses `IssueAutomationOperatorAuthorizationReferen The field name is intentional: `tenant_generation` is the canonical automation binding used by Account's typed API and ADR 0048 for the current tenant-scoped branch. `target_tenant_generation` is reserved for conditional target-tenant/global-role branches, including the future automated branch described above, and is not an alias for the current automation field. Both issuance RPCs also carry the current Logging and Admin reservation owner and positive claim fence. Account authenticates the current reservation claim/CAS result, exact-compares it with the request and its own issuance preconditions, and copies those validated values into the immutable Account issuance tuple; that copied issuance tuple is not a second reservation record and cannot replace the current Logging and Admin claim. -Both issuance paths use the same bounded typed-mutation admission contract before Account issues a reference. The published action-family schema pair defines the typed scope, target, immutable typed `targetOwner`, expected-version, mutation, and audit-reason fields, explicit presence or absence, raw and normalized limits, and the `mutationDigest/v1` golden vectors. Account, Logging and Admin, and the owner reject malformed, over-limit, unsupported, or mismatched typed input before hashing, authorization issuance, persistence, or forwarding. The paths differ only in their authority attestation: the human path carries Account-validated `control-ui` token, role, assurance, generation, and applicable membership evidence; the automation path carries Account-validated exact mTLS workload and versioned policy evidence. Neither caller assertions nor an ingress-local role string is an authority source. For every supported action family, the Account-issued reference carries the exact immutable `authorityEvidenceBundle/v1` defined below. The reference and the canonical complete `postAuthorizationExecutionTuple` separately bind the bundle, `issuanceKind`, exact authenticated workload/actor or automation-policy binding, immutable typed `targetOwner`, `reservationOwnerId`, positive `reservationClaimFence`, and every schema-bound typed presence/absence value through redemption and owner commit; the bundle is authority evidence and does not contain the execution tuple. Only fields that the action-family schema explicitly declares absent may be omitted; an ingress or owner must not omit a declared field because it is unavailable locally. +Both issuance paths use the same bounded typed-mutation admission contract before Account issues a reference. The published action-family schema pair defines the typed scope, target, immutable typed `targetOwner`, expected-version, mutation, and audit-reason fields, explicit presence or absence, raw and normalized limits, and the `mutationDigest/v1` golden vectors. Account, Logging and Admin, and the owner reject malformed, over-limit, unsupported, or mismatched typed input before hashing, authorization issuance, persistence, or forwarding. The paths differ only in their authority attestation: the human path carries Account-validated `control-ui` token, role, assurance when applicable to that role, generation, and applicable membership evidence; the automation path carries Account-validated exact mTLS workload and versioned policy evidence. Neither caller assertions nor an ingress-local role string is an authority source. For every supported action family, the Account-issued reference carries the exact immutable `authorityEvidenceBundle/v1` defined below. The reference and the canonical complete `postAuthorizationExecutionTuple` separately bind the bundle, `issuanceKind`, exact authenticated workload/actor or automation-policy binding, immutable typed `targetOwner`, `reservationOwnerId`, positive `reservationClaimFence`, and every schema-bound typed presence/absence value through redemption and owner commit; the bundle is authority evidence and does not contain the execution tuple. Only fields that the action-family schema explicitly declares absent may be omitted; an ingress or owner must not omit a declared field because it is unavailable locally. `authorityEvidenceBundle/v1` has one canonical logical shape across ADR 0047, ADR 0048, and the Account API: @@ -95,7 +95,9 @@ Both issuance paths use the same bounded typed-mutation admission contract befor `issuanceKind` is an enum with exactly `human_operator` and `automation_operator`; the example above shows the human value and the two values are never combined into one literal. -`authorityTuple` is copied without scalarization or field renaming from the complete canonical shape in the [JWT and token contracts](../system-architecture-jwt-and-token-contracts.md#canonical-authority-tuple). `membershipVersion` is the independently applicable Account membership-version map, including `{}` when no membership applies. `HumanAuthorityEvidence/v1` carries the Account-derived actor account, `control-ui` token `jti`, role, assurance, account generation, and applicable tenant or target-tenant generation. `AutomationAuthorityEvidence/v1` carries the exact authenticated workload, automation-policy identity/version, and applicable tenant generation. The tagged `issuanceEvidence` arm must agree with Account-derived `issuanceKind`; the inapplicable arm and inapplicable authority-scope identifiers are omitted rather than serialized as `null`, empty objects, or sentinels. `sourceEvidenceId` identifies the one Account authority snapshot and its linearization evidence, while `sourceEvidenceVersion` is the corresponding Account-issued source version; together they are the canonical source fence for the bundle and are carried unchanged with the existing `{bundleVersion, sourceVersion, sourceFence, linearization}` reference. Account derives every authority, generation, membership, freshness, and branch-decision member from that one atomic snapshot and stores the source pair with the issuance record. During redemption, Account exact-compares `sourceEvidenceId`, `sourceEvidenceVersion`, the bundle reference, and every snapshot-bound field against the stored issuance record and the current applicable authority evidence; a missing, changed, or mixed-version value rejects redemption. Consumers reject missing, extra, contradictory, separately sourced, stale, expired, wrongly tagged, or non-canonical bundle fields and must redeem the original reference with Account; a copied bundle never becomes a second authority. +For the tenant-scoped `tenantAdmin` branch of `firemud.game-session.start-session/v1`, the human evidence uses the closed `evidenceType: "HumanAuthorityEvidence/v1"` arm with Account-derived `actorAccountId`, `controlUiTokenJti`, `role`, `accountGeneration`, and `tenantGeneration`. This branch explicitly declares `assurance` absent: issuance, exact decoding, forwarding, and redemption reject an added assurance member, including `null` or a sentinel, and never invent an elevation or a JWT assurance claim. This absence is role applicability, not permission to omit unavailable evidence. Global `platformAdmin` and cross-tenant `billingAdmin` branches still require genuine current Account-owned `privileged_control` evidence; they cannot substitute this tenant branch or obtain authority from its copied role or generation values. + +`authorityTuple` is copied without scalarization or field renaming from the complete canonical shape in the [JWT and token contracts](../system-architecture-jwt-and-token-contracts.md#canonical-authority-tuple). `membershipVersion` is the independently applicable Account membership-version map, including `{}` when no membership applies. `HumanAuthorityEvidence/v1` carries the Account-derived actor account, `control-ui` token `jti`, role, assurance only when applicable to that role, account generation, and applicable tenant or target-tenant generation. `AutomationAuthorityEvidence/v1` carries the exact authenticated workload, automation-policy identity/version, and applicable tenant generation. The tagged `issuanceEvidence` arm must agree with Account-derived `issuanceKind`; the inapplicable arm and inapplicable authority-scope identifiers are omitted rather than serialized as `null`, empty objects, or sentinels. `sourceEvidenceId` identifies the one Account authority snapshot and its linearization evidence, while `sourceEvidenceVersion` is the corresponding Account-issued source version; together they are the canonical source fence for the bundle and are carried unchanged with the existing `{bundleVersion, sourceVersion, sourceFence, linearization}` reference. Account derives every authority, generation, membership, freshness, and branch-decision member from that one atomic snapshot and stores the source pair with the issuance record. During redemption, Account exact-compares `sourceEvidenceId`, `sourceEvidenceVersion`, the bundle reference, and every snapshot-bound field against the stored issuance record and the current applicable authority evidence; a missing, changed, or mixed-version value rejects redemption. Consumers reject missing, extra, contradictory, separately sourced, stale, expired, wrongly tagged, or non-canonical bundle fields and must redeem the original reference with Account; a copied bundle never becomes a second authority. For every forwarded owner-mutation family, ADR 0048's canonical complete `postAuthorizationExecutionTuple` is the required post-authorization identity. It explicitly contains ADR 0048's stable `controlPlaneRequestId` for orchestration, reservation, lookup, and correlation across forwarding, `mutationDigest`, `issuanceKind`, Account-returned `authorizationReferenceFingerprint`, exact authenticated workload and actor/policy binding, exact typed `scope`, normalized `actionFamily`, `actionFamilySchemaId`, `actionFamilySchemaVersion`, typed `target`, immutable typed `targetOwner`, typed `expectedVersion`, typed `mutation`, typed `auditReason`, the exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, the exact canonical `authorityEvidenceBundle/v1` defined above (whose issuance identity carries the tagged `actionFamilyRequestIdentity` for domain action/idempotency), and every schema-bound typed presence/absence value. `targetOwner` is distinct from `target`, immutable after reservation, and is never inferred from current routing or owner state. Reservation and pre-authorization Account issuance/recovery compare `preAuthorizationReservationTuple`; post-authorization tuple completion, owner idempotency, terminal/no-commit proof, result lookup, conflict handling, and any later fresh owner attempt carries and compares its own exact tuple; no participant may omit a required identity because it is unavailable locally. @@ -107,7 +109,7 @@ For each future supported executable mutation request, Logging and Admin compute Account's redemption result is an authenticated authorization projection, not the domain mutation outcome. It contains the validated authority tuple, applicable generation and fence, action-family schema pair, request identity, digest, reference fingerprint, expiry, and any required assurance or workload-policy evidence. The domain owner remains responsible for its durable mutation, idempotency record, and terminal outcome. -The canonical encoding is one versioned contract, `mutationDigest/v1`. Each supported action family must name a separately published `actionFamilySchemaId` and `actionFamilySchemaVersion`; those values are explicit inputs to both the digest and the Account authorization reference. This ADR defines that binding but does not claim that any concrete action-family schemas or vector artifacts currently exist. The SHA-256 preimage is the following exact byte grammar; there is no JSON serializer or language-specific alternate: +The canonical encoding is one versioned contract, `mutationDigest/v1`. Each supported action family must name a separately published `actionFamilySchemaId` and `actionFamilySchemaVersion`; those values are explicit inputs to both the digest and the Account authorization reference. This ADR defines that binding. The StartSession action-family schema and shared Java/Python vectors are published; they establish those contract artifacts only, not executable or supported mutation. The SHA-256 preimage is the following exact byte grammar; there is no JSON serializer or language-specific alternate: ```text segment(bytes) = ascii(canonical_decimal_count(byte_length(bytes))) + ":" + bytes @@ -136,7 +138,7 @@ For an `object`, the action-family schema declares one fixed member list and ord Each published action-family schema must define two bounded limit layers. Raw parsing limits cap transport bytes, token/framing length, composite nesting depth, object member count, and array element count before normalization or allocation can expand attacker-controlled input. Normalized limits separately cap normalized string bytes, canonical numeric bytes and scale, each canonical segment length, and the total canonical preimage bytes. Account, Logging and Admin, and the domain owner enforce the same raw and normalized limits before hashing, authorization issuance, persistence, or forwarding. Canonicalization that expands a value beyond any normalized or preimage limit is rejected rather than truncated or hashed. Missing limits, an over-limit value, or disagreement between participants makes the family unsupported or the request invalid; implementations must not parse or hash an unbounded payload and reject it only afterward. -The `mutationDigest` value is the lowercase hexadecimal SHA-256 digest of that preimage, exactly 64 ASCII hexadecimal characters. Any future encoding change requires a new version and an explicit compatibility rule; implementations must not silently reinterpret `mutationDigest/v1`. Before claiming a family supported, Account, Logging & Admin, and every owner implementation must consume the same published action-family schema pair and cross-language golden vectors. Those required vectors must include canonical preimage bytes (hex) and expected digest for null versus absent top-level and optional object members, absent-member count and declared order, composed versus decomposed Unicode strings and keys, post-normalization key collisions, malformed Unicode rejection, numeric/string distinctions, object key ordering, arrays, representative scope/target mutations, and signed-zero normalization and rejection cases; each supported language records passing evidence in its contract tests. Until a concrete action-family schema identified by its schema pair and the corresponding cross-language vectors exist for a family, that family remains unsupported pending those artifacts; this ADR does not claim that the schemas or vectors currently exist. +The `mutationDigest` value is the lowercase hexadecimal SHA-256 digest of that preimage, exactly 64 ASCII hexadecimal characters. Any future encoding change requires a new version and an explicit compatibility rule; implementations must not silently reinterpret `mutationDigest/v1`. Before claiming a family supported, Account, Logging & Admin, and every owner implementation must consume the same published action-family schema pair and cross-language golden vectors. Those required vectors must include canonical preimage bytes (hex) and expected digest for null versus absent top-level and optional object members, absent-member count and declared order, composed versus decomposed Unicode strings and keys, post-normalization key collisions, malformed Unicode rejection, numeric/string distinctions, object key ordering, arrays, representative scope/target mutations, and signed-zero normalization and rejection cases; each supported language records passing evidence in its contract tests. Until a concrete action-family schema identified by its schema pair and the corresponding cross-language vectors exist for a family, that family remains unsupported pending those artifacts. StartSession's published schema and shared Java/Python vectors do not make its mutation executable or supported; each other family still requires its own artifacts. `authorizationReferenceFingerprint` is the versioned, keyed, non-reversible identity of the exact opaque reference. The canonical value is `arfp/v1//`, where the HMAC is HMAC-SHA-256 with `K[keyId]` over this exact byte preimage: diff --git a/design/architecture/microservices/game-session-service/start-session-action-schema.md b/design/architecture/microservices/game-session-service/start-session-action-schema.md new file mode 100644 index 0000000000..f852fb1e4c --- /dev/null +++ b/design/architecture/microservices/game-session-service/start-session-action-schema.md @@ -0,0 +1,54 @@ +# StartSession Operator Action Schema + +## Implementation status + +The shared StartSession action, mutation-digest codec, pre-authorization reservation tuple, post-authorization execution tuple, and Account authority-evidence bundle are present as common-platform-core value and codec contracts with focused Java tests and shared Java/Python digest vectors. Logging & Admin also implements durable StartSession pre-authorization reservation persistence and the read-only `ReadCurrentClaimEvidence` transport for Account claim-evidence handoff. Production reservation construction is write-denied and passive/read-only; mutation-capable construction is isolated to test-only fixtures. These implementations do not establish current Account authority. Account issuance and redemption are not wired; Game Session and Game Design runtime registration and owner execution integration are not implemented. External routing and end-to-end launch proof remain unproved. No external route or runtime activation is enabled by this boundary. + +## Normative contract + +This document defines the StartSession action-family schema `firemud.game-session.start-session`, version `1`, owned by `game-session-service`. It defines the digest input shape for the `StartSession` operator action. It does not make the external operator route routable or establish an authorization decision. + +The request is a JSON object whose declared member order is `actionFamilySchemaId`, `actionFamilySchemaVersion`, `scope`, `target`, `expectedVersion`, `mutation`, and `auditReason`. `expectedVersion` is absent for this creation action and must not appear in the JSON request, including as `null`. Its absence remains an explicit seventh field in the canonical digest preimage. All other top-level members are required. + +| Member | Required shape and constraint | +| --- | --- | +| `actionFamilySchemaId` | String exactly `firemud.game-session.start-session`. | +| `actionFamilySchemaVersion` | String exactly `1`. | +| `scope` | Object with exactly `tenantId`, then `targetNamespace`. | +| `scope.tenantId` | Canonical lowercase, hyphenated, non-nil UUID. | +| `scope.targetNamespace` | Kubernetes workload namespace label: 1–63 lowercase ASCII letters or digits, with internal hyphens allowed and no leading or trailing hyphen. | +| `target` | Object with exactly `gameTemplateId`, then `ownerAccountId`. | +| `target.gameTemplateId` | JSON string matching `[1-9][0-9]*`, within the current owner's signed `long` range. JSON numbers and strings with a sign, leading zero, decimal point, or exponent are rejected. | +| `target.ownerAccountId` | Canonical lowercase, hyphenated, non-nil Account UUID. Private legacy identifier mappings remain the receiver's responsibility. | +| `expectedVersion` | Explicitly absent for StartSession creation. Any supplied value, including `null`, is rejected. | +| `mutation` | Object with the optional member `clientIp`. | +| `mutation.clientIp` | Absent or a string whose NFC-normalized UTF-8 encoding is at most 128 bytes. Empty string is distinct from absence. `null` and all other types are rejected. No address parsing or ownership claim is implied. | +| `auditReason` | Required string, nonblank after NFC normalization, at most 1,000 normalized UTF-8 bytes. | + +For the `auditReason` nonblank constraint, the shared blank codepoint set is exactly U+0009–U+000D, U+0020, U+0085, U+00A0, U+1680, U+2000–U+200A, U+2028, U+2029, U+202F, U+205F, and U+3000. Implementations must use this explicit set rather than a language-provided whitespace predicate. Other codepoints, including U+200B ZERO WIDTH SPACE, do not make an audit reason blank. + +JSON object members must appear in the declared order. Duplicate raw keys, keys colliding after NFC normalization, unknown or missing members, wrong JSON types, malformed Unicode, invalid UTF-8, and trailing tokens are rejected before a digest is returned. Object and array values use the recursive typed grammar from [ADR 0047, Bounded Owner Delegation](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#bounded-owner-delegation); no generic JSON canonicalization is a substitute. + +The schema uses these shared parser and encoding bounds: + +| Limit | Maximum | +| --- | ---: | +| Raw UTF-8 JSON input | 16 KiB | +| Composite nesting depth | 8 | +| Members in one object | 16 | +| Elements in one array | 64 | +| NFC-normalized string or object-key bytes | 4,096 | +| Raw or canonical numeric bytes | 128 | +| Numeric scale | 128 | +| Canonical segment payload | 8,192 bytes | +| Complete `mutationDigest/v1` preimage | 32 KiB | + +## Digest inputs and exclusions + +The SHA-256 preimage follows ADR 0047's exact `mutationDigest/v1` framing. The schema pair and these typed fields are included in the ADR-defined order: `scope`, `target`, absent `expectedVersion`, `mutation`, and `auditReason`. The `mutation` object always declares one member, `clientIp`; if it is omitted from JSON, the digest still includes that member in its declared position with type `absent` and presence `0`. An empty string is encoded as a present `string` and therefore has a different digest. + +The target owner is fixed to `game-session-service` for this schema and is carried separately in the ADR 0048 execution tuple; it is not a digest field. `controlPlaneRequestId`, any separately tagged action-family request identity, reservation owner and claim fence, transport credentials, opaque authorization references, actor assertions, and Account authority evidence are outside these seven grammar fields and are compared at their respective boundaries under [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#bounded-owner-delegation) and [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md#one-correlated-execution). + +The action contains no runtime version or patch input. It does not assert current ownership or authority. Owner-domain checks, source selection and execution remain separate runtime prerequisites outside this shared-contract slice. + +The shared Java implementation exposes `StartSessionOperatorActionCodec.decode(byte[])`, `canonicalPreimage(...)`, and `mutationDigest(...)`, plus the immutable typed action accessors. Shared Java and Python conformance vectors are stored in [the common vector fixture](../../../../services/common-platform-core/src/test/resources/operator/start-session-mutation-digest-v1-vectors.json). diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index 7ca506ddb7..05d8fcf0a9 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -134,6 +134,11 @@ curl -H 'Authorization: Bearer ' \ ## gRPC +- `logging_admin.v1.StartSessionReservationEvidenceService/ReadCurrentClaimEvidence` – internal, read-only Account handoff for the exact durable Logging & Admin StartSession reservation claim. It accepts only an active, unexpired `AUTHORIZATION_PENDING` or `AUTHORIZED` row whose request ID, canonical pre-authorization tuple, mutation digest, original reservation owner/fence, current claim owner/fence, and persisted claim purpose match exactly. `ISSUE` is allowed only for an original claim or a fresh claim recovered from `RESERVED`, after that claim has advanced the same reservation to `AUTHORIZATION_PENDING`; recovery from `AUTHORIZATION_PENDING` is lookup-only until its original Account response is found, then it may enrich the same tuple and perform the one original owner handoff. Recovery from `AUTHORIZED` may only look up that original Account response before the same one-time handoff. No recovery creates a new request, authorization reference, or owner attempt, or changes the original reservation owner/fence. The response returns that stored claim evidence and observation time; it does not issue an authorization reference, advance the reservation, or authorize owner execution. A missing row returns `NOT_FOUND`; stale, mismatched, or expired claims return `FAILED_PRECONDITION`; malformed input returns `INVALID_ARGUMENT`; persistence unavailability returns `UNAVAILABLE`. +- This RPC is the sole entry in `firemud.auth.grpc.public-methods`, so the shared Bearer-JWT interceptor does not authenticate it. The gRPC server still requires a client certificate, and the shared TLS peer interceptor extracts the normalized URI principal and presented-leaf SHA-256 from the same verified TLS session as separate evidence. The receiver permits only `spiffe://firemud/ns//sa/account-service`, no authenticated caller context, and a leaf approved for this exact method by the protected server-owned file in [Configuration](./configuration.md#service-specific-variables). Missing/blank namespace or approval configuration, a missing peer or leaf, an unapproved leaf, malformed/unavailable approval policy, and any different or cross-namespace peer are denied before the reservation read. A JWT header is neither authority nor rejected as a blanket condition. +- The reservation boundary is currently passive in production: Spring/public service and repository constructors deny acquire, recovery-claim acquisition, renewal, expiry, authorization transitions/enrichment, and owner handoff before repository/SQL work. Read methods remain available. There is no configuration, environment, or caller-controlled switch that enables these writes; mutation-capable construction exists only in the isolated test-fixtures source set. The proto/read contract therefore does not claim that production reservation writes or the operator workflow are enabled. +- The persisted canonical tuple can contain an actor Account ID, tenant and target-owner identifiers, operator reason, and optional client IP. Treat these fields as potentially personal or subject-linked data. The 30-second claim lease is a concurrency/recovery lease, not a retention period. Lifecycle and exact handoff remain governed by [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md); transport identity remains governed by [ADR 0038](../../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). Retention, terminalization, legal holds, export/erasure treatment, tombstones, and safe-watermark cleanup are not implemented here and must follow [DATA-01 / ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) and [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md); no retention duration is inferred from the lease. +- Activation remains blocked on this family's owner registry and approved finite schedule, including subject/tenant export, erasure or minimization, legal holds, backups and restore reconciliation. Its nonterminal reservations are live/recoverable work; any future terminal receipts and recovery lineage need cross-owner retry/restore-safe watermarks, while audit reason and client IP require purpose-bound governance and payload minimization. Post-authorization evidence also includes token identifiers and authorization-reference fingerprints, not the opaque reference itself. Proof-qualified terminalization, dependent-owner closure, tombstone/anti-replay preservation and bounded cleanup are still missing; the existing DELETE/TRUNCATE protections remain intact. Isolated run-owned tests cannot satisfy or enable this production activation gate. - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in [`logging_admin_service.proto`](../../../../protos/logging-admin/v1/logging_admin_service.proto); the current gRPC interceptor requires a Bearer JWT, while the target classification remains platform health policy. - `QueryLogs(QueryLogsRequest) returns (QueryLogsResponse)` – queries the service-owned PostgreSQL `log_events` table for the exact tenant and case-insensitive message containment and returns matching stored messages; it does not query the deployed structured-log pipeline. - `ApplyModerationAction(ApplyModerationActionRequest) returns (ApplyModerationActionResponse)` – unavailable/gated implementation contract for moderation policy input/audit until the action-family schema, shared cross-language `mutationDigest/v1` golden vectors, Account authorization-reference issuance, and receiving-boundary validation/redemption exist; it now hard fails closed with an application-level `UNAVAILABLE` error before dispatch or persistence, while separate fixed-category policy/audit evidence and owner enforcement are absent, and it is not current supported external operator mutation. Target behavior uses one Account reference bound to the exact request identity/digest and redeemed exactly once by Logging & Admin for local policy-input/audit persistence; that reference is never forwarded or reused. Any future owner-enforcement command uses a separate Account reference redeemed once by its receiving owner. `EvaluateModerationPolicy` remains the live read contract used at owner enforcement boundaries and carries no mutation authorization reference. diff --git a/design/architecture/microservices/logging-admin-service/configuration.md b/design/architecture/microservices/logging-admin-service/configuration.md index 5f503b51d0..addecea4c4 100644 --- a/design/architecture/microservices/logging-admin-service/configuration.md +++ b/design/architecture/microservices/logging-admin-service/configuration.md @@ -23,9 +23,15 @@ The Logging & Admin Service does **not** connect to Redis at runtime. It consume | `FIREMUD_AUTH_JWT_SECRET` | Legacy HMAC JWT validation secret (transitional only; not for player-facing environments) | *(none)* | | `FIREMUD_AUTH_JWT_SECRET_PATH` | Legacy file path for HMAC JWT validation secret (transitional only; not for player-facing environments) | *(none)* | | `FIREMUD_AUTH_JWT_EXPIRATION_MS` | Lifetime of issued JWTs in milliseconds | `3600000` | +| `FIREMUD_GRPC_WORKLOAD_NAMESPACE` | Namespace required for the exact Account workload identity on the StartSession reservation evidence RPC; blank configuration denies that method | *(none)* | +| `FIREMUD_GRPC_ACCOUNT_RESERVATION_EVIDENCE_APPROVED_LEAF_FILE` | Absolute path to the protected, method-scoped Account leaf-approval file for `ReadCurrentClaimEvidence`; blank, unreadable, or invalid policy denies the method | *(none)* | | `FIREMUD_SERVICES_ACCOUNT_SERVICE` | gRPC endpoint (host:port) for the Account Service | *(none)* | | `FIREMUD_SERVICES_GAME_SESSION_SERVICE` | gRPC endpoint (host:port) for the Game Session Service | *(none)* | +`logging_admin.v1.StartSessionReservationEvidenceService/ReadCurrentClaimEvidence` is the only method exempted from the shared Bearer-JWT interceptor. The server's required client-certificate handshake and verified TLS peer interceptor remain enabled. The receiver requires both the exact Account SPIFFE identity in `FIREMUD_GRPC_WORKLOAD_NAMESPACE` and approval of the SHA-256 fingerprint derived from the presented TLS leaf. It reads the configured file for each request; a missing path, read failure, malformed file, or unapproved leaf denies the request before reservation access. The JWT header is not an identity source for this method. + +The file is a protected server-owned input mounted read-only for Logging & Admin. It contains exactly one required `active=<64 lowercase hexadecimal SHA-256>` line and may contain one `overlap=<64 lowercase hexadecimal SHA-256>;expires-at=` line after it. The entries must name distinct leaves. Blank lines, comments, extra entries, duplicate leaves, uppercase or malformed fingerprints, non-absolute paths, and malformed expiry values are rejected. The overlap leaf is accepted only before its absolute expiry time as evaluated by the Logging & Admin host clock; the two-entry limit bounds overlap to one active and one retiring leaf. Replace the file atomically to rotate or revoke approval: publish a new active leaf with the prior leaf as overlap and an explicit deadline, then replace it with the new active leaf alone; immediate revocation replaces the file without the affected fingerprint. Provisioning and custody of this file, including rotation updates, are environment responsibilities and are not supplied or proven by this code change. No production leaf approval or live rotation is claimed. + ## Proto Files API schemas are kept in [`protos/logging-admin/v1`](../../../../protos/logging-admin/v1). When these change, run `./gradlew generateProto` to refresh generated sources. diff --git a/design/architecture/system-architecture-authz-route-matrix.yaml b/design/architecture/system-architecture-authz-route-matrix.yaml index a8f6ba0f5d..c168512775 100644 --- a/design/architecture/system-architecture-authz-route-matrix.yaml +++ b/design/architecture/system-architecture-authz-route-matrix.yaml @@ -3709,6 +3709,31 @@ routes: implementation_status: known_drift: - current_service_has_no_ReadLogEventReceipt_handler_and_returns_UNIMPLEMENTED; target_Account_mTLS_receipt_readback_and_runtime_proof_are_unavailable + - service: logging-admin-service + route: ReadCurrentClaimEvidence + transport: grpc + scope: account + route_status: target_not_currently_routable + classification: internal_workload + auth_path: exact_mtls_workload + issued_token_state: none + accepted_token_profiles: [] + token_type: none + token_issuer: none + token_audience: none + method_policy: exact_declared_route + allowed_callers: + any_of: [account-service] + mtls_callers: + any_of: ["spiffe://firemud/ns/{namespace}/sa/account-service"] + end_user_token_required: false + caller_context: absent + certificate_instance_approval: + evidence: presented_leaf_der_sha256_from_grpc_tls_session + source: protected_method_scoped_file + maximum_approved_instances: 2 + overlap: explicit_expiring_replacement_only + absent_or_invalid_policy: deny - service: game-session-service route: ToggleFeatureFlag transport: grpc diff --git a/design/project-management/design-alignment/design-capability-allocation-microservices.md b/design/project-management/design-alignment/design-capability-allocation-microservices.md index 4c748a33b5..2a1a6f7b7d 100644 --- a/design/project-management/design-alignment/design-capability-allocation-microservices.md +++ b/design/project-management/design-alignment/design-capability-allocation-microservices.md @@ -18,8 +18,8 @@ This ledger maps every Markdown source under [`design/architecture/microservices | Measure | Count | | --- | ---: | -| Markdown sources discovered | 76 | -| Capability-allocated sources | 74 | +| Markdown sources discovered | 77 | +| Capability-allocated sources | 75 | | Explicitly exempt artifacts | 2 | | Unallocated sources | 0 | | Taxonomy gaps | 0 | @@ -33,8 +33,8 @@ This ledger maps every Markdown source under [`design/architecture/microservices | Configuration contracts | 11 | | Operations contracts | 11 | | Runtime/data contracts | 9 | -| Service-specific design, UX, protocol, and workflow appendices | 20 | -| **Total** | **76** | +| Service-specific design, UX, protocol, and workflow appendices | 21 | +| **Total** | **77** | ## Microservice-Root Artifacts @@ -115,6 +115,7 @@ This ledger maps every Markdown source under [`design/architecture/microservices | `design/architecture/microservices/game-session-service/operations.md` | `PO-4` | `AA-2`, `AR-3`, `EA-1`, `EA-2`, `GR-1`, `SF-2` | Overrides: **Scaling and Region Rebalancing** -> `GR-1`; runtime-slice status under **Current Runtime Status** -> `AA-2`/`EA-1`/`EA-2`; activation/recovery notes -> `AR-3`/`SF-2`. | Operations contract | Live versus target-state status is explicit and does not change capability ownership. | | `design/architecture/microservices/game-session-service/protocols.md` | `EA-1` | `AA-2`, `AA-3`, `EA-2`, `GR-1`, `PO-2`, `PO-4`, `SF-1` | Overrides: **Login and Play Flow** and **Stage-aware command handling** -> `AA-2`/`AA-3`; **Plaintext Telnet pre-login warning** -> `PO-2`/`SF-1`; communication portions of **LOOK and SAY Behavior** plus **Communication request flow** -> `EA-2`; execution portions of request flows -> `GR-1`; metrics subsection -> `PO-4`. | Gameplay protocol contract | Command/presentation ownership is separated from gameplay-rule and social-delivery ownership. | | `design/architecture/microservices/game-session-service/runtime-and-data.md` | `GR-1` | `AA-2`, `AR-2`, `AR-3`, `AS-1`, `GR-4`, `PO-4`, `SF-1`, `SF-2` | Overrides: session keys and **Reconnection and Disconnect Handling** -> `AA-2`; **Runtime Feature Flags** -> `AR-2`; **Script Patch Version Pinning and Rollback** -> `AR-3`/`AS-1`; persistence mechanics in Redis, command/effect execution, and saga sections -> `SF-2`; gameplay effects -> `GR-4`. | Runtime/data contract | No unresolved ambiguity. | +| `design/architecture/microservices/game-session-service/start-session-action-schema.md` | `AR-3` | `AA-1`, `GR-1`, `PO-1`, `SF-1`, `SF-2` | Whole file. Runtime instance launch -> `AR-3`; Account authorization evidence -> `AA-1`; Game Session execution -> `GR-1`; operator ingress -> `PO-1`; canonical typed schema and authorization propagation -> `SF-1`; reservation idempotency -> `SF-2`. | Operator action schema | The action contract does not enable the external route or establish runtime execution. | ## Logging and Admin Service @@ -182,12 +183,12 @@ This ledger maps every Markdown source under [`design/architecture/microservices | Entity Management Service | 5 | 5 | 0 | 0 | | Game Design Service | 13 | 13 | 0 | 0 | | Game Logic Service | 5 | 5 | 0 | 0 | -| Game Session Service | 6 | 6 | 0 | 0 | +| Game Session Service | 7 | 7 | 0 | 0 | | Logging and Admin Service | 8 | 8 | 0 | 0 | | Social and Groups Service | 5 | 5 | 0 | 0 | | Spring Cloud Gateway | 5 | 5 | 0 | 0 | | TCP Proxy Service | 6 | 6 | 0 | 0 | | World Management Service | 7 | 7 | 0 | 0 | -| **Total** | **76** | **74** | **2** | **0** | +| **Total** | **77** | **75** | **2** | **0** | -The inventory covers every path returned by `rg --files design/architecture/microservices -g '*.md'`. Two microservice-root artifacts are explicit governance/template exemptions, all 74 capability-bearing files have one primary allocation, and no source remains unallocated or requires a taxonomy-gap classification. +The inventory covers every path returned by `rg --files design/architecture/microservices -g '*.md'`. Two microservice-root artifacts are explicit governance/template exemptions, all 75 capability-bearing files have one primary allocation, and no source remains unallocated or requires a taxonomy-gap classification. diff --git a/design/project-management/design-alignment/design-capability-allocation.md b/design/project-management/design-alignment/design-capability-allocation.md index a870d50dd4..0cb7e7a469 100644 --- a/design/project-management/design-alignment/design-capability-allocation.md +++ b/design/project-management/design-alignment/design-capability-allocation.md @@ -45,16 +45,16 @@ This file intentionally owns the detailed allocation-validation history; the des | Top-level architecture | 83 | 83 | 0 | 100% classified | | Infrastructure | 6 | 6 | 0 | 100% classified | | Generated references | 2 | 2 | 0 | 100% classified | -| Microservice architecture | 76 | 74 | 0; 2 explicit governance/template exemptions | 100% classified | +| Microservice architecture | 77 | 75 | 0; 2 explicit governance/template exemptions | 100% classified | | Architecture decisions | 183 | 182 | 0; 1 registry exemption | 100% classified | | Product documentation | 7 | 7 | 0 | 100% classified | -| **Total** | **357** | **354** | **0; 3 explicit exemptions** | **100% classified** | +| **Total** | **358** | **355** | **0; 3 explicit exemptions** | **100% classified** | ## Allocation Ledger | Design source | Heading or scope | Primary capability | Secondary handoffs | Source class | Notes or gap | | --- | --- | --- | --- | --- | --- | -| [Microservice architecture allocation](./design-capability-allocation-microservices.md) | All 76 files under `design/architecture/microservices/**` | Per-source allocation | Per-source handoffs | Service design, contract, runtime/data, configuration, operations, and reference sources | All 76 files are accounted for as 74 allocated sources plus 2 exempt governance/template files: `service-documentation-structure.md` and `service-template.md`; complete path-set coverage | +| [Microservice architecture allocation](./design-capability-allocation-microservices.md) | All 77 files under `design/architecture/microservices/**` | Per-source allocation | Per-source handoffs | Service design, contract, runtime/data, configuration, operations, and reference sources | All 77 files are accounted for as 75 allocated sources plus 2 exempt governance/template files: `service-documentation-structure.md` and `service-template.md`; complete path-set coverage | | [Architecture decision registry](../../architecture/decisions/README.md) | Registry plus 182 ADRs | Per-record allocation | Per-record affected capabilities | Decision record | The registry is an index; reviewed, accepted, superseded, withdrawn, and pending records remain distinguishable | | [System architecture allocation](./design-capability-allocation-system.md) | All 83 direct architecture, 6 infrastructure, and 2 generated sources | Per-source allocation | Per-source handoffs | Normative design, runbook, reference, index, and generated sources | Complete path-set coverage | | [Product documentation](../../product/README.md#canonical-sources) | All 7 files under `design/product/**` | Per-source allocation | Per-source product behavior scope | Requirements, taxonomy, index, and observable product behavior | Complete path-set coverage | diff --git a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md index ff0e360ab7..36198ce20e 100644 --- a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md +++ b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md @@ -10,6 +10,10 @@ The implementation record below summarizes the shared runtime, service-contract, Account V25, Game Session V2, and Automation V2 schema activation now has a bounded quiescence slice: base/hosted workloads use non-rolling replacement, the trusted dev-demo path recognizes migration-bearing pushes, preserves that runtime database, stops the three Account, Game Session, and Automation writer Deployments, and verifies their Pods are absent; ordinary pushes retain the established clean namespace reset. Redispatch classification uses the exact namespace-manager deployed-head annotation and fails before mutation if the head or Git ancestry is unproven. The Game Session and Automation V2 migrations check their known V1 indexes plus service-specific active-claim/data prerequisites before changing indexes; this status does not claim equivalent migration validation for Account V25. Focused PostgreSQL failure-path tests are added but remain unverified until Docker-backed service tests run. Candidate PR previews that change Flyway migrations fail before namespace recreation because their scoped runtime path cannot prove Postgres PVC provenance or query migration history; trusted post-merge deployment is the activation path. Recovery is roll-forward only. This does not complete the separate retained-row identity and cross-instance PostgreSQL proof recorded below. +### StartSession reservation evidence leaf-instance gate + +`ReadCurrentClaimEvidence` now has a method-local gate that combines the exact configured Account URI principal, absence of caller context, and the presented TLS leaf's DER SHA-256 approval from a protected per-method file. The file allows one active leaf and at most one retiring leaf with an explicit absolute expiry; replacement can revoke a leaf immediately, and missing, malformed, or unreadable policy denies before reservation access. Requests using an overlap leaf are denied at its expiry even if its line remains in the file. Focused unit tests passed for leaf approval, expiry, revocation, missing evidence, and caller-context handling; the storage-independent socket fixture passed certificate-handshake checks. The complete PostgreSQL-backed real TLS approval/rotation fixture is present but skipped locally because Docker is unavailable, so it requires attributable isolated CI proof. Environment provisioning and custody of the protected file, production fingerprints, certificate issuance/rotation, and live accepted/rejected-leaf readback remain unproved; the change does not claim production activation. See [ADR 0038](../../architecture/decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md), [Logging & Admin configuration](../../architecture/microservices/logging-admin-service/configuration.md), and the [authorization route matrix](../../architecture/system-architecture-authz-route-matrix.yaml). + ### Script-transition cross-service handoff Implementation and proof remain partial: Game Session has durable per-instance pin state, while rollout history and final effect fencing remain incomplete; Automation has tenant readiness and core runtime state, while owner-observation projections and complete cross-boundary propagation/fencing remain incomplete. Current proof does not cover every durable work, handoff, timer, replay, and final-effect boundary, stage-aware dead-letter recovery, or complete no-degraded instance-bound admission. Canonical ownership remains in [scripting contracts](../../architecture/system-architecture-scripting-contracts.md), [scheduler and timers](../../architecture/system-architecture-scripting-scheduler-and-timers.md), [rollout and rollback](../../architecture/system-architecture-scripting-rollout-and-rollback.md), and [owner-read-first control-plane notifications](../../architecture/decisions/adr-0120-owner-read-first-control-plane-notifications.md); detailed status remains in the [Game Session](./game-session-runtime-and-tick-coordination.md#capability-status) and [Automation](./automation-and-scheduler-runtime.md#capability-status) trackers. diff --git a/dev-tools/tests/test_start_session_action_digest.py b/dev-tools/tests/test_start_session_action_digest.py new file mode 100644 index 0000000000..622a176e57 --- /dev/null +++ b/dev-tools/tests/test_start_session_action_digest.py @@ -0,0 +1,335 @@ +#!/usr/bin/env python3 +"""Standard-library conformance checks for StartSession mutationDigest/v1 vectors.""" + +import hashlib +import json +import re +import unicodedata +import unittest +from dataclasses import dataclass +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +FIXTURE = ( + ROOT + / "services/common-platform-core/src/test/resources/operator/" + / "start-session-mutation-digest-v1-vectors.json" +) +SCHEMA_ID = "firemud.game-session.start-session" +SCHEMA_VERSION = "1" +SHARED_WHITESPACE_CODEPOINTS = frozenset( + [*range(0x0009, 0x000E), 0x0020, 0x0085, 0x00A0, 0x1680] + + list(range(0x2000, 0x200B)) + + [0x2028, 0x2029, 0x202F, 0x205F, 0x3000] +) +TOP_LEVEL_ORDER = [ + "actionFamilySchemaId", + "actionFamilySchemaVersion", + "scope", + "target", + "expectedVersion", + "mutation", + "auditReason", +] +UUID_PATTERN = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\Z") +NAMESPACE_PATTERN = re.compile(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\Z") +NUMBER_SOURCE = re.compile(r"-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?\Z") +NUMBER_CANONICAL = re.compile(r"0|-?(?:[1-9][0-9]*(?:\.[0-9]*[1-9])?|0\.[0-9]*[1-9])\Z") + + +@dataclass(frozen=True) +class RawNumber: + lexeme: str + + +@dataclass(frozen=True) +class RawObject: + members: list + + +def reject_constant(_value): + raise ValueError("non-finite numeric value") + + +def parse_json(raw): + if len(raw) > 16 * 1_024: + raise ValueError("raw JSON exceeds its byte limit") + source = raw.decode("utf-8", "strict") + return json.loads( + source, + parse_int=RawNumber, + parse_float=RawNumber, + parse_constant=reject_constant, + object_pairs_hook=lambda pairs: RawObject(pairs), + ) + + +def scalar_string(value, byte_limit=4_096): + if not isinstance(value, str): + raise TypeError("string value required") + if any(0xD800 <= ord(character) <= 0xDFFF for character in value): + raise ValueError("malformed Unicode") + normalized = unicodedata.normalize("NFC", value) + encoded = normalized.encode("utf-8", "strict") + if len(encoded) > byte_limit: + raise ValueError("normalized string exceeds its byte limit") + return normalized + + +def segment(payload): + if len(payload) > 8_192: + raise ValueError("segment exceeds its byte limit") + return str(len(payload)).encode("ascii") + b":" + payload + + +def decimal_value(raw): + lexeme = raw.lexeme + encoded = lexeme.encode("ascii", "strict") + if len(encoded) > 128 or not NUMBER_SOURCE.fullmatch(lexeme): + raise ValueError("numeric source is invalid or too long") + fraction = lexeme.partition(".")[2] + if len(fraction) > 128: + raise ValueError("numeric scale exceeds its limit") + negative = lexeme.startswith("-") + unsigned = lexeme[1:] if negative else lexeme + integer, separator, fraction = unsigned.partition(".") + fraction = fraction.rstrip("0") if separator else "" + nonzero = any(digit != "0" for digit in integer + fraction) + if not nonzero: + canonical = "0" + elif fraction: + canonical = ("-" if negative else "") + integer + "." + fraction + else: + canonical = ("-" if negative else "") + integer + canonical_bytes = canonical.encode("ascii") + if len(canonical_bytes) > 128 or not NUMBER_CANONICAL.fullmatch(canonical): + raise ValueError("canonical number exceeds its limit") + return canonical_bytes + + +def encoded_value(value, depth=0): + if value is ABSENT: + return segment(b"absent") + b"0" + segment(b"") + if value is None: + return segment(b"null") + b"1" + segment(b"") + if isinstance(value, str): + payload = scalar_string(value).encode("utf-8") + return segment(b"string") + b"1" + segment(payload) + if isinstance(value, RawNumber): + return segment(b"number") + b"1" + segment(decimal_value(value)) + if isinstance(value, bool): + return segment(b"boolean") + b"1" + segment(b"true" if value else b"false") + if isinstance(value, RawObject): + if depth >= 8: + raise ValueError("composite nesting is too deep") + if len(value.members) > 16: + raise ValueError("object exceeds its member limit") + normalized_members = [] + seen = set() + for raw_key, member_value in value.members: + key = scalar_string(raw_key).encode("utf-8") + if key in seen: + raise ValueError("duplicate or normalized-colliding object key") + seen.add(key) + normalized_members.append((key, member_value)) + payload = segment(str(len(normalized_members)).encode("ascii")) + for key, member_value in normalized_members: + payload += segment(key) + encoded_value(member_value, depth + 1) + return segment(b"object") + b"1" + segment(payload) + if isinstance(value, list): + if depth >= 8: + raise ValueError("composite nesting is too deep") + if len(value) > 64: + raise ValueError("array exceeds its element limit") + payload = segment(str(len(value)).encode("ascii")) + for item in value: + payload += encoded_value(item, depth + 1) + return segment(b"array") + b"1" + segment(payload) + raise ValueError("unsupported typed JSON value") + + +ABSENT = object() + + +def ordered_members(value, declared_order, optional=()): + if not isinstance(value, RawObject): + raise TypeError("object value required") + if len(value.members) > 16: + raise ValueError("object exceeds its member limit") + members = {} + actual_order = [] + for raw_key, member_value in value.members: + key = scalar_string(raw_key) + if key in members: + raise ValueError("duplicate or normalized-colliding object key") + members[key] = member_value + actual_order.append(key) + if any(key not in declared_order for key in actual_order): + raise ValueError("unknown object member") + expected_order = [key for key in declared_order if key in members or key not in optional] + if actual_order != expected_order: + raise ValueError("missing or out-of-order object member") + return members + + +def canonical_uuid(value, label): + normalized = scalar_string(value) + if not UUID_PATTERN.fullmatch(normalized) or normalized == "00000000-0000-0000-0000-000000000000": + raise ValueError(f"{label} is not a canonical non-nil UUID") + return normalized + + +def action_preimage(raw): + root = parse_json(raw) + members = ordered_members(root, TOP_LEVEL_ORDER, optional={"expectedVersion"}) + if members.get("actionFamilySchemaId") != SCHEMA_ID: + raise ValueError("wrong schema id") + if members.get("actionFamilySchemaVersion") != SCHEMA_VERSION: + raise ValueError("wrong schema version") + if "expectedVersion" in members: + raise ValueError("expectedVersion must be absent") + + scope = ordered_members(members["scope"], ["tenantId", "targetNamespace"]) + tenant_id = canonical_uuid(scope["tenantId"], "tenantId") + namespace = scalar_string(scope["targetNamespace"]) + if len(namespace) > 63 or not NAMESPACE_PATTERN.fullmatch(namespace): + raise ValueError("invalid workload namespace") + + target = ordered_members(members["target"], ["gameTemplateId", "ownerAccountId"]) + template_id = scalar_string(target["gameTemplateId"]) + if not re.fullmatch(r"[1-9][0-9]*", template_id): + raise ValueError("gameTemplateId must be a positive canonical decimal string") + if len(template_id) > 19 or ( + len(template_id) == 19 and template_id > "9223372036854775807" + ): + raise ValueError("gameTemplateId exceeds the current owner long range") + owner_id = canonical_uuid(target["ownerAccountId"], "ownerAccountId") + + mutation = ordered_members(members["mutation"], ["clientIp"], optional={"clientIp"}) + if "clientIp" not in mutation: + client_ip = ABSENT + else: + client_ip = mutation["clientIp"] + if not isinstance(client_ip, str): + raise ValueError("clientIp must be an absent or string value") + client_ip = scalar_string(client_ip, 128) + + audit_reason = scalar_string(members["auditReason"], 1_000) + if not audit_reason or all( + ord(character) in SHARED_WHITESPACE_CODEPOINTS for character in audit_reason + ): + raise ValueError("auditReason must not be blank") + + values = [ + ("actionFamilySchemaId", SCHEMA_ID), + ("actionFamilySchemaVersion", SCHEMA_VERSION), + ( + "scope", + RawObject( + [ + ("tenantId", tenant_id), + ("targetNamespace", namespace), + ] + ), + ), + ( + "target", + RawObject( + [ + ("gameTemplateId", template_id), + ("ownerAccountId", owner_id), + ] + ), + ), + ("expectedVersion", ABSENT), + ("mutation", RawObject([("clientIp", client_ip)])), + ("auditReason", audit_reason), + ] + result = segment(b"mutationDigest/v1") + for name, typed_value in values: + result += segment(name.encode("utf-8")) + encoded_value(typed_value) + if len(result) > 32 * 1_024: + raise ValueError("preimage exceeds its byte limit") + return result + + +def raw_vector_bytes(vector): + if "rawHex" in vector: + return bytes.fromhex(vector["rawHex"]) + return vector["input"].encode("utf-8", "strict") + + +class StartSessionMutationDigestVectorTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.fixture = json.loads(FIXTURE.read_text(encoding="utf-8")) + + def test_action_vectors(self): + results = {} + for vector in self.fixture["vectors"]: + with self.subTest(vector=vector["name"]): + raw = raw_vector_bytes(vector) + if not vector["accepted"]: + with self.assertRaises((TypeError, ValueError, UnicodeError, json.JSONDecodeError)): + action_preimage(raw) + continue + preimage = action_preimage(raw) + digest = hashlib.sha256(preimage).hexdigest() + self.assertEqual(preimage.hex(), vector["preimageHex"]) + self.assertEqual(digest, vector["digest"]) + results[vector["name"]] = digest + + self.assertNotEqual(results["base"], results["changed-target"]) + self.assertNotEqual(results["base"], results["changed-scope"]) + self.assertNotEqual(results["base"], results["changed-audit-reason"]) + self.assertNotEqual(results["client-ip-absent"], results["client-ip-empty"]) + self.assertEqual(results["unicode-composed"], results["unicode-decomposed"]) + + def test_audit_reason_uses_explicit_shared_whitespace_set(self): + base = json.loads(self.fixture["vectors"][0]["input"]) + for codepoint in SHARED_WHITESPACE_CODEPOINTS: + with self.subTest(codepoint=f"U+{codepoint:04X}"): + base["auditReason"] = chr(codepoint) + with self.assertRaises(ValueError): + action_preimage(json.dumps(base, ensure_ascii=True).encode("utf-8")) + + base["auditReason"] = chr(codepoint) + "x" + action_preimage(json.dumps(base, ensure_ascii=True).encode("utf-8")) + + for codepoint in (0x001C, 0x200B): + with self.subTest(outside_codepoint=f"U+{codepoint:04X}"): + base["auditReason"] = chr(codepoint) + action_preimage(json.dumps(base, ensure_ascii=True).encode("utf-8")) + + def test_generic_value_grammar_vectors(self): + encodings = {} + for vector in self.fixture["grammarVectors"]: + with self.subTest(vector=vector["name"]): + if vector["kind"] == "numberLexeme": + if not vector["accepted"]: + with self.assertRaises((ValueError, UnicodeError)): + encoded_value(RawNumber(vector["rawLexeme"])) + continue + canonical = encoded_value(RawNumber(vector["rawLexeme"])) + self.assertEqual(canonical.hex(), vector["canonicalValueHex"]) + encodings[vector["name"]] = canonical.hex() + continue + if vector["kind"] == "reject": + with self.assertRaises((ValueError, UnicodeError, json.JSONDecodeError)): + encoded_value(parse_json(vector["rawValue"].encode("utf-8"))) + continue + if vector["kind"] == "absent": + canonical = encoded_value(ABSENT) + else: + canonical = encoded_value(parse_json(vector["rawValue"].encode("utf-8"))) + self.assertEqual(canonical.hex(), vector["canonicalValueHex"]) + encodings[vector["name"]] = canonical.hex() + + self.assertNotEqual(encodings["absent"], encodings["null"]) + self.assertNotEqual(encodings["number-one"], encodings["string-one"]) + self.assertEqual(encodings["number-signed-zero"], encodings["number-zero"]) + self.assertEqual(encodings["unicode-key-composed"], encodings["unicode-key-decomposed"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/dev-tools/validation/check-design-capability-allocation.py b/dev-tools/validation/check-design-capability-allocation.py index 6c1f736da3..d440d73b35 100644 --- a/dev-tools/validation/check-design-capability-allocation.py +++ b/dev-tools/validation/check-design-capability-allocation.py @@ -749,6 +749,10 @@ def adr_allocation(primary: str, classification: str, *secondary: str) -> tuple[ "EA-1", "Gameplay protocol contract", ), + "design/architecture/microservices/game-session-service/start-session-action-schema.md": ( + "AR-3", + "Operator action schema", + ), "design/architecture/microservices/logging-admin-service/admin-ui.md": ("EA-3", "First-party operator UX"), "design/architecture/microservices/logging-admin-service/analytics-dashboards.md": ( "PO-4", diff --git a/protos/logging-admin/v1/logging_admin_service.proto b/protos/logging-admin/v1/logging_admin_service.proto index 210539837f..cb2e04713c 100644 --- a/protos/logging-admin/v1/logging_admin_service.proto +++ b/protos/logging-admin/v1/logging_admin_service.proto @@ -19,6 +19,41 @@ service LoggingAdminService { rpc ToggleFeatureFlag(ToggleFeatureFlagRequest) returns (ToggleFeatureFlagResponse); } +// Read-only Account evidence for the current Logging/Admin StartSession reservation claim. +service StartSessionReservationEvidenceService { + rpc ReadCurrentClaimEvidence(ReadCurrentClaimEvidenceRequest) + returns (ReadCurrentClaimEvidenceResponse); +} + +enum StartSessionReservationEvidencePurpose { + START_SESSION_RESERVATION_EVIDENCE_PURPOSE_UNSPECIFIED = 0; + START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE = 1; + START_SESSION_RESERVATION_EVIDENCE_PURPOSE_RECOVER = 2; +} + +message ReadCurrentClaimEvidenceRequest { + string control_plane_request_id = 1; + bytes pre_authorization_tuple_json = 2; + string reservation_owner_id = 3; + int64 reservation_claim_fence = 4; + string claim_owner_id = 5; + int64 claim_fence = 6; + StartSessionReservationEvidencePurpose purpose = 7; +} + +message ReadCurrentClaimEvidenceResponse { + string control_plane_request_id = 1; + bytes pre_authorization_tuple_json = 2; + string mutation_digest = 3; + string reservation_owner_id = 4; + int64 reservation_claim_fence = 5; + string claim_owner_id = 6; + int64 claim_fence = 7; + int64 claim_expires_at_epoch_millis = 8; + int64 observed_at_epoch_millis = 9; + StartSessionReservationEvidencePurpose purpose = 10; +} + message PingRequest {} message PingResponse { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcPeerCertificateEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcPeerCertificateEvidence.java new file mode 100644 index 0000000000..b70e020634 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcPeerCertificateEvidence.java @@ -0,0 +1,77 @@ +package net.firedevops.firemud.common.grpc; + +import io.grpc.Context; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.cert.Certificate; +import java.security.cert.CertificateEncodingException; +import java.security.cert.X509Certificate; +import java.util.HexFormat; +import java.util.Optional; +import java.util.regex.Pattern; +import javax.net.ssl.SSLPeerUnverifiedException; +import javax.net.ssl.SSLSession; + +/** The SHA-256 evidence for the leaf presented by the serving gRPC TLS peer. */ +public final class GrpcPeerCertificateEvidence { + public static final Context.Key CONTEXT_KEY = + Context.key("firemud-grpc-peer-certificate-evidence"); + + private static final Pattern SHA256_PATTERN = Pattern.compile("[0-9a-f]{64}"); + + private final String leafSha256; + + private GrpcPeerCertificateEvidence(String leafSha256) { + if (leafSha256 == null || !SHA256_PATTERN.matcher(leafSha256).matches()) { + throw new IllegalArgumentException("Leaf SHA-256 fingerprint must be lowercase hexadecimal"); + } + this.leafSha256 = leafSha256; + } + + /** Returns the evidence currently attached to the serving gRPC context, if verified. */ + public static GrpcPeerCertificateEvidence current() { + return CONTEXT_KEY.get(); + } + + /** Extracts the presented leaf's DER SHA-256 fingerprint from the authenticated TLS session. */ + public static Optional fromSslSession(SSLSession sslSession) { + if (sslSession == null) { + return Optional.empty(); + } + try { + Certificate[] peerCertificates = sslSession.getPeerCertificates(); + if (peerCertificates == null + || peerCertificates.length == 0 + || !(peerCertificates[0] instanceof X509Certificate leaf)) { + return Optional.empty(); + } + return fromCertificate(leaf); + } catch (SSLPeerUnverifiedException | RuntimeException exception) { + return Optional.empty(); + } + } + + /** Extracts only leaf-instance evidence; this fingerprint is not a workload principal. */ + public static Optional fromCertificate(X509Certificate leaf) { + if (leaf == null) { + return Optional.empty(); + } + try { + byte[] encoded = leaf.getEncoded(); + if (encoded == null || encoded.length == 0) { + return Optional.empty(); + } + return Optional.of(new GrpcPeerCertificateEvidence(sha256(encoded))); + } catch (CertificateEncodingException | NoSuchAlgorithmException | RuntimeException exception) { + return Optional.empty(); + } + } + + public String leafSha256() { + return leafSha256; + } + + private static String sha256(byte[] certificateDer) throws NoSuchAlgorithmException { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(certificateDer)); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentityInterceptor.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentityInterceptor.java index 6664b5d2b9..8651d8dc30 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentityInterceptor.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentityInterceptor.java @@ -7,6 +7,7 @@ import io.grpc.ServerCall; import io.grpc.ServerCallHandler; import io.grpc.ServerInterceptor; +import javax.net.ssl.SSLSession; /** * Makes the authenticated TLS peer identity available to gRPC handlers. @@ -19,10 +20,14 @@ public final class GrpcPeerIdentityInterceptor implements ServerInterceptor { @Override public ServerCall.Listener interceptCall( ServerCall call, Metadata headers, ServerCallHandler next) { - GrpcPeerIdentity peerIdentity = - GrpcPeerIdentity.fromSslSession(call.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION)) - .orElse(null); - Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peerIdentity); + SSLSession sslSession = call.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION); + GrpcPeerIdentity peerIdentity = GrpcPeerIdentity.fromSslSession(sslSession).orElse(null); + GrpcPeerCertificateEvidence certificateEvidence = + GrpcPeerCertificateEvidence.fromSslSession(sslSession).orElse(null); + Context context = + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peerIdentity) + .withValue(GrpcPeerCertificateEvidence.CONTEXT_KEY, certificateEvidence); return Contexts.interceptCall(context, call, headers, next); } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/MutationDigestV1.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/MutationDigestV1.java new file mode 100644 index 0000000000..1da36c7cbe --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/MutationDigestV1.java @@ -0,0 +1,299 @@ +package net.firedevops.firemud.common.operator; + +import java.io.ByteArrayOutputStream; +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.text.Normalizer; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.regex.Pattern; + +/** Package-private implementation of the ADR 0047 mutationDigest/v1 byte grammar. */ +final class MutationDigestV1 { + static final int MAX_NORMALIZED_STRING_BYTES = 4_096; + static final int MAX_NUMERIC_BYTES = 128; + static final int MAX_NUMERIC_SCALE = 128; + static final int MAX_SEGMENT_BYTES = 8_192; + static final int MAX_PREIMAGE_BYTES = 32 * 1_024; + + private static final String DOMAIN = "mutationDigest/v1"; + private static final Pattern NUMBER_SOURCE = Pattern.compile("-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?"); + private static final Pattern NUMBER_CANONICAL = + Pattern.compile("0|-?(?:[1-9][0-9]*(?:\\.[0-9]*[1-9])?|0\\.[0-9]*[1-9])"); + + private MutationDigestV1() {} + + static byte[] preimage(StartSessionOperatorAction action) { + Objects.requireNonNull(action, "action is required"); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + writeSegment(output, utf8(DOMAIN)); + writeField(output, "actionFamilySchemaId", string(action.actionFamilySchemaId())); + writeField(output, "actionFamilySchemaVersion", string(action.actionFamilySchemaVersion())); + writeField( + output, + "scope", + object( + List.of( + member("tenantId", string(action.scope().tenantId().toString())), + member("targetNamespace", string(action.scope().targetNamespace()))))); + writeField( + output, + "target", + object( + List.of( + member("gameTemplateId", string(Long.toString(action.target().gameTemplateId()))), + member("ownerAccountId", string(action.target().ownerAccountId().toString()))))); + writeField(output, "expectedVersion", absent()); + Value clientIp = + action.mutation().clientIp() instanceof StartSessionOperatorAction.AbsentClientIp + ? absent() + : string( + ((StartSessionOperatorAction.StringClientIp) action.mutation().clientIp()).value()); + writeField(output, "mutation", object(List.of(member("clientIp", clientIp)))); + writeField(output, "auditReason", string(action.auditReason())); + byte[] preimage = output.toByteArray(); + if (preimage.length > MAX_PREIMAGE_BYTES) { + throw invalid("canonical preimage exceeds its byte limit"); + } + return preimage; + } + + static String sha256Hex(byte[] preimage) { + Objects.requireNonNull(preimage, "preimage is required"); + if (preimage.length > MAX_PREIMAGE_BYTES) { + throw invalid("canonical preimage exceeds its byte limit"); + } + try { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(preimage); + StringBuilder hex = new StringBuilder(digest.length * 2); + for (byte value : digest) { + hex.append(Character.forDigit((value >>> 4) & 0x0f, 16)); + hex.append(Character.forDigit(value & 0x0f, 16)); + } + return hex.toString(); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + static Value absent() { + return new ScalarValue("absent", false, new byte[0]); + } + + static Value nullValue() { + return new ScalarValue("null", true, new byte[0]); + } + + static Value string(String value) { + String normalized = normalize(value, MAX_NORMALIZED_STRING_BYTES, "string"); + return new ScalarValue("string", true, utf8(normalized)); + } + + static Value number(String rawLexeme) { + Objects.requireNonNull(rawLexeme, "number lexeme is required"); + byte[] rawBytes = utf8(rawLexeme); + if (rawBytes.length > MAX_NUMERIC_BYTES || !NUMBER_SOURCE.matcher(rawLexeme).matches()) { + throw invalid("number lexeme is invalid or exceeds its byte limit"); + } + int decimalPoint = rawLexeme.indexOf('.'); + if (decimalPoint >= 0 && rawLexeme.length() - decimalPoint - 1 > MAX_NUMERIC_SCALE) { + throw invalid("number scale exceeds its limit"); + } + BigDecimal decimal; + try { + decimal = new BigDecimal(rawLexeme); + } catch (NumberFormatException exception) { + throw invalid("number lexeme is invalid"); + } + String canonical = decimal.signum() == 0 ? "0" : decimal.stripTrailingZeros().toPlainString(); + byte[] canonicalBytes = utf8(canonical); + if (canonicalBytes.length > MAX_NUMERIC_BYTES + || !NUMBER_CANONICAL.matcher(canonical).matches()) { + throw invalid("canonical number exceeds its byte limit"); + } + return new ScalarValue("number", true, canonicalBytes); + } + + static Value bool(boolean value) { + return new ScalarValue("boolean", true, utf8(value ? "true" : "false")); + } + + static Value object(List members) { + return new ObjectValue(members); + } + + static Value array(List values) { + return new ArrayValue(values); + } + + static Member member(String key, Value value) { + return new Member(key, value); + } + + static byte[] encodedValue(Value value) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + writeValue(output, value); + return output.toByteArray(); + } + + static Value normalizeObject(List rawMembers) { + Objects.requireNonNull(rawMembers, "object members are required"); + if (rawMembers.size() > 16) { + throw invalid("object exceeds its member limit"); + } + List normalizedMembers = new ArrayList<>(rawMembers.size()); + List seenKeys = new ArrayList<>(rawMembers.size()); + for (Member member : rawMembers) { + String key = normalize(member.key(), MAX_NORMALIZED_STRING_BYTES, "object key"); + if (seenKeys.contains(key)) { + throw invalid("object contains a duplicate or normalized-colliding key"); + } + seenKeys.add(key); + normalizedMembers.add(new Member(key, member.value())); + } + return new ObjectValue(normalizedMembers); + } + + private static void writeField(ByteArrayOutputStream output, String name, Value value) { + writeSegment(output, utf8(name)); + writeValue(output, value); + if (output.size() > MAX_PREIMAGE_BYTES) { + throw invalid("canonical preimage exceeds its byte limit"); + } + } + + private static void writeValue(ByteArrayOutputStream output, Value value) { + Objects.requireNonNull(value, "typed value is required"); + String type; + boolean present; + byte[] payload; + if (value instanceof ScalarValue scalar) { + type = scalar.type(); + present = scalar.present(); + payload = scalar.payload(); + } else if (value instanceof ObjectValue object) { + type = "object"; + present = true; + payload = objectPayload(object.members()); + } else if (value instanceof ArrayValue array) { + type = "array"; + present = true; + payload = arrayPayload(array.values()); + } else { + throw invalid("unsupported typed value"); + } + writeSegment(output, utf8(type)); + output.write(present ? '1' : '0'); + writeSegment(output, payload); + } + + private static byte[] objectPayload(List members) { + if (members.size() > 16) { + throw invalid("object exceeds its member limit"); + } + ByteArrayOutputStream output = new ByteArrayOutputStream(); + writeSegment(output, utf8(Integer.toString(members.size()))); + for (Member member : members) { + writeSegment(output, utf8(member.key())); + writeValue(output, member.value()); + } + return boundedPayload(output); + } + + private static byte[] arrayPayload(List values) { + if (values.size() > 64) { + throw invalid("array exceeds its element limit"); + } + ByteArrayOutputStream output = new ByteArrayOutputStream(); + writeSegment(output, utf8(Integer.toString(values.size()))); + for (Value value : values) { + writeValue(output, value); + } + return boundedPayload(output); + } + + private static byte[] boundedPayload(ByteArrayOutputStream output) { + if (output.size() > MAX_SEGMENT_BYTES) { + throw invalid("canonical segment exceeds its byte limit"); + } + return output.toByteArray(); + } + + private static void writeSegment(ByteArrayOutputStream output, byte[] bytes) { + if (bytes.length > MAX_SEGMENT_BYTES) { + throw invalid("canonical segment exceeds its byte limit"); + } + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + + private static String normalize(String value, int byteLimit, String label) { + Objects.requireNonNull(value, label + " is required"); + requireUnicodeScalars(value, label); + String normalized = Normalizer.normalize(value, Normalizer.Form.NFC); + requireUnicodeScalars(normalized, label); + if (utf8(normalized).length > byteLimit) { + throw invalid(label + " exceeds its normalized UTF-8 byte limit"); + } + return normalized; + } + + private static void requireUnicodeScalars(String value, String label) { + for (int index = 0; index < value.length(); index++) { + char current = value.charAt(index); + if (Character.isHighSurrogate(current)) { + if (index + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(index + 1))) { + throw invalid(label + " contains malformed Unicode"); + } + index++; + } else if (Character.isLowSurrogate(current)) { + throw invalid(label + " contains malformed Unicode"); + } + } + } + + private static byte[] utf8(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + sealed interface Value permits ScalarValue, ObjectValue, ArrayValue {} + + record ScalarValue(String type, boolean present, byte[] payload) implements Value { + ScalarValue { + Objects.requireNonNull(type); + payload = payload.clone(); + } + + @Override + public byte[] payload() { + return payload.clone(); + } + } + + record Member(String key, Value value) { + Member { + Objects.requireNonNull(key); + Objects.requireNonNull(value); + } + } + + record ObjectValue(List members) implements Value { + ObjectValue { + members = List.copyOf(members); + } + } + + record ArrayValue(List values) implements Value { + ArrayValue { + values = List.copyOf(values); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundle.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundle.java new file mode 100644 index 0000000000..f5806f916c --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundle.java @@ -0,0 +1,647 @@ +package net.firedevops.firemud.common.operator; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Integrity-only decoder for the closed StartSession human tenant-admin {@code + * authorityEvidenceBundle/v1} contract. + * + *

This value proves only that supplied bytes are canonical and structurally bound to a typed + * StartSession tuple and selected fields from the separate Account bundle reference. It does not + * perform Account's full source/reference validation or establish current Account authority, source + * freshness, a live reservation claim, or permission to dispatch. + */ +public final class StartSessionAuthorityEvidenceBundle { + public static final String BUNDLE_VERSION = "authorityEvidenceBundle/v1"; + public static final String HUMAN_EVIDENCE_TYPE = "HumanAuthorityEvidence/v1"; + public static final int MAX_BUNDLE_BYTES = 128 * 1024; + + private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern SOURCE_EVIDENCE_ID = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Pattern POSITIVE_U64 = Pattern.compile("[1-9][0-9]{0,19}"); + private static final BigInteger MAX_UNSIGNED_LONG = + BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE); + private static final Pattern CANONICAL_UUID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + private static final Set ROOT_FIELDS = + Set.of( + "bundleVersion", + "authorityScope", + "accountProjectionEvidence", + "issuanceOperationIdentity", + "issuanceKind", + "authorityTuple", + "membershipVersion", + "issuanceFence", + "issuanceEvidence"); + private static final Set AUTHORITY_SCOPE_FIELDS = + Set.of("scope", "actionFamily", "applicableAccountId", "applicableTenantId"); + private static final Set SCOPE_FIELDS = Set.of("tenantId", "targetNamespace"); + private static final Set PROJECTION_FIELDS = + Set.of( + "sourceType", + "sourceEvidenceId", + "sourceEvidenceVersion", + "projectionStatus", + "evaluatedAt", + "expiresAt"); + private static final Set OPERATION_FIELDS = + Set.of( + "issuanceOperationId", + "controlPlaneRequestId", + "actionFamilyRequestIdentity", + "mutationDigest"); + private static final Set REQUEST_IDENTITY_FIELDS = + Set.of("requestIdentityKind", "requestId"); + private static final Set HUMAN_TENANT_FIELDS = + Set.of( + "evidenceType", + "actorAccountId", + "controlUiTokenJti", + "role", + "accountGeneration", + "tenantGeneration"); + private static final Set REQUIRED_AUTHORITY_TUPLE_FIELDS = + Set.of( + "issuerAuthGeneration", + "accountAuthorityGeneration", + "tenantAuthorityGeneration", + "membershipAuthorityGeneration", + "privateRealmGrantVersions"); + private static final Set ALLOWED_AUTHORITY_TUPLE_FIELDS = + Set.of( + "issuerAuthGeneration", + "accountAuthorityGeneration", + "tenantAuthorityGeneration", + "membershipAuthorityGeneration", + "privateRealmGrantVersions", + "accountSecurityCutoff", + "tenantBillingCutoff"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final byte[] canonicalBytes; + private final Map value; + + private StartSessionAuthorityEvidenceBundle(byte[] canonicalBytes, Map value) { + this.canonicalBytes = canonicalBytes.clone(); + this.value = immutableObject(value); + } + + /** Strictly decodes one canonical, closed, bounded StartSession tenant-admin bundle. */ + public static StartSessionAuthorityEvidenceBundle decode(byte[] exactCanonicalBytes) { + if (exactCanonicalBytes == null + || exactCanonicalBytes.length == 0 + || exactCanonicalBytes.length > MAX_BUNDLE_BYTES) { + throw denied("Authority evidence bundle is empty or over the supported bound"); + } + try { + String json = strictUtf8(exactCanonicalBytes); + Map decoded = JSON.readValue(json, new TypeReference<>() {}); + requireFields(decoded, ROOT_FIELDS, "authorityEvidenceBundle/v1"); + if (!BUNDLE_VERSION.equals(string(decoded.get("bundleVersion"), "bundleVersion"))) { + throw denied("Unsupported authority evidence bundle version"); + } + validateAuthorityScope(object(decoded.get("authorityScope"), "authorityScope")); + validateProjection( + object(decoded.get("accountProjectionEvidence"), "accountProjectionEvidence")); + validateOperationIdentity( + object(decoded.get("issuanceOperationIdentity"), "issuanceOperationIdentity")); + if (!"human_operator".equals(string(decoded.get("issuanceKind"), "issuanceKind"))) { + throw denied("Only the human StartSession operator branch is supported"); + } + validateAuthorityTuple(object(decoded.get("authorityTuple"), "authorityTuple")); + validateMembershipVersion(object(decoded.get("membershipVersion"), "membershipVersion")); + positiveDecimal(string(decoded.get("issuanceFence"), "issuanceFence"), "issuanceFence"); + validateTenantHumanEvidence(object(decoded.get("issuanceEvidence"), "issuanceEvidence")); + + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(json); + if (!MessageDigest.isEqual(canonical, exactCanonicalBytes)) { + throw denied("Authority evidence bundle is not canonical UTF-8 JSON"); + } + return new StartSessionAuthorityEvidenceBundle(canonical, decoded); + } catch (IllegalArgumentException expected) { + throw expected; + } catch (IOException | RuntimeException malformed) { + throw denied("Authority evidence bundle is malformed"); + } + } + + /** Compares every tuple-bound identity and digest without granting authority or freshness. */ + public void requireTupleBinding(StartSessionPreAuthorizationReservationTuple tuple) { + Objects.requireNonNull(tuple, "pre-authorization tuple is required"); + Map authorityScope = object(value.get("authorityScope"), "authorityScope"); + Map scope = object(authorityScope.get("scope"), "authorityScope.scope"); + Map operation = + object(value.get("issuanceOperationIdentity"), "issuanceOperationIdentity"); + Map identity = + object(operation.get("actionFamilyRequestIdentity"), "actionFamilyRequestIdentity"); + Map human = object(value.get("issuanceEvidence"), "issuanceEvidence"); + String tenantId = tuple.action().scope().tenantId().toString(); + String actorId = tuple.actor().accountId().toString(); + Map authorityTuple = object(value.get("authorityTuple"), "authorityTuple"); + Map tenantGenerations = + object(authorityTuple.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"); + Map membershipGenerations = + object( + authorityTuple.get("membershipAuthorityGeneration"), "membershipAuthorityGeneration"); + Map membershipVersion = + object(value.get("membershipVersion"), "membershipVersion"); + long accountGeneration = + positiveNumber( + authorityTuple.get("accountAuthorityGeneration"), "accountAuthorityGeneration"); + if (!tuple.actionFamily().equals(authorityScope.get("actionFamily")) + || !actorId.equals(authorityScope.get("applicableAccountId")) + || !tenantId.equals(authorityScope.get("applicableTenantId")) + || !tenantId.equals(scope.get("tenantId")) + || !tuple.action().scope().targetNamespace().equals(scope.get("targetNamespace")) + || !tuple.controlPlaneRequestId().equals(operation.get("controlPlaneRequestId")) + || !tuple.controlPlaneRequestId().equals(identity.get("requestId")) + || !"controlPlaneRequestId".equals(identity.get("requestIdentityKind")) + || !tuple.mutationDigest().equals(operation.get("mutationDigest")) + || !actorId.equals(human.get("actorAccountId")) + || !tenantGenerations.keySet().equals(Set.of(tenantId)) + || !membershipGenerations.keySet().equals(Set.of(tenantId)) + || !membershipVersion.keySet().equals(Set.of(tenantId)) + || accountGeneration + != parsePositiveDecimal( + string(human.get("accountGeneration"), "accountGeneration"), "accountGeneration") + || positiveNumber(tenantGenerations.get(tenantId), "tenantAuthorityGeneration") + != parsePositiveDecimal( + string(human.get("tenantGeneration"), "tenantGeneration"), "tenantGeneration")) { + throw denied("Authority evidence differs from the exact StartSession tuple"); + } + if (authorityTuple.containsKey("tenantBillingCutoff")) { + Map billingCutoffs = + object(authorityTuple.get("tenantBillingCutoff"), "tenantBillingCutoff"); + if (!billingCutoffs.isEmpty() && !billingCutoffs.keySet().equals(Set.of(tenantId))) { + throw denied("Tenant billing cutoff differs from the exact StartSession tenant"); + } + } + } + + /** + * Compares the bundle version, source version, and source fence with the corresponding bundle + * fields. This structural comparison is not Account's full source/reference validation, snapshot + * check, or redemption; it does not prove source freshness. + */ + public void requireReferenceBinding(BundleReference reference) { + Objects.requireNonNull(reference, "Account bundle reference is required"); + Map projection = + object(value.get("accountProjectionEvidence"), "accountProjectionEvidence"); + if (!BUNDLE_VERSION.equals(reference.bundleVersion()) + || !reference.sourceVersion().equals(projection.get("sourceEvidenceVersion")) + || !reference.sourceFence().equals(value.get("issuanceFence"))) { + throw denied("Account bundle reference differs from immutable authority evidence"); + } + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String bundleVersion() { + return BUNDLE_VERSION; + } + + public String actionFamily() { + return string( + object(value.get("authorityScope"), "authorityScope").get("actionFamily"), "actionFamily"); + } + + public UUID actorAccountId() { + return uuid( + object(value.get("authorityScope"), "authorityScope").get("applicableAccountId"), + "applicableAccountId"); + } + + public UUID tenantId() { + Map authorityScope = object(value.get("authorityScope"), "authorityScope"); + return uuid(object(authorityScope.get("scope"), "scope").get("tenantId"), "tenantId"); + } + + public String targetNamespace() { + Map authorityScope = object(value.get("authorityScope"), "authorityScope"); + return string( + object(authorityScope.get("scope"), "scope").get("targetNamespace"), "targetNamespace"); + } + + public String controlPlaneRequestId() { + return string( + object(value.get("issuanceOperationIdentity"), "issuanceOperationIdentity") + .get("controlPlaneRequestId"), + "controlPlaneRequestId"); + } + + public String mutationDigest() { + return string( + object(value.get("issuanceOperationIdentity"), "issuanceOperationIdentity") + .get("mutationDigest"), + "mutationDigest"); + } + + public UUID issuanceOperationId() { + return uuid( + object(value.get("issuanceOperationIdentity"), "issuanceOperationIdentity") + .get("issuanceOperationId"), + "issuanceOperationId"); + } + + public String sourceEvidenceId() { + return string( + object(value.get("accountProjectionEvidence"), "accountProjectionEvidence") + .get("sourceEvidenceId"), + "sourceEvidenceId"); + } + + public String sourceEvidenceVersion() { + return string( + object(value.get("accountProjectionEvidence"), "accountProjectionEvidence") + .get("sourceEvidenceVersion"), + "sourceEvidenceVersion"); + } + + public Instant evaluatedAt() { + return instant( + string( + object(value.get("accountProjectionEvidence"), "accountProjectionEvidence") + .get("evaluatedAt"), + "evaluatedAt")); + } + + public Instant expiresAt() { + return instant( + string( + object(value.get("accountProjectionEvidence"), "accountProjectionEvidence") + .get("expiresAt"), + "expiresAt")); + } + + public String issuanceFence() { + return string(value.get("issuanceFence"), "issuanceFence"); + } + + public String evidenceType() { + return string( + object(value.get("issuanceEvidence"), "issuanceEvidence").get("evidenceType"), + "evidenceType"); + } + + public String role() { + return string(object(value.get("issuanceEvidence"), "issuanceEvidence").get("role"), "role"); + } + + public UUID controlUiTokenJti() { + return uuid( + object(value.get("issuanceEvidence"), "issuanceEvidence").get("controlUiTokenJti"), + "controlUiTokenJti"); + } + + public String authorizationExpiresAt() { + return string( + object(value.get("accountProjectionEvidence"), "accountProjectionEvidence") + .get("expiresAt"), + "expiresAt"); + } + + /** Returns the deeply immutable decoded JSON value for Account's exact current-source checks. */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "The constructor recursively freezes nested maps and lists; " + + "JSON scalar leaves are immutable.") + public Map jsonValue() { + return value; + } + + public Map authorityTuple() { + return object(value.get("authorityTuple"), "authorityTuple"); + } + + public Map membershipVersion() { + return object(value.get("membershipVersion"), "membershipVersion"); + } + + private static void validateAuthorityScope(Map scopeValue) { + requireFields(scopeValue, AUTHORITY_SCOPE_FIELDS, "authorityScope"); + Map scope = object(scopeValue.get("scope"), "authorityScope.scope"); + requireFields(scope, SCOPE_FIELDS, "StartSession scope"); + uuid(scope.get("tenantId"), "scope.tenantId"); + if (!GrpcPeerIdentity.isValidNamespace( + string(scope.get("targetNamespace"), "targetNamespace"))) { + throw denied("StartSession target namespace is invalid"); + } + if (!"StartSession".equals(string(scopeValue.get("actionFamily"), "actionFamily"))) { + throw denied("Unsupported StartSession action family"); + } + uuid(scopeValue.get("applicableAccountId"), "applicableAccountId"); + uuid(scopeValue.get("applicableTenantId"), "applicableTenantId"); + if (!scope.get("tenantId").equals(scopeValue.get("applicableTenantId"))) { + throw denied("Tenant scope and applicable tenant must match"); + } + } + + private static void validateProjection(Map projection) { + requireFields(projection, PROJECTION_FIELDS, "accountProjectionEvidence"); + if (!"ACCOUNT".equals(string(projection.get("sourceType"), "sourceType")) + || !"CURRENT".equals(string(projection.get("projectionStatus"), "projectionStatus")) + || !SOURCE_EVIDENCE_ID + .matcher(string(projection.get("sourceEvidenceId"), "sourceEvidenceId")) + .matches()) { + throw denied("Current Account projection evidence is required"); + } + positiveDecimal( + string(projection.get("sourceEvidenceVersion"), "sourceEvidenceVersion"), + "sourceEvidenceVersion"); + Instant evaluatedAt = instant(string(projection.get("evaluatedAt"), "evaluatedAt")); + Instant expiresAt = instant(string(projection.get("expiresAt"), "expiresAt")); + if (!expiresAt.isAfter(evaluatedAt)) { + throw denied("Account projection evidence expiry must follow its evaluation"); + } + } + + private static void validateOperationIdentity(Map operation) { + requireFields(operation, OPERATION_FIELDS, "issuanceOperationIdentity"); + uuid(operation.get("issuanceOperationId"), "issuanceOperationId"); + String requestId = + StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId( + string(operation.get("controlPlaneRequestId"), "controlPlaneRequestId")); + Map identity = + object(operation.get("actionFamilyRequestIdentity"), "actionFamilyRequestIdentity"); + requireFields(identity, REQUEST_IDENTITY_FIELDS, "actionFamilyRequestIdentity"); + if (!"controlPlaneRequestId".equals(identity.get("requestIdentityKind")) + || !requestId.equals(identity.get("requestId")) + || !DIGEST.matcher(string(operation.get("mutationDigest"), "mutationDigest")).matches()) { + throw denied("StartSession operation identity or digest is invalid"); + } + } + + private static void validateAuthorityTuple(Map authority) { + if (!authority.keySet().containsAll(REQUIRED_AUTHORITY_TUPLE_FIELDS) + || !ALLOWED_AUTHORITY_TUPLE_FIELDS.containsAll(authority.keySet())) { + throw denied("Authority tuple has missing or unsupported fields"); + } + positiveNumber(authority.get("issuerAuthGeneration"), "issuerAuthGeneration"); + positiveNumber(authority.get("accountAuthorityGeneration"), "accountAuthorityGeneration"); + mapOfPositiveNumbers(authority.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"); + mapOfPositiveNumbers( + authority.get("membershipAuthorityGeneration"), "membershipAuthorityGeneration"); + if (!(authority.get("privateRealmGrantVersions") instanceof List grants) + || !grants.isEmpty()) { + throw denied("StartSession control-plane authority must not acquire gameplay grants"); + } + if (authority.containsKey("accountSecurityCutoff")) { + validateAccountSecurityCutoff( + object(authority.get("accountSecurityCutoff"), "accountSecurityCutoff")); + } + if (authority.containsKey("tenantBillingCutoff")) { + validateTenantBillingCutoffs( + object(authority.get("tenantBillingCutoff"), "tenantBillingCutoff")); + } + } + + private static void validateAccountSecurityCutoff(Map cutoff) { + requireFields( + cutoff, + Set.of("accountAuthorityGeneration", "outboxStreamKey", "outboxSequence"), + "accountSecurityCutoff"); + positiveNumber(cutoff.get("accountAuthorityGeneration"), "accountAuthorityGeneration"); + boundedText(cutoff.get("outboxStreamKey"), "outboxStreamKey", 256); + positiveNumber(cutoff.get("outboxSequence"), "outboxSequence"); + } + + private static void validateTenantBillingCutoffs(Map cutoffs) { + if (cutoffs.size() > 1) { + throw denied("StartSession bundle must not widen tenant billing scope"); + } + cutoffs.forEach( + (tenantId, raw) -> { + uuid(tenantId, "tenantBillingCutoff tenant ID"); + Map cutoff = object(raw, "tenantBillingCutoff entry"); + requireFields( + cutoff, + Set.of( + "tenantAuthorityGeneration", + "tenantBillingSequence", + "outboxStreamKey", + "outboxSequence"), + "tenantBillingCutoff entry"); + positiveNumber(cutoff.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"); + positiveNumber(cutoff.get("tenantBillingSequence"), "tenantBillingSequence"); + boundedText(cutoff.get("outboxStreamKey"), "outboxStreamKey", 256); + positiveNumber(cutoff.get("outboxSequence"), "outboxSequence"); + }); + } + + private static void validateMembershipVersion(Map membership) { + if (membership.size() > 1) { + throw denied("StartSession bundle must not widen membership scope"); + } + membership.forEach( + (tenantId, version) -> { + uuid(tenantId, "membershipVersion tenant ID"); + positiveNumber(version, "membershipVersion"); + }); + } + + private static void validateTenantHumanEvidence(Map evidence) { + requireFields(evidence, HUMAN_TENANT_FIELDS, "HumanAuthorityEvidence/v1 tenant branch"); + if (!HUMAN_EVIDENCE_TYPE.equals(string(evidence.get("evidenceType"), "evidenceType")) + || !"tenantAdmin".equals(string(evidence.get("role"), "role"))) { + throw denied("Only the current tenantAdmin HumanAuthorityEvidence/v1 arm applies"); + } + uuid(evidence.get("actorAccountId"), "actorAccountId"); + uuid(evidence.get("controlUiTokenJti"), "controlUiTokenJti"); + positiveDecimal( + string(evidence.get("accountGeneration"), "accountGeneration"), "accountGeneration"); + positiveDecimal( + string(evidence.get("tenantGeneration"), "tenantGeneration"), "tenantGeneration"); + } + + private static Instant instant(String value) { + try { + Instant parsed = Instant.parse(value); + if (!parsed.toString().equals(value) || parsed.getNano() % 1_000_000 != 0) { + throw denied("Timestamp is not canonical exact-millisecond UTC text"); + } + return parsed; + } catch (RuntimeException malformed) { + throw denied("Timestamp is malformed"); + } + } + + private static void mapOfPositiveNumbers(Object raw, String field) { + Map values = object(raw, field); + if (values.size() > 1) { + throw denied(field + " must be limited to the selected tenant"); + } + values.forEach( + (key, value) -> { + uuid(key, field + " tenant ID"); + positiveNumber(value, field); + }); + } + + private static long positiveNumber(Object value, String field) { + try { + long parsed = value instanceof Number number ? Long.parseLong(number.toString()) : 0L; + if (parsed <= 0L) { + throw new NumberFormatException(); + } + return parsed; + } catch (RuntimeException malformed) { + throw denied(field + " must be a positive signed 64-bit integer"); + } + } + + private static void positiveDecimal(String value, String field) { + parsePositiveDecimal(value, field); + } + + private static long parsePositiveDecimal(String value, String field) { + if (value == null || !POSITIVE_DECIMAL.matcher(value).matches()) { + throw denied(field + " must be a positive canonical signed 64-bit decimal"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException malformed) { + throw denied(field + " is outside the supported signed 64-bit range"); + } + } + + private static void positiveU64(String value, String field) { + if (value == null || !POSITIVE_U64.matcher(value).matches()) { + throw denied(field + " must be a positive canonical unsigned 64-bit decimal"); + } + try { + if (new BigInteger(value).compareTo(MAX_UNSIGNED_LONG) > 0) { + throw new NumberFormatException(); + } + } catch (NumberFormatException malformed) { + throw denied(field + " is outside the supported unsigned 64-bit range"); + } + } + + private static UUID uuid(Object value, String field) { + String text = string(value, field); + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) + || !CANONICAL_UUID.matcher(text).matches() + || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(); + } + return parsed; + } catch (RuntimeException malformed) { + throw denied(field + " must be a canonical lowercase non-nil UUID"); + } + } + + private static void boundedText(Object value, String field, int maxUtf8Bytes) { + String text = string(value, field); + if (text.getBytes(StandardCharsets.UTF_8).length > maxUtf8Bytes) { + throw denied(field + " exceeds its supported bound"); + } + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException malformed) { + throw denied("Authority evidence bundle is not valid UTF-8"); + } + } + + @SuppressWarnings("unchecked") + private static Map object(Object value, String field) { + if (!(value instanceof Map map) + || map.keySet().stream().anyMatch(key -> !(key instanceof String))) { + throw denied(field + " must be an object"); + } + return (Map) map; + } + + private static void requireFields(Map value, Set fields, String field) { + if (value == null || !value.keySet().equals(fields)) { + throw denied(field + " has missing or unsupported fields"); + } + } + + private static String string(Object value, String field) { + if (!(value instanceof String text) || text.isEmpty()) { + throw denied(field + " must be a nonempty string"); + } + return text; + } + + private static Map immutableObject(Map source) { + Map copy = new LinkedHashMap<>(); + source.forEach((key, value) -> copy.put(key, immutableValue(value))); + return Map.copyOf(copy); + } + + private static Object immutableValue(Object value) { + if (value instanceof Map map) { + Map copy = new LinkedHashMap<>(); + map.forEach( + (key, nested) -> { + if (!(key instanceof String text)) { + throw denied("Object keys must be strings"); + } + copy.put(text, immutableValue(nested)); + }); + return Map.copyOf(copy); + } + if (value instanceof List list) { + return list.stream().map(StartSessionAuthorityEvidenceBundle::immutableValue).toList(); + } + return value; + } + + private static IllegalArgumentException denied(String message) { + return new IllegalArgumentException(message); + } + + /** Separate source provenance returned beside the original bundle bytes. */ + public record BundleReference( + String bundleVersion, String sourceVersion, String sourceFence, String linearization) { + public BundleReference { + if (!BUNDLE_VERSION.equals(bundleVersion)) { + throw denied("Unsupported Account bundle-reference version"); + } + positiveDecimal(sourceVersion, "bundle sourceVersion"); + positiveDecimal(sourceFence, "bundle sourceFence"); + positiveU64(linearization, "bundle linearization"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionOperatorAction.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionOperatorAction.java new file mode 100644 index 0000000000..e7fe79fff3 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionOperatorAction.java @@ -0,0 +1,154 @@ +package net.firedevops.firemud.common.operator; + +import java.nio.charset.StandardCharsets; +import java.text.Normalizer; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; + +/** Immutable typed action covered by the StartSession operator schema. */ +public record StartSessionOperatorAction( + String actionFamilySchemaId, + String actionFamilySchemaVersion, + Scope scope, + Target target, + ExpectedVersion expectedVersion, + Mutation mutation, + String auditReason) { + + public static final String ACTION_FAMILY_SCHEMA_ID = "firemud.game-session.start-session"; + public static final String ACTION_FAMILY_SCHEMA_VERSION = "1"; + public static final String ACTION_FAMILY = "StartSession"; + public static final String OWNER_SERVICE = "game-session-service"; + + private static final Pattern WORKLOAD_NAMESPACE = + Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public StartSessionOperatorAction { + if (!ACTION_FAMILY_SCHEMA_ID.equals(actionFamilySchemaId)) { + throw new IllegalArgumentException("unsupported actionFamilySchemaId"); + } + if (!ACTION_FAMILY_SCHEMA_VERSION.equals(actionFamilySchemaVersion)) { + throw new IllegalArgumentException("unsupported actionFamilySchemaVersion"); + } + Objects.requireNonNull(scope, "scope is required"); + Objects.requireNonNull(target, "target is required"); + Objects.requireNonNull(expectedVersion, "expectedVersion is required"); + if (expectedVersion != ExpectedVersion.ABSENT) { + throw new IllegalArgumentException( + "expectedVersion must be absent for StartSession creation"); + } + Objects.requireNonNull(mutation, "mutation is required"); + auditReason = normalizedString(auditReason, "auditReason", 1_000); + if (isUnicodeBlank(auditReason)) { + throw new IllegalArgumentException("auditReason must not be blank"); + } + } + + public enum ExpectedVersion { + ABSENT + } + + public String actionFamily() { + return ACTION_FAMILY; + } + + /** Returns the immutable ADR 0048 target owner, which is compared outside the digest tuple. */ + public String targetOwner() { + return OWNER_SERVICE; + } + + public record Scope(UUID tenantId, String targetNamespace) { + public Scope { + Objects.requireNonNull(tenantId, "tenantId is required"); + if (NIL_UUID.equals(tenantId)) { + throw new IllegalArgumentException("tenantId must not be nil"); + } + Objects.requireNonNull(targetNamespace, "targetNamespace is required"); + if (targetNamespace.length() > 63 || !WORKLOAD_NAMESPACE.matcher(targetNamespace).matches()) { + throw new IllegalArgumentException("targetNamespace must be a valid workload namespace"); + } + } + } + + public record Target(long gameTemplateId, UUID ownerAccountId) { + public Target { + if (gameTemplateId <= 0) { + throw new IllegalArgumentException("gameTemplateId must be positive"); + } + Objects.requireNonNull(ownerAccountId, "ownerAccountId is required"); + if (NIL_UUID.equals(ownerAccountId)) { + throw new IllegalArgumentException("ownerAccountId must not be nil"); + } + } + } + + public record Mutation(ClientIp clientIp) { + public Mutation { + Objects.requireNonNull(clientIp, "clientIp presence is required"); + } + } + + /** The action schema accepts either an absent clientIp member or a string value. */ + public sealed interface ClientIp permits AbsentClientIp, StringClientIp { + static ClientIp absent() { + return new AbsentClientIp(); + } + + static ClientIp of(String value) { + return new StringClientIp(value); + } + } + + public record AbsentClientIp() implements ClientIp {} + + public record StringClientIp(String value) implements ClientIp { + public StringClientIp { + value = normalizedString(value, "clientIp", 128); + } + } + + private static String normalizedString(String value, String fieldName, int byteLimit) { + Objects.requireNonNull(value, fieldName + " is required"); + requireUnicodeScalars(value, fieldName); + String normalized = Normalizer.normalize(value, Normalizer.Form.NFC); + requireUnicodeScalars(normalized, fieldName); + if (normalized.getBytes(StandardCharsets.UTF_8).length > byteLimit) { + throw new IllegalArgumentException(fieldName + " exceeds its normalized UTF-8 byte limit"); + } + return normalized; + } + + private static void requireUnicodeScalars(String value, String fieldName) { + for (int index = 0; index < value.length(); index++) { + char current = value.charAt(index); + if (Character.isHighSurrogate(current)) { + if (index + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(index + 1))) { + throw new IllegalArgumentException(fieldName + " contains malformed Unicode"); + } + index++; + } else if (Character.isLowSurrogate(current)) { + throw new IllegalArgumentException(fieldName + " contains malformed Unicode"); + } + } + } + + private static boolean isUnicodeBlank(String value) { + return value.codePoints().allMatch(StartSessionOperatorAction::isSharedWhitespace); + } + + private static boolean isSharedWhitespace(int codePoint) { + return (codePoint >= 0x0009 && codePoint <= 0x000D) + || codePoint == 0x0020 + || codePoint == 0x0085 + || codePoint == 0x00A0 + || codePoint == 0x1680 + || (codePoint >= 0x2000 && codePoint <= 0x200A) + || codePoint == 0x2028 + || codePoint == 0x2029 + || codePoint == 0x202F + || codePoint == 0x205F + || codePoint == 0x3000; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodec.java new file mode 100644 index 0000000000..ed4552f151 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodec.java @@ -0,0 +1,605 @@ +package net.firedevops.firemud.common.operator; + +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.text.Normalizer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; + +/** Strict token-preserving JSON codec and digest entry point for StartSession operator actions. */ +public final class StartSessionOperatorActionCodec { + public static final int MAX_RAW_BYTES = 16 * 1_024; + public static final int MAX_NESTING_DEPTH = 8; + public static final int MAX_OBJECT_MEMBERS = 16; + public static final int MAX_ARRAY_ELEMENTS = 64; + public static final int MAX_NORMALIZED_STRING_BYTES = + MutationDigestV1.MAX_NORMALIZED_STRING_BYTES; + public static final int MAX_NUMERIC_BYTES = MutationDigestV1.MAX_NUMERIC_BYTES; + public static final int MAX_NUMERIC_SCALE = MutationDigestV1.MAX_NUMERIC_SCALE; + public static final int MAX_SEGMENT_BYTES = MutationDigestV1.MAX_SEGMENT_BYTES; + public static final int MAX_PREIMAGE_BYTES = MutationDigestV1.MAX_PREIMAGE_BYTES; + + private static final Pattern UUID_PATTERN = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + private static final List TOP_LEVEL_FIELDS = + List.of( + "actionFamilySchemaId", + "actionFamilySchemaVersion", + "scope", + "target", + "expectedVersion", + "mutation", + "auditReason"); + + private StartSessionOperatorActionCodec() {} + + /** Decodes only the declared StartSession schema and rejects every unsupported shape. */ + public static StartSessionOperatorAction decode(byte[] rawJson) { + JsonValue root = new StrictJsonParser(rawJson).parseDocument(); + if (!(root instanceof JsonObject object)) { + throw invalid("StartSession action must be a JSON object"); + } + Map members = + orderedMembers(object, TOP_LEVEL_FIELDS, Set.of("expectedVersion")); + String schemaId = requiredString(members.get("actionFamilySchemaId"), "actionFamilySchemaId"); + String schemaVersion = + requiredString(members.get("actionFamilySchemaVersion"), "actionFamilySchemaVersion"); + if (!StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID.equals(schemaId) + || !StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION.equals(schemaVersion)) { + throw invalid("unsupported StartSession action-family schema pair"); + } + if (members.containsKey("expectedVersion")) { + throw invalid("expectedVersion must be absent for StartSession creation"); + } + StartSessionOperatorAction.Scope scope = readScope(members.get("scope")); + StartSessionOperatorAction.Target target = readTarget(members.get("target")); + StartSessionOperatorAction.Mutation mutation = readMutation(members.get("mutation")); + String auditReason = requiredString(members.get("auditReason"), "auditReason"); + return new StartSessionOperatorAction( + schemaId, + schemaVersion, + scope, + target, + StartSessionOperatorAction.ExpectedVersion.ABSENT, + mutation, + auditReason); + } + + /** Returns the exact ADR 0047 mutationDigest/v1 preimage for one typed action. */ + public static byte[] canonicalPreimage(StartSessionOperatorAction action) { + return MutationDigestV1.preimage(Objects.requireNonNull(action, "action is required")); + } + + /** Decodes an action and returns its exact ADR 0047 mutationDigest/v1 preimage. */ + public static byte[] canonicalPreimage(byte[] rawJson) { + return canonicalPreimage(decode(rawJson)); + } + + /** Returns the lowercase hexadecimal SHA-256 digest for one typed action. */ + public static String mutationDigest(StartSessionOperatorAction action) { + return MutationDigestV1.sha256Hex(canonicalPreimage(action)); + } + + /** Decodes an action and returns its lowercase hexadecimal SHA-256 digest. */ + public static String mutationDigest(byte[] rawJson) { + return mutationDigest(decode(rawJson)); + } + + /* Test bridge for the recursive value grammar. It is not an action-schema decoder. */ + static byte[] canonicalGrammarValueForTest(byte[] rawJson) { + JsonValue parsed = new StrictJsonParser(rawJson).parseDocument(); + return MutationDigestV1.encodedValue(toGrammarValue(parsed)); + } + + static byte[] absentGrammarValueForTest() { + return MutationDigestV1.encodedValue(MutationDigestV1.absent()); + } + + static byte[] canonicalNumberLexemeForTest(String rawLexeme) { + return MutationDigestV1.encodedValue(MutationDigestV1.number(rawLexeme)); + } + + private static StartSessionOperatorAction.Scope readScope(JsonValue value) { + JsonObject object = requireObject(value, "scope"); + Map members = + orderedMembers(object, List.of("tenantId", "targetNamespace"), Set.of()); + UUID tenantId = canonicalUuid(requiredString(members.get("tenantId"), "tenantId"), "tenantId"); + String namespace = requiredString(members.get("targetNamespace"), "targetNamespace"); + return new StartSessionOperatorAction.Scope(tenantId, namespace); + } + + private static StartSessionOperatorAction.Target readTarget(JsonValue value) { + JsonObject object = requireObject(value, "target"); + Map members = + orderedMembers(object, List.of("gameTemplateId", "ownerAccountId"), Set.of()); + JsonValue templateValue = members.get("gameTemplateId"); + if (!(templateValue instanceof JsonString templateIdValue)) { + throw invalid("gameTemplateId must be a positive canonical decimal string"); + } + String templateIdText = + normalizeString(templateIdValue.value(), MAX_NORMALIZED_STRING_BYTES, "gameTemplateId"); + if (!templateIdText.matches("[1-9][0-9]*")) { + throw invalid("gameTemplateId must be a positive canonical decimal string"); + } + long gameTemplateId; + try { + gameTemplateId = Long.parseLong(templateIdText); + } catch (NumberFormatException exception) { + throw invalid("gameTemplateId exceeds the current owner long range"); + } + UUID ownerAccountId = + canonicalUuid( + requiredString(members.get("ownerAccountId"), "ownerAccountId"), "ownerAccountId"); + return new StartSessionOperatorAction.Target(gameTemplateId, ownerAccountId); + } + + private static StartSessionOperatorAction.Mutation readMutation(JsonValue value) { + JsonObject object = requireObject(value, "mutation"); + Map members = + orderedMembers(object, List.of("clientIp"), Set.of("clientIp")); + JsonValue clientIp = members.get("clientIp"); + if (clientIp == null) { + return new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()); + } + if (clientIp instanceof JsonNull) { + throw invalid("clientIp may be absent or a string, but not null"); + } + if (!(clientIp instanceof JsonString string)) { + throw invalid("clientIp must be a string"); + } + String normalized = normalizeString(string.value(), 128, "clientIp"); + return new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.of(normalized)); + } + + private static String requiredString(JsonValue value, String fieldName) { + if (!(value instanceof JsonString string)) { + throw invalid(fieldName + " must be a string"); + } + return normalizeString(string.value(), MAX_NORMALIZED_STRING_BYTES, fieldName); + } + + private static UUID canonicalUuid(String value, String fieldName) { + if (!UUID_PATTERN.matcher(value).matches()) { + throw invalid(fieldName + " must be a canonical lowercase UUID"); + } + UUID uuid; + try { + uuid = UUID.fromString(value); + } catch (IllegalArgumentException exception) { + throw invalid(fieldName + " must be a canonical lowercase UUID"); + } + if (uuid.getMostSignificantBits() == 0L && uuid.getLeastSignificantBits() == 0L) { + throw invalid(fieldName + " must not be nil"); + } + return uuid; + } + + private static JsonObject requireObject(JsonValue value, String fieldName) { + if (!(value instanceof JsonObject object)) { + throw invalid(fieldName + " must be an object"); + } + return object; + } + + private static Map orderedMembers( + JsonObject object, List declaredOrder, Set optionalMembers) { + if (object.members().size() > MAX_OBJECT_MEMBERS) { + throw invalid("object exceeds its member limit"); + } + Map normalizedMembers = new LinkedHashMap<>(); + for (JsonMember member : object.members()) { + String key = normalizeString(member.key().value(), MAX_NORMALIZED_STRING_BYTES, "object key"); + if (normalizedMembers.putIfAbsent(key, member.value()) != null) { + throw invalid("object contains a duplicate or normalized-colliding member"); + } + if (!declaredOrder.contains(key)) { + throw invalid("object contains an unknown member"); + } + } + List expectedOrder = + declaredOrder.stream() + .filter(key -> normalizedMembers.containsKey(key) || !optionalMembers.contains(key)) + .toList(); + if (!new ArrayList<>(normalizedMembers.keySet()).equals(expectedOrder)) { + throw invalid("object members are missing or out of declared order"); + } + return normalizedMembers; + } + + private static MutationDigestV1.Value toGrammarValue(JsonValue value) { + if (value instanceof JsonString string) { + return MutationDigestV1.string(string.value()); + } + if (value instanceof JsonNumber number) { + return MutationDigestV1.number(number.lexeme()); + } + if (value instanceof JsonBoolean bool) { + return MutationDigestV1.bool(bool.value()); + } + if (value instanceof JsonNull) { + return MutationDigestV1.nullValue(); + } + if (value instanceof JsonArray array) { + return MutationDigestV1.array( + array.values().stream().map(StartSessionOperatorActionCodec::toGrammarValue).toList()); + } + if (value instanceof JsonObject object) { + List members = new ArrayList<>(object.members().size()); + for (JsonMember member : object.members()) { + String key = + normalizeString(member.key().value(), MAX_NORMALIZED_STRING_BYTES, "object key"); + members.add(MutationDigestV1.member(key, toGrammarValue(member.value()))); + } + return MutationDigestV1.normalizeObject(members); + } + throw invalid("unsupported JSON value"); + } + + private static String normalizeString(String value, int maxUtf8Bytes, String fieldName) { + requireUnicodeScalars(value, fieldName); + String normalized = Normalizer.normalize(value, Normalizer.Form.NFC); + requireUnicodeScalars(normalized, fieldName); + if (normalized.getBytes(StandardCharsets.UTF_8).length > maxUtf8Bytes) { + throw invalid(fieldName + " exceeds its normalized UTF-8 byte limit"); + } + return normalized; + } + + private static void requireUnicodeScalars(String value, String fieldName) { + for (int index = 0; index < value.length(); index++) { + char current = value.charAt(index); + if (Character.isHighSurrogate(current)) { + if (index + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(index + 1))) { + throw invalid(fieldName + " contains malformed Unicode"); + } + index++; + } else if (Character.isLowSurrogate(current)) { + throw invalid(fieldName + " contains malformed Unicode"); + } + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + private sealed interface JsonValue + permits JsonString, JsonNumber, JsonBoolean, JsonNull, JsonObject, JsonArray { + byte[] rawToken(); + } + + private record JsonString(String value, byte[] rawToken) implements JsonValue { + private JsonString { + rawToken = rawToken.clone(); + } + } + + private record JsonNumber(String lexeme, byte[] rawToken) implements JsonValue { + private JsonNumber { + rawToken = rawToken.clone(); + } + } + + private record JsonBoolean(boolean value, byte[] rawToken) implements JsonValue { + private JsonBoolean { + rawToken = rawToken.clone(); + } + } + + private record JsonNull(byte[] rawToken) implements JsonValue { + private JsonNull { + rawToken = rawToken.clone(); + } + } + + private record JsonMember(JsonString key, JsonValue value) {} + + private record JsonObject(List members, byte[] rawToken) implements JsonValue { + private JsonObject { + members = List.copyOf(members); + rawToken = rawToken.clone(); + } + } + + private record JsonArray(List values, byte[] rawToken) implements JsonValue { + private JsonArray { + values = List.copyOf(values); + rawToken = rawToken.clone(); + } + } + + /** Small bounded parser that retains source tokens and object occurrence order. */ + private static final class StrictJsonParser { + private final byte[] input; + private final String source; + private final int[] byteOffsets; + private int position; + + private StrictJsonParser(byte[] input) { + Objects.requireNonNull(input, "raw JSON is required"); + if (input.length > MAX_RAW_BYTES) { + throw invalid("raw JSON exceeds its byte limit"); + } + this.input = input.clone(); + try { + CharBuffer decoded = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(this.input)); + this.source = decoded.toString(); + } catch (CharacterCodingException exception) { + throw invalid("raw JSON is not valid UTF-8"); + } + this.byteOffsets = computeByteOffsets(this.source, this.input.length); + } + + private JsonValue parseDocument() { + skipWhitespace(); + JsonValue value = parseValue(0); + skipWhitespace(); + if (position != source.length()) { + throw invalid("raw JSON contains trailing tokens"); + } + return value; + } + + private JsonValue parseValue(int parentDepth) { + if (position >= source.length()) { + throw invalid("raw JSON ended before a value"); + } + char next = source.charAt(position); + if (next == '"') { + return parseString(); + } + if (next == '{') { + if (parentDepth + 1 > MAX_NESTING_DEPTH) { + throw invalid("raw JSON exceeds its nesting-depth limit"); + } + return parseObject(parentDepth + 1); + } + if (next == '[') { + if (parentDepth + 1 > MAX_NESTING_DEPTH) { + throw invalid("raw JSON exceeds its nesting-depth limit"); + } + return parseArray(parentDepth + 1); + } + if (next == 't') { + return parseLiteral("true", new JsonBoolean(true, new byte[0])); + } + if (next == 'f') { + return parseLiteral("false", new JsonBoolean(false, new byte[0])); + } + if (next == 'n') { + return parseLiteral("null", new JsonNull(new byte[0])); + } + return parseNumber(); + } + + private JsonValue parseLiteral(String literal, JsonValue placeholder) { + int start = position; + if (!source.startsWith(literal, position)) { + throw invalid("raw JSON contains an invalid token"); + } + position += literal.length(); + byte[] raw = rawToken(start, position); + if (placeholder instanceof JsonBoolean bool) { + return new JsonBoolean(bool.value(), raw); + } + return new JsonNull(raw); + } + + private JsonNumber parseNumber() { + int start = position; + while (position < source.length() && !isValueDelimiter(source.charAt(position))) { + position++; + } + if (start == position) { + throw invalid("raw JSON contains an invalid value token"); + } + byte[] raw = rawToken(start, position); + if (raw.length > MAX_NUMERIC_BYTES) { + throw invalid("numeric token exceeds its byte limit"); + } + return new JsonNumber(source.substring(start, position), raw); + } + + private JsonString parseString() { + int start = position; + position++; + StringBuilder value = new StringBuilder(); + while (position < source.length()) { + char current = source.charAt(position++); + if (current == '"') { + byte[] raw = rawToken(start, position); + String decoded = value.toString(); + requireUnicodeScalars(decoded, "string"); + return new JsonString(decoded, raw); + } + if (current == '\\') { + if (position >= source.length()) { + throw invalid("raw JSON ends inside a string escape"); + } + char escaped = source.charAt(position++); + switch (escaped) { + case '"' -> value.append('"'); + case '\\' -> value.append('\\'); + case '/' -> value.append('/'); + case 'b' -> value.append('\b'); + case 'f' -> value.append('\f'); + case 'n' -> value.append('\n'); + case 'r' -> value.append('\r'); + case 't' -> value.append('\t'); + case 'u' -> appendUnicodeEscape(value); + default -> throw invalid("raw JSON contains an invalid string escape"); + } + } else { + if (current < 0x20) { + throw invalid("raw JSON string contains an unescaped control character"); + } + value.append(current); + } + } + throw invalid("raw JSON string is unterminated"); + } + + private void appendUnicodeEscape(StringBuilder value) { + char first = readHexCodeUnit(); + if (Character.isHighSurrogate(first)) { + if (position + 1 >= source.length() + || source.charAt(position) != '\\' + || source.charAt(position + 1) != 'u') { + throw invalid("raw JSON string contains an unpaired surrogate"); + } + position += 2; + char second = readHexCodeUnit(); + if (!Character.isLowSurrogate(second)) { + throw invalid("raw JSON string contains an unpaired surrogate"); + } + value.append(first).append(second); + } else if (Character.isLowSurrogate(first)) { + throw invalid("raw JSON string contains an unpaired surrogate"); + } else { + value.append(first); + } + } + + private char readHexCodeUnit() { + if (position + 4 > source.length()) { + throw invalid("raw JSON string contains a short Unicode escape"); + } + int value = 0; + for (int index = 0; index < 4; index++) { + char digit = source.charAt(position++); + int hex = Character.digit(digit, 16); + if (hex < 0 || digit > 0x7f) { + throw invalid("raw JSON string contains an invalid Unicode escape"); + } + value = (value << 4) | hex; + } + return (char) value; + } + + private JsonObject parseObject(int depth) { + int start = position++; + skipWhitespace(); + List members = new ArrayList<>(); + if (consume('}')) { + return new JsonObject(members, rawToken(start, position)); + } + while (true) { + if (position >= source.length() || source.charAt(position) != '"') { + throw invalid("raw JSON object member key must be a string"); + } + if (members.size() >= MAX_OBJECT_MEMBERS) { + throw invalid("raw JSON object exceeds its member limit"); + } + JsonString key = parseString(); + skipWhitespace(); + require(':'); + skipWhitespace(); + JsonValue value = parseValue(depth); + members.add(new JsonMember(key, value)); + skipWhitespace(); + if (consume('}')) { + return new JsonObject(members, rawToken(start, position)); + } + require(','); + skipWhitespace(); + } + } + + private JsonArray parseArray(int depth) { + int start = position++; + skipWhitespace(); + List values = new ArrayList<>(); + if (consume(']')) { + return new JsonArray(values, rawToken(start, position)); + } + while (true) { + if (values.size() >= MAX_ARRAY_ELEMENTS) { + throw invalid("raw JSON array exceeds its element limit"); + } + values.add(parseValue(depth)); + skipWhitespace(); + if (consume(']')) { + return new JsonArray(values, rawToken(start, position)); + } + require(','); + skipWhitespace(); + } + } + + private byte[] rawToken(int start, int end) { + return Arrays.copyOfRange(input, byteOffsets[start], byteOffsets[end]); + } + + private void skipWhitespace() { + while (position < source.length()) { + char value = source.charAt(position); + if (value != ' ' && value != '\t' && value != '\r' && value != '\n') { + return; + } + position++; + } + } + + private boolean consume(char expected) { + if (position < source.length() && source.charAt(position) == expected) { + position++; + return true; + } + return false; + } + + private void require(char expected) { + if (!consume(expected)) { + throw invalid("raw JSON punctuation or member order is invalid"); + } + } + + private static boolean isValueDelimiter(char value) { + return value == ',' + || value == ']' + || value == '}' + || value == ' ' + || value == '\t' + || value == '\r' + || value == '\n'; + } + + private static int[] computeByteOffsets(String source, int expectedBytes) { + int[] offsets = new int[source.length() + 1]; + int characterIndex = 0; + int byteIndex = 0; + while (characterIndex < source.length()) { + int codePoint = source.codePointAt(characterIndex); + int characterCount = Character.charCount(codePoint); + int width = codePoint <= 0x7f ? 1 : codePoint <= 0x7ff ? 2 : codePoint <= 0xffff ? 3 : 4; + offsets[characterIndex] = byteIndex; + if (characterCount == 2) { + offsets[characterIndex + 1] = byteIndex; + } + characterIndex += characterCount; + byteIndex += width; + offsets[characterIndex] = byteIndex; + } + if (byteIndex != expectedBytes) { + throw invalid("raw JSON UTF-8 framing is inconsistent"); + } + return offsets; + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTuple.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTuple.java new file mode 100644 index 0000000000..361fe67fe9 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTuple.java @@ -0,0 +1,442 @@ +package net.firedevops.firemud.common.operator; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Immutable, integrity-only canonical post-authorization identity for human StartSession. + * + *

This value binds the complete pre-authorization tuple to Account's exact authorization + * projection and the original reservation claim. It does not authenticate its caller, make an + * Account redemption, or authorize a Game Session mutation. + */ +public final class StartSessionPostAuthorizationExecutionTuple { + public static final String TUPLE_SCHEMA_ID = "postAuthorizationExecutionTuple"; + public static final String TUPLE_SCHEMA_VERSION = "1"; + public static final int MAX_CANONICAL_TUPLE_BYTES = 256 * 1_024; + + private static final Pattern AUTHORIZATION_REFERENCE_FINGERPRINT = + Pattern.compile("arfp/v1/[A-Za-z0-9_-]{1,64}/[0-9a-f]{64}"); + private static final Set ROOT_FIELDS = + Set.of( + "tupleSchemaId", + "tupleSchemaVersion", + "preAuthorizationReservationTuple", + "controlPlaneRequestId", + "mutationDigest", + "issuanceKind", + "authorizationReferenceFingerprint", + "authenticatedWorkloadIdentity", + "actionFamilyRequestIdentity", + "actor", + "automationPolicy", + "actionFamily", + "actionFamilySchemaId", + "actionFamilySchemaVersion", + "scope", + "target", + "targetOwner", + "expectedVersion", + "mutation", + "auditReason", + "authorityTuple", + "membershipVersion", + "issuanceFence", + "reservationOwnerId", + "reservationClaimFence", + "authorityEvidenceBundle", + "authorityEvidenceBundleReference"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final StartSessionPreAuthorizationReservationTuple preAuthorizationTuple; + private final String authenticatedWorkloadIdentity; + private final String authorizationReferenceFingerprint; + private final UUID reservationOwnerId; + private final long reservationClaimFence; + private final StartSessionAuthorityEvidenceBundle authorityEvidenceBundle; + private final StartSessionAuthorityEvidenceBundle.BundleReference bundleReference; + private final byte[] canonicalBytes; + + private StartSessionPostAuthorizationExecutionTuple( + StartSessionPreAuthorizationReservationTuple preAuthorizationTuple, + String authenticatedWorkloadIdentity, + String authorizationReferenceFingerprint, + UUID reservationOwnerId, + long reservationClaimFence, + StartSessionAuthorityEvidenceBundle authorityEvidenceBundle, + StartSessionAuthorityEvidenceBundle.BundleReference bundleReference, + byte[] canonicalBytes) { + this.preAuthorizationTuple = preAuthorizationTuple; + this.authenticatedWorkloadIdentity = authenticatedWorkloadIdentity; + this.authorizationReferenceFingerprint = authorizationReferenceFingerprint; + this.reservationOwnerId = reservationOwnerId; + this.reservationClaimFence = reservationClaimFence; + this.authorityEvidenceBundle = authorityEvidenceBundle; + this.bundleReference = bundleReference; + this.canonicalBytes = canonicalBytes.clone(); + } + + /** + * Creates the full human StartSession tuple from the exact pre-tuple and Account-returned + * evidence. The workload URI must be the same-namespace Logging & Admin mTLS identity. + */ + public static StartSessionPostAuthorizationExecutionTuple createHuman( + StartSessionPreAuthorizationReservationTuple preAuthorizationTuple, + String authenticatedWorkloadIdentity, + String authorizationReferenceFingerprint, + UUID reservationOwnerId, + long reservationClaimFence, + byte[] exactCanonicalAuthorityEvidenceBundle, + StartSessionAuthorityEvidenceBundle.BundleReference bundleReference) { + Objects.requireNonNull(preAuthorizationTuple, "pre-authorization tuple is required"); + Objects.requireNonNull(bundleReference, "original Account bundle reference is required"); + requireLoggingWorkload(authenticatedWorkloadIdentity, preAuthorizationTuple); + requireFingerprint(authorizationReferenceFingerprint); + requireNonNil(reservationOwnerId, "reservationOwnerId"); + if (reservationClaimFence <= 0L) { + throw new IllegalArgumentException("reservationClaimFence must be positive"); + } + + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(exactCanonicalAuthorityEvidenceBundle); + bundle.requireTupleBinding(preAuthorizationTuple); + bundle.requireReferenceBinding(bundleReference); + byte[] canonical = + encode( + preAuthorizationTuple, + authenticatedWorkloadIdentity, + authorizationReferenceFingerprint, + reservationOwnerId, + reservationClaimFence, + bundle, + bundleReference); + return new StartSessionPostAuthorizationExecutionTuple( + preAuthorizationTuple, + authenticatedWorkloadIdentity, + authorizationReferenceFingerprint, + reservationOwnerId, + reservationClaimFence, + bundle, + bundleReference, + canonical); + } + + /** Strictly decodes one complete canonical tuple; decoding does not establish authority. */ + public static StartSessionPostAuthorizationExecutionTuple decode(byte[] exactCanonicalBytes) { + if (exactCanonicalBytes == null + || exactCanonicalBytes.length == 0 + || exactCanonicalBytes.length > MAX_CANONICAL_TUPLE_BYTES) { + throw invalid("post-authorization tuple is empty or exceeds its byte limit"); + } + try { + String json = strictUtf8(exactCanonicalBytes); + byte[] canonicalInput = Rfc8785CanonicalJson.canonicalizeUtf8(json); + if (!MessageDigest.isEqual(canonicalInput, exactCanonicalBytes)) { + throw invalid("post-authorization tuple is not canonical UTF-8 JSON"); + } + Map root = JSON.readValue(json, new TypeReference<>() {}); + requireExactFields(root, ROOT_FIELDS, "post-authorization tuple"); + if (!TUPLE_SCHEMA_ID.equals(string(root.get("tupleSchemaId"), "tupleSchemaId")) + || !TUPLE_SCHEMA_VERSION.equals( + string(root.get("tupleSchemaVersion"), "tupleSchemaVersion"))) { + throw invalid("unsupported post-authorization tuple schema"); + } + + StartSessionPreAuthorizationReservationTuple preTuple = + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + canonicalObject( + root.get("preAuthorizationReservationTuple"), + "preAuthorizationReservationTuple")); + Map referenceValue = + object(root.get("authorityEvidenceBundleReference"), "authorityEvidenceBundleReference"); + requireExactFields( + referenceValue, + Set.of("bundleVersion", "sourceVersion", "sourceFence", "linearization"), + "authorityEvidenceBundleReference"); + StartSessionAuthorityEvidenceBundle.BundleReference reference = + new StartSessionAuthorityEvidenceBundle.BundleReference( + string(referenceValue.get("bundleVersion"), "bundleVersion"), + string(referenceValue.get("sourceVersion"), "sourceVersion"), + string(referenceValue.get("sourceFence"), "sourceFence"), + string(referenceValue.get("linearization"), "linearization")); + Map workloadValue = + object(root.get("authenticatedWorkloadIdentity"), "authenticatedWorkloadIdentity"); + requireExactFields( + workloadValue, Set.of("identityKind", "uri"), "authenticatedWorkloadIdentity"); + if (!"MUTUAL_TLS_SPIFFE".equals(string(workloadValue.get("identityKind"), "identityKind"))) { + throw invalid("unsupported authenticated workload identity kind"); + } + byte[] bundleBytes = + canonicalObject(root.get("authorityEvidenceBundle"), "authorityEvidenceBundle") + .getBytes(StandardCharsets.UTF_8); + StartSessionPostAuthorizationExecutionTuple result = + createHuman( + preTuple, + string(workloadValue.get("uri"), "authenticatedWorkloadIdentity.uri"), + string( + root.get("authorizationReferenceFingerprint"), + "authorizationReferenceFingerprint"), + canonicalUuid(root.get("reservationOwnerId"), "reservationOwnerId"), + positiveLong(root.get("reservationClaimFence"), "reservationClaimFence"), + bundleBytes, + reference); + if (!TUPLE_SCHEMA_ID.equals(string(root.get("tupleSchemaId"), "tupleSchemaId")) + || !MessageDigest.isEqual(result.canonicalBytes, exactCanonicalBytes)) { + throw invalid("post-authorization tuple members are inconsistent or non-canonical"); + } + return result; + } catch (IllegalArgumentException expected) { + throw expected; + } catch (IOException | RuntimeException malformed) { + throw invalid("post-authorization tuple JSON is invalid"); + } + } + + public StartSessionPreAuthorizationReservationTuple preAuthorizationTuple() { + return preAuthorizationTuple; + } + + public String controlPlaneRequestId() { + return preAuthorizationTuple.controlPlaneRequestId(); + } + + public String mutationDigest() { + return preAuthorizationTuple.mutationDigest(); + } + + public String issuanceKind() { + return "human_operator"; + } + + public String authenticatedWorkloadIdentity() { + return authenticatedWorkloadIdentity; + } + + public String authorizationReferenceFingerprint() { + return authorizationReferenceFingerprint; + } + + public UUID reservationOwnerId() { + return reservationOwnerId; + } + + public long reservationClaimFence() { + return reservationClaimFence; + } + + public String issuanceFence() { + return authorityEvidenceBundle.issuanceFence(); + } + + public Map authorityTuple() { + return authorityEvidenceBundle.authorityTuple(); + } + + public Map membershipVersion() { + return authorityEvidenceBundle.membershipVersion(); + } + + public byte[] authorityEvidenceBundleBytes() { + return authorityEvidenceBundle.canonicalBytes(); + } + + public StartSessionAuthorityEvidenceBundle.BundleReference bundleReference() { + return bundleReference; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String canonicalJson() { + return new String(canonicalBytes, StandardCharsets.UTF_8); + } + + private static byte[] encode( + StartSessionPreAuthorizationReservationTuple preTuple, + String workloadIdentity, + String fingerprint, + UUID reservationOwnerId, + long reservationClaimFence, + StartSessionAuthorityEvidenceBundle bundle, + StartSessionAuthorityEvidenceBundle.BundleReference bundleReference) { + Map preValue = readCanonicalObject(preTuple.canonicalJson()); + Map root = new LinkedHashMap<>(); + root.put("tupleSchemaId", TUPLE_SCHEMA_ID); + root.put("tupleSchemaVersion", TUPLE_SCHEMA_VERSION); + root.put("preAuthorizationReservationTuple", preValue); + root.put("controlPlaneRequestId", preTuple.controlPlaneRequestId()); + root.put("mutationDigest", preTuple.mutationDigest()); + root.put("issuanceKind", "human_operator"); + root.put("authorizationReferenceFingerprint", fingerprint); + root.put( + "authenticatedWorkloadIdentity", + Map.of("identityKind", "MUTUAL_TLS_SPIFFE", "uri", workloadIdentity)); + root.put("actionFamilyRequestIdentity", preValue.get("actionFamilyRequestIdentity")); + root.put("actor", preValue.get("actor")); + root.put("automationPolicy", preValue.get("automationPolicy")); + root.put("actionFamily", preValue.get("actionFamily")); + root.put("actionFamilySchemaId", preValue.get("actionFamilySchemaId")); + root.put("actionFamilySchemaVersion", preValue.get("actionFamilySchemaVersion")); + root.put("scope", preValue.get("scope")); + root.put("target", preValue.get("target")); + root.put("targetOwner", preValue.get("targetOwner")); + root.put("expectedVersion", preValue.get("expectedVersion")); + root.put("mutation", preValue.get("mutation")); + root.put("auditReason", preValue.get("auditReason")); + root.put("authorityTuple", bundle.authorityTuple()); + root.put("membershipVersion", bundle.membershipVersion()); + root.put("issuanceFence", bundle.issuanceFence()); + root.put("reservationOwnerId", reservationOwnerId.toString()); + root.put("reservationClaimFence", reservationClaimFence); + root.put("authorityEvidenceBundle", bundle.jsonValue()); + root.put( + "authorityEvidenceBundleReference", + Map.of( + "bundleVersion", bundleReference.bundleVersion(), + "sourceVersion", bundleReference.sourceVersion(), + "sourceFence", bundleReference.sourceFence(), + "linearization", bundleReference.linearization())); + try { + byte[] bytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); + if (bytes.length > MAX_CANONICAL_TUPLE_BYTES) { + throw invalid("post-authorization tuple exceeds its byte limit"); + } + return bytes; + } catch (IOException exception) { + throw new IllegalStateException("could not encode post-authorization tuple", exception); + } + } + + private static void requireLoggingWorkload( + String workloadIdentity, StartSessionPreAuthorizationReservationTuple preTuple) { + Objects.requireNonNull(workloadIdentity, "authenticated workload identity is required"); + GrpcPeerIdentity peer = + GrpcPeerIdentity.parseUri(workloadIdentity) + .orElseThrow(() -> invalid("authenticated workload identity is invalid")); + if (!"logging-admin-service".equals(peer.service()) + || !peer.namespace().equals(preTuple.action().scope().targetNamespace())) { + throw invalid("StartSession requires the same-namespace Logging & Admin mTLS workload"); + } + } + + private static void requireFingerprint(String fingerprint) { + if (fingerprint == null + || !AUTHORIZATION_REFERENCE_FINGERPRINT.matcher(fingerprint).matches()) { + throw invalid("Account authorization-reference fingerprint is malformed"); + } + } + + private static void requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field + " is required"); + if (value.equals(new UUID(0L, 0L))) { + throw invalid(field + " must not be nil"); + } + } + + private static String canonicalObject(Object value, String field) { + Map object = object(value, field); + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(object)), + StandardCharsets.UTF_8); + } catch (IOException exception) { + throw invalid(field + " cannot be decoded as canonical JSON"); + } + } + + private static Map readCanonicalObject(String canonicalJson) { + return JSON.readValue(canonicalJson, new TypeReference<>() {}); + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + .decode(java.nio.ByteBuffer.wrap(bytes)) + .toString(); + } catch (java.nio.charset.CharacterCodingException malformed) { + throw invalid("post-authorization tuple is not valid UTF-8"); + } + } + + private static Map object(Object value, String field) { + if (!(value instanceof Map raw)) { + throw invalid(field + " must be an object"); + } + Map result = new LinkedHashMap<>(); + raw.forEach( + (key, member) -> { + if (!(key instanceof String text)) { + throw invalid(field + " has a non-string key"); + } + result.put(text, member); + }); + return result; + } + + private static void requireExactFields( + Map object, Set fields, String field) { + if (!object.keySet().equals(fields)) { + throw invalid(field + " has missing or unsupported fields"); + } + } + + private static String string(Object value, String field) { + if (!(value instanceof String text)) { + throw invalid(field + " must be a string"); + } + return text; + } + + private static UUID canonicalUuid(Object value, String field) { + String text = string(value, field); + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) || parsed.equals(new UUID(0L, 0L))) { + throw invalid(field + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw invalid(field + " must be a canonical non-nil UUID"); + } + } + + private static long positiveLong(Object value, String field) { + if (!(value instanceof Number number)) { + throw invalid(field + " must be a positive integer"); + } + try { + long parsed = Long.parseLong(number.toString()); + if (parsed <= 0L || !Long.toString(parsed).equals(number.toString())) { + throw invalid(field + " must be a positive canonical integer"); + } + return parsed; + } catch (NumberFormatException malformed) { + throw invalid(field + " must be a positive signed 64-bit integer"); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTuple.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTuple.java new file mode 100644 index 0000000000..c1ecbb42f8 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTuple.java @@ -0,0 +1,384 @@ +package net.firedevops.firemud.common.operator; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.text.Normalizer; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.JacksonException; +import tools.jackson.databind.json.JsonMapper; + +/** + * Immutable shared value and canonical codec for ADR 0048's StartSession {@code + * preAuthorizationReservationTuple/v1}. + * + *

This value describes tuple contents only. Constructing or rehydrating it does not establish + * authenticated actor authority, reservation ownership, a claim, or permission to dispatch. + */ +public final class StartSessionPreAuthorizationReservationTuple { + public static final String TUPLE_SCHEMA_ID = "preAuthorizationReservationTuple"; + public static final String TUPLE_SCHEMA_VERSION = "1"; + public static final int MAX_CONTROL_PLANE_REQUEST_ID_UTF8_BYTES = 128; + private static final int MAX_CANONICAL_TUPLE_UTF8_BYTES = 8 * 1_024; + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final Set ROOT_FIELDS = + Set.of( + "tupleSchemaId", + "tupleSchemaVersion", + "actionFamilyRequestIdentity", + "actor", + "automationPolicy", + "actionFamily", + "actionFamilySchemaId", + "actionFamilySchemaVersion", + "scope", + "target", + "targetOwner", + "expectedVersion", + "mutation", + "auditReason"); + + private final String controlPlaneRequestId; + private final HumanActor actor; + private final StartSessionOperatorAction action; + + private StartSessionPreAuthorizationReservationTuple( + String controlPlaneRequestId, HumanActor actor, StartSessionOperatorAction action) { + this.controlPlaneRequestId = requireCanonicalControlPlaneRequestId(controlPlaneRequestId); + this.actor = Objects.requireNonNull(actor, "actor is required"); + this.action = Objects.requireNonNull(action, "action is required"); + } + + /** Creates tuple contents from typed values; the actor argument is not authenticated evidence. */ + public static StartSessionPreAuthorizationReservationTuple createHuman( + String controlPlaneRequestId, UUID actorAccountId, StartSessionOperatorAction action) { + return new StartSessionPreAuthorizationReservationTuple( + controlPlaneRequestId, new HumanActor(actorAccountId), action); + } + + /** Rehydrates the exact canonical ADR 0048 tuple value. This does not establish authority. */ + public static StartSessionPreAuthorizationReservationTuple fromCanonicalJson(String json) { + Objects.requireNonNull(json, "tuple JSON is required"); + if (json.getBytes(StandardCharsets.UTF_8).length > MAX_CANONICAL_TUPLE_UTF8_BYTES) { + throw new IllegalArgumentException("pre-authorization tuple exceeds its byte limit"); + } + try { + String canonical = + new String(Rfc8785CanonicalJson.canonicalizeUtf8(json), StandardCharsets.UTF_8); + if (!canonical.equals(json)) { + throw new IllegalArgumentException("pre-authorization tuple is not canonical JSON"); + } + Object decoded = JSON.readValue(json, Map.class); + Map root = requireObject(decoded, "tuple"); + requireExactFields(root, ROOT_FIELDS, "tuple"); + if (!TUPLE_SCHEMA_ID.equals(requireString(root.get("tupleSchemaId"), "tupleSchemaId")) + || !TUPLE_SCHEMA_VERSION.equals( + requireString(root.get("tupleSchemaVersion"), "tupleSchemaVersion"))) { + throw new IllegalArgumentException("unsupported pre-authorization tuple schema"); + } + + Map identity = + requireObject(root.get("actionFamilyRequestIdentity"), "actionFamilyRequestIdentity"); + requireExactFields( + identity, Set.of("requestIdentityKind", "requestId"), "actionFamilyRequestIdentity"); + if (!"controlPlaneRequestId" + .equals(requireString(identity.get("requestIdentityKind"), "requestIdentityKind"))) { + throw new IllegalArgumentException( + "StartSession request identity must be controlPlaneRequestId"); + } + String controlPlaneRequestId = requireString(identity.get("requestId"), "requestId"); + + Map actorObject = requireObject(root.get("actor"), "actor"); + requireExactFields(actorObject, Set.of("kind", "accountId"), "actor"); + if (!"HUMAN".equals(requireString(actorObject.get("kind"), "actor.kind"))) { + throw new IllegalArgumentException("StartSession reservation actor must be human"); + } + HumanActor actor = + new HumanActor(requireCanonicalUuid(actorObject.get("accountId"), "actor.accountId")); + + Map automation = + requireObject(root.get("automationPolicy"), "automationPolicy"); + requireExactFields(automation, Set.of("presence"), "automationPolicy"); + if (!"ABSENT" + .equals(requireString(automation.get("presence"), "automationPolicy.presence"))) { + throw new IllegalArgumentException( + "human StartSession tuple must explicitly omit automation policy"); + } + + String actionFamily = requireString(root.get("actionFamily"), "actionFamily"); + String schemaId = requireString(root.get("actionFamilySchemaId"), "actionFamilySchemaId"); + String schemaVersion = + requireString(root.get("actionFamilySchemaVersion"), "actionFamilySchemaVersion"); + if (!StartSessionOperatorAction.ACTION_FAMILY.equals(actionFamily) + || !StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID.equals(schemaId) + || !StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION.equals(schemaVersion)) { + throw new IllegalArgumentException("unsupported StartSession action-family schema"); + } + + Map scopeObject = requireObject(root.get("scope"), "scope"); + requireExactFields(scopeObject, Set.of("tenantId", "targetNamespace"), "scope"); + StartSessionOperatorAction.Scope scope = + new StartSessionOperatorAction.Scope( + requireCanonicalUuid(scopeObject.get("tenantId"), "scope.tenantId"), + requireString(scopeObject.get("targetNamespace"), "scope.targetNamespace")); + + Map targetObject = requireObject(root.get("target"), "target"); + requireExactFields(targetObject, Set.of("gameTemplateId", "ownerAccountId"), "target"); + StartSessionOperatorAction.Target target = + new StartSessionOperatorAction.Target( + requirePositiveCanonicalLong(targetObject.get("gameTemplateId")), + requireCanonicalUuid(targetObject.get("ownerAccountId"), "target.ownerAccountId")); + + Map ownerObject = requireObject(root.get("targetOwner"), "targetOwner"); + requireExactFields(ownerObject, Set.of("ownerService"), "targetOwner"); + if (!StartSessionOperatorAction.OWNER_SERVICE.equals( + requireString(ownerObject.get("ownerService"), "targetOwner.ownerService"))) { + throw new IllegalArgumentException("StartSession targetOwner is immutable and unsupported"); + } + + Map expectedVersion = + requireObject(root.get("expectedVersion"), "expectedVersion"); + requireExactFields(expectedVersion, Set.of("presence"), "expectedVersion"); + if (!"ABSENT" + .equals(requireString(expectedVersion.get("presence"), "expectedVersion.presence"))) { + throw new IllegalArgumentException( + "StartSession expectedVersion must be explicitly absent"); + } + + Map mutationObject = requireObject(root.get("mutation"), "mutation"); + requireExactFields(mutationObject, Set.of("clientIp"), "mutation"); + Map clientIpObject = + requireObject(mutationObject.get("clientIp"), "mutation.clientIp"); + String clientIpPresence = + requireString(clientIpObject.get("presence"), "mutation.clientIp.presence"); + StartSessionOperatorAction.ClientIp clientIp; + if ("ABSENT".equals(clientIpPresence)) { + requireExactFields(clientIpObject, Set.of("presence"), "mutation.clientIp"); + clientIp = StartSessionOperatorAction.ClientIp.absent(); + } else if ("PRESENT".equals(clientIpPresence)) { + requireExactFields(clientIpObject, Set.of("presence", "value"), "mutation.clientIp"); + clientIp = + StartSessionOperatorAction.ClientIp.of( + requireString(clientIpObject.get("value"), "mutation.clientIp.value")); + } else { + throw new IllegalArgumentException("mutation.clientIp presence must be ABSENT or PRESENT"); + } + + StartSessionOperatorAction action = + new StartSessionOperatorAction( + schemaId, + schemaVersion, + scope, + target, + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(clientIp), + requireString(root.get("auditReason"), "auditReason")); + StartSessionPreAuthorizationReservationTuple tuple = + new StartSessionPreAuthorizationReservationTuple(controlPlaneRequestId, actor, action); + if (!tuple.canonicalJson().equals(json)) { + throw new IllegalArgumentException("pre-authorization tuple shape is not canonical"); + } + return tuple; + } catch (JacksonException malformed) { + throw new IllegalArgumentException("pre-authorization tuple JSON is invalid", malformed); + } catch (IOException exception) { + throw new IllegalArgumentException("pre-authorization tuple JSON is invalid", exception); + } + } + + public String actionFamily() { + return action.actionFamily(); + } + + public String controlPlaneRequestId() { + return controlPlaneRequestId; + } + + public HumanActor actor() { + return actor; + } + + public NoAutomationPolicy automationPolicy() { + return NoAutomationPolicy.ABSENT; + } + + public StartSessionOperatorAction action() { + return action; + } + + /** Validate a stable request key without silently normalizing or changing its identity. */ + public static String requireCanonicalControlPlaneRequestId(String value) { + Objects.requireNonNull(value, "controlPlaneRequestId is required"); + if (!Normalizer.isNormalized(value, Normalizer.Form.NFC)) { + throw new IllegalArgumentException("controlPlaneRequestId must already be NFC-normalized"); + } + return requireBoundedText(value, "controlPlaneRequestId"); + } + + public String targetOwner() { + return action.targetOwner(); + } + + /** Returns ADR 0047's digest over the seven action-schema grammar fields. */ + public String mutationDigest() { + return StartSessionOperatorActionCodec.mutationDigest(action); + } + + /** Returns the complete canonical typed tuple, including explicit absence values. */ + public String canonicalJson() { + Map scope = + Map.of( + "tenantId", action.scope().tenantId().toString(), + "targetNamespace", action.scope().targetNamespace()); + Map target = + Map.of( + "gameTemplateId", Long.toString(action.target().gameTemplateId()), + "ownerAccountId", action.target().ownerAccountId().toString()); + Map clientIp = + action.mutation().clientIp() instanceof StartSessionOperatorAction.AbsentClientIp + ? Map.of("presence", "ABSENT") + : Map.of( + "presence", + "PRESENT", + "value", + ((StartSessionOperatorAction.StringClientIp) action.mutation().clientIp()).value()); + Map root = new LinkedHashMap<>(); + root.put("tupleSchemaId", TUPLE_SCHEMA_ID); + root.put("tupleSchemaVersion", TUPLE_SCHEMA_VERSION); + root.put( + "actionFamilyRequestIdentity", + Map.of("requestIdentityKind", "controlPlaneRequestId", "requestId", controlPlaneRequestId)); + root.put("actor", Map.of("kind", "HUMAN", "accountId", actor.accountId().toString())); + root.put("automationPolicy", Map.of("presence", automationPolicy().name())); + root.put("actionFamily", action.actionFamily()); + root.put("actionFamilySchemaId", action.actionFamilySchemaId()); + root.put("actionFamilySchemaVersion", action.actionFamilySchemaVersion()); + root.put("scope", scope); + root.put("target", target); + root.put("targetOwner", Map.of("ownerService", action.targetOwner())); + root.put("expectedVersion", Map.of("presence", action.expectedVersion().name())); + root.put("mutation", Map.of("clientIp", clientIp)); + root.put("auditReason", action.auditReason()); + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)), + StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new IllegalStateException("could not encode StartSession reservation tuple", exception); + } + } + + public record HumanActor(UUID accountId) { + public HumanActor { + Objects.requireNonNull(accountId, "actor accountId is required"); + if (accountId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("actor accountId must not be nil"); + } + } + } + + public enum NoAutomationPolicy { + ABSENT + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof StartSessionPreAuthorizationReservationTuple that)) { + return false; + } + return controlPlaneRequestId.equals(that.controlPlaneRequestId) + && actor.equals(that.actor) + && action.equals(that.action); + } + + @Override + public int hashCode() { + return Objects.hash(controlPlaneRequestId, actor, action); + } + + private static String requireBoundedText(String value, String fieldName) { + Objects.requireNonNull(value, fieldName + " is required"); + String normalized = Normalizer.normalize(value, Normalizer.Form.NFC); + if (normalized.isBlank() + || normalized.codePoints().anyMatch(Character::isISOControl) + || normalized.getBytes(StandardCharsets.UTF_8).length + > MAX_CONTROL_PLANE_REQUEST_ID_UTF8_BYTES) { + throw new IllegalArgumentException(fieldName + " is blank or exceeds its bound"); + } + for (int index = 0; index < normalized.length(); index++) { + char current = normalized.charAt(index); + if (Character.isHighSurrogate(current)) { + if (index + 1 >= normalized.length() + || !Character.isLowSurrogate(normalized.charAt(index + 1))) { + throw new IllegalArgumentException(fieldName + " contains malformed Unicode"); + } + index++; + } else if (Character.isLowSurrogate(current)) { + throw new IllegalArgumentException(fieldName + " contains malformed Unicode"); + } + } + return normalized; + } + + private static UUID requireCanonicalUuid(Object value, String fieldName) { + String text = requireString(value, fieldName); + UUID parsed; + try { + parsed = UUID.fromString(text); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException(fieldName + " must be a canonical UUID", exception); + } + if (!parsed.toString().equals(text) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(fieldName + " must be a canonical non-nil UUID"); + } + return parsed; + } + + private static long requirePositiveCanonicalLong(Object value) { + String text = requireString(value, "target.gameTemplateId"); + if (!text.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException( + "target.gameTemplateId must be a positive canonical integer"); + } + try { + return Long.parseLong(text); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "target.gameTemplateId exceeds its supported range", exception); + } + } + + private static String requireString(Object value, String fieldName) { + if (!(value instanceof String text)) { + throw new IllegalArgumentException(fieldName + " must be a string"); + } + return text; + } + + @SuppressWarnings("unchecked") + private static Map requireObject(Object value, String fieldName) { + if (!(value instanceof Map map)) { + throw new IllegalArgumentException(fieldName + " must be an object"); + } + for (Object key : map.keySet()) { + if (!(key instanceof String)) { + throw new IllegalArgumentException(fieldName + " contains a non-string field name"); + } + } + return (Map) map; + } + + private static void requireExactFields( + Map object, Set expectedFields, String fieldName) { + if (!object.keySet().equals(expectedFields)) { + throw new IllegalArgumentException(fieldName + " has missing or unsupported fields"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentityTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentityTest.java index 529c239a43..01c36ef4fc 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentityTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentityTest.java @@ -10,9 +10,11 @@ import io.grpc.ServerCall; import io.grpc.ServerCallHandler; import io.grpc.ServerInterceptor; +import java.security.MessageDigest; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.ArrayList; +import java.util.HexFormat; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import javax.net.ssl.SSLSession; @@ -99,6 +101,20 @@ void validPeerIdentityReachesHandlerContext() throws Exception { .containsExactly(GAME_DESIGN_URI, "firemud", "game-design-service"); } + @Test + void presentedLeafFingerprintComesFromTheAuthenticatedTlsSessionContext() throws Exception { + SSLSession session = sessionWithUriSans(GAME_DESIGN_URI); + byte[] encodedLeaf = GAME_DESIGN_URI.getBytes(java.nio.charset.StandardCharsets.US_ASCII); + String expectedFingerprint = + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(encodedLeaf)); + + assertThat(GrpcPeerCertificateEvidence.fromSslSession(session)) + .get() + .extracting(GrpcPeerCertificateEvidence::leafSha256) + .isEqualTo(expectedFingerprint); + assertThat(interceptAndObserveLeafFingerprint(session)).isEqualTo(expectedFingerprint); + } + @Test void knownServiceIdentityParsesAndUnknownServiceIsRejected() throws Exception { assertThat( @@ -149,8 +165,27 @@ private static GrpcPeerIdentity interceptAndObserve(SSLSession session) throws E return observed.get(); } + private static String interceptAndObserveLeafFingerprint(SSLSession session) throws Exception { + @SuppressWarnings("unchecked") + ServerCall call = mock(ServerCall.class); + Attributes attributes = + Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, session).build(); + when(call.getAttributes()).thenReturn(attributes); + + AtomicReference observed = new AtomicReference<>(); + ServerCallHandler next = + (ignoredCall, ignoredHeaders) -> { + observed.set(GrpcPeerCertificateEvidence.current()); + return new ServerCall.Listener<>() {}; + }; + new GrpcPeerIdentityInterceptor().interceptCall(call, new Metadata(), next); + return observed.get().leafSha256(); + } + private static SSLSession sessionWithUriSans(String... uris) throws Exception { X509Certificate certificate = mock(X509Certificate.class); + when(certificate.getEncoded()) + .thenReturn(uris[0].getBytes(java.nio.charset.StandardCharsets.US_ASCII)); List> sans = new ArrayList<>(); for (String uri : uris) { sans.add(List.of(6, uri)); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodecTest.java new file mode 100644 index 0000000000..a31ffcdfbf --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodecTest.java @@ -0,0 +1,266 @@ +package net.firedevops.firemud.common.operator; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import org.junit.jupiter.api.Test; + +class StartSessionOperatorActionCodecTest { + private static final String VECTOR_RESOURCE = + "/operator/start-session-mutation-digest-v1-vectors.json"; + private static final ObjectMapper JSON = new ObjectMapper(); + + @Test + void matchesSharedActionVectors() throws IOException { + JsonNode vectors = fixture().path("vectors"); + String baseDigest = null; + String changedTargetDigest = null; + String changedScopeDigest = null; + String changedReasonDigest = null; + String composedDigest = null; + String decomposedDigest = null; + String absentClientIpDigest = null; + String emptyClientIpDigest = null; + + for (JsonNode vector : vectors) { + byte[] raw = rawVectorBytes(vector); + String name = vector.path("name").asText(); + if (!vector.path("accepted").asBoolean()) { + assertThatThrownBy(() -> StartSessionOperatorActionCodec.decode(raw)) + .as("vector %s", name) + .isInstanceOf(IllegalArgumentException.class); + continue; + } + + StartSessionOperatorAction action = StartSessionOperatorActionCodec.decode(raw); + byte[] preimage = StartSessionOperatorActionCodec.canonicalPreimage(action); + String digest = StartSessionOperatorActionCodec.mutationDigest(action); + assertThat(hex(preimage)) + .as("preimage for %s", name) + .isEqualTo(vector.path("preimageHex").asText()); + assertThat(digest).as("digest for %s", name).isEqualTo(vector.path("digest").asText()); + switch (name) { + case "base" -> baseDigest = digest; + case "changed-target" -> changedTargetDigest = digest; + case "changed-scope" -> changedScopeDigest = digest; + case "changed-audit-reason" -> changedReasonDigest = digest; + case "client-ip-absent" -> absentClientIpDigest = digest; + case "client-ip-empty" -> emptyClientIpDigest = digest; + case "unicode-composed" -> composedDigest = digest; + case "unicode-decomposed" -> decomposedDigest = digest; + default -> { + // Individual golden values above prove the remaining mutation vectors. + } + } + } + + assertThat(absentClientIpDigest).isNotEqualTo(emptyClientIpDigest); + assertThat(composedDigest).isEqualTo(decomposedDigest); + assertThat(baseDigest) + .isNotEqualTo(absentClientIpDigest) + .isNotEqualTo(changedTargetDigest) + .isNotEqualTo(changedScopeDigest) + .isNotEqualTo(changedReasonDigest); + } + + @Test + void matchesSharedGenericValueGrammarVectors() throws IOException { + java.util.Map encodings = new java.util.HashMap<>(); + for (JsonNode vector : fixture().path("grammarVectors")) { + String name = vector.path("name").asText(); + String kind = vector.path("kind").asText(); + if ("numberLexeme".equals(kind)) { + String rawLexeme = vector.path("rawLexeme").asText(); + if (!vector.path("accepted").asBoolean()) { + assertThatThrownBy( + () -> StartSessionOperatorActionCodec.canonicalNumberLexemeForTest(rawLexeme)) + .as("numeric lexeme vector %s", name) + .isInstanceOf(IllegalArgumentException.class); + continue; + } + String encoded = + hex(StartSessionOperatorActionCodec.canonicalNumberLexemeForTest(rawLexeme)); + assertThat(encoded) + .as("numeric lexeme vector %s", name) + .isEqualTo(vector.path("canonicalValueHex").asText()); + encodings.put(name, encoded); + continue; + } + if ("reject".equals(kind)) { + byte[] raw = vector.path("rawValue").asText().getBytes(StandardCharsets.UTF_8); + assertThatThrownBy(() -> StartSessionOperatorActionCodec.canonicalGrammarValueForTest(raw)) + .as("grammar vector %s", name) + .isInstanceOf(IllegalArgumentException.class); + continue; + } + + byte[] encoded; + if ("absent".equals(kind)) { + encoded = StartSessionOperatorActionCodec.absentGrammarValueForTest(); + } else { + byte[] raw = vector.path("rawValue").asText().getBytes(StandardCharsets.UTF_8); + encoded = StartSessionOperatorActionCodec.canonicalGrammarValueForTest(raw); + } + String encodedHex = hex(encoded); + assertThat(encodedHex) + .as("canonical value for %s", name) + .isEqualTo(vector.path("canonicalValueHex").asText()); + encodings.put(name, encodedHex); + } + + assertThat(encodings.get("absent")).isNotEqualTo(encodings.get("null")); + assertThat(encodings.get("number-one")).isNotEqualTo(encodings.get("string-one")); + assertThat(encodings.get("number-signed-zero")).isEqualTo(encodings.get("number-zero")); + assertThat(encodings.get("unicode-key-composed")) + .isEqualTo(encodings.get("unicode-key-decomposed")); + } + + @Test + void exposesOnlyTypedImmutableStartSessionFields() throws IOException { + JsonNode base = findVector("base"); + StartSessionOperatorAction action = + StartSessionOperatorActionCodec.decode(rawVectorBytes(base)); + + assertThat(StartSessionOperatorAction.OWNER_SERVICE).isEqualTo("game-session-service"); + assertThat(action.targetOwner()).isEqualTo("game-session-service"); + assertThat(action.actionFamilySchemaId()).isEqualTo("firemud.game-session.start-session"); + assertThat(action.actionFamilySchemaVersion()).isEqualTo("1"); + assertThat(action.expectedVersion()) + .isEqualTo(StartSessionOperatorAction.ExpectedVersion.ABSENT); + assertThat(action.scope().tenantId().toString()) + .isEqualTo("22222222-2222-4222-8222-222222222222"); + assertThat(action.target().gameTemplateId()).isEqualTo(42L); + assertThat(action.mutation().clientIp()) + .isInstanceOf(StartSessionOperatorAction.StringClientIp.class); + assertThat(action.auditReason()).isEqualTo("scheduled launch"); + } + + @Test + void rejectsRawUtf8AndActionSpecificOversizeInputs() throws IOException { + assertThatThrownBy( + () -> + StartSessionOperatorActionCodec.decode( + new byte[] {'{', '"', (byte) 0xff, '"', ':', '1', '}'})) + .isInstanceOf(IllegalArgumentException.class); + + byte[] oversizedRaw = new byte[StartSessionOperatorActionCodec.MAX_RAW_BYTES + 1]; + assertThatThrownBy(() -> StartSessionOperatorActionCodec.decode(oversizedRaw)) + .isInstanceOf(IllegalArgumentException.class); + + String base = findVector("base").path("input").asText(); + String oversizedReason = base.replace("scheduled launch", "x".repeat(1_001)); + assertThatThrownBy( + () -> + StartSessionOperatorActionCodec.decode( + oversizedReason.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + + String oversizedClientIp = base.replace("192.0.2.1", "x".repeat(129)); + assertThatThrownBy( + () -> + StartSessionOperatorActionCodec.decode( + oversizedClientIp.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void auditReasonUsesExplicitSharedWhitespaceSet() throws IOException { + int[] sharedWhitespaceCodepoints = { + 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x0020, 0x0085, 0x00A0, 0x1680, + 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, + 0x2009, 0x200A, 0x2028, 0x2029, 0x202F, 0x205F, 0x3000 + }; + String base = findVector("base").path("input").asText(); + for (int codePoint : sharedWhitespaceCodepoints) { + String blankReason = new String(Character.toChars(codePoint)); + String blankInput = replaceAuditReason(base, blankReason); + assertThatThrownBy( + () -> + StartSessionOperatorActionCodec.decode( + blankInput.getBytes(StandardCharsets.UTF_8))) + .as("blank audit reason U+%04X", codePoint) + .isInstanceOf(IllegalArgumentException.class); + + String nonblankInput = replaceAuditReason(base, blankReason + "x"); + assertThat( + StartSessionOperatorActionCodec.decode( + nonblankInput.getBytes(StandardCharsets.UTF_8))) + .as("nonblank audit reason containing U+%04X", codePoint) + .isNotNull(); + } + + for (int codePoint : new int[] {0x001C, 0x200B}) { + String outsideWhitespaceSetInput = + replaceAuditReason(base, new String(Character.toChars(codePoint))); + assertThat( + StartSessionOperatorActionCodec.decode( + outsideWhitespaceSetInput.getBytes(StandardCharsets.UTF_8))) + .as("nonblank audit reason U+%04X outside the shared set", codePoint) + .isNotNull(); + } + } + + @Test + void rejectsObjectMemberAndArrayElementLimitViolations() { + String tooManyMembers = "{" + String.join(",", Collections.nCopies(17, "\"k\":0")) + "}"; + assertThatThrownBy( + () -> + StartSessionOperatorActionCodec.canonicalGrammarValueForTest( + tooManyMembers.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + + String tooManyElements = "[" + String.join(",", Collections.nCopies(65, "0")) + "]"; + assertThatThrownBy( + () -> + StartSessionOperatorActionCodec.canonicalGrammarValueForTest( + tooManyElements.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + + String tooDeep = "[".repeat(9) + "0" + "]".repeat(9); + assertThatThrownBy( + () -> + StartSessionOperatorActionCodec.canonicalGrammarValueForTest( + tooDeep.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static JsonNode fixture() throws IOException { + try (InputStream stream = + StartSessionOperatorActionCodecTest.class.getResourceAsStream(VECTOR_RESOURCE)) { + if (stream == null) { + throw new IOException("missing shared StartSession digest vector resource"); + } + return JSON.readTree(stream); + } + } + + private static JsonNode findVector(String name) throws IOException { + for (JsonNode vector : fixture().path("vectors")) { + if (name.equals(vector.path("name").asText())) { + return vector; + } + } + throw new IOException("missing vector: " + name); + } + + private static String replaceAuditReason(String input, String auditReason) { + return input.replace("\"scheduled launch\"", JSON.valueToTree(auditReason).toString()); + } + + private static byte[] rawVectorBytes(JsonNode vector) { + if (vector.has("rawHex")) { + return java.util.HexFormat.of().parseHex(vector.path("rawHex").asText()); + } + return vector.path("input").asText().getBytes(StandardCharsets.UTF_8); + } + + private static String hex(byte[] bytes) { + return java.util.HexFormat.of().formatHex(bytes); + } +} diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundleTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundleTest.java new file mode 100644 index 0000000000..458f7004fb --- /dev/null +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundleTest.java @@ -0,0 +1,359 @@ +package net.firedevops.firemud.common.operator; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.Test; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.json.JsonMapper; + +class StartSessionAuthorityEvidenceBundleTest { + private static final UUID TENANT_ID = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR_ID = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID OWNER_ACCOUNT_ID = + UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID ISSUANCE_ID = UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final String EVALUATED_AT = "2026-10-09T00:00:00Z"; + private static final String EXPIRES_AT = "2026-10-09T00:05:00Z"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void decodesCanonicalTenantAdminBundleAndBindsTupleAndSeparateReference() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("bundle-βeta"); + byte[] bytes = canonical(validValue(tuple)); + StartSessionAuthorityEvidenceBundle.BundleReference reference = reference(); + + StartSessionAuthorityEvidenceBundle decoded = StartSessionAuthorityEvidenceBundle.decode(bytes); + decoded.requireTupleBinding(tuple); + decoded.requireReferenceBinding(reference); + + assertThat(decoded.canonicalBytes()).containsExactly(bytes); + assertThat(decoded.actionFamily()).isEqualTo("StartSession"); + assertThat(decoded.actorAccountId()).isEqualTo(ACTOR_ID); + assertThat(decoded.tenantId()).isEqualTo(TENANT_ID); + assertThat(decoded.targetNamespace()).isEqualTo("world-runtime"); + assertThat(decoded.controlPlaneRequestId()).isEqualTo("bundle-βeta"); + assertThat(decoded.mutationDigest()).isEqualTo(tuple.mutationDigest()).matches("[0-9a-f]{64}"); + assertThat(decoded.expiresAt()).isEqualTo(Instant.parse(EXPIRES_AT)); + assertThat(decoded.issuanceFence()).isEqualTo("23"); + assertThat(decoded.evidenceType()) + .isEqualTo(StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE); + assertThat(decoded.role()).isEqualTo("tenantAdmin"); + + byte[] exposed = decoded.canonicalBytes(); + exposed[0] = (byte) '!'; + assertThat(decoded.canonicalBytes()).containsExactly(bytes); + } + + @Test + void exposesOnlyDeeplyImmutableJsonValue() throws Exception { + byte[] bytes = canonical(validValue(tuple("bundle-immutable-json"))); + StartSessionAuthorityEvidenceBundle decoded = StartSessionAuthorityEvidenceBundle.decode(bytes); + Map jsonValue = decoded.jsonValue(); + Map authorityTuple = object(jsonValue.get("authorityTuple")); + List grantVersions = (List) authorityTuple.get("privateRealmGrantVersions"); + + assertThatThrownBy(() -> jsonValue.put("unexpected", true)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> authorityTuple.put("unexpected", true)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(grantVersions::clear).isInstanceOf(UnsupportedOperationException.class); + assertThat(decoded.canonicalBytes()).containsExactly(bytes); + } + + @Test + void rejectsChangedTupleActorScopeRequestOrRawMutationDigest() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("bundle-binding"); + byte[] bytes = canonical(validValue(tuple)); + StartSessionOperatorAction changedAction = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target(91L, OWNER_ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.of("203.0.113.19")), + "bundle codec contract"); + StartSessionPreAuthorizationReservationTuple changedDigest = + StartSessionPreAuthorizationReservationTuple.createHuman( + tuple.controlPlaneRequestId(), ACTOR_ID, changedAction); + StartSessionPreAuthorizationReservationTuple changedRequest = tuple("other-request"); + + assertThatThrownBy( + () -> + StartSessionAuthorityEvidenceBundle.decode(bytes) + .requireTupleBinding(changedDigest)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + StartSessionAuthorityEvidenceBundle.decode(bytes) + .requireTupleBinding(changedRequest)) + .isInstanceOf(IllegalArgumentException.class); + + Map prefixedDigest = read(bytes); + object(prefixedDigest.get("issuanceOperationIdentity")) + .put("mutationDigest", "sha256:" + tuple.mutationDigest()); + assertThatThrownBy(() -> StartSessionAuthorityEvidenceBundle.decode(canonical(prefixedDigest))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void requiresRawLowercaseSha256MutationDigestAndRejectsChangedIdentityFields() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("bundle-operation"); + Map changedIdentity = mutableValue(tuple); + object( + object(changedIdentity.get("issuanceOperationIdentity")) + .get("actionFamilyRequestIdentity")) + .put("requestId", "different-request"); + assertThatThrownBy(() -> StartSessionAuthorityEvidenceBundle.decode(canonical(changedIdentity))) + .isInstanceOf(IllegalArgumentException.class); + + Map uppercaseDigest = mutableValue(tuple); + object(uppercaseDigest.get("issuanceOperationIdentity")).put("mutationDigest", "A".repeat(64)); + assertThatThrownBy(() -> StartSessionAuthorityEvidenceBundle.decode(canonical(uppercaseDigest))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsAutomationGlobalRoleExtraAssuranceAndUnknownFields() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("bundle-closed"); + + Map automation = mutableValue(tuple); + automation.put("issuanceKind", "automation_operator"); + assertThatThrownBy(() -> StartSessionAuthorityEvidenceBundle.decode(canonical(automation))) + .isInstanceOf(IllegalArgumentException.class); + + Map globalRole = mutableValue(tuple); + object(globalRole.get("issuanceEvidence")).put("role", "platformAdmin"); + assertThatThrownBy(() -> StartSessionAuthorityEvidenceBundle.decode(canonical(globalRole))) + .isInstanceOf(IllegalArgumentException.class); + + Map assurance = mutableValue(tuple); + object(assurance.get("issuanceEvidence")).put("assurance", "not-applicable"); + assertThatThrownBy(() -> StartSessionAuthorityEvidenceBundle.decode(canonical(assurance))) + .isInstanceOf(IllegalArgumentException.class); + + Map unknown = mutableValue(tuple); + unknown.put("sourceReference", Map.of("unexpected", true)); + assertThatThrownBy(() -> StartSessionAuthorityEvidenceBundle.decode(canonical(unknown))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsMalformedUtf8DuplicateKeysTrailingTokensAndNoncanonicalBytes() throws Exception { + byte[] valid = canonical(validValue(tuple("bundle-json"))); + byte[] malformedUtf8 = Arrays.copyOf(valid, valid.length + 1); + malformedUtf8[malformedUtf8.length - 1] = (byte) 0xff; + String duplicate = + new String(valid, StandardCharsets.UTF_8) + .replaceFirst("\\{", "{\"bundleVersion\":\"authorityEvidenceBundle/v1\","); + + assertThatThrownBy(() -> StartSessionAuthorityEvidenceBundle.decode(malformedUtf8)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + StartSessionAuthorityEvidenceBundle.decode( + duplicate.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + StartSessionAuthorityEvidenceBundle.decode( + (new String(valid, StandardCharsets.UTF_8) + "{}") + .getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + StartSessionAuthorityEvidenceBundle.decode( + (new String(valid, StandardCharsets.UTF_8) + " ") + .getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + StartSessionAuthorityEvidenceBundle.decode(Arrays.copyOf(valid, valid.length - 1))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsInvalidExpiryAndReferenceOverflowOrMismatch() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("bundle-expiry"); + Map expiredAtEvaluation = mutableValue(tuple); + object(expiredAtEvaluation.get("accountProjectionEvidence")).put("expiresAt", EVALUATED_AT); + assertThatThrownBy( + () -> StartSessionAuthorityEvidenceBundle.decode(canonical(expiredAtEvaluation))) + .isInstanceOf(IllegalArgumentException.class); + + StartSessionAuthorityEvidenceBundle decoded = + StartSessionAuthorityEvidenceBundle.decode(canonical(validValue(tuple))); + assertThatThrownBy( + () -> + decoded.requireReferenceBinding( + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "18", "23", "17"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + decoded.requireReferenceBinding( + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "24", "17"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "9223372036854775808", + "23", + "17")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551616")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsOversizedBundlesAndOutOfScopeTenantAuthority() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("bundle-bounds"); + assertThatThrownBy( + () -> + StartSessionAuthorityEvidenceBundle.decode( + new byte[StartSessionAuthorityEvidenceBundle.MAX_BUNDLE_BYTES + 1])) + .isInstanceOf(IllegalArgumentException.class); + + Map widened = mutableValue(tuple); + Map authority = object(widened.get("authorityTuple")); + authority.put( + "tenantAuthorityGeneration", + Map.of(TENANT_ID.toString(), 5L, UUID.randomUUID().toString(), 2L)); + assertThatThrownBy(() -> StartSessionAuthorityEvidenceBundle.decode(canonical(widened))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static StartSessionPreAuthorizationReservationTuple tuple(String requestId) { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target(91L, OWNER_ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "bundle codec contract"); + return StartSessionPreAuthorizationReservationTuple.createHuman(requestId, ACTOR_ID, action); + } + + private static Map validValue( + StartSessionPreAuthorizationReservationTuple tuple) { + String tenantId = TENANT_ID.toString(); + Map projection = + new LinkedHashMap<>( + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + EVALUATED_AT, + "expiresAt", + EXPIRES_AT)); + Map identity = + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map authority = + new LinkedHashMap<>( + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of())); + Map evidence = + new LinkedHashMap<>( + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR_ID.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + return new LinkedHashMap<>( + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantId, "targetNamespace", "world-runtime"), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR_ID.toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + identity, + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(tenantId, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + evidence)); + } + + private static Map mutableValue( + StartSessionPreAuthorizationReservationTuple tuple) throws Exception { + return read(canonical(validValue(tuple))); + } + + private static StartSessionAuthorityEvidenceBundle.BundleReference reference() { + return new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "23", "18446744073709551615"); + } + + private static byte[] canonical(Object value) throws IOException { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private static Map read(byte[] bytes) throws IOException { + return JSON.readValue(bytes, new TypeReference<>() {}); + } + + @SuppressWarnings("unchecked") + private static Map object(Object value) { + return (Map) value; + } +} diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTupleTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTupleTest.java new file mode 100644 index 0000000000..067ace1439 --- /dev/null +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTupleTest.java @@ -0,0 +1,223 @@ +package net.firedevops.firemud.common.operator; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class StartSessionPostAuthorizationExecutionTupleTest { + private static final UUID TENANT = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID RESERVATION_OWNER = + UUID.fromString("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID ISSUANCE_ID = UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final String WORKLOAD = + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + + @Test + void retainsTheCompletePreTupleAndExactAuthorityEvidenceThroughCanonicalRoundTrip() + throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = create("post-tuple-roundtrip"); + byte[] bytes = tuple.canonicalBytes(); + StartSessionPostAuthorizationExecutionTuple decoded = + StartSessionPostAuthorizationExecutionTuple.decode(bytes); + + assertThat(decoded.canonicalBytes()).containsExactly(bytes); + assertThat(decoded.preAuthorizationTuple().canonicalJson()) + .isEqualTo(tuple.preAuthorizationTuple().canonicalJson()); + assertThat(decoded.controlPlaneRequestId()).isEqualTo("post-tuple-roundtrip"); + assertThat(decoded.mutationDigest()).matches("[0-9a-f]{64}"); + assertThat(decoded.issuanceKind()).isEqualTo("human_operator"); + assertThat(decoded.authenticatedWorkloadIdentity()).isEqualTo(WORKLOAD); + assertThat(decoded.authorizationReferenceFingerprint()).isEqualTo(FINGERPRINT); + assertThat(decoded.reservationOwnerId()).isEqualTo(RESERVATION_OWNER); + assertThat(decoded.reservationClaimFence()).isEqualTo(19L); + assertThat(decoded.issuanceFence()).isEqualTo("23"); + assertJsonNumber(decoded.authorityTuple().get("accountAuthorityGeneration"), 2L); + assertJsonNumber(decoded.membershipVersion().get(TENANT.toString()), 5L); + } + + @Test + void rejectsWorkloadFingerprintReferenceAndDirectTupleSubstitution() throws Exception { + StartSessionPreAuthorizationReservationTuple pre = preTuple("post-tuple-substitution"); + byte[] bundle = bundle(pre, "17"); + StartSessionAuthorityEvidenceBundle.BundleReference reference = reference("17"); + + assertThatThrownBy( + () -> + StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + "spiffe://firemud/ns/another-runtime/sa/logging-admin-service", + FINGERPRINT, + RESERVATION_OWNER, + 19L, + bundle, + reference)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("same-namespace"); + assertThatThrownBy( + () -> + StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + WORKLOAD, + "sha256:" + "b".repeat(64), + RESERVATION_OWNER, + 19L, + bundle, + reference)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("fingerprint"); + assertThatThrownBy( + () -> + StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, WORKLOAD, FINGERPRINT, RESERVATION_OWNER, 19L, bundle, reference("18"))) + .isInstanceOf(IllegalArgumentException.class); + + Map changed = + JSON.readValue(tupleBytes(create("post-tuple-substitution")), Map.class); + changed.put("controlPlaneRequestId", "different-request"); + byte[] changedBytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(changed)); + assertThatThrownBy(() -> StartSessionPostAuthorizationExecutionTuple.decode(changedBytes)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void returnsDefensiveEvidenceCopiesAndRejectsNonCanonicalOrUnknownTupleFields() throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = create("post-tuple-defensive"); + byte[] exposedTuple = tuple.canonicalBytes(); + byte[] exposedBundle = tuple.authorityEvidenceBundleBytes(); + exposedTuple[0] = (byte) '!'; + exposedBundle[0] = (byte) '!'; + assertThat(tuple.canonicalBytes()[0]).isNotEqualTo((byte) '!'); + assertThat(tuple.authorityEvidenceBundleBytes()[0]).isNotEqualTo((byte) '!'); + + assertThatThrownBy( + () -> + StartSessionPostAuthorizationExecutionTuple.decode( + (tuple.canonicalJson() + " ") + .getBytes(java.nio.charset.StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + + Map unknown = JSON.readValue(tuple.canonicalBytes(), Map.class); + unknown.put("authorizationReference", "not persisted here"); + byte[] unknownBytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(unknown)); + assertThatThrownBy(() -> StartSessionPostAuthorizationExecutionTuple.decode(unknownBytes)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static StartSessionPostAuthorizationExecutionTuple create(String requestId) { + StartSessionPreAuthorizationReservationTuple pre = preTuple(requestId); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, WORKLOAD, FINGERPRINT, RESERVATION_OWNER, 19L, bundle(pre, "17"), reference("17")); + } + + private static StartSessionPreAuthorizationReservationTuple preTuple(String requestId) { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, "world-runtime"), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "canonical StartSession owner attempt"); + return StartSessionPreAuthorizationReservationTuple.createHuman(requestId, ACTOR, action); + } + + private static byte[] bundle(StartSessionPreAuthorizationReservationTuple tuple, String version) { + String tenantId = TENANT.toString(); + Map projection = + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", version, + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"); + Map identity = + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map authority = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()); + Map evidence = + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3"); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantId, "targetNamespace", "world-runtime"), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + identity, + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(tenantId, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + evidence); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException exception) { + throw new IllegalStateException(exception); + } + } + + private static StartSessionAuthorityEvidenceBundle.BundleReference reference(String version) { + return new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, version, "23", "18446744073709551615"); + } + + private static byte[] tupleBytes(StartSessionPostAuthorizationExecutionTuple tuple) { + return tuple.canonicalBytes(); + } + + private static void assertJsonNumber(Object actual, long expected) { + assertThat(actual).isInstanceOf(Number.class); + assertThat(((Number) actual).longValue()).isEqualTo(expected); + } +} diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTupleTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTupleTest.java new file mode 100644 index 0000000000..1b83f4c8ef --- /dev/null +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTupleTest.java @@ -0,0 +1,143 @@ +package net.firedevops.firemud.common.operator; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class StartSessionPreAuthorizationReservationTupleTest { + private static final UUID TENANT_ID = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR_ID = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID OTHER_ACTOR_ID = + UUID.fromString("a44b728e-b58f-4fc1-a891-7644baef6ddc"); + private static final UUID OWNER_ACCOUNT_ID = + UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + + @Test + void canonicalBytesMatchThePreAuthorizationReservationTupleV1Encoding() { + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "tuple-contract-01", ACTOR_ID, action(StartSessionOperatorAction.ClientIp.absent())); + String expected = + "{\"actionFamily\":\"StartSession\"," + + "\"actionFamilyRequestIdentity\":{\"requestId\":\"tuple-contract-01\"," + + "\"requestIdentityKind\":\"controlPlaneRequestId\"}," + + "\"actionFamilySchemaId\":\"firemud.game-session.start-session\"," + + "\"actionFamilySchemaVersion\":\"1\"," + + "\"actor\":{\"accountId\":\"a4f5f4eb-8243-4d42-903a-33495456a622\"," + + "\"kind\":\"HUMAN\"}," + + "\"auditReason\":\"tuple codec contract\"," + + "\"automationPolicy\":{\"presence\":\"ABSENT\"}," + + "\"expectedVersion\":{\"presence\":\"ABSENT\"}," + + "\"mutation\":{\"clientIp\":{\"presence\":\"ABSENT\"}}," + + "\"scope\":{\"targetNamespace\":\"world-runtime\"," + + "\"tenantId\":\"9f8f06b4-36e5-4d11-9c2a-5adfd7f41531\"}," + + "\"target\":{\"gameTemplateId\":\"91\"," + + "\"ownerAccountId\":\"36aa9ce5-0ebc-4c14-9f6b-d160edc6059a\"}," + + "\"targetOwner\":{\"ownerService\":\"game-session-service\"}," + + "\"tupleSchemaId\":\"preAuthorizationReservationTuple\"," + + "\"tupleSchemaVersion\":\"1\"}"; + + assertThat(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8)) + .containsExactly(expected.getBytes(StandardCharsets.UTF_8)); + assertThat( + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(expected) + .canonicalJson() + .getBytes(StandardCharsets.UTF_8)) + .containsExactly(expected.getBytes(StandardCharsets.UTF_8)); + assertThat(tuple.mutationDigest()) + .isEqualTo(StartSessionOperatorActionCodec.mutationDigest(tuple.action())); + } + + @Test + void roundTripsTypedContentsAndSameRequestIdWithDifferentActorIsAConflict() { + StartSessionOperatorAction action = + action(StartSessionOperatorAction.ClientIp.of("203.0.113.8")); + StartSessionPreAuthorizationReservationTuple original = + StartSessionPreAuthorizationReservationTuple.createHuman( + "tuple-conflict-01", ACTOR_ID, action); + StartSessionPreAuthorizationReservationTuple rehydrated = + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(original.canonicalJson()); + StartSessionPreAuthorizationReservationTuple changedActor = + StartSessionPreAuthorizationReservationTuple.createHuman( + "tuple-conflict-01", OTHER_ACTOR_ID, action); + + assertThat(rehydrated).isEqualTo(original); + assertThat(rehydrated.canonicalJson()).isEqualTo(original.canonicalJson()); + assertThat(rehydrated.mutationDigest()).isEqualTo(original.mutationDigest()); + assertThat(changedActor.controlPlaneRequestId()).isEqualTo(original.controlPlaneRequestId()); + assertThat(changedActor).isNotEqualTo(original); + assertThat(changedActor.canonicalJson()).isNotEqualTo(original.canonicalJson()); + // The action digest excludes reservation identity and actor; it cannot replace tuple + // comparison. + assertThat(changedActor.mutationDigest()).isEqualTo(original.mutationDigest()); + assertThat(original.canonicalJson()) + .contains("\"clientIp\":{\"presence\":\"PRESENT\",\"value\":\"203.0.113.8\"}"); + } + + @Test + void strictDecoderRejectsNoncanonicalAndUnsupportedTupleShapes() { + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "tuple-strict-01", ACTOR_ID, action(StartSessionOperatorAction.ClientIp.absent())); + String json = tuple.canonicalJson(); + String withUnknownRootField = + json.replace( + "\"tupleSchemaVersion\":\"1\"}", "\"tupleSchemaVersion\":\"1\",\"unexpected\":true}"); + String missingTargetOwner = + json.replace(",\"targetOwner\":{\"ownerService\":\"game-session-service\"}", ""); + String invalidExpectedVersion = + json.replace( + "\"expectedVersion\":{\"presence\":\"ABSENT\"}", + "\"expectedVersion\":{\"presence\":\"PRESENT\"}"); + String invalidActorKind = json.replace("\"kind\":\"HUMAN\"", "\"kind\":\"WORKLOAD\""); + + assertThatThrownBy( + () -> StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(" " + json)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical JSON"); + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + withUnknownRootField)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(missingTargetOwner)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + invalidExpectedVersion)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("expectedVersion"); + assertThatThrownBy( + () -> StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(invalidActorKind)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("actor must be human"); + } + + @Test + void strictDecoderRejectsNonObjectJsonRootsAsIllegalArgument() { + for (String json : List.of("[]", "\"tuple\"", "1", "true", "null")) { + assertThatThrownBy(() -> StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(json)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + private static StartSessionOperatorAction action(StartSessionOperatorAction.ClientIp clientIp) { + return new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target(91L, OWNER_ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(clientIp), + "tuple codec contract"); + } +} diff --git a/services/common-platform-core/src/test/resources/operator/start-session-mutation-digest-v1-vectors.json b/services/common-platform-core/src/test/resources/operator/start-session-mutation-digest-v1-vectors.json new file mode 100644 index 0000000000..84fff4c3c2 --- /dev/null +++ b/services/common-platform-core/src/test/resources/operator/start-session-mutation-digest-v1-vectors.json @@ -0,0 +1,181 @@ +{ + "schemaId": "firemud.game-session.start-session", + "schemaVersion": "1", + "vectors": [ + { + "name": "base", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"scheduled launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343231343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743133333a313a31383a636c69656e744970363a737472696e6731393a3139322e302e322e3131313a6175646974526561736f6e363a737472696e673131363a7363686564756c6564206c61756e6368", + "digest": "f81e35e943d51078a1d1c5eb7f3175bedbd7e704f55fe7b450050b852dd62e29" + }, + { + "name": "changed-target", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"43\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"scheduled launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343331343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743133333a313a31383a636c69656e744970363a737472696e6731393a3139322e302e322e3131313a6175646974526561736f6e363a737472696e673131363a7363686564756c6564206c61756e6368", + "digest": "5c736b3aa5c0772f0edef9fbf00a60b585ab99cccf774cb08196f7eb5cca346d" + }, + { + "name": "changed-scope", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"44444444-4444-4444-8444-444444444444\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"scheduled launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d34343434343434343434343431353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343231343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743133333a313a31383a636c69656e744970363a737472696e6731393a3139322e302e322e3131313a6175646974526561736f6e363a737472696e673131363a7363686564756c6564206c61756e6368", + "digest": "cdb171f110e99654085d935f9dd0c9d0dd46877272976080b01f84320ec45008" + }, + { + "name": "changed-audit-reason", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"operator launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343231343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743133333a313a31383a636c69656e744970363a737472696e6731393a3139322e302e322e3131313a6175646974526561736f6e363a737472696e673131353a6f70657261746f72206c61756e6368", + "digest": "43ac8a4e4c8618c090ed7cd298a223e42dffca4519c7a1c38509b8cc1eb16867" + }, + { + "name": "client-ip-absent", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{},\"auditReason\":\"scheduled launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343231343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743132343a313a31383a636c69656e744970363a616273656e7430303a31313a6175646974526561736f6e363a737472696e673131363a7363686564756c6564206c61756e6368", + "digest": "01b67879242b7213c9dd9dafbed8a4ed5cbec72ba671d9a04c263bf3b52e3195" + }, + { + "name": "client-ip-empty", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"\"},\"auditReason\":\"scheduled launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343231343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743132343a313a31383a636c69656e744970363a737472696e6731303a31313a6175646974526561736f6e363a737472696e673131363a7363686564756c6564206c61756e6368", + "digest": "880d0f5718ce3f1150d559b6e1df62bbe22249cfb95774b3040715be29966ec1" + }, + { + "name": "unicode-composed", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"caf\\u00e9 launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343231343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743133333a313a31383a636c69656e744970363a737472696e6731393a3139322e302e322e3131313a6175646974526561736f6e363a737472696e673131323a636166c3a9206c61756e6368", + "digest": "7dd8d54b05c485e62d580b1b31bbdc0d6e5634d0caaf234a643d1cc46a5dab09" + }, + { + "name": "unicode-decomposed", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"cafe\\u0301 launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343231343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743133333a313a31383a636c69656e744970363a737472696e6731393a3139322e302e322e3131313a6175646974526561736f6e363a737472696e673131323a636166c3a9206c61756e6368", + "digest": "7dd8d54b05c485e62d580b1b31bbdc0d6e5634d0caaf234a643d1cc46a5dab09" + }, + { + "name": "client-ip-null", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":null},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "expected-version-null", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"expectedVersion\":null,\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "expected-version-present", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"expectedVersion\":1,\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "wrong-type-client-ip", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":7},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "duplicate-root-key", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "normalized-key-collision", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"t\\u00e9\":\"x\",\"te\\u0301\":\"y\"},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "unknown-member", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"192.0.2.1\",\"extra\":true},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "missing-audit-reason", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{}}" + }, + { + "name": "wrong-scope-member-order", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"targetNamespace\":\"firemud\",\"tenantId\":\"22222222-2222-4222-8222-222222222222\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "malformed-unicode", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{},\"auditReason\":\"\\uD800\"}" + }, + { + "name": "invalid-utf8", + "accepted": false, + "rawHex": "7b22616374696f6e46616d696c79536368656d614964223a22666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e222c22616374696f6e46616d696c79536368656d6156657273696f6e223a2231222c2273636f7065223a7b2274656e616e744964223a2232323232323232322d323232322d343232322d383232322d323232323232323232323232222c227461726765744e616d657370616365223a22666972656d7564227d2c22746172676574223a7b2267616d6554656d706c6174654964223a223432222c226f776e65724163636f756e744964223a2233333333333333332d333333332d343333332d383333332d333333333333333333333333227d2c226d75746174696f6e223a7b22636c69656e744970223a223139322e302e322e31227d2c226175646974526561736f6e223a22ff227d" + }, + { + "name": "numeric-template-id-rejected", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":42,\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "non-canonical-template-id-string", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"042\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "template-id-overflow-rejected", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"9223372036854775808\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "nil-owner-account-id", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"00000000-0000-0000-0000-000000000000\"},\"mutation\":{},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "audit-reason-nel-blank", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"\\u0085\"}" + }, + { + "name": "audit-reason-zero-width-space", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"\\u200b\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343231343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743133333a313a31383a636c69656e744970363a737472696e6731393a3139322e302e322e3131313a6175646974526561736f6e363a737472696e6731333ae2808b", + "digest": "5c0ceb368d52ff6c9a36b24a2a88883ec7620611a9a6a6a9bbfbaabbadce9f5d" + } + ], + "grammarVectors": [ + {"name": "absent", "kind": "absent", "canonicalValueHex": "363a616273656e7430303a"}, + {"name": "null", "kind": "raw", "rawValue": "null", "canonicalValueHex": "343a6e756c6c31303a"}, + {"name": "number-one", "kind": "raw", "rawValue": "1", "canonicalValueHex": "363a6e756d62657231313a31"}, + {"name": "string-one", "kind": "raw", "rawValue": "\"1\"", "canonicalValueHex": "363a737472696e6731313a31"}, + {"name": "number-ten-trailing-zeroes", "kind": "raw", "rawValue": "10.000", "canonicalValueHex": "363a6e756d62657231323a3130"}, + {"name": "number-negative-decimal", "kind": "raw", "rawValue": "-12.3400", "canonicalValueHex": "363a6e756d62657231363a2d31322e3334"}, + {"name": "number-signed-zero", "kind": "raw", "rawValue": "-0.00", "canonicalValueHex": "363a6e756d62657231313a30"}, + {"name": "number-zero", "kind": "raw", "rawValue": "0", "canonicalValueHex": "363a6e756d62657231313a30"}, + {"name": "array-order", "kind": "raw", "rawValue": "[1,\"1\",null]", "canonicalValueHex": "353a61727261793133363a313a33363a6e756d62657231313a31363a737472696e6731313a31343a6e756c6c31303a"}, + {"name": "unicode-key-composed", "kind": "raw", "rawValue": "{\"\\u00e9\":\"x\"}", "canonicalValueHex": "363a6f626a6563743131393a313a31323ac3a9363a737472696e6731313a78"}, + {"name": "unicode-key-decomposed", "kind": "raw", "rawValue": "{\"e\\u0301\":\"x\"}", "canonicalValueHex": "363a6f626a6563743131393a313a31323ac3a9363a737472696e6731313a78"}, + {"name": "malformed-surrogate-rejected", "kind": "reject", "rawValue": "\"\\uD800\""}, + {"name": "eight-empty-composites-accepted", "kind": "raw", "rawValue": "[[[[[[[[]]]]]]]]", "canonicalValueHex": "353a6172726179313130303a313a31353a61727261793138363a313a31353a61727261793137323a313a31353a61727261793135383a313a31353a61727261793134343a313a31353a61727261793133303a313a31353a61727261793131363a313a31353a617272617931333a313a30"}, + {"name": "ninth-empty-composite-rejected", "kind": "reject", "rawValue": "[[[[[[[[[]]]]]]]]]"}, + {"name": "nesting-depth-rejected", "kind": "reject", "rawValue": "[[[[[[[[[0]]]]]]]]]"}, + {"name": "duplicate-object-key-rejected", "kind": "reject", "rawValue": "{\"a\":1,\"a\":2}"}, + {"name": "normalized-object-key-collision-rejected", "kind": "reject", "rawValue": "{\"\\u00e9\":1,\"e\\u0301\":2}"}, + {"name": "number-space-prefix-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": " 1"}, + {"name": "number-space-suffix-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "1 "}, + {"name": "number-trailing-point-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "1."}, + {"name": "number-leading-point-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": ".5"}, + {"name": "number-nan-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "NaN"}, + {"name": "number-infinity-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "Infinity"}, + {"name": "number-negative-infinity-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "-Infinity"}, + {"name": "number-exponent-lexeme-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "1e3"}, + {"name": "number-plus-lexeme-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "+1"}, + {"name": "number-leading-zero-lexeme-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "01"}, + {"name": "number-exponent-rejected", "kind": "reject", "rawValue": "1e3"}, + {"name": "number-plus-rejected", "kind": "reject", "rawValue": "+1"}, + {"name": "number-leading-zero-rejected", "kind": "reject", "rawValue": "01"} + ] +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/AuthTokenInterceptor.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AuthTokenInterceptor.java index 4edf985984..a9992ad1e4 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/AuthTokenInterceptor.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AuthTokenInterceptor.java @@ -33,6 +33,7 @@ public AuthTokenInterceptor(JwtUtil jwtUtil, Set unauthenticatedMethods) public ServerCall.Listener interceptCall( ServerCall call, Metadata headers, ServerCallHandler next) { if (unauthenticatedMethods.contains(call.getMethodDescriptor().getFullMethodName())) { + SessionContext.clear(); return next.startCall(call, headers); } String authHeader = headers.get(AUTH_HEADER); diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java index 7c41c48784..a8387b25f2 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java @@ -9,7 +9,9 @@ import io.grpc.ServerCall.Listener; import io.grpc.ServerCallHandler; import io.grpc.Status; +import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.security.AuthTokenInterceptor; @@ -67,6 +69,67 @@ void rejectsMalformedJwtClaims() { assertThat(SessionContext.getScopedRolesMap()).isEmpty(); } + @Test + void clearsStaleThreadLocalContextBeforeUnauthenticatedMethodHandler() { + AuthTokenInterceptor interceptor = + new AuthTokenInterceptor(jwtUtil, Set.of(METHOD.getFullMethodName())); + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall call = Mockito.mock(ServerCall.class); + AtomicReference accountIdSeenByHandler = new AtomicReference<>("not-called"); + ServerCallHandler next = + (serverCall, headers) -> { + accountIdSeenByHandler.set(SessionContext.getAccountId()); + return new Listener<>() {}; + }; + + Mockito.when(call.getMethodDescriptor()).thenReturn(METHOD); + SessionContext.setContext("stale-account", List.of("platformAdmin"), Map.of()); + + interceptor.interceptCall(call, new Metadata(), next); + + assertThat(accountIdSeenByHandler.get()).isNull(); + assertThat(SessionContext.getAccountId()).isNull(); + assertThat(SessionContext.getGlobalRoles()).isEmpty(); + } + + @Test + void clearingStaleThreadLocalContextPreservesAnExistingGrpcJwtContext() { + AuthTokenInterceptor jwtInterceptor = new AuthTokenInterceptor(jwtUtil); + AuthTokenInterceptor publicMethodInterceptor = + new AuthTokenInterceptor(jwtUtil, Set.of(METHOD.getFullMethodName())); + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall call = Mockito.mock(ServerCall.class); + AtomicReference accountIdSeenByHandler = new AtomicReference<>(); + AtomicReference> rolesSeenByHandler = new AtomicReference<>(); + ServerCallHandler publicHandler = + (serverCall, headers) -> { + accountIdSeenByHandler.set(SessionContext.getAccountId()); + rolesSeenByHandler.set(SessionContext.getGlobalRoles()); + return new Listener<>() {}; + }; + ServerCallHandler next = + (serverCall, headers) -> + publicMethodInterceptor.interceptCall(serverCall, headers, publicHandler); + + Mockito.when(call.getMethodDescriptor()).thenReturn(METHOD); + Metadata headers = new Metadata(); + String token = + jwtUtil.generateToken( + "account", + Map.of( + "accountId", "42", + "globalRoles", List.of("platformAdmin"), + "scopedRoles", Map.of())); + headers.put(AUTH_HEADER, "Bearer " + token); + SessionContext.setContext("stale-account", List.of("moderator"), Map.of()); + + jwtInterceptor.interceptCall(call, headers, next); + + assertThat(accountIdSeenByHandler.get()).isEqualTo("42"); + assertThat(rolesSeenByHandler.get()).containsExactly("platformAdmin"); + assertThat(SessionContext.getAccountId()).isNull(); + } + @Test void appliesSessionContextDuringCallbacksAndClearsAfterCompletion() { AuthTokenInterceptor interceptor = new AuthTokenInterceptor(jwtUtil); diff --git a/services/logging-admin-service/build.gradle.kts b/services/logging-admin-service/build.gradle.kts index 3f355d19a2..c3da9c94a7 100644 --- a/services/logging-admin-service/build.gradle.kts +++ b/services/logging-admin-service/build.gradle.kts @@ -2,6 +2,7 @@ apply(from = "${rootDir}/gradle/proto-convention.gradle") plugins { + `java-test-fixtures` id("net.firedevops.firemud.secured-sql-aop-service-conventions") id("net.firedevops.firemud.openapi-conventions") id("net.firedevops.firemud.jooq-conventions") @@ -12,4 +13,13 @@ firemudJooq { } dependencies { + testImplementation(libs.grpc.inprocess) + testImplementation(libs.grpc.netty.shaded) + testImplementation(testFixtures(project(":logging-admin-service"))) + testCompileOnly(libs.spotbugs.annotations) + testFixturesApi(libs.testcontainers.postgresql) + testFixturesImplementation(libs.jooq) + testFixturesImplementation(libs.postgresql) + testFixturesImplementation(libs.spring.boot.starter.test) + testFixturesImplementation(libs.testcontainers.postgresql) } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationService.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationService.java new file mode 100644 index 0000000000..a72aee9a6c --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationService.java @@ -0,0 +1,727 @@ +package net.firedevops.firemud.loggingadmin.operator; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.loggingadmin.repository.StartSessionPreAuthorizationReservationRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +/** Durable, bounded Logging/Admin claim lifecycle for StartSession authorization and handoff. */ +@Service +public final class StartSessionPreAuthorizationReservationService { + public static final Duration CLAIM_TTL = Duration.ofSeconds(30); + + private final StartSessionPreAuthorizationReservationRepository repository; + private final Clock clock; + private final MutationCapability mutationCapability; + + @Autowired + public StartSessionPreAuthorizationReservationService( + StartSessionPreAuthorizationReservationRepository repository) { + this(repository, Clock.systemUTC(), null); + } + + StartSessionPreAuthorizationReservationService( + StartSessionPreAuthorizationReservationRepository repository, Clock clock) { + this(repository, clock, null); + } + + private StartSessionPreAuthorizationReservationService( + StartSessionPreAuthorizationReservationRepository repository, + Clock clock, + MutationCapability mutationCapability) { + this.repository = Objects.requireNonNull(repository, "repository is required"); + this.clock = Objects.requireNonNull(clock, "clock is required"); + this.mutationCapability = mutationCapability; + } + + /** + * Atomically creates one reservation or returns the exact existing reservation as a duplicate. + * Only the first caller receives a claim capability; an exact duplicate cannot dispatch work. + */ + public Acquisition acquire(StartSessionPreAuthorizationReservationTuple tuple) { + requireMutationCapability(); + Objects.requireNonNull(tuple, "tuple is required"); + if (!tuple.isAuthorityDerived()) { + throw new IllegalArgumentException( + "initial reservation requires an actor derived from the authenticated request context"); + } + Instant now = clock.instant(); + UUID ownerId = UUID.randomUUID(); + StartSessionPreAuthorizationReservationRepository.AcquireResult result = + repository.acquire(tuple, ownerId, epochMillis(now), epochMillis(now.plus(CLAIM_TTL))); + ClaimHandle claim = + result.created() + ? new ClaimHandle( + tuple, + tuple.mutationDigest(), + ownerId, + ownerId, + result.snapshot().reservationClaimFence(), + result.snapshot().claimFence(), + ClaimPurpose.ORIGINAL) + : null; + return new Acquisition(result.snapshot(), claim); + } + + /** Read-only lookup by the one stable orchestration key. */ + public Optional find(String controlPlaneRequestId) { + return repository.find(controlPlaneRequestId); + } + + /** Read-only exact lookup; a reused key with any tuple difference conflicts. */ + public Optional findExact(StartSessionPreAuthorizationReservationTuple tuple) { + Objects.requireNonNull(tuple, "tuple is required"); + return repository.findExact(tuple); + } + + /** + * Reads one exact active Account evidence claim. Issue evidence is available only after the + * reservation is pending and only for an original or reserved-state recovery claim. Recovery + * evidence is read-only and may inspect the pending or already-authorized original response. + */ + public Optional readCurrentClaimEvidence( + String controlPlaneRequestId, + StartSessionPreAuthorizationReservationTuple tuple, + UUID reservationOwnerId, + long reservationClaimFence, + UUID currentClaimOwnerId, + long currentClaimFence, + ReadPurpose purpose) { + if (controlPlaneRequestId == null) { + throw new IllegalArgumentException("controlPlaneRequestId is required"); + } + String canonicalControlPlaneRequestId = + StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId( + controlPlaneRequestId); + Objects.requireNonNull(tuple, "tuple is required"); + Objects.requireNonNull(reservationOwnerId, "reservationOwnerId is required"); + Objects.requireNonNull(currentClaimOwnerId, "currentClaimOwnerId is required"); + Objects.requireNonNull(purpose, "purpose is required"); + if (!canonicalControlPlaneRequestId.equals(tuple.controlPlaneRequestId()) + || reservationOwnerId.equals(new UUID(0L, 0L)) + || currentClaimOwnerId.equals(new UUID(0L, 0L)) + || reservationClaimFence <= 0L + || currentClaimFence <= 0L) { + throw new IllegalArgumentException("exact reservation claim identity is required"); + } + if (purpose == ReadPurpose.ISSUE && currentClaimFence < reservationClaimFence) { + throw new StaleReservationClaimException(tuple.controlPlaneRequestId()); + } + if (purpose == ReadPurpose.RECOVER + && (reservationOwnerId.equals(currentClaimOwnerId) + || currentClaimFence <= reservationClaimFence)) { + throw new StaleReservationClaimException(tuple.controlPlaneRequestId()); + } + + Optional read = + repository.readCurrentClaim( + tuple, + reservationOwnerId, + reservationClaimFence, + currentClaimOwnerId, + currentClaimFence, + purpose, + epochMillis(clock.instant())); + if (read.isEmpty()) { + return Optional.empty(); + } + StartSessionPreAuthorizationReservationRepository.CurrentClaimResult result = + read.orElseThrow(); + long observedAtEpochMillis = epochMillis(clock.instant()); + Snapshot snapshot = result.snapshot(); + boolean allowedState = + purpose == ReadPurpose.ISSUE + ? snapshot.state() == State.AUTHORIZATION_PENDING + : snapshot.state() == State.AUTHORIZATION_PENDING + || snapshot.state() == State.AUTHORIZED; + if (snapshot.phase() != Phase.ACCOUNT_AUTHORIZATION + || !allowedState + || snapshot.claimState() != ClaimState.ACTIVE + || snapshot.reservationClaimFence() != reservationClaimFence + || snapshot.claimFence() != currentClaimFence + || !snapshot.tuple().canonicalJson().equals(tuple.canonicalJson()) + || !snapshot.mutationDigest().equals(tuple.mutationDigest()) + || !result.reservationOwnerId().equals(reservationOwnerId) + || !result.currentClaimOwnerId().equals(currentClaimOwnerId) + || !claimPurposeAllowsRead(snapshot, purpose, reservationOwnerId, currentClaimOwnerId) + || snapshot.claimExpiresAtEpochMillis() <= observedAtEpochMillis) { + throw new StaleReservationClaimException(tuple.controlPlaneRequestId()); + } + return Optional.of( + new CurrentClaimEvidence( + snapshot, + result.reservationOwnerId(), + result.currentClaimOwnerId(), + purpose, + observedAtEpochMillis)); + } + + /** + * Durably enters AUTHORIZATION_PENDING before the Account call is dispatched by a later + * integration. Only the first successful transition returns {@code mayDispatch=true}; observing + * the pending state again never authorizes another issuance call. + */ + public PendingTransition markAuthorizationPending(ClaimHandle claim) { + requireMutationCapability(); + requireClaim(claim); + if (!isIssueClaimPurpose(claim.purpose)) { + throw new StaleReservationClaimException(claim.controlPlaneRequestId()); + } + StartSessionPreAuthorizationReservationRepository.TransitionResult result = + repository.markAuthorizationPending( + claim.tuple, + claim.mutationDigest, + claim.reservationOwnerId, + claim.reservationFence, + claim.ownerId, + claim.fence, + epochMillis(clock.instant())); + return new PendingTransition(result.snapshot(), result.transitioned()); + } + + /** Renew only the exact current, active claim before its expiry. */ + public Snapshot renew(ClaimHandle claim, Phase expectedPhase, State expectedState) { + requireMutationCapability(); + requireClaim(claim); + Instant now = clock.instant(); + return repository.renew( + claim.tuple, + claim.mutationDigest, + claim.ownerId, + claim.fence, + expectedPhase, + expectedState, + epochMillis(now), + epochMillis(now.plus(CLAIM_TTL))); + } + + /** + * Advance the current fence after the exact claim expires. Expiry leaves the phase and state + * unchanged; it is not evidence that Account authorization did not happen. + */ + public Snapshot expireClaim(ClaimHandle claim, Phase expectedPhase, State expectedState) { + requireMutationCapability(); + requireClaim(claim); + return repository.expireClaim( + claim.tuple, + claim.mutationDigest, + claim.ownerId, + claim.fence, + expectedPhase, + expectedState, + epochMillis(clock.instant())); + } + + /** + * Acquire one fresh state-scoped recovery claim after expiry. A RESERVED claim can only finish + * the first pending transition and issue once; a pending claim can only recover Account's + * original response; an authorized claim can only look up that same response and record the + * original bounded owner handoff. Original reservation owner/fence evidence remains immutable. + */ + public Optional acquireAuthorizationRecoveryClaim( + StartSessionPreAuthorizationReservationTuple tuple) { + requireMutationCapability(); + Objects.requireNonNull(tuple, "tuple is required"); + Instant now = clock.instant(); + UUID recoveryOwnerId = UUID.randomUUID(); + Optional acquired = + repository.acquireRecoveryClaim( + tuple, recoveryOwnerId, epochMillis(now), epochMillis(now.plus(CLAIM_TTL))); + return acquired.map( + result -> + new RecoveryAcquisition( + result.snapshot(), + new ClaimHandle( + tuple, + tuple.mutationDigest(), + result.reservationOwnerId(), + recoveryOwnerId, + result.snapshot().reservationClaimFence(), + result.snapshot().claimFence(), + result.snapshot().claimPurpose()))); + } + + /** + * Enriches the exact live authorization-pending reservation with the original response returned + * by the authenticated Account client. Callers must not derive this value from caller assertions; + * the shared tuple validates structure but does not establish Account authority or source + * freshness. Only its canonical post-authorization tuple is persisted; the opaque reference is + * not. + */ + public AuthorizationCompletion completeAuthorization( + ClaimHandle claim, StartSessionPostAuthorizationExecutionTuple postAuthorizationTuple) { + requireMutationCapability(); + requirePostAuthorizationBinding(claim, postAuthorizationTuple); + long now = epochMillis(clock.instant()); + if (StartSessionAuthorityEvidenceBundle.decode( + postAuthorizationTuple.authorityEvidenceBundleBytes()) + .expiresAt() + .toEpochMilli() + <= now) { + throw new StaleReservationClaimException(claim.controlPlaneRequestId()); + } + StartSessionPreAuthorizationReservationRepository.AuthorizationTransitionResult result = + repository.completeAuthorization( + claim.tuple, + claim.mutationDigest, + claim.reservationOwnerId, + claim.reservationFence, + claim.ownerId, + claim.fence, + postAuthorizationTuple.canonicalJson(), + now); + return new AuthorizationCompletion(result.snapshot(), result.transitioned()); + } + + /** + * Persists the exact owner handoff before any external forward call. Only the first successful + * exact transition returns {@code mayDispatch=true}; duplicates only observe the pending row. + */ + public OwnerExecutionTransition beginOwnerExecution( + ClaimHandle claim, + StartSessionPostAuthorizationExecutionTuple postAuthorizationTuple, + OwnerExecutionHandoff handoff) { + requireMutationCapability(); + requirePostAuthorizationBinding(claim, postAuthorizationTuple); + Objects.requireNonNull(handoff, "owner execution handoff is required"); + long now = epochMillis(clock.instant()); + if (StartSessionAuthorityEvidenceBundle.decode( + postAuthorizationTuple.authorityEvidenceBundleBytes()) + .expiresAt() + .toEpochMilli() + <= now) { + throw new StaleReservationClaimException(claim.controlPlaneRequestId()); + } + StartSessionPreAuthorizationReservationRepository.OwnerExecutionTransitionResult result = + repository.beginOwnerExecution( + claim.tuple, + claim.mutationDigest, + claim.reservationOwnerId, + claim.reservationFence, + claim.ownerId, + claim.fence, + postAuthorizationTuple.canonicalJson(), + handoff.handoffId(), + now); + return new OwnerExecutionTransition(result.snapshot(), result.mayDispatch()); + } + + /** + * Read-only exact post-authorization snapshot; it does not revalidate authority or claim + * freshness and is not a commit-spanning compare-and-set proof. + */ + public Optional findAuthorizedExact( + StartSessionPreAuthorizationReservationTuple tuple) { + Objects.requireNonNull(tuple, "tuple is required"); + return repository.findAuthorizedExact(tuple); + } + + private static void requirePostAuthorizationBinding( + ClaimHandle claim, StartSessionPostAuthorizationExecutionTuple postAuthorizationTuple) { + requireClaim(claim); + Objects.requireNonNull(postAuthorizationTuple, "post-authorization tuple is required"); + if (!claim + .tuple + .canonicalJson() + .equals(postAuthorizationTuple.preAuthorizationTuple().canonicalJson()) + || !claim.mutationDigest.equals(postAuthorizationTuple.mutationDigest()) + || !claim.reservationOwnerId.equals(postAuthorizationTuple.reservationOwnerId()) + || claim.reservationFence != postAuthorizationTuple.reservationClaimFence()) { + throw new IdempotencyConflictException(claim.controlPlaneRequestId()); + } + } + + private static void requireClaim(ClaimHandle claim) { + Objects.requireNonNull(claim, "claim is required"); + } + + private static long epochMillis(Instant instant) { + long millis = instant.toEpochMilli(); + if (millis <= 0) { + throw new IllegalArgumentException("reservation time must be after the Unix epoch"); + } + return millis; + } + + public enum Phase { + ACCOUNT_AUTHORIZATION, + OWNER_EXECUTION + } + + public enum State { + RESERVED, + AUTHORIZATION_PENDING, + AUTHORIZED, + OWNER_EXECUTION_PENDING + } + + public enum ClaimState { + ACTIVE, + EXPIRED + } + + public enum ReadPurpose { + ISSUE, + RECOVER + } + + public enum ClaimPurpose { + ORIGINAL, + RESERVED_RECOVERY_ISSUE, + AUTHORIZATION_RECOVERY, + AUTHORIZED_RESPONSE_RECOVERY + } + + public record Snapshot( + StartSessionPreAuthorizationReservationTuple tuple, + String mutationDigest, + Phase phase, + State state, + long reservationClaimFence, + long claimFence, + long claimExpiresAtEpochMillis, + ClaimState claimState, + ClaimPurpose claimPurpose) { + public Snapshot { + Objects.requireNonNull(tuple, "tuple is required"); + Objects.requireNonNull(mutationDigest, "mutationDigest is required"); + Objects.requireNonNull(phase, "phase is required"); + Objects.requireNonNull(state, "state is required"); + Objects.requireNonNull(claimState, "claimState is required"); + if (reservationClaimFence != 1 || claimFence < reservationClaimFence) { + throw new IllegalArgumentException("reservation claim fences are invalid"); + } + if (claimExpiresAtEpochMillis <= 0) { + throw new IllegalArgumentException("claim expiry must be positive"); + } + if (!tuple.mutationDigest().equals(mutationDigest)) { + throw new IllegalArgumentException("stored mutationDigest does not match the typed tuple"); + } + if ((phase == Phase.ACCOUNT_AUTHORIZATION && state == State.OWNER_EXECUTION_PENDING) + || (phase == Phase.OWNER_EXECUTION && state != State.OWNER_EXECUTION_PENDING)) { + throw new IllegalArgumentException("reservation phase and state are inconsistent"); + } + if (claimState == ClaimState.EXPIRED + ? claimPurpose != null + : !purposeAllowedForState(state, claimPurpose)) { + throw new IllegalArgumentException("reservation claim purpose and state are inconsistent"); + } + if (claimState == ClaimState.ACTIVE + && ((claimPurpose == ClaimPurpose.ORIGINAL && claimFence != reservationClaimFence) + || (claimPurpose != ClaimPurpose.ORIGINAL && claimFence <= reservationClaimFence))) { + throw new IllegalArgumentException("reservation claim purpose and fence are inconsistent"); + } + } + } + + /** Exact immutable post-authorization state; no raw or encrypted opaque reference is included. */ + public record AuthorizedSnapshot( + Snapshot reservationSnapshot, + StartSessionPostAuthorizationExecutionTuple postAuthorizationTuple, + UUID reservationOwnerId, + UUID currentClaimOwnerId, + OwnerExecutionHandoff handoff) { + public AuthorizedSnapshot { + Objects.requireNonNull(reservationSnapshot, "reservationSnapshot is required"); + Objects.requireNonNull(postAuthorizationTuple, "postAuthorizationTuple is required"); + requireNonNil(reservationOwnerId, "reservationOwnerId"); + if (reservationSnapshot.claimState() == ClaimState.ACTIVE) { + requireNonNil(currentClaimOwnerId, "currentClaimOwnerId"); + } else if (currentClaimOwnerId != null) { + throw new IllegalArgumentException( + "expired reservation cannot retain a current claim owner"); + } + if (!reservationSnapshot + .tuple() + .canonicalJson() + .equals(postAuthorizationTuple.preAuthorizationTuple().canonicalJson()) + || !reservationOwnerId.equals(postAuthorizationTuple.reservationOwnerId()) + || reservationSnapshot.reservationClaimFence() + != postAuthorizationTuple.reservationClaimFence() + || (reservationSnapshot.phase() == Phase.ACCOUNT_AUTHORIZATION + && reservationSnapshot.state() == State.AUTHORIZED + && handoff != null) + || (reservationSnapshot.phase() == Phase.OWNER_EXECUTION + && reservationSnapshot.state() == State.OWNER_EXECUTION_PENDING + && handoff == null) + || (reservationSnapshot.state() != State.AUTHORIZED + && reservationSnapshot.state() != State.OWNER_EXECUTION_PENDING)) { + throw new IllegalArgumentException("post-authorization snapshot is inconsistent"); + } + } + } + + /** Immutable handoff identity written before the owner allocates its attempt and fence. */ + public record OwnerExecutionHandoff(UUID handoffId) { + public OwnerExecutionHandoff { + requireNonNil(handoffId, "handoffId"); + } + } + + public record AuthorizationCompletion(AuthorizedSnapshot snapshot, boolean transitioned) { + public AuthorizationCompletion { + Objects.requireNonNull(snapshot, "snapshot is required"); + } + } + + public record OwnerExecutionTransition(AuthorizedSnapshot snapshot, boolean mayDispatch) { + public OwnerExecutionTransition { + Objects.requireNonNull(snapshot, "snapshot is required"); + if (mayDispatch + && (snapshot.reservationSnapshot().phase() != Phase.OWNER_EXECUTION + || snapshot.reservationSnapshot().state() != State.OWNER_EXECUTION_PENDING + || snapshot.handoff() == null)) { + throw new IllegalArgumentException("dispatch requires the durable exact owner handoff"); + } + } + } + + private static void requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field + " is required"); + if (value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(field + " must not be nil"); + } + } + + private void requireMutationCapability() { + if (mutationCapability == null) { + throw new UnsupportedOperationException( + "StartSession reservation mutations are disabled for production construction"); + } + } + + private static final class MutationCapability { + private MutationCapability() {} + } + + private static boolean purposeAllowedForState(State state, ClaimPurpose purpose) { + if (purpose == null) { + return false; + } + return switch (state) { + case RESERVED -> + purpose == ClaimPurpose.ORIGINAL || purpose == ClaimPurpose.RESERVED_RECOVERY_ISSUE; + case AUTHORIZATION_PENDING -> + purpose == ClaimPurpose.ORIGINAL + || purpose == ClaimPurpose.RESERVED_RECOVERY_ISSUE + || purpose == ClaimPurpose.AUTHORIZATION_RECOVERY; + case AUTHORIZED, OWNER_EXECUTION_PENDING -> + purpose == ClaimPurpose.ORIGINAL + || purpose == ClaimPurpose.RESERVED_RECOVERY_ISSUE + || purpose == ClaimPurpose.AUTHORIZATION_RECOVERY + || purpose == ClaimPurpose.AUTHORIZED_RESPONSE_RECOVERY; + }; + } + + private static boolean isIssueClaimPurpose(ClaimPurpose purpose) { + return purpose == ClaimPurpose.ORIGINAL || purpose == ClaimPurpose.RESERVED_RECOVERY_ISSUE; + } + + public static boolean claimPurposeAllowsRead( + Snapshot snapshot, ReadPurpose purpose, UUID reservationOwnerId, UUID currentClaimOwnerId) { + Objects.requireNonNull(purpose, "purpose is required"); + if (purpose == ReadPurpose.ISSUE) { + return snapshot.state() == State.AUTHORIZATION_PENDING + && ((snapshot.claimPurpose() == ClaimPurpose.ORIGINAL + && reservationOwnerId.equals(currentClaimOwnerId) + && snapshot.claimFence() == snapshot.reservationClaimFence()) + || (snapshot.claimPurpose() == ClaimPurpose.RESERVED_RECOVERY_ISSUE + && !reservationOwnerId.equals(currentClaimOwnerId) + && snapshot.claimFence() > snapshot.reservationClaimFence())); + } + return !reservationOwnerId.equals(currentClaimOwnerId) + && snapshot.claimFence() > snapshot.reservationClaimFence() + && (snapshot.state() == State.AUTHORIZATION_PENDING + && snapshot.claimPurpose() == ClaimPurpose.AUTHORIZATION_RECOVERY + || snapshot.state() == State.AUTHORIZED + && (snapshot.claimPurpose() == ClaimPurpose.AUTHORIZATION_RECOVERY + || snapshot.claimPurpose() == ClaimPurpose.AUTHORIZED_RESPONSE_RECOVERY)); + } + + /** Opaque capability returned only to the caller that acquired a new claim. */ + public static final class ClaimHandle { + private final StartSessionPreAuthorizationReservationTuple tuple; + private final String mutationDigest; + private final UUID reservationOwnerId; + private final UUID ownerId; + private final long reservationFence; + private final long fence; + private final ClaimPurpose purpose; + + private ClaimHandle( + StartSessionPreAuthorizationReservationTuple tuple, + String mutationDigest, + UUID reservationOwnerId, + UUID ownerId, + long reservationFence, + long fence, + ClaimPurpose purpose) { + this.tuple = Objects.requireNonNull(tuple, "tuple is required"); + this.mutationDigest = Objects.requireNonNull(mutationDigest, "mutationDigest is required"); + this.reservationOwnerId = + Objects.requireNonNull(reservationOwnerId, "reservationOwnerId is required"); + this.ownerId = Objects.requireNonNull(ownerId, "ownerId is required"); + this.reservationFence = reservationFence; + this.fence = fence; + this.purpose = Objects.requireNonNull(purpose, "claim purpose is required"); + if (reservationOwnerId.equals(new UUID(0L, 0L)) + || ownerId.equals(new UUID(0L, 0L)) + || reservationFence <= 0 + || fence < reservationFence + || (purpose == ClaimPurpose.ORIGINAL + && (!reservationOwnerId.equals(ownerId) || fence != reservationFence)) + || (purpose != ClaimPurpose.ORIGINAL + && (reservationOwnerId.equals(ownerId) || fence <= reservationFence))) { + throw new IllegalArgumentException("reservation claim fences are invalid"); + } + } + + public String controlPlaneRequestId() { + return tuple.controlPlaneRequestId(); + } + + public long claimFence() { + return fence; + } + + public StartSessionPreAuthorizationReservationTuple tuple() { + return tuple; + } + + public String mutationDigest() { + return mutationDigest; + } + + /** Original tuple owner/fence and current fenced claim, kept distinct during recovery. */ + public ClaimEvidence claimEvidence() { + return new ClaimEvidence(reservationOwnerId, reservationFence, ownerId, fence); + } + + public boolean isRecoveryLookupOnly() { + return purpose == ClaimPurpose.AUTHORIZATION_RECOVERY + || purpose == ClaimPurpose.AUTHORIZED_RESPONSE_RECOVERY; + } + + public ClaimPurpose purpose() { + return purpose; + } + } + + public record Acquisition(Snapshot snapshot, ClaimHandle claim) { + public Acquisition { + Objects.requireNonNull(snapshot, "snapshot is required"); + if (claim != null + && (claim.purpose != ClaimPurpose.ORIGINAL + || snapshot.claimPurpose() != ClaimPurpose.ORIGINAL + || snapshot.phase() != Phase.ACCOUNT_AUTHORIZATION + || snapshot.state() != State.RESERVED + || snapshot.claimState() != ClaimState.ACTIVE + || snapshot.claimFence() != claim.fence + || !snapshot.tuple().canonicalJson().equals(claim.tuple.canonicalJson()) + || !snapshot.mutationDigest().equals(claim.mutationDigest))) { + throw new IllegalArgumentException("initial claim does not match its reservation"); + } + } + + public boolean newlyAcquired() { + return claim != null; + } + } + + public static final class PendingTransition { + private final Snapshot snapshot; + private final boolean mayDispatchAccountAuthorization; + + private PendingTransition(Snapshot snapshot, boolean mayDispatchAccountAuthorization) { + this.snapshot = Objects.requireNonNull(snapshot, "snapshot is required"); + this.mayDispatchAccountAuthorization = mayDispatchAccountAuthorization; + if (snapshot.state() != State.AUTHORIZATION_PENDING && mayDispatchAccountAuthorization) { + throw new IllegalArgumentException("dispatch requires durable AUTHORIZATION_PENDING state"); + } + } + + public Snapshot snapshot() { + return snapshot; + } + + public boolean mayDispatchAccountAuthorization() { + return mayDispatchAccountAuthorization; + } + } + + public record RecoveryAcquisition(Snapshot snapshot, ClaimHandle claim) { + public RecoveryAcquisition { + Objects.requireNonNull(snapshot, "snapshot is required"); + Objects.requireNonNull(claim, "claim is required"); + if (snapshot.phase() != Phase.ACCOUNT_AUTHORIZATION + || snapshot.state() == State.OWNER_EXECUTION_PENDING + || snapshot.claimState() != ClaimState.ACTIVE + || claim.purpose == ClaimPurpose.ORIGINAL + || snapshot.claimPurpose() != claim.purpose + || snapshot.claimFence() != claim.fence + || !snapshot.tuple().canonicalJson().equals(claim.tuple.canonicalJson()) + || !snapshot.mutationDigest().equals(claim.mutationDigest)) { + throw new IllegalArgumentException("recovery claim is not a valid state-scoped claim"); + } + } + } + + public record ClaimEvidence( + UUID reservationOwnerId, + long reservationClaimFence, + UUID currentClaimOwnerId, + long currentClaimFence) { + public ClaimEvidence { + Objects.requireNonNull(reservationOwnerId, "reservationOwnerId is required"); + Objects.requireNonNull(currentClaimOwnerId, "currentClaimOwnerId is required"); + if (reservationClaimFence != 1 || currentClaimFence < reservationClaimFence) { + throw new IllegalArgumentException("reservation claim evidence is invalid"); + } + } + } + + public record CurrentClaimEvidence( + Snapshot snapshot, + UUID reservationOwnerId, + UUID currentClaimOwnerId, + ReadPurpose purpose, + long observedAtEpochMillis) { + public CurrentClaimEvidence { + Objects.requireNonNull(snapshot, "snapshot is required"); + Objects.requireNonNull(reservationOwnerId, "reservationOwnerId is required"); + Objects.requireNonNull(currentClaimOwnerId, "currentClaimOwnerId is required"); + Objects.requireNonNull(purpose, "purpose is required"); + if (observedAtEpochMillis <= 0L + || snapshot.claimExpiresAtEpochMillis() <= observedAtEpochMillis) { + throw new IllegalArgumentException("current claim evidence must be fresh and unexpired"); + } + } + } + + public static class IdempotencyConflictException extends RuntimeException { + public IdempotencyConflictException(String controlPlaneRequestId) { + super( + "controlPlaneRequestId is already bound to a different StartSession tuple: " + + controlPlaneRequestId); + } + } + + public static class StaleReservationClaimException extends RuntimeException { + public StaleReservationClaimException(String controlPlaneRequestId) { + super("StartSession reservation claim is stale: " + controlPlaneRequestId); + } + } + + public static class ReservationClaimNotExpiredException extends RuntimeException { + public ReservationClaimNotExpiredException(String controlPlaneRequestId) { + super("StartSession reservation claim has not expired: " + controlPlaneRequestId); + } + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTuple.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTuple.java new file mode 100644 index 0000000000..145f53b78d --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTuple.java @@ -0,0 +1,140 @@ +package net.firedevops.firemud.loggingadmin.operator; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.security.SessionContext; + +/** Logging/Admin authority wrapper around the shared immutable StartSession tuple value. */ +public final class StartSessionPreAuthorizationReservationTuple { + public static final String TUPLE_SCHEMA_ID = + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .TUPLE_SCHEMA_ID; + public static final String TUPLE_SCHEMA_VERSION = + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .TUPLE_SCHEMA_VERSION; + public static final int MAX_CONTROL_PLANE_REQUEST_ID_UTF8_BYTES = + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .MAX_CONTROL_PLANE_REQUEST_ID_UTF8_BYTES; + public static final int MAX_CANONICAL_TUPLE_UTF8_BYTES = 8 * 1_024; + + private final net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + value; + private final boolean authorityDerived; + + private StartSessionPreAuthorizationReservationTuple( + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple value, + boolean authorityDerived) { + this.value = Objects.requireNonNull(value, "tuple value is required"); + this.authorityDerived = authorityDerived; + } + + /** Builds the tuple from the current authenticated tenant-admin request context. */ + public static StartSessionPreAuthorizationReservationTuple fromCurrentTenantAdmin( + String controlPlaneRequestId, StartSessionOperatorAction action) { + Objects.requireNonNull(action, "action is required"); + if (SessionContext.isInternalService() || !SessionContext.hasAuthenticatedCallerContext()) { + throw new IllegalArgumentException("a human control-ui identity is required"); + } + String tenantId = action.scope().tenantId().toString(); + if (!SessionContext.getScopedRoles(tenantId).contains("tenantAdmin")) { + throw new IllegalArgumentException("tenantAdmin authority is required for the target tenant"); + } + UUID actorAccountId = requireCanonicalUuid(SessionContext.getAccountId(), "actor accountId"); + return new StartSessionPreAuthorizationReservationTuple( + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .createHuman(controlPlaneRequestId, actorAccountId, action), + true); + } + + /** Rehydrates only tuple contents; persisted bytes do not establish request authority. */ + public static StartSessionPreAuthorizationReservationTuple fromCanonicalJson(String json) { + return new StartSessionPreAuthorizationReservationTuple( + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .fromCanonicalJson(json), + false); + } + + public String actionFamily() { + return value.actionFamily(); + } + + public String controlPlaneRequestId() { + return value.controlPlaneRequestId(); + } + + public HumanActor actor() { + return new HumanActor(value.actor().accountId()); + } + + public NoAutomationPolicy automationPolicy() { + return NoAutomationPolicy.ABSENT; + } + + public StartSessionOperatorAction action() { + return value.action(); + } + + public boolean isAuthorityDerived() { + return authorityDerived; + } + + /** Validate a stable request key without silently normalizing or changing its identity. */ + public static String requireCanonicalControlPlaneRequestId(String value) { + return net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .requireCanonicalControlPlaneRequestId(value); + } + + public String targetOwner() { + return value.targetOwner(); + } + + /** Returns ADR 0047's digest over the seven action-schema grammar fields. */ + public String mutationDigest() { + return value.mutationDigest(); + } + + /** Returns the single shared canonical encoding for ADR 0048's typed tuple. */ + public String canonicalJson() { + return value.canonicalJson(); + } + + public record HumanActor(UUID accountId) { + public HumanActor { + Objects.requireNonNull(accountId, "actor accountId is required"); + if (accountId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("actor accountId must not be nil"); + } + } + } + + public enum NoAutomationPolicy { + ABSENT + } + + @Override + public boolean equals(Object other) { + return this == other + || other instanceof StartSessionPreAuthorizationReservationTuple that + && value.equals(that.value); + } + + @Override + public int hashCode() { + return value.hashCode(); + } + + private static UUID requireCanonicalUuid(String value, String fieldName) { + Objects.requireNonNull(value, fieldName + " is required"); + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException(fieldName + " must be a canonical UUID", exception); + } + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(fieldName + " must be a canonical non-nil UUID"); + } + return parsed; + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java new file mode 100644 index 0000000000..458ec5c22d --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java @@ -0,0 +1,977 @@ +package net.firedevops.firemud.loggingadmin.repository; + +import static net.firedevops.firemud.loggingadmin.jooq.tables.StartSessionPreAuthorizationReservations.START_SESSION_PRE_AUTHORIZATION_RESERVATIONS; + +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.loggingadmin.jooq.tables.StartSessionPreAuthorizationReservations; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.AuthorizedSnapshot; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimPurpose; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimState; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.OwnerExecutionHandoff; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Phase; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Snapshot; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.State; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationTuple; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.impl.DSL; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; + +/** jOOQ persistence for the single-key StartSession ADR 0048 reservation phase. */ +@Repository +public class StartSessionPreAuthorizationReservationRepository { + private static final StartSessionPreAuthorizationReservations TABLE = + START_SESSION_PRE_AUTHORIZATION_RESERVATIONS; + private static final Field POST_AUTHORIZATION_TUPLE_JSON = + DSL.field(DSL.name("post_authorization_execution_tuple_json"), String.class); + private static final Field OWNER_EXECUTION_HANDOFF_ID = + DSL.field(DSL.name("owner_execution_handoff_id"), UUID.class); + private static final Field CLAIM_PURPOSE = + DSL.field(DSL.name("claim_purpose"), String.class); + private static final Field[] FULL_ROW_FIELDS = { + TABLE.CONTROL_PLANE_REQUEST_ID, + TABLE.PRE_AUTHORIZATION_TUPLE_JSON, + TABLE.MUTATION_DIGEST, + TABLE.PHASE, + TABLE.STATE, + TABLE.RESERVATION_OWNER_ID, + TABLE.RESERVATION_CLAIM_FENCE, + TABLE.CLAIM_OWNER_ID, + TABLE.CLAIM_FENCE, + TABLE.CLAIM_EXPIRES_AT_EPOCH_MS, + TABLE.CLAIM_STATE, + TABLE.CREATED_AT_EPOCH_MS, + TABLE.UPDATED_AT_EPOCH_MS, + POST_AUTHORIZATION_TUPLE_JSON, + OWNER_EXECUTION_HANDOFF_ID, + CLAIM_PURPOSE + }; + + private final DSLContext dsl; + private final MutationCapability mutationCapability; + + @Autowired + public StartSessionPreAuthorizationReservationRepository(DSLContext dsl) { + this(dsl, null); + } + + private StartSessionPreAuthorizationReservationRepository( + DSLContext dsl, MutationCapability mutationCapability) { + this.dsl = dsl; + this.mutationCapability = mutationCapability; + } + + public AcquireResult acquire( + StartSessionPreAuthorizationReservationTuple tuple, + UUID ownerId, + long nowEpochMillis, + long expiresAtEpochMillis) { + requireMutationCapability(); + requireBoundedClaim(ownerId, nowEpochMillis, expiresAtEpochMillis); + if (!tuple.isAuthorityDerived()) { + throw new IllegalArgumentException( + "initial reservation requires an authority-derived StartSession tuple"); + } + String tupleJson = tuple.canonicalJson(); + String mutationDigest = tuple.mutationDigest(); + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + int inserted = + tx.insertInto(TABLE) + .set(TABLE.CONTROL_PLANE_REQUEST_ID, tuple.controlPlaneRequestId()) + .set(TABLE.PRE_AUTHORIZATION_TUPLE_JSON, tupleJson) + .set(TABLE.MUTATION_DIGEST, mutationDigest) + .set(TABLE.PHASE, Phase.ACCOUNT_AUTHORIZATION.name()) + .set(TABLE.STATE, State.RESERVED.name()) + .set(TABLE.RESERVATION_OWNER_ID, ownerId) + .set(TABLE.RESERVATION_CLAIM_FENCE, 1L) + .set(TABLE.CLAIM_OWNER_ID, ownerId) + .set(TABLE.CLAIM_FENCE, 1L) + .set(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS, expiresAtEpochMillis) + .set(TABLE.CLAIM_STATE, ClaimState.ACTIVE.name()) + .set(CLAIM_PURPOSE, ClaimPurpose.ORIGINAL.name()) + .set(TABLE.CREATED_AT_EPOCH_MS, nowEpochMillis) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .onConflict(TABLE.CONTROL_PLANE_REQUEST_ID) + .doNothing() + .execute(); + Record row = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); + if (row == null) { + throw new IllegalStateException("reservation row was not visible after acquire"); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + return new AcquireResult(snapshot, inserted == 1); + }); + } + + public Optional find(String controlPlaneRequestId) { + StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId( + controlPlaneRequestId); + Record row = selectFullRowByRequestId(dsl, controlPlaneRequestId, false); + return Optional.ofNullable(row).map(this::toSnapshot); + } + + public Optional findExact(StartSessionPreAuthorizationReservationTuple tuple) { + return find(tuple.controlPlaneRequestId()) + .map( + snapshot -> { + if (!snapshot.tuple().canonicalJson().equals(tuple.canonicalJson()) + || !snapshot.mutationDigest().equals(tuple.mutationDigest())) { + throw new StartSessionPreAuthorizationReservationService + .IdempotencyConflictException(tuple.controlPlaneRequestId()); + } + return snapshot; + }); + } + + /** Reads an exact, current Account-authorization claim without locking or changing the row. */ + public Optional readCurrentClaim( + StartSessionPreAuthorizationReservationTuple tuple, + UUID reservationOwnerId, + long reservationClaimFence, + UUID currentClaimOwnerId, + long currentClaimFence, + StartSessionPreAuthorizationReservationService.ReadPurpose purpose, + long observedAtEpochMillis) { + Objects.requireNonNull(tuple, "tuple is required"); + Objects.requireNonNull(purpose, "purpose is required"); + requireClaimOwner(currentClaimOwnerId, currentClaimFence, observedAtEpochMillis); + if (reservationOwnerId == null + || reservationOwnerId.equals(new UUID(0L, 0L)) + || reservationClaimFence <= 0L) { + throw new IllegalArgumentException("original reservation claim identity must be positive"); + } + + Record row = selectFullRowByRequestId(dsl, tuple.controlPlaneRequestId(), false); + if (row == null) { + return Optional.empty(); + } + + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, tuple.mutationDigest()); + UUID storedReservationOwnerId = row.get(TABLE.RESERVATION_OWNER_ID); + UUID storedClaimOwnerId = row.get(TABLE.CLAIM_OWNER_ID); + boolean exactCurrentClaim = + reservationOwnerId.equals(storedReservationOwnerId) + && reservationClaimFence == snapshot.reservationClaimFence() + && currentClaimOwnerId.equals(storedClaimOwnerId) + && currentClaimFence == snapshot.claimFence() + && snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION + && snapshot.claimState() == ClaimState.ACTIVE + && snapshot.claimExpiresAtEpochMillis() > observedAtEpochMillis + && StartSessionPreAuthorizationReservationService.claimPurposeAllowsRead( + snapshot, purpose, reservationOwnerId, currentClaimOwnerId); + if (!exactCurrentClaim) { + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + } + if (purpose == StartSessionPreAuthorizationReservationService.ReadPurpose.RECOVER + && snapshot.state() == State.AUTHORIZED) { + toAuthorizedSnapshot(row); + } + return Optional.of( + new CurrentClaimResult(snapshot, storedReservationOwnerId, storedClaimOwnerId)); + } + + public TransitionResult markAuthorizationPending( + StartSessionPreAuthorizationReservationTuple tuple, + String mutationDigest, + UUID reservationOwnerId, + long reservationClaimFence, + UUID currentClaimOwnerId, + long currentClaimFence, + long nowEpochMillis) { + requireMutationCapability(); + requireCurrentClaimIdentity( + reservationOwnerId, + reservationClaimFence, + currentClaimOwnerId, + currentClaimFence, + nowEpochMillis); + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + int updated = + tx.update(TABLE) + .set(TABLE.STATE, State.AUTHORIZATION_PENDING.name()) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) + .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) + .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) + .and(TABLE.PHASE.eq(Phase.ACCOUNT_AUTHORIZATION.name())) + .and(TABLE.STATE.eq(State.RESERVED.name())) + .and(TABLE.RESERVATION_OWNER_ID.eq(reservationOwnerId)) + .and(TABLE.RESERVATION_CLAIM_FENCE.eq(reservationClaimFence)) + .and(TABLE.CLAIM_OWNER_ID.eq(currentClaimOwnerId)) + .and(TABLE.CLAIM_FENCE.eq(currentClaimFence)) + .and(TABLE.CLAIM_STATE.eq(ClaimState.ACTIVE.name())) + .and( + CLAIM_PURPOSE.in( + ClaimPurpose.ORIGINAL.name(), + ClaimPurpose.RESERVED_RECOVERY_ISSUE.name())) + .and(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.gt(nowEpochMillis)) + .execute(); + Record row = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); + if (row == null) { + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + if (updated == 1) { + return new TransitionResult(snapshot, true); + } + if (isCurrentClaim(row, currentClaimOwnerId, currentClaimFence, nowEpochMillis) + && snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION + && snapshot.state() == State.AUTHORIZATION_PENDING + && isIssueClaimPurpose(snapshot.claimPurpose())) { + return new TransitionResult(snapshot, false); + } + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + }); + } + + /** Original-claim overload retained for focused repository tests and original callers. */ + public TransitionResult markAuthorizationPending( + StartSessionPreAuthorizationReservationTuple tuple, + String mutationDigest, + UUID ownerId, + long claimFence, + long nowEpochMillis) { + requireMutationCapability(); + return markAuthorizationPending( + tuple, mutationDigest, ownerId, claimFence, ownerId, claimFence, nowEpochMillis); + } + + /** + * Atomically stores Account's full post-authorization identity on the exact live claim. The + * post-tuple is structural evidence only and contains no opaque authorization reference. + */ + public AuthorizationTransitionResult completeAuthorization( + StartSessionPreAuthorizationReservationTuple tuple, + String mutationDigest, + UUID reservationOwnerId, + long reservationClaimFence, + UUID currentClaimOwnerId, + long currentClaimFence, + String postAuthorizationTupleJson, + long nowEpochMillis) { + requireMutationCapability(); + requireCurrentClaimIdentity( + reservationOwnerId, + reservationClaimFence, + currentClaimOwnerId, + currentClaimFence, + nowEpochMillis); + Objects.requireNonNull(tuple, "tuple is required"); + StartSessionPostAuthorizationExecutionTuple postTuple = + decodePostAuthorizationTuple(postAuthorizationTupleJson); + requirePostTupleBinding( + tuple, mutationDigest, reservationOwnerId, reservationClaimFence, postTuple); + if (StartSessionAuthorityEvidenceBundle.decode(postTuple.authorityEvidenceBundleBytes()) + .expiresAt() + .toEpochMilli() + <= nowEpochMillis) { + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + } + + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + Record row = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); + if (row == null) { + throw stale(tuple); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + requireExactLiveClaim( + row, + snapshot, + reservationOwnerId, + reservationClaimFence, + currentClaimOwnerId, + currentClaimFence, + nowEpochMillis); + + if (snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION + && snapshot.state() == State.AUTHORIZATION_PENDING) { + if (!isPendingAuthorizationClaimPurpose(snapshot.claimPurpose())) { + throw stale(tuple); + } + int updated = + tx.update(TABLE) + .set(TABLE.STATE, State.AUTHORIZED.name()) + .set(POST_AUTHORIZATION_TUPLE_JSON, postAuthorizationTupleJson) + .set(OWNER_EXECUTION_HANDOFF_ID, (UUID) null) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) + .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) + .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) + .and(TABLE.PHASE.eq(Phase.ACCOUNT_AUTHORIZATION.name())) + .and(TABLE.STATE.eq(State.AUTHORIZATION_PENDING.name())) + .and(TABLE.RESERVATION_OWNER_ID.eq(reservationOwnerId)) + .and(TABLE.RESERVATION_CLAIM_FENCE.eq(reservationClaimFence)) + .and(TABLE.CLAIM_OWNER_ID.eq(currentClaimOwnerId)) + .and(TABLE.CLAIM_FENCE.eq(currentClaimFence)) + .and(TABLE.CLAIM_STATE.eq(ClaimState.ACTIVE.name())) + .and(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.gt(nowEpochMillis)) + .and(POST_AUTHORIZATION_TUPLE_JSON.isNull()) + .execute(); + if (updated != 1) { + throw stale(tuple); + } + return new AuthorizationTransitionResult( + toAuthorizedSnapshot( + selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true)), + true); + } + + if ((snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION + && snapshot.state() == State.AUTHORIZED) + || (snapshot.phase() == Phase.OWNER_EXECUTION + && snapshot.state() == State.OWNER_EXECUTION_PENDING)) { + if (snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION + && !isAuthorizedResponseClaimPurpose(snapshot.claimPurpose())) { + throw stale(tuple); + } + String persistedTuple = row.get(POST_AUTHORIZATION_TUPLE_JSON); + if (!postAuthorizationTupleJson.equals(persistedTuple)) { + throw conflict(tuple); + } + return new AuthorizationTransitionResult(toAuthorizedSnapshot(row), false); + } + throw stale(tuple); + }); + } + + /** + * Atomically records the immutable owner handoff. A duplicate exact observation never grants a + * second dispatch; the first successful AUTHORIZED-to-pending transition does. + */ + public OwnerExecutionTransitionResult beginOwnerExecution( + StartSessionPreAuthorizationReservationTuple tuple, + String mutationDigest, + UUID reservationOwnerId, + long reservationClaimFence, + UUID currentClaimOwnerId, + long currentClaimFence, + String postAuthorizationTupleJson, + UUID handoffId, + long nowEpochMillis) { + requireMutationCapability(); + requireCurrentClaimIdentity( + reservationOwnerId, + reservationClaimFence, + currentClaimOwnerId, + currentClaimFence, + nowEpochMillis); + requireNonNil(handoffId, "handoffId"); + Objects.requireNonNull(tuple, "tuple is required"); + StartSessionPostAuthorizationExecutionTuple postTuple = + decodePostAuthorizationTuple(postAuthorizationTupleJson); + requirePostTupleBinding( + tuple, mutationDigest, reservationOwnerId, reservationClaimFence, postTuple); + if (StartSessionAuthorityEvidenceBundle.decode(postTuple.authorityEvidenceBundleBytes()) + .expiresAt() + .toEpochMilli() + <= nowEpochMillis) { + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + } + + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + Record row = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); + if (row == null) { + throw stale(tuple); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + requireExactLiveClaim( + row, + snapshot, + reservationOwnerId, + reservationClaimFence, + currentClaimOwnerId, + currentClaimFence, + nowEpochMillis); + boolean mayBeginOwnerExecution = + snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION + && snapshot.state() == State.AUTHORIZED; + boolean mayReplayOwnerExecution = + snapshot.phase() == Phase.OWNER_EXECUTION + && snapshot.state() == State.OWNER_EXECUTION_PENDING; + if (!mayBeginOwnerExecution && !mayReplayOwnerExecution) { + throw stale(tuple); + } + if (mayBeginOwnerExecution && !isOwnerHandoffClaimPurpose(snapshot.claimPurpose())) { + throw stale(tuple); + } + String persistedTuple = row.get(POST_AUTHORIZATION_TUPLE_JSON); + if (!postAuthorizationTupleJson.equals(persistedTuple)) { + throw conflict(tuple); + } + + if (mayBeginOwnerExecution) { + int updated = + tx.update(TABLE) + .set(TABLE.PHASE, Phase.OWNER_EXECUTION.name()) + .set(TABLE.STATE, State.OWNER_EXECUTION_PENDING.name()) + .set(OWNER_EXECUTION_HANDOFF_ID, handoffId) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) + .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) + .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) + .and(TABLE.PHASE.eq(Phase.ACCOUNT_AUTHORIZATION.name())) + .and(TABLE.STATE.eq(State.AUTHORIZED.name())) + .and(TABLE.RESERVATION_OWNER_ID.eq(reservationOwnerId)) + .and(TABLE.RESERVATION_CLAIM_FENCE.eq(reservationClaimFence)) + .and(TABLE.CLAIM_OWNER_ID.eq(currentClaimOwnerId)) + .and(TABLE.CLAIM_FENCE.eq(currentClaimFence)) + .and(TABLE.CLAIM_STATE.eq(ClaimState.ACTIVE.name())) + .and(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.gt(nowEpochMillis)) + .and(POST_AUTHORIZATION_TUPLE_JSON.eq(postAuthorizationTupleJson)) + .and(OWNER_EXECUTION_HANDOFF_ID.isNull()) + .execute(); + if (updated != 1) { + throw stale(tuple); + } + return new OwnerExecutionTransitionResult( + toAuthorizedSnapshot( + selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true)), + true); + } + + if (mayReplayOwnerExecution) { + if (!handoffId.equals(row.get(OWNER_EXECUTION_HANDOFF_ID))) { + throw conflict(tuple); + } + return new OwnerExecutionTransitionResult(toAuthorizedSnapshot(row), false); + } + throw stale(tuple); + }); + } + + /** Read-only storage snapshot of the exact full post-authorization tuple and any handoff. */ + public Optional findAuthorizedExact( + StartSessionPreAuthorizationReservationTuple tuple) { + Objects.requireNonNull(tuple, "tuple is required"); + Record row = selectFullRowByRequestId(dsl, tuple.controlPlaneRequestId(), false); + if (row == null) { + return Optional.empty(); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, tuple.mutationDigest()); + if (snapshot.state() != State.AUTHORIZED && snapshot.state() != State.OWNER_EXECUTION_PENDING) { + return Optional.empty(); + } + return Optional.of(toAuthorizedSnapshot(row)); + } + + public Snapshot renew( + StartSessionPreAuthorizationReservationTuple tuple, + String mutationDigest, + UUID ownerId, + long claimFence, + Phase expectedPhase, + State expectedState, + long nowEpochMillis, + long expiresAtEpochMillis) { + requireMutationCapability(); + requireClaimOwner(ownerId, claimFence, nowEpochMillis); + Objects.requireNonNull(expectedPhase, "expectedPhase is required"); + Objects.requireNonNull(expectedState, "expectedState is required"); + requireBoundedClaim(ownerId, nowEpochMillis, expiresAtEpochMillis); + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + int updated = + tx.update(TABLE) + .set(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS, expiresAtEpochMillis) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) + .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) + .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) + .and(TABLE.PHASE.eq(expectedPhase.name())) + .and(TABLE.STATE.eq(expectedState.name())) + .and(TABLE.CLAIM_OWNER_ID.eq(ownerId)) + .and(TABLE.CLAIM_FENCE.eq(claimFence)) + .and(TABLE.CLAIM_STATE.eq(ClaimState.ACTIVE.name())) + .and(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.gt(nowEpochMillis)) + .execute(); + Record row = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); + if (row == null) { + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + if (updated != 1) { + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + } + return snapshot; + }); + } + + public Snapshot expireClaim( + StartSessionPreAuthorizationReservationTuple tuple, + String mutationDigest, + UUID ownerId, + long claimFence, + Phase expectedPhase, + State expectedState, + long nowEpochMillis) { + requireMutationCapability(); + requireClaimOwner(ownerId, claimFence, nowEpochMillis); + Objects.requireNonNull(expectedPhase, "expectedPhase is required"); + Objects.requireNonNull(expectedState, "expectedState is required"); + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + int updated = + tx.update(TABLE) + .setNull(TABLE.CLAIM_OWNER_ID) + .set(TABLE.CLAIM_FENCE, TABLE.CLAIM_FENCE.add(1L)) + .set(TABLE.CLAIM_STATE, ClaimState.EXPIRED.name()) + .set(CLAIM_PURPOSE, (String) null) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) + .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) + .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) + .and(TABLE.PHASE.eq(expectedPhase.name())) + .and(TABLE.STATE.eq(expectedState.name())) + .and(TABLE.CLAIM_OWNER_ID.eq(ownerId)) + .and(TABLE.CLAIM_FENCE.eq(claimFence)) + .and(TABLE.CLAIM_STATE.eq(ClaimState.ACTIVE.name())) + .and(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.le(nowEpochMillis)) + .execute(); + Record row = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); + if (row == null) { + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + if (updated == 1) { + return snapshot; + } + if (isCurrentClaim(row, ownerId, claimFence, nowEpochMillis)) { + throw new StartSessionPreAuthorizationReservationService + .ReservationClaimNotExpiredException(tuple.controlPlaneRequestId()); + } + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + }); + } + + public Optional acquireRecoveryClaim( + StartSessionPreAuthorizationReservationTuple tuple, + UUID recoveryOwnerId, + long nowEpochMillis, + long expiresAtEpochMillis) { + requireMutationCapability(); + requireBoundedClaim(recoveryOwnerId, nowEpochMillis, expiresAtEpochMillis); + String mutationDigest = tuple.mutationDigest(); + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + Record row = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); + if (row == null) { + return Optional.empty(); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + ClaimPurpose recoveryPurpose = recoveryPurpose(snapshot.phase(), snapshot.state()); + if (recoveryPurpose == null) { + return Optional.empty(); + } + UUID reservationOwnerId = row.get(TABLE.RESERVATION_OWNER_ID); + UUID previousOwnerId = row.get(TABLE.CLAIM_OWNER_ID); + String previousClaimState = row.get(TABLE.CLAIM_STATE); + long previousFence = row.get(TABLE.CLAIM_FENCE); + long previousExpiry = row.get(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS); + if (!ClaimState.EXPIRED.name().equals(previousClaimState) + && !(ClaimState.ACTIVE.name().equals(previousClaimState) + && previousExpiry <= nowEpochMillis)) { + return Optional.empty(); + } + if (reservationOwnerId.equals(recoveryOwnerId) + || recoveryOwnerId.equals(previousOwnerId)) { + return Optional.empty(); + } + if (snapshot.state() == State.AUTHORIZED) { + toAuthorizedSnapshot(row); + } + long recoveryFence = Math.addExact(previousFence, 1L); + int updated = + tx.update(TABLE) + .set(TABLE.CLAIM_OWNER_ID, recoveryOwnerId) + .set(TABLE.CLAIM_FENCE, recoveryFence) + .set(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS, expiresAtEpochMillis) + .set(TABLE.CLAIM_STATE, ClaimState.ACTIVE.name()) + .set(CLAIM_PURPOSE, recoveryPurpose.name()) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) + .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) + .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) + .and(TABLE.PHASE.eq(Phase.ACCOUNT_AUTHORIZATION.name())) + .and(TABLE.STATE.eq(snapshot.state().name())) + .and(TABLE.CLAIM_FENCE.eq(previousFence)) + .and(TABLE.CLAIM_STATE.eq(previousClaimState)) + .and( + previousOwnerId == null + ? TABLE.CLAIM_OWNER_ID.isNull() + : TABLE.CLAIM_OWNER_ID.eq(previousOwnerId)) + .and( + snapshot.claimPurpose() == null + ? CLAIM_PURPOSE.isNull() + : CLAIM_PURPOSE.eq(snapshot.claimPurpose().name())) + .and( + ClaimState.EXPIRED.name().equals(previousClaimState) + ? DSL.trueCondition() + : TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.le(nowEpochMillis)) + .execute(); + if (updated != 1) { + return Optional.empty(); + } + Record updatedRow = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); + if (updatedRow == null) { + throw new IllegalStateException("recovery claim row disappeared after update"); + } + return Optional.of(new RecoveryClaimResult(toSnapshot(updatedRow), reservationOwnerId)); + }); + } + + private StartSessionPostAuthorizationExecutionTuple decodePostAuthorizationTuple(String json) { + if (json == null || json.isEmpty()) { + throw new IllegalArgumentException("post-authorization tuple is required"); + } + StartSessionPostAuthorizationExecutionTuple decoded = + StartSessionPostAuthorizationExecutionTuple.decode(json.getBytes(StandardCharsets.UTF_8)); + if (!decoded.canonicalJson().equals(json)) { + throw new IllegalArgumentException("post-authorization tuple must be canonical JSON"); + } + return decoded; + } + + private void requirePostTupleBinding( + StartSessionPreAuthorizationReservationTuple tuple, + String mutationDigest, + UUID reservationOwnerId, + long reservationClaimFence, + StartSessionPostAuthorizationExecutionTuple postTuple) { + if (!tuple.controlPlaneRequestId().equals(postTuple.controlPlaneRequestId()) + || !tuple.canonicalJson().equals(postTuple.preAuthorizationTuple().canonicalJson()) + || !tuple.mutationDigest().equals(mutationDigest) + || !postTuple.mutationDigest().equals(mutationDigest) + || !reservationOwnerId.equals(postTuple.reservationOwnerId()) + || reservationClaimFence != postTuple.reservationClaimFence()) { + throw conflict(tuple); + } + } + + private static ClaimPurpose recoveryPurpose(Phase phase, State state) { + if (phase != Phase.ACCOUNT_AUTHORIZATION) { + return null; + } + return switch (state) { + case RESERVED -> ClaimPurpose.RESERVED_RECOVERY_ISSUE; + case AUTHORIZATION_PENDING -> ClaimPurpose.AUTHORIZATION_RECOVERY; + case AUTHORIZED -> ClaimPurpose.AUTHORIZED_RESPONSE_RECOVERY; + case OWNER_EXECUTION_PENDING -> null; + }; + } + + private static boolean isIssueClaimPurpose(ClaimPurpose purpose) { + return purpose == ClaimPurpose.ORIGINAL || purpose == ClaimPurpose.RESERVED_RECOVERY_ISSUE; + } + + private static boolean isPendingAuthorizationClaimPurpose(ClaimPurpose purpose) { + return purpose == ClaimPurpose.ORIGINAL + || purpose == ClaimPurpose.RESERVED_RECOVERY_ISSUE + || purpose == ClaimPurpose.AUTHORIZATION_RECOVERY; + } + + private static boolean isAuthorizedResponseClaimPurpose(ClaimPurpose purpose) { + return purpose == ClaimPurpose.ORIGINAL + || purpose == ClaimPurpose.RESERVED_RECOVERY_ISSUE + || purpose == ClaimPurpose.AUTHORIZATION_RECOVERY + || purpose == ClaimPurpose.AUTHORIZED_RESPONSE_RECOVERY; + } + + private static boolean isOwnerHandoffClaimPurpose(ClaimPurpose purpose) { + return isAuthorizedResponseClaimPurpose(purpose); + } + + private void requireCurrentClaimIdentity( + UUID reservationOwnerId, + long reservationClaimFence, + UUID currentClaimOwnerId, + long currentClaimFence, + long nowEpochMillis) { + requireNonNil(reservationOwnerId, "reservationOwnerId"); + requireNonNil(currentClaimOwnerId, "currentClaimOwnerId"); + if (reservationClaimFence <= 0L + || currentClaimFence < reservationClaimFence + || nowEpochMillis <= 0L) { + throw new IllegalArgumentException("reservation owner claim identity must be positive"); + } + } + + private void requireExactLiveClaim( + Record row, + Snapshot snapshot, + UUID reservationOwnerId, + long reservationClaimFence, + UUID currentClaimOwnerId, + long currentClaimFence, + long nowEpochMillis) { + if (!reservationOwnerId.equals(row.get(TABLE.RESERVATION_OWNER_ID)) + || reservationClaimFence != snapshot.reservationClaimFence() + || !currentClaimOwnerId.equals(row.get(TABLE.CLAIM_OWNER_ID)) + || currentClaimFence != snapshot.claimFence() + || snapshot.claimState() != ClaimState.ACTIVE + || snapshot.claimExpiresAtEpochMillis() <= nowEpochMillis) { + throw stale(snapshot.tuple()); + } + } + + private AuthorizedSnapshot toAuthorizedSnapshot(Record row) { + if (row == null) { + throw new IllegalStateException( + "StartSession row disappeared after post-authorization write"); + } + Snapshot snapshot = toSnapshot(row); + String storedTuple = row.get(POST_AUTHORIZATION_TUPLE_JSON); + if (storedTuple == null) { + throw new IllegalStateException("authorized StartSession row is missing its post-tuple"); + } + StartSessionPostAuthorizationExecutionTuple postTuple; + try { + postTuple = decodePostAuthorizationTuple(storedTuple); + } catch (RuntimeException malformed) { + throw new IllegalStateException("stored StartSession post-authorization tuple is malformed"); + } + if (!snapshot.tuple().canonicalJson().equals(postTuple.preAuthorizationTuple().canonicalJson()) + || !snapshot.mutationDigest().equals(postTuple.mutationDigest()) + || !row.get(TABLE.RESERVATION_OWNER_ID).equals(postTuple.reservationOwnerId()) + || snapshot.reservationClaimFence() != postTuple.reservationClaimFence()) { + throw new IllegalStateException("stored StartSession post-tuple binding is inconsistent"); + } + + UUID handoffId = row.get(OWNER_EXECUTION_HANDOFF_ID); + OwnerExecutionHandoff handoff = null; + if (snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION && snapshot.state() == State.AUTHORIZED) { + if (handoffId != null) { + throw new IllegalStateException("authorized StartSession row has premature handoff fields"); + } + } else if (snapshot.phase() == Phase.OWNER_EXECUTION + && snapshot.state() == State.OWNER_EXECUTION_PENDING) { + if (handoffId == null) { + throw new IllegalStateException("owner-pending StartSession row is missing handoff fields"); + } + try { + handoff = new OwnerExecutionHandoff(handoffId); + } catch (RuntimeException malformed) { + throw new IllegalStateException("stored StartSession owner handoff is malformed"); + } + } else { + throw new IllegalStateException("StartSession row is not in a post-authorization state"); + } + return new AuthorizedSnapshot( + snapshot, + postTuple, + row.get(TABLE.RESERVATION_OWNER_ID), + row.get(TABLE.CLAIM_OWNER_ID), + handoff); + } + + private Record selectFullRowByRequestId( + DSLContext context, String controlPlaneRequestId, boolean forUpdate) { + var query = + context + .select(FULL_ROW_FIELDS) + .from(TABLE) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(controlPlaneRequestId)); + return forUpdate ? query.forUpdate().fetchOne() : query.fetchOne(); + } + + private static void requireNonNil(UUID value, String fieldName) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(fieldName + " must be a non-nil UUID"); + } + } + + private static StartSessionPreAuthorizationReservationService.StaleReservationClaimException + stale(StartSessionPreAuthorizationReservationTuple tuple) { + return new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + } + + private static StartSessionPreAuthorizationReservationService.IdempotencyConflictException + conflict(StartSessionPreAuthorizationReservationTuple tuple) { + return new StartSessionPreAuthorizationReservationService.IdempotencyConflictException( + tuple.controlPlaneRequestId()); + } + + private void requireMutationCapability() { + if (mutationCapability == null) { + throw new UnsupportedOperationException( + "StartSession reservation writes are disabled for production construction"); + } + } + + private static final class MutationCapability { + private MutationCapability() {} + } + + private void requireBoundedClaim(UUID ownerId, long nowEpochMillis, long expiresAtEpochMillis) { + requireClaimOwner(ownerId, 1L, nowEpochMillis); + if (expiresAtEpochMillis <= nowEpochMillis + || expiresAtEpochMillis - nowEpochMillis + > StartSessionPreAuthorizationReservationService.CLAIM_TTL.toMillis()) { + throw new IllegalArgumentException("reservation claim must have a bounded positive expiry"); + } + } + + private void requireClaimOwner(UUID ownerId, long claimFence, long nowEpochMillis) { + if (ownerId == null + || ownerId.equals(new UUID(0L, 0L)) + || claimFence <= 0L + || nowEpochMillis <= 0L) { + throw new IllegalArgumentException("reservation claim identity and time must be positive"); + } + } + + private Snapshot toSnapshot(Record row) { + String requestId = row.get(TABLE.CONTROL_PLANE_REQUEST_ID); + String tupleJson = row.get(TABLE.PRE_AUTHORIZATION_TUPLE_JSON); + String storedDigest = row.get(TABLE.MUTATION_DIGEST); + StartSessionPreAuthorizationReservationTuple tuple; + try { + tuple = StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(tupleJson); + } catch (RuntimeException exception) { + throw new IllegalStateException( + "stored StartSession pre-authorization tuple is malformed for " + requestId, exception); + } + if (!requestId.equals(tuple.controlPlaneRequestId())) { + throw new IllegalStateException( + "stored StartSession tuple key does not match reservation key " + requestId); + } + String recomputedDigest = tuple.mutationDigest(); + if (!recomputedDigest.equals(storedDigest)) { + throw new IllegalStateException( + "stored StartSession mutationDigest does not match its full tuple for " + requestId); + } + Phase phase = enumValue(Phase.class, row.get(TABLE.PHASE), "phase", requestId); + State state = enumValue(State.class, row.get(TABLE.STATE), "state", requestId); + ClaimState claimState = + enumValue(ClaimState.class, row.get(TABLE.CLAIM_STATE), "claimState", requestId); + String storedClaimPurpose = row.get(CLAIM_PURPOSE); + ClaimPurpose claimPurpose = + storedClaimPurpose == null + ? null + : enumValue(ClaimPurpose.class, storedClaimPurpose, "claimPurpose", requestId); + UUID reservationOwnerId = row.get(TABLE.RESERVATION_OWNER_ID); + UUID currentClaimOwnerId = row.get(TABLE.CLAIM_OWNER_ID); + long originalFence = row.get(TABLE.RESERVATION_CLAIM_FENCE); + long currentFence = row.get(TABLE.CLAIM_FENCE); + long createdAt = row.get(TABLE.CREATED_AT_EPOCH_MS); + long updatedAt = row.get(TABLE.UPDATED_AT_EPOCH_MS); + boolean supportedPhaseState = + (phase == Phase.ACCOUNT_AUTHORIZATION + && (state == State.RESERVED + || state == State.AUTHORIZATION_PENDING + || state == State.AUTHORIZED)) + || (phase == Phase.OWNER_EXECUTION && state == State.OWNER_EXECUTION_PENDING); + if (!supportedPhaseState + || reservationOwnerId == null + || reservationOwnerId.equals(new UUID(0L, 0L)) + || originalFence != 1L + || currentFence < originalFence + || createdAt <= 0L + || updatedAt <= 0L + || (claimState == ClaimState.ACTIVE + && (currentClaimOwnerId == null + || currentClaimOwnerId.equals(new UUID(0L, 0L)) + || claimPurpose == null + || (claimPurpose == ClaimPurpose.ORIGINAL + && (!reservationOwnerId.equals(currentClaimOwnerId) + || currentFence != originalFence)) + || (claimPurpose != ClaimPurpose.ORIGINAL + && (reservationOwnerId.equals(currentClaimOwnerId) + || currentFence <= originalFence)))) + || (claimState == ClaimState.EXPIRED + && (currentClaimOwnerId != null + || currentFence <= originalFence + || claimPurpose != null))) { + throw new IllegalStateException("stored StartSession reservation lifecycle is malformed"); + } + return new Snapshot( + tuple, + storedDigest, + phase, + state, + originalFence, + currentFence, + row.get(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS), + claimState, + claimPurpose); + } + + private void requireExactTuple( + Record row, StartSessionPreAuthorizationReservationTuple tuple, String mutationDigest) { + if (!tuple.controlPlaneRequestId().equals(row.get(TABLE.CONTROL_PLANE_REQUEST_ID)) + || !tuple.canonicalJson().equals(row.get(TABLE.PRE_AUTHORIZATION_TUPLE_JSON)) + || !tuple.mutationDigest().equals(mutationDigest) + || !mutationDigest.equals(row.get(TABLE.MUTATION_DIGEST))) { + throw new StartSessionPreAuthorizationReservationService.IdempotencyConflictException( + tuple.controlPlaneRequestId()); + } + } + + private boolean isCurrentClaim(Record row, UUID ownerId, long claimFence, long nowEpochMillis) { + return ownerId.equals(row.get(TABLE.CLAIM_OWNER_ID)) + && claimFence == row.get(TABLE.CLAIM_FENCE) + && ClaimState.ACTIVE.name().equals(row.get(TABLE.CLAIM_STATE)) + && row.get(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS) > nowEpochMillis; + } + + private > T enumValue( + Class enumClass, String value, String fieldName, String requestId) { + try { + return Enum.valueOf(enumClass, value); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "stored StartSession reservation " + fieldName + " is invalid for " + requestId, + exception); + } + } + + public record AcquireResult(Snapshot snapshot, boolean created) {} + + public record TransitionResult(Snapshot snapshot, boolean transitioned) {} + + public record AuthorizationTransitionResult(AuthorizedSnapshot snapshot, boolean transitioned) {} + + public record OwnerExecutionTransitionResult(AuthorizedSnapshot snapshot, boolean mayDispatch) {} + + public record RecoveryClaimResult(Snapshot snapshot, UUID reservationOwnerId) {} + + public record CurrentClaimResult( + Snapshot snapshot, UUID reservationOwnerId, UUID currentClaimOwnerId) {} +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceGrpcService.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceGrpcService.java new file mode 100644 index 0000000000..0c785a911a --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceGrpcService.java @@ -0,0 +1,265 @@ +package net.firedevops.firemud.loggingadmin.service.impl; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.sql.SQLTransientException; +import java.util.Arrays; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.CurrentClaimEvidence; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ReadPurpose; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceRequest; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidenceServiceGrpc; +import org.jooq.exception.DataAccessException; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.TransientDataAccessException; +import org.springframework.grpc.server.service.GrpcService; + +/** Read-only Account handoff for the exact current StartSession reservation claim. */ +@GrpcService +public class StartSessionReservationEvidenceGrpcService + extends StartSessionReservationEvidenceServiceGrpc + .StartSessionReservationEvidenceServiceImplBase { + private final StartSessionPreAuthorizationReservationService reservationService; + private final StartSessionReservationEvidenceLeafApproval leafApproval; + private final String workloadNamespace; + + public StartSessionReservationEvidenceGrpcService( + StartSessionPreAuthorizationReservationService reservationService, + StartSessionReservationEvidenceLeafApproval leafApproval, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this.reservationService = reservationService; + this.leafApproval = leafApproval; + this.workloadNamespace = workloadNamespace; + } + + @Override + public void readCurrentClaimEvidence( + ReadCurrentClaimEvidenceRequest request, + StreamObserver responseObserver) { + if (SessionContext.hasAuthenticatedCallerContext() + || !isAccountPeer() + || !leafApproval.isApproved(GrpcPeerCertificateEvidence.current())) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Verified same-namespace Account workload identity without caller context is required"); + return; + } + + ParsedRequest parsed; + try { + parsed = parseRequest(request); + } catch (IllegalArgumentException exception) { + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "Canonical StartSession reservation claim evidence is required"); + return; + } + + Optional current; + try { + current = + reservationService.readCurrentClaimEvidence( + parsed.controlPlaneRequestId(), + parsed.tuple(), + parsed.reservationOwnerId(), + parsed.reservationClaimFence(), + parsed.claimOwnerId(), + parsed.claimFence(), + parsed.purpose()); + } catch (IllegalArgumentException exception) { + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "StartSession reservation claim evidence is invalid"); + return; + } catch (StartSessionPreAuthorizationReservationService.IdempotencyConflictException + | StartSessionPreAuthorizationReservationService.StaleReservationClaimException exception) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "The exact active StartSession reservation claim is unavailable"); + return; + } catch (DataAccessResourceFailureException | TransientDataAccessException exception) { + fail( + responseObserver, + Status.UNAVAILABLE, + "StartSession reservation evidence is temporarily unavailable"); + return; + } catch (DataAccessException exception) { + boolean unavailable = isTransientDatabaseFailure(exception); + fail( + responseObserver, + unavailable ? Status.UNAVAILABLE : Status.INTERNAL, + unavailable + ? "StartSession reservation evidence is temporarily unavailable" + : "StartSession reservation evidence could not be read"); + return; + } catch (RuntimeException exception) { + fail( + responseObserver, Status.INTERNAL, "StartSession reservation evidence could not be read"); + return; + } + + if (current.isEmpty()) { + fail( + responseObserver, + Status.NOT_FOUND, + "No StartSession reservation exists for the exact request ID"); + return; + } + + CurrentClaimEvidence evidence = current.orElseThrow(); + var snapshot = evidence.snapshot(); + ReadCurrentClaimEvidenceResponse response = + ReadCurrentClaimEvidenceResponse.newBuilder() + .setControlPlaneRequestId(snapshot.tuple().controlPlaneRequestId()) + .setPreAuthorizationTupleJson( + com.google.protobuf.ByteString.copyFrom( + snapshot.tuple().canonicalJson().getBytes(StandardCharsets.UTF_8))) + .setMutationDigest(snapshot.mutationDigest()) + .setReservationOwnerId(evidence.reservationOwnerId().toString()) + .setReservationClaimFence(snapshot.reservationClaimFence()) + .setClaimOwnerId(evidence.currentClaimOwnerId().toString()) + .setClaimFence(snapshot.claimFence()) + .setClaimExpiresAtEpochMillis(snapshot.claimExpiresAtEpochMillis()) + .setObservedAtEpochMillis(evidence.observedAtEpochMillis()) + .setPurpose(toWirePurpose(evidence.purpose())) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + private static boolean isTransientDatabaseFailure(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLTransientException) { + return true; + } + if (cause instanceof SQLException sqlException) { + String sqlState = sqlException.getSQLState(); + if (sqlState != null && sqlState.startsWith("08")) { + return true; + } + } + } + return false; + } + + private ParsedRequest parseRequest(ReadCurrentClaimEvidenceRequest request) { + if (!request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("unknown request fields are not supported"); + } + String requestId = + StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId( + request.getControlPlaneRequestId()); + UUID reservationOwnerId = parseCanonicalNonNilUuid(request.getReservationOwnerId()); + UUID claimOwnerId = parseCanonicalNonNilUuid(request.getClaimOwnerId()); + long reservationClaimFence = request.getReservationClaimFence(); + long claimFence = request.getClaimFence(); + if (reservationOwnerId == null + || claimOwnerId == null + || reservationClaimFence <= 0L + || claimFence <= 0L + || request.getPreAuthorizationTupleJson().isEmpty() + || request.getPreAuthorizationTupleJson().size() + > StartSessionPreAuthorizationReservationTuple.MAX_CANONICAL_TUPLE_UTF8_BYTES) { + throw new IllegalArgumentException("reservation claim identity is malformed"); + } + + byte[] tupleBytes = request.getPreAuthorizationTupleJson().toByteArray(); + String tupleJson = decodeStrictUtf8(tupleBytes); + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(tupleJson); + if (!Arrays.equals(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8), tupleBytes) + || !requestId.equals(tuple.controlPlaneRequestId())) { + throw new IllegalArgumentException("request key does not match the exact canonical tuple"); + } + + ReadPurpose purpose = + switch (request.getPurpose()) { + case START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE -> ReadPurpose.ISSUE; + case START_SESSION_RESERVATION_EVIDENCE_PURPOSE_RECOVER -> ReadPurpose.RECOVER; + default -> throw new IllegalArgumentException("read purpose is required"); + }; + return new ParsedRequest( + requestId, + tuple, + reservationOwnerId, + reservationClaimFence, + claimOwnerId, + claimFence, + purpose); + } + + private boolean isAccountPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + return peer != null + && GrpcPeerIdentity.isValidNamespace(workloadNamespace) + && peer.uri().equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"); + } + + private static UUID parseCanonicalNonNilUuid(String value) { + if (value == null) { + return null; + } + try { + UUID parsed = UUID.fromString(value); + return !parsed.equals(new UUID(0L, 0L)) && parsed.toString().equals(value) ? parsed : null; + } catch (IllegalArgumentException exception) { + return null; + } + } + + private static String decodeStrictUtf8(byte[] value) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(value)) + .toString(); + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("tuple JSON is not valid UTF-8", exception); + } + } + + private static StartSessionReservationEvidencePurpose toWirePurpose(ReadPurpose purpose) { + return switch (purpose) { + case ISSUE -> + StartSessionReservationEvidencePurpose.START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE; + case RECOVER -> + StartSessionReservationEvidencePurpose.START_SESSION_RESERVATION_EVIDENCE_PURPOSE_RECOVER; + }; + } + + private static void fail( + StreamObserver responseObserver, + Status status, + String description) { + responseObserver.onError(status.withDescription(description).asRuntimeException()); + } + + private record ParsedRequest( + String controlPlaneRequestId, + StartSessionPreAuthorizationReservationTuple tuple, + UUID reservationOwnerId, + long reservationClaimFence, + UUID claimOwnerId, + long claimFence, + ReadPurpose purpose) {} +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceLeafApproval.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceLeafApproval.java new file mode 100644 index 0000000000..91ec6342f8 --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceLeafApproval.java @@ -0,0 +1,115 @@ +package net.firedevops.firemud.loggingadmin.service.impl; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +/** Method-scoped approved leaf instances for ReadCurrentClaimEvidence. */ +@Component +public final class StartSessionReservationEvidenceLeafApproval { + private static final int MAX_POLICY_BYTES = 180; + private static final Pattern ACTIVE_ENTRY = Pattern.compile("active=([0-9a-f]{64})"); + private static final Pattern OVERLAP_ENTRY = + Pattern.compile("overlap=([0-9a-f]{64});expires-at=([0-9]{1,19})"); + + private final String approvalFile; + + public StartSessionReservationEvidenceLeafApproval( + @Value("${firemud.grpc.account-reservation-evidence.approved-leaf-file:}") + String approvalFile) { + this.approvalFile = approvalFile; + } + + /** Reads the trusted policy on every request; missing or invalid policy denies the peer. */ + public boolean isApproved(GrpcPeerCertificateEvidence certificateEvidence) { + if (certificateEvidence == null || approvalFile == null || approvalFile.isBlank()) { + return false; + } + + Optional approvalSet = readApprovalSet(); + if (approvalSet.isEmpty()) { + return false; + } + + String presentedFingerprint = certificateEvidence.leafSha256(); + ApprovalSet approval = approvalSet.orElseThrow(); + if (approval.activeFingerprint().equals(presentedFingerprint)) { + return true; + } + return approval.overlapFingerprint() != null + && approval.overlapFingerprint().equals(presentedFingerprint) + && Instant.now().toEpochMilli() < approval.overlapExpiresAtEpochMillis(); + } + + private Optional readApprovalSet() { + try { + Path path = Path.of(approvalFile); + if (!path.isAbsolute() || !Files.isRegularFile(path)) { + return Optional.empty(); + } + byte[] content; + try (InputStream input = Files.newInputStream(path)) { + content = input.readNBytes(MAX_POLICY_BYTES + 1); + } + if (content.length == 0 || content.length > MAX_POLICY_BYTES) { + return Optional.empty(); + } + String text = decodeStrictUtf8(content); + List lines = text.lines().toList(); + if (lines.isEmpty() || lines.size() > 2) { + return Optional.empty(); + } + + Matcher active = ACTIVE_ENTRY.matcher(lines.getFirst()); + if (!active.matches()) { + return Optional.empty(); + } + String activeFingerprint = active.group(1); + if (lines.size() == 1) { + return Optional.of(new ApprovalSet(activeFingerprint, null, 0L)); + } + + Matcher overlap = OVERLAP_ENTRY.matcher(lines.get(1)); + if (!overlap.matches() || activeFingerprint.equals(overlap.group(1))) { + return Optional.empty(); + } + long expiresAt; + try { + expiresAt = Long.parseLong(overlap.group(2)); + } catch (NumberFormatException exception) { + return Optional.empty(); + } + if (expiresAt <= 0L) { + return Optional.empty(); + } + return Optional.of(new ApprovalSet(activeFingerprint, overlap.group(1), expiresAt)); + } catch (IOException | RuntimeException exception) { + return Optional.empty(); + } + } + + private static String decodeStrictUtf8(byte[] value) throws CharacterCodingException { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(value)) + .toString(); + } + + private record ApprovalSet( + String activeFingerprint, String overlapFingerprint, long overlapExpiresAtEpochMillis) {} +} diff --git a/services/logging-admin-service/src/main/resources/application.yml b/services/logging-admin-service/src/main/resources/application.yml index bae9c9dcf0..6a39443553 100644 --- a/services/logging-admin-service/src/main/resources/application.yml +++ b/services/logging-admin-service/src/main/resources/application.yml @@ -62,7 +62,13 @@ firemud: http: enabled: true role-requirement: PRIVILEGED + grpc: + public-methods: + - logging_admin.v1.StartSessionReservationEvidenceService/ReadCurrentClaimEvidence grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} ca-cert: ${FIREMUD_GRPC_CA_CERT_PATH:certs/ca.crt} + workload-namespace: ${FIREMUD_GRPC_WORKLOAD_NAMESPACE:} + account-reservation-evidence: + approved-leaf-file: ${FIREMUD_GRPC_ACCOUNT_RESERVATION_EVIDENCE_APPROVED_LEAF_FILE:} diff --git a/services/logging-admin-service/src/main/resources/db/migration/V2__start_session_pre_authorization_reservations.sql b/services/logging-admin-service/src/main/resources/db/migration/V2__start_session_pre_authorization_reservations.sql new file mode 100644 index 0000000000..9b70577808 --- /dev/null +++ b/services/logging-admin-service/src/main/resources/db/migration/V2__start_session_pre_authorization_reservations.sql @@ -0,0 +1,29 @@ +CREATE TABLE start_session_pre_authorization_reservations ( + control_plane_request_id VARCHAR(128) PRIMARY KEY, + pre_authorization_tuple_json VARCHAR(8192) NOT NULL, + mutation_digest VARCHAR(64) NOT NULL, + phase VARCHAR(32) NOT NULL + CONSTRAINT start_session_pre_authorization_reservations_phase_check + CHECK (phase = 'ACCOUNT_AUTHORIZATION'), + state VARCHAR(40) NOT NULL + CONSTRAINT start_session_pre_authorization_reservations_state_check + CHECK (state IN ('RESERVED', 'AUTHORIZATION_PENDING')), + reservation_owner_id UUID NOT NULL, + reservation_claim_fence BIGINT NOT NULL + CHECK (reservation_claim_fence = 1), + claim_owner_id UUID, + claim_fence BIGINT NOT NULL + CHECK (claim_fence >= reservation_claim_fence), + claim_expires_at_epoch_ms BIGINT NOT NULL + CHECK (claim_expires_at_epoch_ms > 0), + claim_state VARCHAR(16) NOT NULL + CHECK (claim_state IN ('ACTIVE', 'EXPIRED')), + created_at_epoch_ms BIGINT NOT NULL + CHECK (created_at_epoch_ms > 0), + updated_at_epoch_ms BIGINT NOT NULL + CHECK (updated_at_epoch_ms > 0), + CHECK ( + (claim_state = 'ACTIVE' AND claim_owner_id IS NOT NULL) + OR (claim_state = 'EXPIRED' AND claim_owner_id IS NULL) + ) +); diff --git a/services/logging-admin-service/src/main/resources/db/migration/V3__start_session_post_authorization_execution.sql b/services/logging-admin-service/src/main/resources/db/migration/V3__start_session_post_authorization_execution.sql new file mode 100644 index 0000000000..4a0007811b --- /dev/null +++ b/services/logging-admin-service/src/main/resources/db/migration/V3__start_session_post_authorization_execution.sql @@ -0,0 +1,173 @@ +ALTER TABLE start_session_pre_authorization_reservations + ADD COLUMN post_authorization_execution_tuple_json TEXT, + ADD COLUMN owner_execution_handoff_id UUID; + +ALTER TABLE start_session_pre_authorization_reservations + DROP CONSTRAINT start_session_pre_authorization_reservations_phase_check; + +ALTER TABLE start_session_pre_authorization_reservations + DROP CONSTRAINT start_session_pre_authorization_reservations_state_check; + +ALTER TABLE start_session_pre_authorization_reservations + ADD CONSTRAINT start_session_pre_authorization_reservations_phase_check + CHECK (phase IN ('ACCOUNT_AUTHORIZATION', 'OWNER_EXECUTION')), + ADD CONSTRAINT start_session_pre_authorization_reservations_state_check + CHECK ( + (phase = 'ACCOUNT_AUTHORIZATION' + AND state IN ('RESERVED', 'AUTHORIZATION_PENDING', 'AUTHORIZED')) + OR (phase = 'OWNER_EXECUTION' AND state = 'OWNER_EXECUTION_PENDING') + ), + ADD CONSTRAINT start_session_pre_authorization_reservations_reservation_owner_non_nil_check + CHECK (reservation_owner_id <> '00000000-0000-0000-0000-000000000000'::UUID), + ADD CONSTRAINT start_session_pre_authorization_reservations_claim_owner_non_nil_check + CHECK ( + claim_owner_id IS NULL + OR claim_owner_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + ADD CONSTRAINT start_session_pre_authorization_reservations_handoff_non_nil_check + CHECK ( + owner_execution_handoff_id IS NULL + OR owner_execution_handoff_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + ADD CONSTRAINT start_session_pre_authorization_reservations_post_tuple_bound_check + CHECK ( + post_authorization_execution_tuple_json IS NULL + OR octet_length(post_authorization_execution_tuple_json) BETWEEN 1 AND 262144 + ), + ADD CONSTRAINT start_session_pre_authorization_reservations_post_state_shape_check + CHECK ( + (phase = 'ACCOUNT_AUTHORIZATION' + AND state IN ('RESERVED', 'AUTHORIZATION_PENDING') + AND post_authorization_execution_tuple_json IS NULL + AND owner_execution_handoff_id IS NULL) + OR (phase = 'ACCOUNT_AUTHORIZATION' + AND state = 'AUTHORIZED' + AND post_authorization_execution_tuple_json IS NOT NULL + AND owner_execution_handoff_id IS NULL) + OR (phase = 'OWNER_EXECUTION' + AND state = 'OWNER_EXECUTION_PENDING' + AND post_authorization_execution_tuple_json IS NOT NULL + AND owner_execution_handoff_id IS NOT NULL) + ); + +-- jOOQ's H2 DDL parser cannot model PostgreSQL trigger functions; PostgreSQL still applies the +-- complete immutable-evidence and phase-transition guards below. +-- [jooq ignore start] +CREATE FUNCTION guard_start_session_reservation_insert() +RETURNS trigger AS $$ +BEGIN + IF NEW.phase <> 'ACCOUNT_AUTHORIZATION' + OR NEW.state <> 'RESERVED' + OR NEW.reservation_owner_id = '00000000-0000-0000-0000-000000000000'::UUID + OR NEW.reservation_claim_fence <> 1 + OR NEW.claim_owner_id IS DISTINCT FROM NEW.reservation_owner_id + OR NEW.claim_fence <> 1 + OR NEW.claim_state <> 'ACTIVE' + OR NEW.post_authorization_execution_tuple_json IS NOT NULL + OR NEW.owner_execution_handoff_id IS NOT NULL THEN + RAISE EXCEPTION 'StartSession reservation must begin in the exact reserved state'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER start_session_reservation_insert_guard + BEFORE INSERT ON start_session_pre_authorization_reservations + FOR EACH ROW + EXECUTE FUNCTION guard_start_session_reservation_insert(); + +CREATE FUNCTION guard_start_session_post_authorization_execution() +RETURNS trigger AS $$ +BEGIN + IF NEW.control_plane_request_id IS DISTINCT FROM OLD.control_plane_request_id + OR NEW.pre_authorization_tuple_json IS DISTINCT FROM OLD.pre_authorization_tuple_json + OR NEW.mutation_digest IS DISTINCT FROM OLD.mutation_digest + OR NEW.reservation_owner_id IS DISTINCT FROM OLD.reservation_owner_id + OR NEW.reservation_claim_fence IS DISTINCT FROM OLD.reservation_claim_fence + OR NEW.created_at_epoch_ms IS DISTINCT FROM OLD.created_at_epoch_ms THEN + RAISE EXCEPTION 'StartSession reservation identity is immutable'; + END IF; + + IF OLD.post_authorization_execution_tuple_json IS NOT NULL + AND NEW.post_authorization_execution_tuple_json + IS DISTINCT FROM OLD.post_authorization_execution_tuple_json THEN + RAISE EXCEPTION 'StartSession post-authorization tuple is immutable'; + END IF; + IF OLD.owner_execution_handoff_id IS NOT NULL + AND NEW.owner_execution_handoff_id IS DISTINCT FROM OLD.owner_execution_handoff_id THEN + RAISE EXCEPTION 'StartSession owner handoff is immutable'; + END IF; + + IF NOT ( + (NEW.phase = OLD.phase AND NEW.state = OLD.state) + OR (OLD.phase = 'ACCOUNT_AUTHORIZATION' AND OLD.state = 'RESERVED' + AND NEW.phase = 'ACCOUNT_AUTHORIZATION' AND NEW.state = 'AUTHORIZATION_PENDING') + OR (OLD.phase = 'ACCOUNT_AUTHORIZATION' AND OLD.state = 'AUTHORIZATION_PENDING' + AND NEW.phase = 'ACCOUNT_AUTHORIZATION' AND NEW.state = 'AUTHORIZED') + OR (OLD.phase = 'ACCOUNT_AUTHORIZATION' AND OLD.state = 'AUTHORIZED' + AND NEW.phase = 'OWNER_EXECUTION' AND NEW.state = 'OWNER_EXECUTION_PENDING') + ) THEN + RAISE EXCEPTION 'StartSession phase-qualified transition is not permitted'; + END IF; + + IF OLD.phase = 'ACCOUNT_AUTHORIZATION' AND OLD.state = 'AUTHORIZATION_PENDING' + AND NEW.phase = 'ACCOUNT_AUTHORIZATION' AND NEW.state = 'AUTHORIZED' THEN + IF OLD.post_authorization_execution_tuple_json IS NOT NULL + OR NEW.post_authorization_execution_tuple_json IS NULL + OR NEW.owner_execution_handoff_id IS NOT NULL + OR NEW.claim_owner_id IS DISTINCT FROM OLD.claim_owner_id + OR NEW.claim_fence IS DISTINCT FROM OLD.claim_fence + OR NEW.claim_expires_at_epoch_ms IS DISTINCT FROM OLD.claim_expires_at_epoch_ms + OR NEW.claim_state IS DISTINCT FROM OLD.claim_state THEN + RAISE EXCEPTION 'StartSession authorization enrichment must preserve the exact claim'; + END IF; + END IF; + + IF OLD.phase = 'ACCOUNT_AUTHORIZATION' AND OLD.state = 'AUTHORIZED' + AND NEW.phase = 'OWNER_EXECUTION' AND NEW.state = 'OWNER_EXECUTION_PENDING' THEN + IF OLD.post_authorization_execution_tuple_json IS NULL + OR NEW.post_authorization_execution_tuple_json + IS DISTINCT FROM OLD.post_authorization_execution_tuple_json + OR NEW.owner_execution_handoff_id IS NULL + OR OLD.owner_execution_handoff_id IS NOT NULL + OR NEW.claim_owner_id IS DISTINCT FROM OLD.claim_owner_id + OR NEW.claim_fence IS DISTINCT FROM OLD.claim_fence + OR NEW.claim_expires_at_epoch_ms IS DISTINCT FROM OLD.claim_expires_at_epoch_ms + OR NEW.claim_state IS DISTINCT FROM OLD.claim_state THEN + RAISE EXCEPTION 'StartSession owner handoff must preserve the exact claim and tuple'; + END IF; + END IF; + + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER start_session_post_authorization_execution_guard + BEFORE UPDATE ON start_session_pre_authorization_reservations + FOR EACH ROW + EXECUTE FUNCTION guard_start_session_post_authorization_execution(); + +CREATE FUNCTION reject_start_session_reservation_delete() +RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'StartSession reservation evidence cannot be deleted'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER start_session_reservation_no_delete + BEFORE DELETE ON start_session_pre_authorization_reservations + FOR EACH ROW + EXECUTE FUNCTION reject_start_session_reservation_delete(); + +CREATE FUNCTION reject_start_session_reservation_truncate() +RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'StartSession reservation evidence cannot be truncated'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER start_session_reservation_no_truncate + BEFORE TRUNCATE ON start_session_pre_authorization_reservations + FOR EACH STATEMENT + EXECUTE FUNCTION reject_start_session_reservation_truncate(); +-- [jooq ignore stop] diff --git a/services/logging-admin-service/src/main/resources/db/migration/V4__start_session_state_scoped_claim_recovery.sql b/services/logging-admin-service/src/main/resources/db/migration/V4__start_session_state_scoped_claim_recovery.sql new file mode 100644 index 0000000000..02acd9a291 --- /dev/null +++ b/services/logging-admin-service/src/main/resources/db/migration/V4__start_session_state_scoped_claim_recovery.sql @@ -0,0 +1,207 @@ +ALTER TABLE start_session_pre_authorization_reservations + ADD COLUMN claim_purpose VARCHAR(40); + +UPDATE start_session_pre_authorization_reservations +SET claim_purpose = CASE + WHEN claim_state = 'EXPIRED' THEN NULL + WHEN claim_owner_id = reservation_owner_id + AND claim_fence = reservation_claim_fence THEN 'ORIGINAL' + WHEN state = 'RESERVED' THEN 'RESERVED_RECOVERY_ISSUE' + ELSE 'AUTHORIZATION_RECOVERY' +END; + +ALTER TABLE start_session_pre_authorization_reservations + ADD CONSTRAINT start_session_pre_authorization_reservations_claim_purpose_shape_check + CHECK ( + (claim_state = 'EXPIRED' + AND claim_owner_id IS NULL + AND claim_purpose IS NULL) + OR (claim_state = 'ACTIVE' + AND claim_owner_id IS NOT NULL + AND claim_purpose IS NOT NULL + AND claim_purpose IN ( + 'ORIGINAL', + 'RESERVED_RECOVERY_ISSUE', + 'AUTHORIZATION_RECOVERY', + 'AUTHORIZED_RESPONSE_RECOVERY' + ) + AND ( + (claim_purpose = 'ORIGINAL' + AND claim_owner_id = reservation_owner_id + AND claim_fence = reservation_claim_fence) + OR (claim_purpose <> 'ORIGINAL' + AND claim_owner_id <> reservation_owner_id + AND claim_fence > reservation_claim_fence) + ) + AND ( + claim_purpose = 'ORIGINAL' + OR (claim_purpose = 'RESERVED_RECOVERY_ISSUE' + AND state IN ( + 'RESERVED', + 'AUTHORIZATION_PENDING', + 'AUTHORIZED', + 'OWNER_EXECUTION_PENDING' + )) + OR (claim_purpose = 'AUTHORIZATION_RECOVERY' + AND state IN ( + 'AUTHORIZATION_PENDING', + 'AUTHORIZED', + 'OWNER_EXECUTION_PENDING' + )) + OR (claim_purpose = 'AUTHORIZED_RESPONSE_RECOVERY' + AND state IN ('AUTHORIZED', 'OWNER_EXECUTION_PENDING')) + ) + ) + ); + +-- jOOQ's H2 DDL parser cannot model PostgreSQL trigger functions; PostgreSQL still applies the +-- complete claim-purpose provenance and same-state recovery guards below. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION guard_start_session_reservation_insert() +RETURNS trigger AS $$ +BEGIN + IF NEW.phase <> 'ACCOUNT_AUTHORIZATION' + OR NEW.state <> 'RESERVED' + OR NEW.reservation_owner_id = '00000000-0000-0000-0000-000000000000'::UUID + OR NEW.reservation_claim_fence <> 1 + OR NEW.claim_owner_id IS DISTINCT FROM NEW.reservation_owner_id + OR NEW.claim_fence <> 1 + OR NEW.claim_state <> 'ACTIVE' + OR NEW.claim_purpose IS DISTINCT FROM 'ORIGINAL' + OR NEW.claim_expires_at_epoch_ms <= NEW.created_at_epoch_ms + OR NEW.claim_expires_at_epoch_ms - NEW.created_at_epoch_ms > 30000 + OR NEW.post_authorization_execution_tuple_json IS NOT NULL + OR NEW.owner_execution_handoff_id IS NOT NULL THEN + RAISE EXCEPTION 'StartSession reservation must begin in the exact reserved state'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION guard_start_session_post_authorization_execution() +RETURNS trigger AS $$ +DECLARE + state_transition BOOLEAN; + claim_unchanged BOOLEAN; +BEGIN + IF NEW.control_plane_request_id IS DISTINCT FROM OLD.control_plane_request_id + OR NEW.pre_authorization_tuple_json IS DISTINCT FROM OLD.pre_authorization_tuple_json + OR NEW.mutation_digest IS DISTINCT FROM OLD.mutation_digest + OR NEW.reservation_owner_id IS DISTINCT FROM OLD.reservation_owner_id + OR NEW.reservation_claim_fence IS DISTINCT FROM OLD.reservation_claim_fence + OR NEW.created_at_epoch_ms IS DISTINCT FROM OLD.created_at_epoch_ms THEN + RAISE EXCEPTION 'StartSession reservation identity is immutable'; + END IF; + IF NEW.updated_at_epoch_ms < OLD.updated_at_epoch_ms THEN + RAISE EXCEPTION 'StartSession reservation update time cannot move backwards'; + END IF; + + IF OLD.post_authorization_execution_tuple_json IS NOT NULL + AND NEW.post_authorization_execution_tuple_json + IS DISTINCT FROM OLD.post_authorization_execution_tuple_json THEN + RAISE EXCEPTION 'StartSession post-authorization tuple is immutable'; + END IF; + IF OLD.owner_execution_handoff_id IS NOT NULL + AND NEW.owner_execution_handoff_id IS DISTINCT FROM OLD.owner_execution_handoff_id THEN + RAISE EXCEPTION 'StartSession owner handoff is immutable'; + END IF; + + state_transition := NEW.phase IS DISTINCT FROM OLD.phase OR NEW.state IS DISTINCT FROM OLD.state; + claim_unchanged := + NEW.claim_owner_id IS NOT DISTINCT FROM OLD.claim_owner_id + AND NEW.claim_fence = OLD.claim_fence + AND NEW.claim_expires_at_epoch_ms = OLD.claim_expires_at_epoch_ms + AND NEW.claim_state = OLD.claim_state + AND NEW.claim_purpose IS NOT DISTINCT FROM OLD.claim_purpose; + + IF NOT ( + (NEW.phase = OLD.phase AND NEW.state = OLD.state) + OR (OLD.phase = 'ACCOUNT_AUTHORIZATION' AND OLD.state = 'RESERVED' + AND NEW.phase = 'ACCOUNT_AUTHORIZATION' AND NEW.state = 'AUTHORIZATION_PENDING') + OR (OLD.phase = 'ACCOUNT_AUTHORIZATION' AND OLD.state = 'AUTHORIZATION_PENDING' + AND NEW.phase = 'ACCOUNT_AUTHORIZATION' AND NEW.state = 'AUTHORIZED') + OR (OLD.phase = 'ACCOUNT_AUTHORIZATION' AND OLD.state = 'AUTHORIZED' + AND NEW.phase = 'OWNER_EXECUTION' AND NEW.state = 'OWNER_EXECUTION_PENDING') + ) THEN + RAISE EXCEPTION 'StartSession phase-qualified transition is not permitted'; + END IF; + + IF state_transition THEN + IF NOT claim_unchanged THEN + RAISE EXCEPTION 'StartSession phase transition must preserve claim provenance'; + END IF; + IF OLD.phase = 'ACCOUNT_AUTHORIZATION' AND OLD.state = 'AUTHORIZATION_PENDING' + AND NEW.phase = 'ACCOUNT_AUTHORIZATION' AND NEW.state = 'AUTHORIZED' THEN + IF OLD.post_authorization_execution_tuple_json IS NOT NULL + OR NEW.post_authorization_execution_tuple_json IS NULL + OR NEW.owner_execution_handoff_id IS NOT NULL THEN + RAISE EXCEPTION 'StartSession authorization enrichment shape is invalid'; + END IF; + ELSIF OLD.phase = 'ACCOUNT_AUTHORIZATION' AND OLD.state = 'AUTHORIZED' + AND NEW.phase = 'OWNER_EXECUTION' AND NEW.state = 'OWNER_EXECUTION_PENDING' THEN + IF OLD.post_authorization_execution_tuple_json IS NULL + OR NEW.post_authorization_execution_tuple_json + IS DISTINCT FROM OLD.post_authorization_execution_tuple_json + OR NEW.owner_execution_handoff_id IS NULL + OR OLD.owner_execution_handoff_id IS NOT NULL THEN + RAISE EXCEPTION 'StartSession owner handoff shape is invalid'; + END IF; + END IF; + RETURN NEW; + END IF; + + IF claim_unchanged THEN + RETURN NEW; + END IF; + + -- A live claim may be renewed only by its holder before expiry, preserving its state-scoped + -- purpose and extending it by no more than the bounded 30-second lease. + IF OLD.claim_state = 'ACTIVE' + AND NEW.claim_state = 'ACTIVE' + AND NEW.claim_owner_id = OLD.claim_owner_id + AND NEW.claim_fence = OLD.claim_fence + AND NEW.claim_purpose = OLD.claim_purpose + AND OLD.claim_expires_at_epoch_ms > NEW.updated_at_epoch_ms + AND NEW.claim_expires_at_epoch_ms > OLD.claim_expires_at_epoch_ms + AND NEW.claim_expires_at_epoch_ms > NEW.updated_at_epoch_ms + AND NEW.claim_expires_at_epoch_ms - NEW.updated_at_epoch_ms <= 30000 THEN + RETURN NEW; + END IF; + + -- Expiration advances the fence and clears only the current owner and claim purpose. + IF OLD.claim_state = 'ACTIVE' + AND OLD.claim_expires_at_epoch_ms <= NEW.updated_at_epoch_ms + AND NEW.claim_state = 'EXPIRED' + AND NEW.claim_owner_id IS NULL + AND NEW.claim_fence = OLD.claim_fence + 1 + AND NEW.claim_expires_at_epoch_ms = OLD.claim_expires_at_epoch_ms + AND NEW.claim_purpose IS NULL THEN + RETURN NEW; + END IF; + + -- Recovery may reassign only an expired lease, for a purpose determined by the durable state. + IF (OLD.claim_state = 'EXPIRED' + OR (OLD.claim_state = 'ACTIVE' + AND OLD.claim_expires_at_epoch_ms <= NEW.updated_at_epoch_ms)) + AND OLD.state <> 'OWNER_EXECUTION_PENDING' + AND NEW.claim_state = 'ACTIVE' + AND NEW.claim_owner_id IS NOT NULL + AND NEW.claim_owner_id <> OLD.reservation_owner_id + AND NEW.claim_owner_id IS DISTINCT FROM OLD.claim_owner_id + AND NEW.claim_fence = OLD.claim_fence + 1 + AND NEW.claim_expires_at_epoch_ms > NEW.updated_at_epoch_ms + AND NEW.claim_expires_at_epoch_ms - NEW.updated_at_epoch_ms <= 30000 + AND ( + (OLD.state = 'RESERVED' AND NEW.claim_purpose = 'RESERVED_RECOVERY_ISSUE') + OR (OLD.state = 'AUTHORIZATION_PENDING' + AND NEW.claim_purpose = 'AUTHORIZATION_RECOVERY') + OR (OLD.state = 'AUTHORIZED' + AND NEW.claim_purpose = 'AUTHORIZED_RESPONSE_RECOVERY') + ) THEN + RETURN NEW; + END IF; + + RAISE EXCEPTION 'StartSession same-state claim transition is not permitted'; +END; +$$ LANGUAGE plpgsql; +-- [jooq ignore stop] diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java index b7a04a6f7e..fb290e412e 100644 --- a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java @@ -21,6 +21,7 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.http.HttpHeaders; +import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.bean.override.mockito.MockitoBean; @@ -68,6 +69,7 @@ static void configure(DynamicPropertyRegistry registry) { @LocalServerPort private int port; @Autowired private RequestMappingHandlerMapping requestMappingHandlerMapping; + @Autowired private JdbcTemplate jdbcTemplate; @MockitoBean private AccountClient accountClient; @MockitoBean private GameSessionClient gameSessionClient; @@ -89,6 +91,31 @@ void pingEndpointReturnsPong() throws Exception { assertThat(response.body()).contains("pong"); } + @Test + void applicationBootAppliesReservationMigrationsThroughV4() { + assertThat( + jdbcTemplate.queryForObject( + "SELECT COUNT(*) FROM flyway_schema_history_logging_admin_service " + + "WHERE version IN ('3', '4') AND success", + Integer.class)) + .isEqualTo(2); + assertThat( + jdbcTemplate.queryForObject( + "SELECT COUNT(*) FROM information_schema.tables " + + "WHERE table_schema = 'logging_admin_service' " + + "AND table_name = 'start_session_pre_authorization_reservations'", + Integer.class)) + .isEqualTo(1); + assertThat( + jdbcTemplate.queryForObject( + "SELECT COUNT(*) FROM information_schema.columns " + + "WHERE table_schema = 'logging_admin_service' " + + "AND table_name = 'start_session_pre_authorization_reservations' " + + "AND column_name = 'claim_purpose'", + Integer.class)) + .isEqualTo(1); + } + @Test void publicReportPersistenceControllerMappingIsAbsent() { assertThat( diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java new file mode 100644 index 0000000000..b795b7f886 --- /dev/null +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java @@ -0,0 +1,1358 @@ +package net.firedevops.firemud.loggingadmin; + +import static net.firedevops.firemud.loggingadmin.jooq.tables.StartSessionPreAuthorizationReservations.START_SESSION_PRE_AUTHORIZATION_RESERVATIONS; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimPurpose; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimState; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Phase; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ReadPurpose; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.State; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.loggingadmin.repository.StartSessionPreAuthorizationReservationRepository; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.json.JsonMapper; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class StartSessionPreAuthorizationReservationPostgresIntegrationTest { + private static final long NOW_EPOCH_MILLIS = 1_800_000_000_000L; + private static final Map FLYWAY_PLACEHOLDERS = Map.of("serviceSchema", "public"); + private static final UUID TENANT_ID = UUID.fromString("ffbe29e3-a8d2-4b7d-a046-cf1af57ae904"); + private static final UUID ACTOR_ID = UUID.fromString("4c5b3e92-f60d-4e3d-8b8f-6d89b28495d8"); + private static final UUID ISSUANCE_ID = UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final String WORKLOAD = + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private DriverManagerDataSource dataSource; + private DSLContext dsl; + private StartSessionPreAuthorizationReservationRepository repository; + + @BeforeEach + void migrateAndCreateRepository() { + dataSource = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .locations("classpath:db/migration") + .placeholders(FLYWAY_PLACEHOLDERS) + .cleanDisabled(false) + .load() + .clean(); + Flyway.configure() + .dataSource(dataSource) + .locations("classpath:db/migration") + .placeholders(FLYWAY_PLACEHOLDERS) + .target(MigrationVersion.fromVersion("4")) + .load() + .migrate(); + dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + repository = + StartSessionReservationMutationTestFixtures.forRunOwnedPostgres(postgres).repository(); + } + + @AfterEach + void clearAuthenticatedContext() { + SessionContext.clear(); + } + + @Test + void concurrentExactAcquiresPersistOneDurableReservationOwner() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = + tuple("postgres-concurrent-01", "same action"); + int callerCount = 8; + ExecutorService executor = Executors.newFixedThreadPool(callerCount); + CountDownLatch ready = new CountDownLatch(callerCount); + CountDownLatch start = new CountDownLatch(1); + List> futures = + new ArrayList<>(); + try { + for (int index = 0; index < callerCount; index++) { + futures.add( + executor.submit( + () -> { + ready.countDown(); + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("concurrent acquire gate timed out"); + } + return acquire(tuple, UUID.randomUUID()); + })); + } + assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + List results = + new ArrayList<>(); + for (Future future : + futures) { + results.add(future.get(10, TimeUnit.SECONDS)); + } + + assertThat(results) + .filteredOn(StartSessionPreAuthorizationReservationRepository.AcquireResult::created) + .hasSize(1); + assertThat(results) + .allSatisfy(result -> assertThat(result.snapshot().tuple()).isEqualTo(tuple)); + assertThat(dsl.fetchCount(START_SESSION_PRE_AUTHORIZATION_RESERVATIONS)).isEqualTo(1); + } finally { + executor.shutdownNow(); + } + } + + @Test + void upgradeFromV1RetainsExistingLogEventsThroughV4() { + Flyway.configure() + .dataSource(dataSource) + .locations("classpath:db/migration") + .placeholders(FLYWAY_PLACEHOLDERS) + .cleanDisabled(false) + .target(MigrationVersion.fromVersion("1")) + .load() + .clean(); + Flyway.configure() + .dataSource(dataSource) + .locations("classpath:db/migration") + .placeholders(FLYWAY_PLACEHOLDERS) + .target(MigrationVersion.fromVersion("1")) + .load() + .migrate(); + + dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + long existingLogEventId = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO log_events (tenant_id, type, message, timestamp, account_id) " + + "VALUES (?, ?, ?, ?, ?) RETURNING id", + 42L, + "audit", + "existing row before reservation migrations", + java.sql.Timestamp.valueOf("2026-10-10 12:00:00"), + 7L), + "The V1 log row must be inserted before the reservation migrations") + .get(0, Long.class); + + Flyway.configure() + .dataSource(dataSource) + .locations("classpath:db/migration") + .placeholders(FLYWAY_PLACEHOLDERS) + .target(MigrationVersion.fromVersion("3")) + .load() + .migrate(); + + StartSessionPreAuthorizationReservationTuple originalTuple = + tuple("postgres-v3-original-backfill", "V3 original claim backfill fixture"); + StartSessionPreAuthorizationReservationTuple expiredTuple = + tuple("postgres-v3-expired-backfill", "V3 expired claim backfill fixture"); + StartSessionPreAuthorizationReservationTuple reservedRecoveryTuple = + tuple("postgres-v3-reserved-recovery-backfill", "V3 reserved recovery backfill fixture"); + StartSessionPreAuthorizationReservationTuple pendingTuple = + tuple("postgres-v3-authorization-recovery-backfill", "V3 authorization recovery fixture"); + UUID originalOwner = UUID.fromString("39a96323-f6e0-4a64-a3c3-7a3a346f2696"); + UUID recoveryOwner = UUID.fromString("05bd6075-3e08-4a83-97c2-9af3481a9492"); + insertV3OriginalReservation(originalTuple, originalOwner); + insertV3OriginalReservation(expiredTuple, originalOwner); + expireV3Claim(expiredTuple, NOW_EPOCH_MILLIS + 30_000L); + insertV3OriginalReservation(reservedRecoveryTuple, originalOwner); + expireV3Claim(reservedRecoveryTuple, NOW_EPOCH_MILLIS + 30_000L); + recoverV3Claim( + reservedRecoveryTuple, + recoveryOwner, + NOW_EPOCH_MILLIS + 60_000L, + NOW_EPOCH_MILLIS + 30_001L); + insertV3OriginalReservation(pendingTuple, originalOwner); + dsl.execute( + "UPDATE start_session_pre_authorization_reservations SET state = 'AUTHORIZATION_PENDING', " + + "updated_at_epoch_ms = ? WHERE control_plane_request_id = ?", + NOW_EPOCH_MILLIS + 1_000L, + pendingTuple.controlPlaneRequestId()); + expireV3Claim(pendingTuple, NOW_EPOCH_MILLIS + 30_000L); + recoverV3Claim( + pendingTuple, recoveryOwner, NOW_EPOCH_MILLIS + 60_000L, NOW_EPOCH_MILLIS + 30_001L); + + Flyway.configure() + .dataSource(dataSource) + .locations("classpath:db/migration") + .placeholders(FLYWAY_PLACEHOLDERS) + .target(MigrationVersion.fromVersion("4")) + .load() + .migrate(); + + assertThat( + Objects.requireNonNull( + dsl.fetchOne("SELECT message FROM log_events WHERE id = ?", existingLogEventId), + "The V1 log row must remain after the reservation migrations") + .get(0, String.class)) + .isEqualTo("existing row before reservation migrations"); + assertThat(repository.findExact(pendingTuple).orElseThrow().claimPurpose()) + .isEqualTo(ClaimPurpose.AUTHORIZATION_RECOVERY); + assertThat(claimPurpose(originalTuple.controlPlaneRequestId())).isEqualTo("ORIGINAL"); + assertThat(claimPurpose(expiredTuple.controlPlaneRequestId())).isNull(); + assertThat(claimPurpose(reservedRecoveryTuple.controlPlaneRequestId())) + .isEqualTo("RESERVED_RECOVERY_ISSUE"); + assertThat(claimPurpose(pendingTuple.controlPlaneRequestId())) + .isEqualTo("AUTHORIZATION_RECOVERY"); + assertThat(repository.findExact(pendingTuple).orElseThrow().reservationClaimFence()) + .isEqualTo(1L); + assertThat(repository.findExact(pendingTuple).orElseThrow().claimFence()).isEqualTo(3L); + assertThat( + dsl.fetch( + "SELECT version FROM flyway_schema_history WHERE success ORDER BY installed_rank") + .getValues("version", String.class)) + .containsExactly("1", "2", "3", "4"); + } + + @Test + void activeClaimsRequirePurposeWhileExpiredClaimsKeepNullPurpose() { + StartSessionPreAuthorizationReservationTuple rejectedInsertTuple = + tuple("postgres-null-purpose-insert", "active claim purpose insert guard"); + UUID rejectedOwner = UUID.fromString("cd2900f9-2a8b-4dd3-a495-15180eb78f67"); + + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO start_session_pre_authorization_reservations (" + + "control_plane_request_id, pre_authorization_tuple_json, mutation_digest, phase, state, " + + "reservation_owner_id, reservation_claim_fence, claim_owner_id, claim_fence, " + + "claim_expires_at_epoch_ms, claim_state, claim_purpose, created_at_epoch_ms, " + + "updated_at_epoch_ms, post_authorization_execution_tuple_json, owner_execution_handoff_id) " + + "VALUES (?, ?, ?, 'ACCOUNT_AUTHORIZATION', 'RESERVED', ?, 1, ?, 1, ?, 'ACTIVE', NULL, ?, ?, NULL, NULL)", + rejectedInsertTuple.controlPlaneRequestId(), + rejectedInsertTuple.canonicalJson(), + rejectedInsertTuple.mutationDigest(), + rejectedOwner, + rejectedOwner, + NOW_EPOCH_MILLIS + 30_000L, + NOW_EPOCH_MILLIS, + NOW_EPOCH_MILLIS)); + assertThat(dsl.fetchCount(START_SESSION_PRE_AUTHORIZATION_RESERVATIONS)).isZero(); + + StartSessionPreAuthorizationReservationTuple tuple = + tuple("postgres-null-purpose-update", "active claim purpose update guard"); + UUID owner = UUID.fromString("dd58a5f2-c3b9-4b95-b9f8-396dece825b8"); + repository.acquire(tuple, owner, NOW_EPOCH_MILLIS, NOW_EPOCH_MILLIS + 30_000L); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE start_session_pre_authorization_reservations SET claim_purpose = NULL " + + "WHERE control_plane_request_id = ?", + tuple.controlPlaneRequestId())) + .isInstanceOf(RuntimeException.class); + assertThat(repository.findExact(tuple).orElseThrow().claimPurpose()) + .isEqualTo(ClaimPurpose.ORIGINAL); + + var expired = + repository.expireClaim( + tuple, + tuple.mutationDigest(), + owner, + 1L, + Phase.ACCOUNT_AUTHORIZATION, + State.RESERVED, + NOW_EPOCH_MILLIS + 30_000L); + assertThat(expired.claimState()).isEqualTo(ClaimState.EXPIRED); + assertThat(expired.claimPurpose()).isNull(); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT claim_purpose FROM start_session_pre_authorization_reservations " + + "WHERE control_plane_request_id = ?", + tuple.controlPlaneRequestId()), + "The expired reservation row must remain readable") + .get(0, String.class)) + .isNull(); + } + + @Test + void sameRequestIdWithChangedTupleConflictsAndFullTupleIsPersisted() { + StartSessionPreAuthorizationReservationTuple original = + tuple("postgres-conflict-02", "same action"); + acquire(original, UUID.randomUUID()); + StartSessionPreAuthorizationReservationTuple changed = + tuple("postgres-conflict-02", "changed audit reason"); + + assertThatThrownBy(() -> acquire(changed, UUID.randomUUID())) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.IdempotencyConflictException.class); + + String storedTuple = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT pre_authorization_tuple_json FROM start_session_pre_authorization_reservations " + + "WHERE control_plane_request_id = ?", + original.controlPlaneRequestId()), + "The original committed reservation must remain readable") + .get(0, String.class); + assertThat(storedTuple) + .contains(ACTOR_ID.toString()) + .contains("\"ownerService\":\"game-session-service\"") + .contains("\"expectedVersion\":{\"presence\":\"ABSENT\"}") + .contains("\"clientIp\":{\"presence\":\"ABSENT\"}"); + } + + @Test + void expiryRecoveryFencesStaleOwnerAndCannotInventTerminalOutcome() { + StartSessionPreAuthorizationReservationTuple tuple = + tuple("postgres-recovery-03", "recovery fixture"); + UUID originalOwner = UUID.randomUUID(); + repository.acquire(tuple, originalOwner, NOW_EPOCH_MILLIS, NOW_EPOCH_MILLIS + 30_000L); + + var firstTransition = + repository.markAuthorizationPending( + tuple, tuple.mutationDigest(), originalOwner, 1L, NOW_EPOCH_MILLIS + 1_000L); + assertThat(firstTransition.transitioned()).isTrue(); + assertThat(firstTransition.snapshot().state()).isEqualTo(State.AUTHORIZATION_PENDING); + var duplicateTransition = + repository.markAuthorizationPending( + tuple, tuple.mutationDigest(), originalOwner, 1L, NOW_EPOCH_MILLIS + 1_000L); + assertThat(duplicateTransition.transitioned()).isFalse(); + + var expired = + repository.expireClaim( + tuple, + tuple.mutationDigest(), + originalOwner, + 1L, + Phase.ACCOUNT_AUTHORIZATION, + State.AUTHORIZATION_PENDING, + NOW_EPOCH_MILLIS + 30_000L); + assertThat(expired.claimState()).isEqualTo(ClaimState.EXPIRED); + assertThat(expired.claimFence()).isEqualTo(2L); + assertThat(expired.reservationClaimFence()).isEqualTo(1L); + assertThat(expired.state()).isEqualTo(State.AUTHORIZATION_PENDING); + + assertThatThrownBy( + () -> + repository.renew( + tuple, + tuple.mutationDigest(), + originalOwner, + 1L, + Phase.ACCOUNT_AUTHORIZATION, + State.AUTHORIZATION_PENDING, + NOW_EPOCH_MILLIS + 30_001L, + NOW_EPOCH_MILLIS + 60_001L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + + UUID recoveryOwner = UUID.randomUUID(); + var recovery = + repository + .acquireRecoveryClaim( + tuple, recoveryOwner, NOW_EPOCH_MILLIS + 30_001L, NOW_EPOCH_MILLIS + 60_001L) + .orElseThrow(); + assertThat(recovery.reservationOwnerId()).isEqualTo(originalOwner); + assertThat(recovery.snapshot().claimFence()).isEqualTo(3L); + assertThat(recovery.snapshot().reservationClaimFence()).isEqualTo(1L); + assertThat(recovery.snapshot().claimState()).isEqualTo(ClaimState.ACTIVE); + assertThat(recovery.snapshot().state()).isEqualTo(State.AUTHORIZATION_PENDING); + assertThat(recovery.snapshot().claimPurpose()).isEqualTo(ClaimPurpose.AUTHORIZATION_RECOVERY); + assertThat( + repository.acquireRecoveryClaim( + tuple, UUID.randomUUID(), NOW_EPOCH_MILLIS + 30_002L, NOW_EPOCH_MILLIS + 60_002L)) + .isEmpty(); + + var recoveredRecord = repository.findExact(tuple).orElseThrow(); + assertThat(recoveredRecord.phase()).isEqualTo(Phase.ACCOUNT_AUTHORIZATION); + assertThat(recoveredRecord.state()).isEqualTo(State.AUTHORIZATION_PENDING); + assertThat(recoveredRecord.reservationClaimFence()).isEqualTo(1L); + assertThat(recoveredRecord.claimFence()).isEqualTo(3L); + assertThat(State.values()) + .containsExactly( + State.RESERVED, + State.AUTHORIZATION_PENDING, + State.AUTHORIZED, + State.OWNER_EXECUTION_PENDING); + } + + @Test + void expiredReservedRecoveryMayIssueOnlyAfterSameReservationBecomesPending() { + StartSessionPreAuthorizationReservationTuple tuple = + tuple("postgres-reserved-recovery-03a", "reserved recovery fixture"); + UUID reservationOwner = UUID.fromString("bbf0aa73-6aeb-48d5-b4b6-2c454a6732ad"); + UUID recoveryOwner = UUID.fromString("109b9916-f068-4d49-944b-ae4b0ae95ee2"); + repository.acquire(tuple, reservationOwner, NOW_EPOCH_MILLIS, NOW_EPOCH_MILLIS + 30_000L); + var expired = + repository.expireClaim( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + Phase.ACCOUNT_AUTHORIZATION, + State.RESERVED, + NOW_EPOCH_MILLIS + 30_000L); + assertThat(expired.claimPurpose()).isNull(); + var recovery = + repository + .acquireRecoveryClaim( + tuple, recoveryOwner, NOW_EPOCH_MILLIS + 30_001L, NOW_EPOCH_MILLIS + 60_001L) + .orElseThrow(); + assertThat(recovery.snapshot().claimPurpose()).isEqualTo(ClaimPurpose.RESERVED_RECOVERY_ISSUE); + assertThat(recovery.snapshot().state()).isEqualTo(State.RESERVED); + assertThat(recovery.reservationOwnerId()).isEqualTo(reservationOwner); + assertThat(recovery.snapshot().reservationClaimFence()).isEqualTo(1L); + assertThat(recovery.snapshot().claimFence()).isEqualTo(3L); + + var pending = + repository.markAuthorizationPending( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + recoveryOwner, + 3L, + NOW_EPOCH_MILLIS + 30_002L); + assertThat(pending.transitioned()).isTrue(); + assertThat(pending.snapshot().claimPurpose()).isEqualTo(ClaimPurpose.RESERVED_RECOVERY_ISSUE); + var issueEvidence = + repository + .readCurrentClaim( + tuple, + reservationOwner, + 1L, + recoveryOwner, + 3L, + ReadPurpose.ISSUE, + NOW_EPOCH_MILLIS + 30_003L) + .orElseThrow(); + assertThat(issueEvidence.snapshot().state()).isEqualTo(State.AUTHORIZATION_PENDING); + assertThat(issueEvidence.snapshot().claimPurpose()) + .isEqualTo(ClaimPurpose.RESERVED_RECOVERY_ISSUE); + assertThatThrownBy( + () -> + repository.readCurrentClaim( + tuple, + reservationOwner, + 1L, + recoveryOwner, + 3L, + ReadPurpose.RECOVER, + NOW_EPOCH_MILLIS + 30_003L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + assertThat( + repository + .markAuthorizationPending( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + recoveryOwner, + 3L, + NOW_EPOCH_MILLIS + 30_004L) + .transitioned()) + .isFalse(); + } + + @Test + void concurrentExpiredPendingRecoveryClaimsHaveOneFenceWinner() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = + tuple("postgres-concurrent-recovery-03aa", "concurrent recovery fixture"); + UUID reservationOwner = UUID.fromString("444a3c54-4c0d-4157-9d57-e0dfc7746552"); + repository.acquire(tuple, reservationOwner, NOW_EPOCH_MILLIS, NOW_EPOCH_MILLIS + 30_000L); + repository.markAuthorizationPending( + tuple, tuple.mutationDigest(), reservationOwner, 1L, NOW_EPOCH_MILLIS + 1_000L); + repository.expireClaim( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + Phase.ACCOUNT_AUTHORIZATION, + State.AUTHORIZATION_PENDING, + NOW_EPOCH_MILLIS + 30_000L); + + int contenders = 2; + ExecutorService executor = Executors.newFixedThreadPool(contenders); + CountDownLatch ready = new CountDownLatch(contenders); + CountDownLatch start = new CountDownLatch(1); + List>> + futures = new ArrayList<>(); + try { + for (int index = 0; index < contenders; index++) { + UUID recoveryOwner = UUID.randomUUID(); + futures.add( + executor.submit( + () -> { + ready.countDown(); + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("concurrent recovery gate timed out"); + } + return repository.acquireRecoveryClaim( + tuple, recoveryOwner, NOW_EPOCH_MILLIS + 30_001L, NOW_EPOCH_MILLIS + 60_001L); + })); + } + assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + List> + results = new ArrayList<>(); + for (Future> + future : futures) { + results.add(future.get(10, TimeUnit.SECONDS)); + } + assertThat(results).filteredOn(Optional::isPresent).hasSize(1); + assertThat(results).filteredOn(Optional::isEmpty).hasSize(1); + assertThat(repository.findExact(tuple).orElseThrow().claimPurpose()) + .isEqualTo(ClaimPurpose.AUTHORIZATION_RECOVERY); + } finally { + executor.shutdownNow(); + } + } + + @Test + void expiredAuthorizedRecoveryReadsOnlyOriginalResponseAndHandsOffOnce() { + StartSessionPreAuthorizationReservationTuple tuple = + tuple("postgres-authorized-recovery-03b", "authorized recovery fixture"); + UUID reservationOwner = UUID.fromString("55ca8360-6f05-4f3a-8a9a-5cd78899b311"); + UUID recoveryOwner = UUID.fromString("8d57aaea-2ceb-4c87-a673-30d5cc83c86e"); + StartSessionPostAuthorizationExecutionTuple postTuple = + postTuple(tuple, reservationOwner, 1L, FINGERPRINT); + repository.acquire(tuple, reservationOwner, NOW_EPOCH_MILLIS, NOW_EPOCH_MILLIS + 30_000L); + repository.markAuthorizationPending( + tuple, tuple.mutationDigest(), reservationOwner, 1L, NOW_EPOCH_MILLIS + 1_000L); + repository.completeAuthorization( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + postTuple.canonicalJson(), + NOW_EPOCH_MILLIS + 2_000L); + repository.expireClaim( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + Phase.ACCOUNT_AUTHORIZATION, + State.AUTHORIZED, + NOW_EPOCH_MILLIS + 30_000L); + + var recovery = + repository + .acquireRecoveryClaim( + tuple, recoveryOwner, NOW_EPOCH_MILLIS + 30_001L, NOW_EPOCH_MILLIS + 60_001L) + .orElseThrow(); + assertThat(recovery.snapshot().state()).isEqualTo(State.AUTHORIZED); + assertThat(recovery.snapshot().claimPurpose()) + .isEqualTo(ClaimPurpose.AUTHORIZED_RESPONSE_RECOVERY); + var originalResponseLookup = + repository + .readCurrentClaim( + tuple, + reservationOwner, + 1L, + recoveryOwner, + recovery.snapshot().claimFence(), + ReadPurpose.RECOVER, + NOW_EPOCH_MILLIS + 30_002L) + .orElseThrow(); + assertThat(originalResponseLookup.snapshot().state()).isEqualTo(State.AUTHORIZED); + assertThat(originalResponseLookup.snapshot().claimPurpose()) + .isEqualTo(ClaimPurpose.AUTHORIZED_RESPONSE_RECOVERY); + assertThatThrownBy( + () -> + repository.readCurrentClaim( + tuple, + reservationOwner, + 1L, + recoveryOwner, + recovery.snapshot().claimFence(), + ReadPurpose.ISSUE, + NOW_EPOCH_MILLIS + 30_002L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + assertThatThrownBy( + () -> + repository.completeAuthorization( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + recoveryOwner, + recovery.snapshot().claimFence(), + postTuple(tuple, reservationOwner, 1L, "arfp/v1/other-key/" + "c".repeat(64)) + .canonicalJson(), + NOW_EPOCH_MILLIS + 30_003L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.IdempotencyConflictException.class); + + UUID handoffId = UUID.fromString("5d751e16-5637-4ea9-a8a2-4dc61b9f1325"); + var handoff = + repository.beginOwnerExecution( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + recoveryOwner, + recovery.snapshot().claimFence(), + postTuple.canonicalJson(), + handoffId, + NOW_EPOCH_MILLIS + 30_004L); + assertThat(handoff.mayDispatch()).isTrue(); + assertThat(handoff.snapshot().reservationOwnerId()).isEqualTo(reservationOwner); + assertThat(handoff.snapshot().currentClaimOwnerId()).isEqualTo(recoveryOwner); + assertThat(handoff.snapshot().postAuthorizationTuple().canonicalJson()) + .isEqualTo(postTuple.canonicalJson()); + assertThat( + repository + .beginOwnerExecution( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + recoveryOwner, + recovery.snapshot().claimFence(), + postTuple.canonicalJson(), + handoffId, + NOW_EPOCH_MILLIS + 30_005L) + .mayDispatch()) + .isFalse(); + + repository.expireClaim( + tuple, + tuple.mutationDigest(), + recoveryOwner, + recovery.snapshot().claimFence(), + Phase.OWNER_EXECUTION, + State.OWNER_EXECUTION_PENDING, + NOW_EPOCH_MILLIS + 60_001L); + assertThat( + repository.acquireRecoveryClaim( + tuple, + UUID.fromString("a2b6aafd-5598-4c99-8f36-b51b1ea47c6e"), + NOW_EPOCH_MILLIS + 60_002L, + NOW_EPOCH_MILLIS + 90_002L)) + .isEmpty(); + assertThat(repository.findAuthorizedExact(tuple).orElseThrow().handoff().handoffId()) + .isEqualTo(handoffId); + assertThat(dsl.fetchCount(START_SESSION_PRE_AUTHORIZATION_RESERVATIONS)).isEqualTo(1); + } + + @Test + void exactAuthorizationEnrichmentAndOwnerHandoffAreDurableBeforeDispatch() { + StartSessionPreAuthorizationReservationTuple tuple = + tuple("postgres-post-authorization-05", "post-authorization fixture"); + UUID reservationOwner = UUID.fromString("6641ea9e-dc0a-4f5d-80d0-6d87104a2fe7"); + UUID handoffId = UUID.fromString("dcb77e1f-e82a-4e07-a74a-1a4c92d1640c"); + StartSessionPostAuthorizationExecutionTuple postTuple = + postTuple(tuple, reservationOwner, 1L, FINGERPRINT); + repository.acquire(tuple, reservationOwner, NOW_EPOCH_MILLIS, NOW_EPOCH_MILLIS + 30_000L); + repository.markAuthorizationPending( + tuple, tuple.mutationDigest(), reservationOwner, 1L, NOW_EPOCH_MILLIS + 1_000L); + + var authorized = + repository.completeAuthorization( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + postTuple.canonicalJson(), + NOW_EPOCH_MILLIS + 2_000L); + assertThat(authorized.transitioned()).isTrue(); + assertThat(authorized.snapshot().reservationSnapshot().phase()) + .isEqualTo(Phase.ACCOUNT_AUTHORIZATION); + assertThat(authorized.snapshot().reservationSnapshot().state()).isEqualTo(State.AUTHORIZED); + assertThat(authorized.snapshot().reservationSnapshot().reservationClaimFence()).isEqualTo(1L); + assertThat(authorized.snapshot().postAuthorizationTuple().canonicalBytes()) + .containsExactly(postTuple.canonicalBytes()); + assertThat(authorized.snapshot().handoff()).isNull(); + + var duplicateAuthorization = + repository.completeAuthorization( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + postTuple.canonicalJson(), + NOW_EPOCH_MILLIS + 3_000L); + assertThat(duplicateAuthorization.transitioned()).isFalse(); + + var firstHandoff = + repository.beginOwnerExecution( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + postTuple.canonicalJson(), + handoffId, + NOW_EPOCH_MILLIS + 4_000L); + assertThat(firstHandoff.mayDispatch()).isTrue(); + assertThat(firstHandoff.snapshot().reservationSnapshot().phase()) + .isEqualTo(Phase.OWNER_EXECUTION); + assertThat(firstHandoff.snapshot().reservationSnapshot().state()) + .isEqualTo(State.OWNER_EXECUTION_PENDING); + assertThat(firstHandoff.snapshot().reservationSnapshot().reservationClaimFence()).isEqualTo(1L); + assertThat(firstHandoff.snapshot().handoff().handoffId()).isEqualTo(handoffId); + + var duplicateHandoff = + repository.beginOwnerExecution( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + postTuple.canonicalJson(), + handoffId, + NOW_EPOCH_MILLIS + 5_000L); + assertThat(duplicateHandoff.mayDispatch()).isFalse(); + assertThat(repository.findAuthorizedExact(tuple)) + .isPresent() + .get() + .satisfies( + snapshot -> { + assertThat(snapshot.postAuthorizationTuple().canonicalBytes()) + .containsExactly(postTuple.canonicalBytes()); + assertThat(snapshot.handoff()).isEqualTo(firstHandoff.snapshot().handoff()); + assertThat(snapshot.reservationOwnerId()).isEqualTo(reservationOwner); + assertThat(snapshot.currentClaimOwnerId()).isEqualTo(reservationOwner); + }); + + assertThatThrownBy( + () -> + repository.beginOwnerExecution( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + postTuple.canonicalJson(), + UUID.fromString("53d31d97-a8c3-48a1-9815-b3e3228bb6f2"), + NOW_EPOCH_MILLIS + 5_500L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.IdempotencyConflictException.class); + StartSessionPostAuthorizationExecutionTuple changedFingerprint = + postTuple(tuple, reservationOwner, 1L, "arfp/v1/other-key/" + "c".repeat(64)); + assertThatThrownBy( + () -> + repository.beginOwnerExecution( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + changedFingerprint.canonicalJson(), + handoffId, + NOW_EPOCH_MILLIS + 6_000L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.IdempotencyConflictException.class); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE start_session_pre_authorization_reservations " + + "SET post_authorization_execution_tuple_json = ? " + + "WHERE control_plane_request_id = ?", + postTuple.canonicalJson() + " ", + tuple.controlPlaneRequestId())) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM start_session_pre_authorization_reservations " + + "WHERE control_plane_request_id = ?", + tuple.controlPlaneRequestId())) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> dsl.execute("TRUNCATE TABLE start_session_pre_authorization_reservations")) + .isInstanceOf(RuntimeException.class); + } + + @Test + void phaseMismatchExpiredClaimAndChangedTupleCannotEnrichOrDispatch() { + StartSessionPreAuthorizationReservationTuple tuple = + tuple("postgres-post-stale-08", "post-authorization stale fixture"); + UUID reservationOwner = UUID.fromString("fb2827eb-6614-4cec-9e4a-e6c653ab827e"); + StartSessionPostAuthorizationExecutionTuple postTuple = + postTuple(tuple, reservationOwner, 1L, FINGERPRINT); + repository.acquire(tuple, reservationOwner, NOW_EPOCH_MILLIS, NOW_EPOCH_MILLIS + 30_000L); + + assertThatThrownBy( + () -> + repository.completeAuthorization( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + postTuple.canonicalJson(), + NOW_EPOCH_MILLIS + 1_000L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + + repository.markAuthorizationPending( + tuple, tuple.mutationDigest(), reservationOwner, 1L, NOW_EPOCH_MILLIS + 2_000L); + assertThatThrownBy( + () -> + repository.completeAuthorization( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + postTuple.canonicalJson(), + NOW_EPOCH_MILLIS + 30_000L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + + StartSessionPreAuthorizationReservationTuple changedTuple = + tuple(tuple.controlPlaneRequestId(), "changed action tuple"); + StartSessionPostAuthorizationExecutionTuple changedPostTuple = + postTuple(changedTuple, reservationOwner, 1L, FINGERPRINT); + assertThatThrownBy( + () -> + repository.completeAuthorization( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + changedPostTuple.canonicalJson(), + NOW_EPOCH_MILLIS + 3_000L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.IdempotencyConflictException.class); + assertThatThrownBy( + () -> + repository.beginOwnerExecution( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + postTuple.canonicalJson(), + UUID.fromString("f80cc7af-327c-44ab-96cc-23a84ff0ab4a"), + NOW_EPOCH_MILLIS + 4_000L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + assertThat(repository.findExact(tuple).orElseThrow().state()) + .isEqualTo(State.AUTHORIZATION_PENDING); + assertThat(repository.findAuthorizedExact(tuple)).isEmpty(); + } + + @Test + void recoveryClaimMayEnrichTheOriginalResponseButCannotReplaceOriginalFence() { + StartSessionPreAuthorizationReservationTuple tuple = + tuple("postgres-post-recovery-06", "post-authorization recovery fixture"); + UUID reservationOwner = UUID.fromString("06126c36-e190-43cb-932c-0f585ae2f795"); + UUID recoveryOwner = UUID.fromString("66369c32-4c13-4108-8cbc-e8c6103780b2"); + StartSessionPostAuthorizationExecutionTuple postTuple = + postTuple(tuple, reservationOwner, 1L, FINGERPRINT); + repository.acquire(tuple, reservationOwner, NOW_EPOCH_MILLIS, NOW_EPOCH_MILLIS + 30_000L); + repository.markAuthorizationPending( + tuple, tuple.mutationDigest(), reservationOwner, 1L, NOW_EPOCH_MILLIS + 1_000L); + repository.expireClaim( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + Phase.ACCOUNT_AUTHORIZATION, + State.AUTHORIZATION_PENDING, + NOW_EPOCH_MILLIS + 30_000L); + var recovery = + repository + .acquireRecoveryClaim( + tuple, recoveryOwner, NOW_EPOCH_MILLIS + 30_001L, NOW_EPOCH_MILLIS + 60_001L) + .orElseThrow(); + + var enriched = + repository.completeAuthorization( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + recoveryOwner, + recovery.snapshot().claimFence(), + postTuple.canonicalJson(), + NOW_EPOCH_MILLIS + 30_002L); + assertThat(enriched.transitioned()).isTrue(); + assertThat(enriched.snapshot().reservationSnapshot().reservationClaimFence()).isEqualTo(1L); + assertThat(enriched.snapshot().reservationSnapshot().claimFence()).isEqualTo(3L); + assertThat(enriched.snapshot().postAuthorizationTuple().reservationOwnerId()) + .isEqualTo(reservationOwner); + assertThat(enriched.snapshot().postAuthorizationTuple().reservationClaimFence()).isEqualTo(1L); + + var recoveryHandoff = + repository.beginOwnerExecution( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + recoveryOwner, + recovery.snapshot().claimFence(), + postTuple.canonicalJson(), + UUID.fromString("d3f21a41-f718-4d82-9438-411377a10852"), + NOW_EPOCH_MILLIS + 30_004L); + assertThat(recoveryHandoff.mayDispatch()).isTrue(); + assertThat(recoveryHandoff.snapshot().reservationOwnerId()).isEqualTo(reservationOwner); + assertThat(recoveryHandoff.snapshot().currentClaimOwnerId()).isEqualTo(recoveryOwner); + assertThat(recoveryHandoff.snapshot().reservationSnapshot().reservationClaimFence()) + .isEqualTo(1L); + assertThat(recoveryHandoff.snapshot().reservationSnapshot().claimFence()).isEqualTo(3L); + + assertThatThrownBy( + () -> + repository.beginOwnerExecution( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + postTuple.canonicalJson(), + UUID.fromString("d3f21a41-f718-4d82-9438-411377a10852"), + NOW_EPOCH_MILLIS + 30_003L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + assertThatThrownBy( + () -> + repository.beginOwnerExecution( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + recoveryOwner, + recovery.snapshot().claimFence() - 1L, + postTuple.canonicalJson(), + UUID.fromString("d3f21a41-f718-4d82-9438-411377a10852"), + NOW_EPOCH_MILLIS + 30_005L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + } + + @Test + void concurrentExactOwnerHandoffCasReturnsOnlyOneDispatchWinner() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = + tuple("postgres-post-concurrent-07", "concurrent handoff fixture"); + UUID reservationOwner = UUID.fromString("8a320d67-5c29-4671-a29e-21ac2bb93c71"); + UUID handoffId = UUID.fromString("7e1604ee-0a58-4fc5-a7ef-302ce18b53d0"); + StartSessionPostAuthorizationExecutionTuple postTuple = + postTuple(tuple, reservationOwner, 1L, FINGERPRINT); + repository.acquire(tuple, reservationOwner, NOW_EPOCH_MILLIS, NOW_EPOCH_MILLIS + 30_000L); + repository.markAuthorizationPending( + tuple, tuple.mutationDigest(), reservationOwner, 1L, NOW_EPOCH_MILLIS + 1_000L); + repository.completeAuthorization( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + postTuple.canonicalJson(), + NOW_EPOCH_MILLIS + 2_000L); + + int contenders = 2; + ExecutorService executor = Executors.newFixedThreadPool(contenders); + CountDownLatch ready = new CountDownLatch(contenders); + CountDownLatch start = new CountDownLatch(1); + List> + futures = new ArrayList<>(); + try { + for (int index = 0; index < contenders; index++) { + futures.add( + executor.submit( + () -> { + ready.countDown(); + try { + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("owner handoff gate timed out"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw interrupted; + } + return repository.beginOwnerExecution( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + postTuple.canonicalJson(), + handoffId, + NOW_EPOCH_MILLIS + 3_000L); + })); + } + boolean allReady; + try { + allReady = ready.await(5, TimeUnit.SECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw interrupted; + } + assertThat(allReady).isTrue(); + start.countDown(); + List + results = new ArrayList<>(); + try { + for (Future< + StartSessionPreAuthorizationReservationRepository.OwnerExecutionTransitionResult> + future : futures) { + results.add(future.get(10, TimeUnit.SECONDS)); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw interrupted; + } + assertThat(results) + .filteredOn( + StartSessionPreAuthorizationReservationRepository.OwnerExecutionTransitionResult + ::mayDispatch) + .hasSize(1); + assertThat(results).filteredOn(result -> !result.mayDispatch()).hasSize(1); + } finally { + executor.shutdownNow(); + } + } + + @Test + void currentClaimReadReturnsExactIssueAndRecoverySnapshotsAndRejectsStaleInputs() { + String requestId = "13c00ed3-c8e7-4fac-9d0b-129b3a7d09dc"; + StartSessionPreAuthorizationReservationTuple tuple = + tuple(requestId, "current-claim read fixture"); + UUID originalOwner = UUID.fromString("a5b1f46b-e8e4-420a-b904-226f941d1f19"); + UUID recoveryOwner = UUID.fromString("510c4b0e-fb34-43fb-839a-7cb641d0419e"); + repository.acquire(tuple, originalOwner, NOW_EPOCH_MILLIS, NOW_EPOCH_MILLIS + 30_000L); + repository.markAuthorizationPending( + tuple, tuple.mutationDigest(), originalOwner, 1L, NOW_EPOCH_MILLIS + 1_000L); + + var issueRead = + repository + .readCurrentClaim( + tuple, + originalOwner, + 1L, + originalOwner, + 1L, + ReadPurpose.ISSUE, + NOW_EPOCH_MILLIS + 2_000L) + .orElseThrow(); + assertThat(issueRead.snapshot().state()).isEqualTo(State.AUTHORIZATION_PENDING); + assertThat(issueRead.snapshot().tuple().canonicalJson()).isEqualTo(tuple.canonicalJson()); + assertThat(issueRead.snapshot().mutationDigest()).isEqualTo(tuple.mutationDigest()); + assertThat(issueRead.reservationOwnerId()).isEqualTo(originalOwner); + assertThat(issueRead.currentClaimOwnerId()).isEqualTo(originalOwner); + + repository.expireClaim( + tuple, + tuple.mutationDigest(), + originalOwner, + 1L, + Phase.ACCOUNT_AUTHORIZATION, + State.AUTHORIZATION_PENDING, + NOW_EPOCH_MILLIS + 30_000L); + var recoveredClaim = + repository + .acquireRecoveryClaim( + tuple, recoveryOwner, NOW_EPOCH_MILLIS + 30_001L, NOW_EPOCH_MILLIS + 60_001L) + .orElseThrow(); + assertThat(recoveredClaim.snapshot().reservationClaimFence()).isEqualTo(1L); + assertThat(recoveredClaim.snapshot().claimFence()).isEqualTo(3L); + + var recoveryRead = + repository + .readCurrentClaim( + tuple, + originalOwner, + 1L, + recoveryOwner, + 3L, + ReadPurpose.RECOVER, + NOW_EPOCH_MILLIS + 30_002L) + .orElseThrow(); + assertThat(recoveryRead.snapshot().tuple().canonicalJson()).isEqualTo(tuple.canonicalJson()); + assertThat(recoveryRead.snapshot().mutationDigest()).isEqualTo(tuple.mutationDigest()); + assertThat(recoveryRead.reservationOwnerId()).isEqualTo(originalOwner); + assertThat(recoveryRead.currentClaimOwnerId()).isEqualTo(recoveryOwner); + assertThat(recoveryRead.snapshot().claimFence()).isEqualTo(3L); + assertThat(recoveryRead.snapshot().claimPurpose()) + .isEqualTo(ClaimPurpose.AUTHORIZATION_RECOVERY); + + assertThatThrownBy( + () -> + repository.readCurrentClaim( + tuple, + originalOwner, + 1L, + recoveryOwner, + 3L, + ReadPurpose.ISSUE, + NOW_EPOCH_MILLIS + 30_003L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + + assertThatThrownBy( + () -> + repository.readCurrentClaim( + tuple, + originalOwner, + 1L, + originalOwner, + 1L, + ReadPurpose.ISSUE, + NOW_EPOCH_MILLIS + 30_002L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + assertThatThrownBy( + () -> + repository.readCurrentClaim( + tuple, + originalOwner, + 1L, + recoveryOwner, + 3L, + ReadPurpose.RECOVER, + NOW_EPOCH_MILLIS + 60_001L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + + StartSessionPreAuthorizationReservationTuple tamperedTuple = + tuple(requestId, "tampered tuple fixture"); + assertThatThrownBy( + () -> + repository.readCurrentClaim( + tamperedTuple, + originalOwner, + 1L, + recoveryOwner, + 3L, + ReadPurpose.RECOVER, + NOW_EPOCH_MILLIS + 30_002L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.IdempotencyConflictException.class); + } + + @Test + void immutableDigestGuardRejectsMutationAndReservationEvidenceRemainsReadable() { + StartSessionPreAuthorizationReservationTuple tuple = + tuple("postgres-integrity-04", "integrity fixture"); + acquire(tuple, UUID.randomUUID()); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE start_session_pre_authorization_reservations SET mutation_digest = ? " + + "WHERE control_plane_request_id = ?", + "0".repeat(64), + tuple.controlPlaneRequestId())) + .isInstanceOf(RuntimeException.class); + assertThat(repository.find(tuple.controlPlaneRequestId()).orElseThrow().mutationDigest()) + .isEqualTo(tuple.mutationDigest()); + } + + private StartSessionPreAuthorizationReservationRepository.AcquireResult acquire( + StartSessionPreAuthorizationReservationTuple tuple, UUID ownerId) { + return repository.acquire(tuple, ownerId, NOW_EPOCH_MILLIS, NOW_EPOCH_MILLIS + 30_000L); + } + + private void insertV3OriginalReservation( + StartSessionPreAuthorizationReservationTuple tuple, UUID reservationOwner) { + dsl.execute( + "INSERT INTO start_session_pre_authorization_reservations (" + + "control_plane_request_id, pre_authorization_tuple_json, mutation_digest, phase, state, " + + "reservation_owner_id, reservation_claim_fence, claim_owner_id, claim_fence, " + + "claim_expires_at_epoch_ms, claim_state, created_at_epoch_ms, updated_at_epoch_ms, " + + "post_authorization_execution_tuple_json, owner_execution_handoff_id) " + + "VALUES (?, ?, ?, 'ACCOUNT_AUTHORIZATION', 'RESERVED', ?, 1, ?, 1, ?, 'ACTIVE', ?, ?, NULL, NULL)", + tuple.controlPlaneRequestId(), + tuple.canonicalJson(), + tuple.mutationDigest(), + reservationOwner, + reservationOwner, + NOW_EPOCH_MILLIS + 30_000L, + NOW_EPOCH_MILLIS, + NOW_EPOCH_MILLIS); + } + + private void expireV3Claim(StartSessionPreAuthorizationReservationTuple tuple, long expiredAt) { + dsl.execute( + "UPDATE start_session_pre_authorization_reservations SET claim_owner_id = NULL, " + + "claim_fence = claim_fence + 1, claim_state = 'EXPIRED', updated_at_epoch_ms = ? " + + "WHERE control_plane_request_id = ?", + expiredAt, + tuple.controlPlaneRequestId()); + } + + private void recoverV3Claim( + StartSessionPreAuthorizationReservationTuple tuple, + UUID recoveryOwner, + long expiresAt, + long updatedAt) { + dsl.execute( + "UPDATE start_session_pre_authorization_reservations SET claim_owner_id = ?, " + + "claim_fence = claim_fence + 1, claim_expires_at_epoch_ms = ?, claim_state = 'ACTIVE', " + + "updated_at_epoch_ms = ? WHERE control_plane_request_id = ?", + recoveryOwner, + expiresAt, + updatedAt, + tuple.controlPlaneRequestId()); + } + + private String claimPurpose(String controlPlaneRequestId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT claim_purpose FROM start_session_pre_authorization_reservations " + + "WHERE control_plane_request_id = ?", + controlPlaneRequestId), + "The migrated reservation row must remain readable") + .get("claim_purpose", String.class); + } + + private static StartSessionPreAuthorizationReservationTuple tuple( + String requestId, String auditReason) { + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(TENANT_ID.toString(), List.of("tenantAdmin")), + false, + null, + null); + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target( + 29L, UUID.fromString("be78a8de-a113-48c4-a247-39e3505aed8c")), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + auditReason); + return StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin(requestId, action); + } + + private static StartSessionPostAuthorizationExecutionTuple postTuple( + StartSessionPreAuthorizationReservationTuple tuple, + UUID reservationOwner, + long reservationFence, + String fingerprint) { + return StartSessionPostAuthorizationExecutionTuple.createHuman( + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .fromCanonicalJson(tuple.canonicalJson()), + WORKLOAD, + fingerprint, + reservationOwner, + reservationFence, + authorityEvidenceBundle(tuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityEvidenceBundle( + StartSessionPreAuthorizationReservationTuple tuple) { + String tenantId = TENANT_ID.toString(); + Map value = + Map.of( + "bundleVersion", StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantId, "targetNamespace", "world-runtime"), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR_ID.toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + Instant.ofEpochMilli(NOW_EPOCH_MILLIS - 1_000L).toString(), + "expiresAt", + Instant.ofEpochMilli(NOW_EPOCH_MILLIS + 300_000L).toString()), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", Map.of(tenantId, 5L), + "issuanceFence", "23", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR_ID.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException exception) { + throw new IllegalStateException("could not encode test authority bundle", exception); + } + } +} diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionReservationEvidenceGrpcMutualTlsIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionReservationEvidenceGrpcMutualTlsIntegrationTest.java new file mode 100644 index 0000000000..030398a20e --- /dev/null +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionReservationEvidenceGrpcMutualTlsIntegrationTest.java @@ -0,0 +1,977 @@ +package net.firedevops.firemud.loggingadmin; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import com.google.protobuf.ByteString; +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslProvider; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyFactory; +import java.security.KeyStore; +import java.security.MessageDigest; +import java.security.Principal; +import java.security.PrivateKey; +import java.security.cert.Certificate; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.security.spec.PKCS8EncodedKeySpec; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.KeyManager; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.SSLHandshakeException; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509ExtendedKeyManager; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.loggingadmin.service.impl.StartSessionReservationEvidenceGrpcService; +import net.firedevops.firemud.loggingadmin.service.impl.StartSessionReservationEvidenceLeafApproval; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceRequest; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidenceServiceGrpc; +import net.firedevops.firemud.test.TestContainerImages; +import net.firedevops.firemud.test.TlsTestSupport; +import org.flywaydb.core.Flyway; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.Mockito; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@SuppressWarnings("resource") +class StartSessionReservationEvidenceGrpcMutualTlsIntegrationTest { + private static final String PUBLIC_METHOD = + "logging_admin.v1.StartSessionReservationEvidenceService/ReadCurrentClaimEvidence"; + private static final UUID TENANT_ID = UUID.fromString("f03e136b-522b-4ea1-b8a1-4a9f0811ea1d"); + private static final UUID ACTOR_ID = UUID.fromString("4cc8c9f1-45e6-4c9b-b22e-94c27e3dc91f"); + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String WRONG_SERVICE_URI = + "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String WRONG_NAMESPACE_URI = "spiffe://firemud/ns/other/sa/account-service"; + + @Test + void socketMtlsCertificateChecksDoNotRequirePersistence(@TempDir Path temporaryDirectory) + throws Exception { + TestWorkloadPki pki = TestWorkloadPki.create(temporaryDirectory); + assertThat(GrpcPeerIdentity.fromCertificate(readCertificate(pki.serverCertificate()))) + .get() + .extracting(GrpcPeerIdentity::uri) + .isEqualTo("spiffe://firemud/ns/test/sa/logging-admin-service"); + + Server server = + startTransport(pki, Mockito.mock(StartSessionPreAuthorizationReservationService.class)); + try { + assertTlsHandshakeAccepted(server, pki, pki.accountClient()); + assertHandshakeRejected( + server, pki, pki.clientWithoutCertificate(), "missing client certificate"); + assertHandshakeRejected( + server, pki, pki.untrustedAccountClient(), "untrusted client certificate chain"); + } finally { + server.shutdownNow(); + } + } + + @Nested + @Testcontainers(disabledWithoutDocker = true) + @SuppressWarnings("resource") + class DatabaseBackedReservationEvidenceTest { + @Container + static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void socketMtlsUsesTheVerifiedAccountPeerAndExactJwtExemption(@TempDir Path temporaryDirectory) + throws Exception { + DriverManagerDataSource dataSource = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .locations("classpath:db/migration") + .placeholders(Map.of("serviceSchema", "public")) + .load() + .migrate(); + StartSessionPreAuthorizationReservationService reservationService = + StartSessionReservationMutationTestFixtures.forRunOwnedPostgres(postgres).service(); + TestWorkloadPki pki = TestWorkloadPki.create(temporaryDirectory); + assertThat(GrpcPeerIdentity.fromCertificate(readCertificate(pki.serverCertificate()))) + .get() + .extracting(GrpcPeerIdentity::uri) + .isEqualTo("spiffe://firemud/ns/test/sa/logging-admin-service"); + StartSessionPreAuthorizationReservationTuple tuple = + tuple("grpc-mtls-reservation-evidence-01"); + var acquisition = reservationService.acquire(tuple); + assertThat(acquisition.newlyAcquired()).isTrue(); + assertThat( + reservationService + .markAuthorizationPending(acquisition.claim()) + .mayDispatchAccountAuthorization()) + .isTrue(); + var claim = acquisition.claim().claimEvidence(); + ReadCurrentClaimEvidenceRequest request = + ReadCurrentClaimEvidenceRequest.newBuilder() + .setControlPlaneRequestId(tuple.controlPlaneRequestId()) + .setPreAuthorizationTupleJson( + ByteString.copyFrom(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8))) + .setReservationOwnerId(claim.reservationOwnerId().toString()) + .setReservationClaimFence(claim.reservationClaimFence()) + .setClaimOwnerId(claim.currentClaimOwnerId().toString()) + .setClaimFence(claim.currentClaimFence()) + .setPurpose( + StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE) + .build(); + + Path approvedLeaves = temporaryDirectory.resolve("account-reservation-evidence-leaves.txt"); + String originalLeaf = certificateSha256(pki.accountClient().certificate()); + String replacementLeaf = certificateSha256(pki.replacementAccountClient().certificate()); + writeApprovedLeaves(approvedLeaves, "active=" + originalLeaf + "\n"); + + Server server = startTransport(pki, reservationService, true, approvedLeaves); + try { + ReadCurrentClaimEvidenceResponse response = read(server, pki, pki.accountClient(), request); + assertThat(response.getControlPlaneRequestId()).isEqualTo(tuple.controlPlaneRequestId()); + assertThat(response.getPreAuthorizationTupleJson().toByteArray()) + .containsExactly(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8)); + assertThat(response.getMutationDigest()).isEqualTo(tuple.mutationDigest()); + assertThat(response.getReservationOwnerId()) + .isEqualTo(claim.reservationOwnerId().toString()); + assertThat(response.getReservationClaimFence()).isEqualTo(claim.reservationClaimFence()); + assertThat(response.getClaimOwnerId()).isEqualTo(claim.currentClaimOwnerId().toString()); + assertThat(response.getClaimFence()).isEqualTo(claim.currentClaimFence()); + assertThat(response.getPurpose()) + .isEqualTo( + StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE); + assertThat(reservationService.findExact(tuple)).isPresent(); + + assertTlsHandshakeAccepted(server, pki, pki.accountClient()); + assertHandshakeRejected( + server, pki, pki.clientWithoutCertificate(), "missing client certificate"); + assertHandshakeRejected( + server, pki, pki.untrustedAccountClient(), "untrusted client certificate chain"); + assertThat(readStatus(server, pki, pki.wrongServiceClient(), request)) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(readStatus(server, pki, pki.wrongNamespaceClient(), request)) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(readStatus(server, pki, pki.replacementAccountClient(), request)) + .as("a CA-trusted same-URI leaf without instance approval must be denied") + .isEqualTo(Status.Code.PERMISSION_DENIED); + + long overlapExpiresAt = System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(2); + writeApprovedLeaves( + approvedLeaves, + "active=" + + replacementLeaf + + "\noverlap=" + + originalLeaf + + ";expires-at=" + + overlapExpiresAt + + "\n"); + assertThat(read(server, pki, pki.accountClient(), request).getControlPlaneRequestId()) + .isEqualTo(tuple.controlPlaneRequestId()); + assertThat( + read(server, pki, pki.replacementAccountClient(), request) + .getControlPlaneRequestId()) + .isEqualTo(tuple.controlPlaneRequestId()); + + writeApprovedLeaves(approvedLeaves, "active=" + replacementLeaf + "\n"); + assertThat(readStatus(server, pki, pki.accountClient(), request)) + .as("trusted replacement must revoke the previous leaf") + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + read(server, pki, pki.replacementAccountClient(), request) + .getControlPlaneRequestId()) + .isEqualTo(tuple.controlPlaneRequestId()); + } finally { + server.shutdownNow(); + } + } + } + + private static Server startTransport( + TestWorkloadPki pki, StartSessionPreAuthorizationReservationService reservationService) + throws Exception { + return startTransport(pki, reservationService, false); + } + + private static Server startTransport( + TestWorkloadPki pki, + StartSessionPreAuthorizationReservationService reservationService, + boolean seedStaleThreadLocalCallerContext) + throws Exception { + return startTransport(pki, reservationService, seedStaleThreadLocalCallerContext, null); + } + + private static Server startTransport( + TestWorkloadPki pki, + StartSessionPreAuthorizationReservationService reservationService, + boolean seedStaleThreadLocalCallerContext, + Path approvedLeafFile) + throws Exception { + var serverTls = + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.serverCertificate().toFile(), pki.serverPrivateKey().toFile()), + SslProvider.JDK) + .trustManager(pki.trustedCaCertificate().toFile()) + .clientAuth(ClientAuth.REQUIRE) + .protocols("TLSv1.3") + .build(); + StartSessionReservationEvidenceGrpcService receiver = + new StartSessionReservationEvidenceGrpcService( + reservationService, + new StartSessionReservationEvidenceLeafApproval( + approvedLeafFile == null ? "" : approvedLeafFile.toString()), + "test"); + ServerInterceptor staleThreadLocalCallerContextSeeder = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + if (seedStaleThreadLocalCallerContext + && PUBLIC_METHOD.equals(call.getMethodDescriptor().getFullMethodName())) { + SessionContext.setContext("stale-account", List.of("platformAdmin"), Map.of()); + } + return next.startCall(call, headers); + } + }; + var authenticatedReceiver = + ServerInterceptors.intercept( + receiver, + new AuthTokenInterceptor( + new JwtUtil("a".repeat(64), 3_600_000L), Set.of(PUBLIC_METHOD)), + new GrpcPeerIdentityInterceptor()); + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext(serverTls) + .addService( + ServerInterceptors.intercept( + authenticatedReceiver, staleThreadLocalCallerContextSeeder)) + .build() + .start(); + } + + private static ReadCurrentClaimEvidenceResponse read( + Server server, + TestWorkloadPki pki, + TestWorkloadPki.ClientIdentity clientIdentity, + ReadCurrentClaimEvidenceRequest request) + throws Exception { + ManagedChannel channel = clientChannel(server, pki, clientIdentity); + try { + return StartSessionReservationEvidenceServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(10, TimeUnit.SECONDS) + .readCurrentClaimEvidence(request); + } finally { + channel.shutdownNow(); + } + } + + private static Status.Code readStatus( + Server server, + TestWorkloadPki pki, + TestWorkloadPki.ClientIdentity clientIdentity, + ReadCurrentClaimEvidenceRequest request) + throws Exception { + try { + read(server, pki, clientIdentity, request); + return Status.Code.OK; + } catch (StatusRuntimeException ex) { + return ex.getStatus().getCode(); + } + } + + private static void assertHandshakeRejected( + Server server, + TestWorkloadPki pki, + TestWorkloadPki.ClientIdentity clientIdentity, + String description) + throws Exception { + RawClientTls clientTls = rawClientTls(pki, clientIdentity); + Throwable failure = + catchThrowable( + () -> { + try (SSLSocket socket = clientSocket(server, clientTls.context())) { + socket.startHandshake(); + socket.getInputStream().read(); + } + }); + assertThat(failure).as(description).isNotNull(); + assertThat(failure) + .as("%s must surface a TLS handshake exception", description) + .isInstanceOf(SSLHandshakeException.class); + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) + .as( + "%s must fail during the TLS certificate handshake; failure chain: %s", + description, throwableChain(failure)) + .isTrue(); + if (clientIdentity.certificate() != null) { + clientTls.assertIdentitySelected(clientIdentity, ACCOUNT_URI); + assertThat(clientTls.keyManager().requestedIssuers()) + .as("%s server issuer hints must exclude the selected account chain issuer", description) + .isNotEmpty() + .doesNotContain(clientTls.keyManager().selectedChain()[0].getIssuerX500Principal()); + } + } + + private static String throwableChain(Throwable failure) { + List causes = new ArrayList<>(); + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + causes.add(cause.getClass().getName() + ": " + cause.getMessage()); + } + return String.join(" -> ", causes); + } + + private static void assertTlsHandshakeAccepted( + Server server, TestWorkloadPki pki, TestWorkloadPki.ClientIdentity clientIdentity) + throws Exception { + RawClientTls clientTls = rawClientTls(pki, clientIdentity); + try (SSLSocket socket = clientSocket(server, clientTls.context())) { + socket.startHandshake(); + assertThat(socket.getSession().getProtocol()).isEqualTo("TLSv1.3"); + assertThat(socket.getApplicationProtocol()).isEqualTo("h2"); + } + clientTls.assertIdentitySelected(clientIdentity, ACCOUNT_URI); + } + + private static SSLSocket clientSocket(Server server, SSLContext context) throws Exception { + SSLSocket socket = + (SSLSocket) context.getSocketFactory().createSocket("127.0.0.1", server.getPort()); + socket.setSoTimeout(10_000); + SSLParameters parameters = socket.getSSLParameters(); + parameters.setEndpointIdentificationAlgorithm("HTTPS"); + parameters.setProtocols(new String[] {"TLSv1.3"}); + parameters.setApplicationProtocols(new String[] {"h2"}); + socket.setSSLParameters(parameters); + return socket; + } + + private static RawClientTls rawClientTls( + TestWorkloadPki pki, TestWorkloadPki.ClientIdentity clientIdentity) throws Exception { + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null, null); + trustStore.setCertificateEntry( + "logging-admin-test-ca", readCertificate(pki.trustedCaCertificate())); + TrustManagerFactory trustManagers = + TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagers.init(trustStore); + + ExplicitClientIdentityKeyManager explicitClientIdentity = null; + KeyManager[] keyManagers = null; + if (clientIdentity.certificate() != null) { + KeyStore clientKeyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + char[] password = TestWorkloadPki.STORE_PASSWORD.toCharArray(); + clientKeyStore.load(null, password); + clientKeyStore.setKeyEntry( + "logging-admin-test-client", + readPrivateKey(clientIdentity.privateKey()), + password, + new Certificate[] {readCertificate(clientIdentity.certificate())}); + KeyManagerFactory clientKeyManagers = + KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + clientKeyManagers.init(clientKeyStore, password); + explicitClientIdentity = + new ExplicitClientIdentityKeyManager( + (X509ExtendedKeyManager) clientKeyManagers.getKeyManagers()[0], + "logging-admin-test-client"); + keyManagers = new KeyManager[] {explicitClientIdentity}; + } + + SSLContext context = SSLContext.getInstance("TLS"); + context.init(keyManagers, trustManagers.getTrustManagers(), null); + return new RawClientTls(context, explicitClientIdentity); + } + + private record RawClientTls(SSLContext context, ExplicitClientIdentityKeyManager keyManager) { + void assertIdentitySelected(TestWorkloadPki.ClientIdentity clientIdentity, String expectedUri) + throws Exception { + assertThat(keyManager) + .as("raw TLS probe must have a client identity key manager") + .isNotNull(); + X509Certificate expectedCertificate = readCertificate(clientIdentity.certificate()); + assertThat(keyManager.selectedAlias()).isEqualTo("logging-admin-test-client"); + assertThat(keyManager.selectedChain()).containsExactly(expectedCertificate); + assertThat(GrpcPeerIdentity.fromCertificate(keyManager.selectedChain()[0])) + .get() + .extracting(GrpcPeerIdentity::uri) + .isEqualTo(expectedUri); + } + } + + /** + * Test-only key manager that selects its one explicit identity even when the server's issuer hint + * excludes that identity's issuer; this makes the untrusted-chain probe exercise rejection of the + * presented certificate rather than omission of a client certificate. + */ + private static final class ExplicitClientIdentityKeyManager extends X509ExtendedKeyManager { + private final X509ExtendedKeyManager delegate; + private final String explicitAlias; + private String selectedAlias; + private X509Certificate[] selectedChain; + private List requestedIssuers = List.of(); + + private ExplicitClientIdentityKeyManager( + X509ExtendedKeyManager delegate, String explicitAlias) { + this.delegate = delegate; + this.explicitAlias = explicitAlias; + } + + @Override + public String[] getClientAliases(String keyType, Principal[] issuers) { + return supports(keyType) ? new String[] {explicitAlias} : null; + } + + @Override + public String chooseClientAlias( + String[] keyTypes, Principal[] issuers, java.net.Socket socket) { + captureIssuers(issuers); + return supports(keyTypes) ? selectExplicitAlias() : null; + } + + @Override + public String[] getServerAliases(String keyType, Principal[] issuers) { + return delegate.getServerAliases(keyType, issuers); + } + + @Override + public String chooseServerAlias(String keyType, Principal[] issuers, java.net.Socket socket) { + return delegate.chooseServerAlias(keyType, issuers, socket); + } + + @Override + public X509Certificate[] getCertificateChain(String alias) { + X509Certificate[] chain = delegate.getCertificateChain(alias); + if (explicitAlias.equals(alias)) { + selectedChain = chain == null ? null : chain.clone(); + } + return chain; + } + + @Override + public PrivateKey getPrivateKey(String alias) { + return delegate.getPrivateKey(alias); + } + + @Override + public String chooseEngineClientAlias( + String[] keyTypes, Principal[] issuers, SSLEngine engine) { + captureIssuers(issuers); + return supports(keyTypes) ? selectExplicitAlias() : null; + } + + @Override + public String chooseEngineServerAlias(String keyType, Principal[] issuers, SSLEngine engine) { + return delegate.chooseEngineServerAlias(keyType, issuers, engine); + } + + private boolean supports(String keyType) { + PrivateKey key = delegate.getPrivateKey(explicitAlias); + return key != null && key.getAlgorithm().equalsIgnoreCase(keyType); + } + + private boolean supports(String[] keyTypes) { + return keyTypes != null && Arrays.stream(keyTypes).anyMatch(this::supports); + } + + private String selectExplicitAlias() { + selectedAlias = explicitAlias; + return explicitAlias; + } + + private void captureIssuers(Principal[] issuers) { + requestedIssuers = issuers == null ? List.of() : List.copyOf(Arrays.asList(issuers.clone())); + } + + private String selectedAlias() { + return selectedAlias; + } + + private X509Certificate[] selectedChain() { + return selectedChain == null ? new X509Certificate[0] : selectedChain.clone(); + } + + private List requestedIssuers() { + return requestedIssuers; + } + } + + private static PrivateKey readPrivateKey(Path privateKey) throws Exception { + String encoded = + Files.readString(privateKey) + .replace("-----BEGIN PRIVATE KEY-----", "") + .replace("-----END PRIVATE KEY-----", "") + .replaceAll("\\s", ""); + return KeyFactory.getInstance("RSA") + .generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(encoded))); + } + + private static ManagedChannel clientChannel( + Server server, TestWorkloadPki pki, TestWorkloadPki.ClientIdentity clientIdentity) + throws Exception { + var clientTls = + GrpcSslContexts.configure(GrpcSslContexts.forClient(), SslProvider.JDK) + .trustManager(pki.trustedCaCertificate().toFile()) + .protocols("TLSv1.3"); + if (clientIdentity.certificate() != null) { + clientTls.keyManager( + clientIdentity.certificate().toFile(), clientIdentity.privateKey().toFile()); + } + return NettyChannelBuilder.forAddress("127.0.0.1", server.getPort()) + .overrideAuthority("localhost") + .sslContext(clientTls.build()) + .build(); + } + + private static X509Certificate readCertificate(Path certificate) throws Exception { + try (var input = Files.newInputStream(certificate)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static String certificateSha256(Path certificate) throws Exception { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(readCertificate(certificate).getEncoded())); + } + + private static void writeApprovedLeaves(Path target, String policy) throws IOException { + Path targetParent = + Objects.requireNonNull(target.getParent(), "approval policy target must have a parent"); + Path replacement = Files.createTempFile(targetParent, "approved-leaves-", ".txt"); + try { + Files.writeString(replacement, policy, StandardCharsets.US_ASCII); + Files.move( + replacement, + target, + java.nio.file.StandardCopyOption.ATOMIC_MOVE, + java.nio.file.StandardCopyOption.REPLACE_EXISTING); + } finally { + Files.deleteIfExists(replacement); + } + } + + private static StartSessionPreAuthorizationReservationTuple tuple(String requestId) { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target( + 29L, UUID.fromString("4ecbb112-6962-4df5-87d0-9271f982a614")), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "socket mTLS Account evidence integration test"); + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(TENANT_ID.toString(), List.of("tenantAdmin")), + false, + null, + null); + try { + return StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin(requestId, action); + } finally { + SessionContext.clear(); + } + } + + /** + * Test-only keytool material, issued into a temporary directory and never shared or activated. + */ + private static final class TestWorkloadPki { + private static final String STORE_PASSWORD = "logging-reservation-test-only"; + + private final Path trustedCaCertificate; + private final Path serverCertificate; + private final Path serverPrivateKey; + private final ClientIdentity accountClient; + private final ClientIdentity replacementAccountClient; + private final ClientIdentity wrongServiceClient; + private final ClientIdentity wrongNamespaceClient; + private final ClientIdentity untrustedAccountClient; + + private TestWorkloadPki( + Path trustedCaCertificate, + Path serverCertificate, + Path serverPrivateKey, + ClientIdentity accountClient, + ClientIdentity replacementAccountClient, + ClientIdentity wrongServiceClient, + ClientIdentity wrongNamespaceClient, + ClientIdentity untrustedAccountClient) { + this.trustedCaCertificate = trustedCaCertificate; + this.serverCertificate = serverCertificate; + this.serverPrivateKey = serverPrivateKey; + this.accountClient = accountClient; + this.replacementAccountClient = replacementAccountClient; + this.wrongServiceClient = wrongServiceClient; + this.wrongNamespaceClient = wrongNamespaceClient; + this.untrustedAccountClient = untrustedAccountClient; + } + + static TestWorkloadPki create(Path directory) throws Exception { + Files.createDirectories(directory); + Path trustedCaStore = createCa(directory, "trusted-ca"); + Path trustedCaCertificate = exportCa(directory, trustedCaStore, "trusted-ca"); + Path untrustedCaStore = createCa(directory, "untrusted-ca"); + Path untrustedCaCertificate = exportCa(directory, untrustedCaStore, "untrusted-ca"); + Identity server = + issueIdentity( + directory, + trustedCaStore, + trustedCaCertificate, + "logging-admin-server", + "spiffe://firemud/ns/test/sa/logging-admin-service", + true); + ClientIdentity account = + asClient( + issueIdentity( + directory, + trustedCaStore, + trustedCaCertificate, + "account-service", + ACCOUNT_URI, + false)); + ClientIdentity wrongService = + asClient( + issueIdentity( + directory, + trustedCaStore, + trustedCaCertificate, + "wrong-service", + WRONG_SERVICE_URI, + false)); + ClientIdentity replacementAccount = + asClient( + issueIdentity( + directory, + trustedCaStore, + trustedCaCertificate, + "account-service-renewed", + ACCOUNT_URI, + false)); + ClientIdentity wrongNamespace = + asClient( + issueIdentity( + directory, + trustedCaStore, + trustedCaCertificate, + "wrong-namespace", + WRONG_NAMESPACE_URI, + false)); + ClientIdentity untrustedAccount = + asClient( + issueIdentity( + directory, + untrustedCaStore, + untrustedCaCertificate, + "untrusted-account", + ACCOUNT_URI, + false)); + return new TestWorkloadPki( + trustedCaCertificate, + server.certificate(), + server.privateKey(), + account, + replacementAccount, + wrongService, + wrongNamespace, + untrustedAccount); + } + + Path trustedCaCertificate() { + return trustedCaCertificate; + } + + Path serverCertificate() { + return serverCertificate; + } + + Path serverPrivateKey() { + return serverPrivateKey; + } + + ClientIdentity accountClient() { + return accountClient; + } + + ClientIdentity replacementAccountClient() { + return replacementAccountClient; + } + + ClientIdentity wrongServiceClient() { + return wrongServiceClient; + } + + ClientIdentity wrongNamespaceClient() { + return wrongNamespaceClient; + } + + ClientIdentity untrustedAccountClient() { + return untrustedAccountClient; + } + + ClientIdentity clientWithoutCertificate() { + return new ClientIdentity(null, null); + } + + private static Path createCa(Path directory, String alias) throws Exception { + Path store = directory.resolve(alias + ".p12"); + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD Logging reservation " + alias + " test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + return store; + } + + private static Path exportCa(Path directory, Path store, String alias) throws Exception { + Path certificate = directory.resolve(alias + ".crt"); + runKeytool( + "-exportcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-rfc"); + return certificate; + } + + private static Identity issueIdentity( + Path directory, + Path caStore, + Path caCertificate, + String alias, + String workloadUri, + boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + Path privateKey = directory.resolve(alias + ".key"); + String san = "URI:" + workloadUri + (server ? ",DNS:localhost,IP:127.0.0.1" : ""); + String extendedKeyUsage = server ? "serverAuth" : "clientAuth"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + extendedKeyUsage, + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + caStoreAlias(caStore), + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + extendedKeyUsage, + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + caStoreAlias(caStore), + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caCertificate.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + var key = (java.security.PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()); + byte[] certBytes = keyStore.getCertificate(alias).getEncoded(); + writePem(certificate, "CERTIFICATE", certBytes); + writePem(privateKey, "PRIVATE KEY", key.getEncoded()); + return new Identity(certificate, privateKey); + } + + private static ClientIdentity asClient(Identity identity) { + return new ClientIdentity(identity.certificate(), identity.privateKey()); + } + + private static String caStoreAlias(Path caStore) { + Objects.requireNonNull( + caStore.getParent(), "CA store must have a test-owned parent directory"); + Path fileName = Objects.requireNonNull(caStore.getFileName(), "CA store must name a file"); + return fileName.toString().replace(".p12", ""); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + List command = new ArrayList<>(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Path outputFile = Files.createTempFile("firemud-logging-reservation-keytool-", ".log"); + try { + Process process = + new ProcessBuilder(command) + .redirectErrorStream(true) + .redirectOutput(outputFile.toFile()) + .start(); + if (!process.waitFor(30, TimeUnit.SECONDS)) { + process.destroyForcibly(); + process.waitFor(5, TimeUnit.SECONDS); + throw new IllegalStateException("keytool exceeded its 30-second test-fixture timeout"); + } + String output = Files.readString(outputFile, StandardCharsets.UTF_8); + if (process.exitValue() != 0) { + throw new IllegalStateException("keytool failed: " + output); + } + } finally { + Files.deleteIfExists(outputFile); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + + private record Identity(Path certificate, Path privateKey) {} + + private record ClientIdentity(Path certificate, Path privateKey) {} + } +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationServiceTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationServiceTest.java new file mode 100644 index 0000000000..163abcea2a --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationServiceTest.java @@ -0,0 +1,639 @@ +package net.firedevops.firemud.loggingadmin.operator; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.loggingadmin.StartSessionReservationMutationTestFixtures; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Acquisition; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.AuthorizedSnapshot; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimPurpose; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimState; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.OwnerExecutionHandoff; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Phase; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.RecoveryAcquisition; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Snapshot; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.State; +import net.firedevops.firemud.loggingadmin.repository.StartSessionPreAuthorizationReservationRepository; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import tools.jackson.databind.json.JsonMapper; + +class StartSessionPreAuthorizationReservationServiceTest { + private static final long NOW_EPOCH_MILLIS = 1_800_000_000_000L; + private static final UUID TENANT_ID = UUID.fromString("3d3c5ca5-6d43-4db6-821d-8a0de883a467"); + private static final UUID ACTOR_ID = UUID.fromString("863843ee-f00a-4905-a9ad-11f706f1b693"); + private static final UUID ISSUANCE_ID = UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private final StartSessionPreAuthorizationReservationRepository repository = + mock(StartSessionPreAuthorizationReservationRepository.class); + private final Clock clock = Clock.fixed(Instant.ofEpochMilli(NOW_EPOCH_MILLIS), ZoneOffset.UTC); + private final StartSessionPreAuthorizationReservationService service = + StartSessionReservationMutationTestFixtures.forMockBackedUnitTest(repository, clock); + + @AfterEach + void clearAuthenticatedContext() { + SessionContext.clear(); + } + + @Test + void firstAcquisitionGetsOneBoundedClaimAndExactDuplicateGetsNoClaim() { + StartSessionPreAuthorizationReservationTuple tuple = tuple("service-unit-01"); + Snapshot initial = snapshot(tuple, State.RESERVED, 1L, 1L, ClaimState.ACTIVE); + when(repository.acquire(any(), any(), eq(NOW_EPOCH_MILLIS), eq(NOW_EPOCH_MILLIS + 30_000L))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.AcquireResult(initial, true)) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.AcquireResult(initial, false)); + + Acquisition first = service.acquire(tuple); + Acquisition duplicate = service.acquire(tuple); + + assertThat(first.newlyAcquired()).isTrue(); + assertThat(first.claim()).isNotNull(); + assertThat(first.claim().claimFence()).isEqualTo(1L); + assertThat(duplicate.newlyAcquired()).isFalse(); + assertThat(duplicate.claim()).isNull(); + verify(repository, org.mockito.Mockito.times(2)) + .acquire(any(), any(), eq(NOW_EPOCH_MILLIS), eq(NOW_EPOCH_MILLIS + 30_000L)); + } + + @Test + void parsedTupleCannotBeUsedAsAnInitialReservationAuthorityAssertion() { + StartSessionPreAuthorizationReservationTuple parsed = + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + tuple("service-unit-02").canonicalJson()); + + assertThat(parsed.isAuthorityDerived()).isFalse(); + assertThatThrownBy(() -> service.acquire(parsed)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("actor derived"); + } + + @Test + void expiredPendingClaimCanOnlyBeReacquiredAsReadOnlyRecoveryClaim() { + StartSessionPreAuthorizationReservationTuple tuple = tuple("service-unit-03"); + Snapshot recovered = snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 3L, ClaimState.ACTIVE); + when(repository.acquireRecoveryClaim( + eq(tuple), any(), eq(NOW_EPOCH_MILLIS), eq(NOW_EPOCH_MILLIS + 30_000L))) + .thenReturn( + Optional.of( + new StartSessionPreAuthorizationReservationRepository.RecoveryClaimResult( + recovered, UUID.fromString("6e0ef777-8661-4139-80eb-904b75de5860")))); + + Optional acquisition = service.acquireAuthorizationRecoveryClaim(tuple); + + assertThat(acquisition).isPresent(); + assertThat(acquisition.orElseThrow().claim().isRecoveryLookupOnly()).isTrue(); + assertThat(acquisition.orElseThrow().snapshot().reservationClaimFence()).isEqualTo(1L); + assertThat(acquisition.orElseThrow().snapshot().claimFence()).isEqualTo(3L); + assertThat(acquisition.orElseThrow().snapshot().state()).isEqualTo(State.AUTHORIZATION_PENDING); + assertThat(acquisition.orElseThrow().claim().claimEvidence().reservationClaimFence()) + .isEqualTo(1L); + assertThat(acquisition.orElseThrow().claim().claimEvidence().currentClaimFence()).isEqualTo(3L); + assertThatThrownBy(() -> service.markAuthorizationPending(acquisition.orElseThrow().claim())) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + } + + @Test + void expiredReservedClaimMayAdvanceOnceButDoesNotBecomeLookupOnly() { + StartSessionPreAuthorizationReservationTuple tuple = tuple("service-unit-reserved-recovery"); + UUID reservationOwnerId = UUID.fromString("c962ffad-5621-47a2-a38a-87d5d2ce96e1"); + Snapshot recovered = snapshot(tuple, State.RESERVED, 1L, 3L, ClaimState.ACTIVE); + Snapshot pending = + new Snapshot( + tuple, + tuple.mutationDigest(), + Phase.ACCOUNT_AUTHORIZATION, + State.AUTHORIZATION_PENDING, + 1L, + 3L, + NOW_EPOCH_MILLIS + 30_000L, + ClaimState.ACTIVE, + ClaimPurpose.RESERVED_RECOVERY_ISSUE); + when(repository.acquireRecoveryClaim( + eq(tuple), any(), eq(NOW_EPOCH_MILLIS), eq(NOW_EPOCH_MILLIS + 30_000L))) + .thenReturn( + Optional.of( + new StartSessionPreAuthorizationReservationRepository.RecoveryClaimResult( + recovered, reservationOwnerId))); + when(repository.markAuthorizationPending( + eq(tuple), + eq(tuple.mutationDigest()), + eq(reservationOwnerId), + eq(1L), + any(), + eq(3L), + eq(NOW_EPOCH_MILLIS))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.TransitionResult(pending, true)); + + RecoveryAcquisition acquisition = + service.acquireAuthorizationRecoveryClaim(tuple).orElseThrow(); + + assertThat(acquisition.claim().purpose()).isEqualTo(ClaimPurpose.RESERVED_RECOVERY_ISSUE); + assertThat(acquisition.claim().isRecoveryLookupOnly()).isFalse(); + var transition = service.markAuthorizationPending(acquisition.claim()); + assertThat(transition.mayDispatchAccountAuthorization()).isTrue(); + assertThat(transition.snapshot().claimPurpose()) + .isEqualTo(ClaimPurpose.RESERVED_RECOVERY_ISSUE); + } + + @Test + void currentClaimReadEchoesExactIssueAndRecoveryOwnershipWithoutMutation() { + String requestId = "start-session/operator/βeta"; + UUID reservationOwnerId = UUID.fromString("3bacbd32-12e5-46d2-9504-51aab74052bd"); + UUID recoveryOwnerId = UUID.fromString("a7bf2688-9f75-4ad8-ab45-7f65c7adbd97"); + StartSessionPreAuthorizationReservationTuple tuple = tuple(requestId); + Snapshot issueSnapshot = + snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 1L, ClaimState.ACTIVE); + Snapshot recoverySnapshot = + snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 3L, ClaimState.ACTIVE); + Snapshot authorizedRecoverySnapshot = + snapshot(tuple, State.AUTHORIZED, 1L, 5L, ClaimState.ACTIVE); + when(repository.readCurrentClaim( + tuple, + reservationOwnerId, + 1L, + reservationOwnerId, + 1L, + StartSessionPreAuthorizationReservationService.ReadPurpose.ISSUE, + NOW_EPOCH_MILLIS)) + .thenReturn( + Optional.of( + new StartSessionPreAuthorizationReservationRepository.CurrentClaimResult( + issueSnapshot, reservationOwnerId, reservationOwnerId))); + when(repository.readCurrentClaim( + tuple, + reservationOwnerId, + 1L, + recoveryOwnerId, + 3L, + StartSessionPreAuthorizationReservationService.ReadPurpose.RECOVER, + NOW_EPOCH_MILLIS)) + .thenReturn( + Optional.of( + new StartSessionPreAuthorizationReservationRepository.CurrentClaimResult( + recoverySnapshot, reservationOwnerId, recoveryOwnerId))); + when(repository.readCurrentClaim( + tuple, + reservationOwnerId, + 1L, + recoveryOwnerId, + 5L, + StartSessionPreAuthorizationReservationService.ReadPurpose.RECOVER, + NOW_EPOCH_MILLIS)) + .thenReturn( + Optional.of( + new StartSessionPreAuthorizationReservationRepository.CurrentClaimResult( + authorizedRecoverySnapshot, reservationOwnerId, recoveryOwnerId))); + + var issue = + service + .readCurrentClaimEvidence( + requestId, + tuple, + reservationOwnerId, + 1L, + reservationOwnerId, + 1L, + StartSessionPreAuthorizationReservationService.ReadPurpose.ISSUE) + .orElseThrow(); + var recovery = + service + .readCurrentClaimEvidence( + requestId, + tuple, + reservationOwnerId, + 1L, + recoveryOwnerId, + 3L, + StartSessionPreAuthorizationReservationService.ReadPurpose.RECOVER) + .orElseThrow(); + var authorizedRecovery = + service + .readCurrentClaimEvidence( + requestId, + tuple, + reservationOwnerId, + 1L, + recoveryOwnerId, + 5L, + StartSessionPreAuthorizationReservationService.ReadPurpose.RECOVER) + .orElseThrow(); + + assertThat(issue.snapshot().tuple().canonicalJson()).isEqualTo(tuple.canonicalJson()); + assertThat(issue.snapshot().mutationDigest()).isEqualTo(tuple.mutationDigest()); + assertThat(issue.reservationOwnerId()).isEqualTo(reservationOwnerId); + assertThat(issue.currentClaimOwnerId()).isEqualTo(reservationOwnerId); + assertThat(issue.snapshot().claimFence()).isEqualTo(1L); + assertThat(issue.purpose()) + .isEqualTo(StartSessionPreAuthorizationReservationService.ReadPurpose.ISSUE); + assertThat(issue.observedAtEpochMillis()).isEqualTo(NOW_EPOCH_MILLIS); + assertThat(recovery.reservationOwnerId()).isEqualTo(reservationOwnerId); + assertThat(recovery.currentClaimOwnerId()).isEqualTo(recoveryOwnerId); + assertThat(recovery.snapshot().reservationClaimFence()).isEqualTo(1L); + assertThat(recovery.snapshot().claimFence()).isEqualTo(3L); + assertThat(recovery.purpose()) + .isEqualTo(StartSessionPreAuthorizationReservationService.ReadPurpose.RECOVER); + assertThat(authorizedRecovery.snapshot().state()).isEqualTo(State.AUTHORIZED); + assertThat(authorizedRecovery.snapshot().claimPurpose()) + .isEqualTo(ClaimPurpose.AUTHORIZED_RESPONSE_RECOVERY); + verify(repository) + .readCurrentClaim( + tuple, + reservationOwnerId, + 1L, + reservationOwnerId, + 1L, + StartSessionPreAuthorizationReservationService.ReadPurpose.ISSUE, + NOW_EPOCH_MILLIS); + verify(repository) + .readCurrentClaim( + tuple, + reservationOwnerId, + 1L, + recoveryOwnerId, + 3L, + StartSessionPreAuthorizationReservationService.ReadPurpose.RECOVER, + NOW_EPOCH_MILLIS); + } + + @Test + void currentClaimReadRejectsWrongPurposeFreshnessAndExpiredSnapshots() { + String requestId = "start-session/operator/expiry"; + UUID reservationOwnerId = UUID.fromString("871ec253-4fe6-4e9f-9584-c74f9795f78a"); + UUID recoveryOwnerId = UUID.fromString("ec1e7980-e05a-4200-bde8-66cd314b0930"); + StartSessionPreAuthorizationReservationTuple tuple = tuple(requestId); + Snapshot lookupOnlyRecovery = + snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 3L, ClaimState.ACTIVE); + when(repository.readCurrentClaim( + tuple, + reservationOwnerId, + 1L, + recoveryOwnerId, + 3L, + StartSessionPreAuthorizationReservationService.ReadPurpose.ISSUE, + NOW_EPOCH_MILLIS)) + .thenReturn( + Optional.of( + new StartSessionPreAuthorizationReservationRepository.CurrentClaimResult( + lookupOnlyRecovery, reservationOwnerId, recoveryOwnerId))); + + assertThatThrownBy( + () -> + service.readCurrentClaimEvidence( + requestId, + tuple, + reservationOwnerId, + 1L, + recoveryOwnerId, + 3L, + StartSessionPreAuthorizationReservationService.ReadPurpose.ISSUE)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + assertThatThrownBy( + () -> + service.readCurrentClaimEvidence( + requestId, + tuple, + reservationOwnerId, + 1L, + reservationOwnerId, + 1L, + StartSessionPreAuthorizationReservationService.ReadPurpose.RECOVER)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + verify(repository) + .readCurrentClaim( + tuple, + reservationOwnerId, + 1L, + recoveryOwnerId, + 3L, + StartSessionPreAuthorizationReservationService.ReadPurpose.ISSUE, + NOW_EPOCH_MILLIS); + + Snapshot expired = + new Snapshot( + tuple, + tuple.mutationDigest(), + Phase.ACCOUNT_AUTHORIZATION, + State.AUTHORIZATION_PENDING, + 1L, + 1L, + NOW_EPOCH_MILLIS, + ClaimState.ACTIVE, + ClaimPurpose.ORIGINAL); + when(repository.readCurrentClaim( + tuple, + reservationOwnerId, + 1L, + reservationOwnerId, + 1L, + StartSessionPreAuthorizationReservationService.ReadPurpose.ISSUE, + NOW_EPOCH_MILLIS)) + .thenReturn( + Optional.of( + new StartSessionPreAuthorizationReservationRepository.CurrentClaimResult( + expired, reservationOwnerId, reservationOwnerId))); + + assertThatThrownBy( + () -> + service.readCurrentClaimEvidence( + requestId, + tuple, + reservationOwnerId, + 1L, + reservationOwnerId, + 1L, + StartSessionPreAuthorizationReservationService.ReadPurpose.ISSUE)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + } + + @Test + void durableAuthorizationAndOwnerTransitionExposeOnlyTheFirstHandoffForDispatch() { + StartSessionPreAuthorizationReservationTuple tuple = tuple("service-post-authorization"); + Snapshot reserved = snapshot(tuple, State.RESERVED, 1L, 1L, ClaimState.ACTIVE); + when(repository.acquire(any(), any(), eq(NOW_EPOCH_MILLIS), eq(NOW_EPOCH_MILLIS + 30_000L))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.AcquireResult(reserved, true)); + Acquisition acquired = service.acquire(tuple); + var claim = acquired.claim(); + UUID owner = claim.claimEvidence().reservationOwnerId(); + StartSessionPostAuthorizationExecutionTuple postTuple = + postTuple(tuple, owner, Instant.ofEpochMilli(NOW_EPOCH_MILLIS + 300_000L)); + + AuthorizedSnapshot authorizedSnapshot = + new AuthorizedSnapshot( + snapshot(tuple, State.AUTHORIZED, 1L, 1L, ClaimState.ACTIVE), + postTuple, + owner, + owner, + null); + when(repository.completeAuthorization( + eq(tuple), + eq(tuple.mutationDigest()), + eq(owner), + eq(1L), + eq(owner), + eq(1L), + eq(postTuple.canonicalJson()), + eq(NOW_EPOCH_MILLIS))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.AuthorizationTransitionResult( + authorizedSnapshot, true)); + + var completed = service.completeAuthorization(claim, postTuple); + + assertThat(completed.transitioned()).isTrue(); + assertThat(completed.snapshot().reservationSnapshot().state()).isEqualTo(State.AUTHORIZED); + assertThat(completed.snapshot().postAuthorizationTuple().canonicalBytes()) + .containsExactly(postTuple.canonicalBytes()); + + OwnerExecutionHandoff handoff = + new OwnerExecutionHandoff(UUID.fromString("dcb77e1f-e82a-4e07-a74a-1a4c92d1640c")); + AuthorizedSnapshot pendingSnapshot = + new AuthorizedSnapshot( + new Snapshot( + tuple, + tuple.mutationDigest(), + Phase.OWNER_EXECUTION, + State.OWNER_EXECUTION_PENDING, + 1L, + 1L, + NOW_EPOCH_MILLIS + 30_000L, + ClaimState.ACTIVE, + ClaimPurpose.ORIGINAL), + postTuple, + owner, + owner, + handoff); + when(repository.beginOwnerExecution( + eq(tuple), + eq(tuple.mutationDigest()), + eq(owner), + eq(1L), + eq(owner), + eq(1L), + eq(postTuple.canonicalJson()), + eq(handoff.handoffId()), + eq(NOW_EPOCH_MILLIS))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.OwnerExecutionTransitionResult( + pendingSnapshot, true)) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.OwnerExecutionTransitionResult( + pendingSnapshot, false)); + + var first = service.beginOwnerExecution(claim, postTuple, handoff); + var duplicate = service.beginOwnerExecution(claim, postTuple, handoff); + + assertThat(first.mayDispatch()).isTrue(); + assertThat(first.snapshot().handoff()).isEqualTo(handoff); + assertThat(duplicate.mayDispatch()).isFalse(); + verify(repository) + .completeAuthorization( + eq(tuple), + eq(tuple.mutationDigest()), + eq(owner), + eq(1L), + eq(owner), + eq(1L), + eq(postTuple.canonicalJson()), + eq(NOW_EPOCH_MILLIS)); + verify(repository, org.mockito.Mockito.times(2)) + .beginOwnerExecution( + eq(tuple), + eq(tuple.mutationDigest()), + eq(owner), + eq(1L), + eq(owner), + eq(1L), + eq(postTuple.canonicalJson()), + eq(handoff.handoffId()), + eq(NOW_EPOCH_MILLIS)); + } + + @Test + void phaseQualifiedStateModelHasNoSyntheticTerminalOutcome() { + assertThat(State.values()) + .containsExactly( + State.RESERVED, + State.AUTHORIZATION_PENDING, + State.AUTHORIZED, + State.OWNER_EXECUTION_PENDING); + assertThat(Phase.values()).containsExactly(Phase.ACCOUNT_AUTHORIZATION, Phase.OWNER_EXECUTION); + } + + @Test + void annotationConfigContextSelectsRepositoryConstructorWithoutDatabase() { + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); + context.registerBean(StartSessionPreAuthorizationReservationRepository.class, () -> repository); + context.register(StartSessionPreAuthorizationReservationService.class); + + try { + context.refresh(); + + assertThat(context.getBean(StartSessionPreAuthorizationReservationService.class)).isNotNull(); + } finally { + context.close(); + } + } + + private static Snapshot snapshot( + StartSessionPreAuthorizationReservationTuple tuple, + State state, + long reservationFence, + long currentFence, + ClaimState claimState) { + return new Snapshot( + tuple, + tuple.mutationDigest(), + Phase.ACCOUNT_AUTHORIZATION, + state, + reservationFence, + currentFence, + NOW_EPOCH_MILLIS + 30_000L, + claimState, + claimState == ClaimState.EXPIRED + ? null + : currentFence == reservationFence + ? ClaimPurpose.ORIGINAL + : state == State.RESERVED + ? ClaimPurpose.RESERVED_RECOVERY_ISSUE + : state == State.AUTHORIZATION_PENDING + ? ClaimPurpose.AUTHORIZATION_RECOVERY + : ClaimPurpose.AUTHORIZED_RESPONSE_RECOVERY); + } + + private static StartSessionPreAuthorizationReservationTuple tuple(String requestId) { + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(TENANT_ID.toString(), List.of("tenantAdmin")), + false, + null, + null); + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target( + 17L, UUID.fromString("2a9a4d47-a544-4984-bbc4-8e85f84116e4")), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "unit-test StartSession prerequisite"); + return StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin(requestId, action); + } + + private static StartSessionPostAuthorizationExecutionTuple postTuple( + StartSessionPreAuthorizationReservationTuple tuple, + UUID reservationOwner, + Instant expiresAt) { + return StartSessionPostAuthorizationExecutionTuple.createHuman( + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .fromCanonicalJson(tuple.canonicalJson()), + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service", + FINGERPRINT, + reservationOwner, + 1L, + authorityEvidenceBundle(tuple, expiresAt), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityEvidenceBundle( + StartSessionPreAuthorizationReservationTuple tuple, Instant expiresAt) { + String tenantId = TENANT_ID.toString(); + Map value = + Map.of( + "bundleVersion", StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantId, "targetNamespace", "world-runtime"), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR_ID.toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + Instant.ofEpochMilli(NOW_EPOCH_MILLIS - 1_000L).toString(), + "expiresAt", + expiresAt.toString()), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", Map.of(tenantId, 5L), + "issuanceFence", "23", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR_ID.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException exception) { + throw new IllegalStateException("could not encode test authority bundle", exception); + } + } +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTupleTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTupleTest.java new file mode 100644 index 0000000000..85c8e3a164 --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTupleTest.java @@ -0,0 +1,171 @@ +package net.firedevops.firemud.loggingadmin.operator; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionOperatorActionCodec; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +class StartSessionPreAuthorizationReservationTupleTest { + private static final UUID TENANT_ID = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR_ID = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + + @AfterEach + void clearAuthenticatedContext() { + SessionContext.clear(); + } + + @Test + void createsCanonicalHumanOnlyTupleFromCurrentTenantAdminAndPreservesAbsence() { + setTenantAdminContext(TENANT_ID, ACTOR_ID); + StartSessionOperatorAction action = action(StartSessionOperatorAction.ClientIp.absent()); + + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-01", action); + String canonicalJson = tuple.canonicalJson(); + + assertThat(tuple.actor().accountId()).isEqualTo(ACTOR_ID); + assertThat(tuple.isAuthorityDerived()).isTrue(); + assertThat(tuple.automationPolicy()) + .isEqualTo(StartSessionPreAuthorizationReservationTuple.NoAutomationPolicy.ABSENT); + assertThat(tuple.targetOwner()).isEqualTo(StartSessionOperatorAction.OWNER_SERVICE); + assertThat(tuple.mutationDigest()) + .isEqualTo(StartSessionOperatorActionCodec.mutationDigest(action)); + assertThat(canonicalJson) + .contains("\"requestIdentityKind\":\"controlPlaneRequestId\"") + .contains("\"targetOwner\":{\"ownerService\":\"game-session-service\"}") + .contains("\"expectedVersion\":{\"presence\":\"ABSENT\"}") + .contains("\"clientIp\":{\"presence\":\"ABSENT\"}") + .contains("\"automationPolicy\":{\"presence\":\"ABSENT\"}") + .doesNotContain("authorityDerived"); + StartSessionPreAuthorizationReservationTuple rehydrated = + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(canonicalJson); + assertThat(rehydrated).isEqualTo(tuple); + assertThat(rehydrated.isAuthorityDerived()).isFalse(); + assertThat( + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .fromCanonicalJson(canonicalJson) + .canonicalJson()) + .isEqualTo(canonicalJson); + } + + @Test + void preservesPresentClientIpAsASeparateTypedPresenceValue() { + setTenantAdminContext(TENANT_ID, ACTOR_ID); + StartSessionOperatorAction action = + action(StartSessionOperatorAction.ClientIp.of("203.0.113.8")); + + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-02", action); + + assertThat(tuple.canonicalJson()) + .contains("\"clientIp\":{\"presence\":\"PRESENT\",\"value\":\"203.0.113.8\"}"); + assertThat( + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(tuple.canonicalJson())) + .isEqualTo(tuple); + } + + @Test + void rejectsMissingHumanAuthorityAndDoesNotAcceptOtherRoleAsTenantAdmin() { + StartSessionOperatorAction action = action(StartSessionOperatorAction.ClientIp.absent()); + SessionContext.setContext(ACTOR_ID.toString(), List.of(), Map.of(), false, null, null); + + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-03", action)) + .isInstanceOf(IllegalArgumentException.class); + + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(TENANT_ID.toString(), List.of("moderator")), + false, + null, + null); + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-03", action)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsInternalOrWrongTenantAuthority() { + StartSessionOperatorAction action = action(StartSessionOperatorAction.ClientIp.absent()); + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(TENANT_ID.toString(), List.of("tenantAdmin")), + true, + "logging-admin-service", + "instance-1"); + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-04", action)) + .isInstanceOf(IllegalArgumentException.class); + + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(UUID.randomUUID().toString(), List.of("tenantAdmin")), + false, + null, + null); + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-04", action)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsNonCanonicalAndUnsupportedPersistedTupleShapes() { + setTenantAdminContext(TENANT_ID, ACTOR_ID); + String canonicalJson = + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-05", action(StartSessionOperatorAction.ClientIp.absent())) + .canonicalJson(); + + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(" " + canonicalJson)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + canonicalJson.replace("\"presence\":\"ABSENT\"", "\"presence\":\"NULL\""))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static void setTenantAdminContext(UUID tenantId, UUID actorId) { + SessionContext.setContext( + actorId.toString(), + List.of(), + Map.of(tenantId.toString(), List.of("tenantAdmin")), + false, + null, + null); + } + + private static StartSessionOperatorAction action(StartSessionOperatorAction.ClientIp clientIp) { + return new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target( + 91L, UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a")), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(clientIp), + "approved StartSession prerequisite"); + } +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionReservationMutationBoundaryTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionReservationMutationBoundaryTest.java new file mode 100644 index 0000000000..c9bcc30c58 --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionReservationMutationBoundaryTest.java @@ -0,0 +1,200 @@ +package net.firedevops.firemud.loggingadmin.operator; + +import static net.firedevops.firemud.loggingadmin.jooq.tables.StartSessionPreAuthorizationReservations.START_SESSION_PRE_AUTHORIZATION_RESERVATIONS; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ReadPurpose; +import net.firedevops.firemud.loggingadmin.repository.StartSessionPreAuthorizationReservationRepository; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.jooq.tools.jdbc.MockConnection; +import org.jooq.tools.jdbc.MockDataProvider; +import org.jooq.tools.jdbc.MockResult; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +class StartSessionReservationMutationBoundaryTest { + private static final long NOW_EPOCH_MILLIS = 1_800_000_000_000L; + private static final UUID TENANT_ID = UUID.fromString("86376245-2491-41c1-b87f-322a486f74d9"); + private static final UUID ACTOR_ID = UUID.fromString("0f11d69b-334d-42de-a844-2d557ba4e9a4"); + private static final UUID TARGET_ID = UUID.fromString("b2800980-9e55-4c62-a07d-d10f53bcfb22"); + + @AfterEach + void clearAuthenticatedContext() { + SessionContext.clear(); + } + + @Test + void productionServiceDeniesEveryMutationBeforeRepositoryCallsButLeavesReadsAvailable() { + StartSessionPreAuthorizationReservationRepository repository = + mock(StartSessionPreAuthorizationReservationRepository.class); + StartSessionPreAuthorizationReservationService service = + new StartSessionPreAuthorizationReservationService( + repository, Clock.fixed(Instant.ofEpochMilli(NOW_EPOCH_MILLIS), ZoneOffset.UTC)); + + assertThatThrownBy(() -> service.acquire(null)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> service.acquireAuthorizationRecoveryClaim(null)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> service.markAuthorizationPending(null)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> service.renew(null, null, null)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> service.expireClaim(null, null, null)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> service.completeAuthorization(null, null)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> service.beginOwnerExecution(null, null, null)) + .isInstanceOf(UnsupportedOperationException.class); + verifyNoInteractions(repository); + + StartSessionPreAuthorizationReservationTuple tuple = tuple("passive-service-read"); + when(repository.find(tuple.controlPlaneRequestId())).thenReturn(Optional.empty()); + when(repository.findExact(tuple)).thenReturn(Optional.empty()); + when(repository.findAuthorizedExact(tuple)).thenReturn(Optional.empty()); + when(repository.readCurrentClaim( + tuple, ACTOR_ID, 1L, ACTOR_ID, 1L, ReadPurpose.ISSUE, NOW_EPOCH_MILLIS)) + .thenReturn(Optional.empty()); + + assertThat(service.find(tuple.controlPlaneRequestId())).isEmpty(); + assertThat(service.findExact(tuple)).isEmpty(); + assertThat(service.findAuthorizedExact(tuple)).isEmpty(); + assertThat( + service.readCurrentClaimEvidence( + tuple.controlPlaneRequestId(), + tuple, + ACTOR_ID, + 1L, + ACTOR_ID, + 1L, + ReadPurpose.ISSUE)) + .isEmpty(); + verify(repository).find(tuple.controlPlaneRequestId()); + verify(repository).findExact(tuple); + verify(repository).findAuthorizedExact(tuple); + verify(repository) + .readCurrentClaim(tuple, ACTOR_ID, 1L, ACTOR_ID, 1L, ReadPurpose.ISSUE, NOW_EPOCH_MILLIS); + } + + @Test + void productionRepositoryDeniesEveryMutationBeforeDslCallsButLeavesFindAvailable() { + DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); + AtomicInteger executions = new AtomicInteger(); + MockDataProvider provider = + context -> { + executions.incrementAndGet(); + return new MockResult[] { + new MockResult(0, resultDsl.newResult(START_SESSION_PRE_AUTHORIZATION_RESERVATIONS)) + }; + }; + DSLContext dsl = DSL.using(new MockConnection(provider), SQLDialect.POSTGRES); + StartSessionPreAuthorizationReservationRepository repository = + new StartSessionPreAuthorizationReservationRepository(dsl); + + assertThatThrownBy(() -> repository.acquire(null, null, 0L, 0L)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> repository.acquireRecoveryClaim(null, null, 0L, 0L)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> repository.markAuthorizationPending(null, null, null, 0L, 0L)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy( + () -> repository.markAuthorizationPending(null, null, null, 0L, null, 0L, 0L)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> repository.renew(null, null, null, 0L, null, null, 0L, 0L)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> repository.expireClaim(null, null, null, 0L, null, null, 0L)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy( + () -> repository.completeAuthorization(null, null, null, 0L, null, 0L, null, 0L)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy( + () -> repository.beginOwnerExecution(null, null, null, 0L, null, 0L, null, null, 0L)) + .isInstanceOf(UnsupportedOperationException.class); + + assertThat(executions).hasValue(0); + StartSessionPreAuthorizationReservationTuple tuple = tuple("passive-repository-read"); + assertThat(repository.find(tuple.controlPlaneRequestId())).isEmpty(); + assertThat(repository.findExact(tuple)).isEmpty(); + assertThat(repository.findAuthorizedExact(tuple)).isEmpty(); + assertThat( + repository.readCurrentClaim( + tuple, + ACTOR_ID, + 1L, + UUID.fromString("36c9365a-5411-4e20-981c-a5b2a97e224e"), + 2L, + ReadPurpose.RECOVER, + NOW_EPOCH_MILLIS)) + .isEmpty(); + assertThat(executions).hasValue(4); + } + + @Test + void springConstructsPassiveRepositoryAndKeepsWritesDeniedBeforeSql() { + DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); + AtomicInteger executions = new AtomicInteger(); + MockDataProvider provider = + context -> { + executions.incrementAndGet(); + return new MockResult[] { + new MockResult(0, resultDsl.newResult(START_SESSION_PRE_AUTHORIZATION_RESERVATIONS)) + }; + }; + DSLContext dsl = DSL.using(new MockConnection(provider), SQLDialect.POSTGRES); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); + context.registerBean(DSLContext.class, () -> dsl); + context.registerBean(StartSessionPreAuthorizationReservationRepository.class); + + try { + context.refresh(); + StartSessionPreAuthorizationReservationRepository repository = + context.getBean(StartSessionPreAuthorizationReservationRepository.class); + StartSessionPreAuthorizationReservationTuple tuple = tuple("spring-passive-repository"); + + assertThatThrownBy(() -> repository.acquire(null, null, 0L, 0L)) + .isInstanceOf(UnsupportedOperationException.class); + assertThat(executions).hasValue(0); + assertThat(repository.find(tuple.controlPlaneRequestId())).isEmpty(); + assertThat(executions).hasValue(1); + } finally { + context.close(); + } + } + + private static StartSessionPreAuthorizationReservationTuple tuple(String requestId) { + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(TENANT_ID.toString(), List.of("tenantAdmin")), + false, + null, + null); + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target(19L, TARGET_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "unit-test passive read"); + return StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin(requestId, action); + } +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceGrpcServiceTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceGrpcServiceTest.java new file mode 100644 index 0000000000..c503a3a8c9 --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceGrpcServiceTest.java @@ -0,0 +1,641 @@ +package unit.net.firedevops.firemud.loggingadmin.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.inprocess.InProcessChannelBuilder; +import io.grpc.inprocess.InProcessServerBuilder; +import io.grpc.stub.MetadataUtils; +import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.cert.CertificateEncodingException; +import java.security.cert.X509Certificate; +import java.sql.SQLException; +import java.sql.SQLTransientException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimPurpose; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimState; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.CurrentClaimEvidence; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Phase; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ReadPurpose; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Snapshot; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.State; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.loggingadmin.service.impl.StartSessionReservationEvidenceGrpcService; +import net.firedevops.firemud.loggingadmin.service.impl.StartSessionReservationEvidenceLeafApproval; +import net.firedevops.firemud.loggingadmin.v1.LoggingAdminServiceGrpc; +import net.firedevops.firemud.loggingadmin.v1.PingRequest; +import net.firedevops.firemud.loggingadmin.v1.PingResponse; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceRequest; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidenceServiceGrpc; +import org.jooq.exception.DataAccessException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.TransientDataAccessResourceException; + +class StartSessionReservationEvidenceGrpcServiceTest { + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String REQUEST_ID = "start-session/evidence/βeta"; + private static final UUID RESERVATION_OWNER_ID = + UUID.fromString("c207c44a-92b8-4460-b8f1-53b52d5339f0"); + private static final UUID RECOVERY_OWNER_ID = + UUID.fromString("160c30d2-4912-4c8d-8957-0538d9462d08"); + private static final long OBSERVED_AT = 1_800_000_000_000L; + private static final byte[] APPROVED_LEAF_DER = + "test account leaf certificate".getBytes(StandardCharsets.US_ASCII); + private static final byte[] UNAPPROVED_LEAF_DER = + "other same-uri leaf certificate".getBytes(StandardCharsets.US_ASCII); + private static final String APPROVED_LEAF_SHA256 = sha256(APPROVED_LEAF_DER); + private final StartSessionPreAuthorizationReservationService reservationService = + mock(StartSessionPreAuthorizationReservationService.class); + @TempDir private Path temporaryDirectory; + private StartSessionReservationEvidenceGrpcService service; + + @BeforeEach + void configureApprovedAccountLeaf() throws Exception { + Path approvalFile = temporaryDirectory.resolve("approved-leaves.txt"); + Files.writeString( + approvalFile, "active=" + APPROVED_LEAF_SHA256 + "\n", StandardCharsets.US_ASCII); + service = + new StartSessionReservationEvidenceGrpcService( + reservationService, + new StartSessionReservationEvidenceLeafApproval(approvalFile.toString()), + "test"); + } + + @AfterEach + void clearAuthenticatedContext() { + SessionContext.clear(); + } + + @Test + void returnsExactIssueAndRecoveryEvidenceToSameNamespaceAccountPeer() { + StartSessionPreAuthorizationReservationTuple tuple = tuple(REQUEST_ID); + for (StartSessionReservationEvidencePurpose purpose : + List.of( + StartSessionReservationEvidencePurpose.START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE, + StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_RECOVER)) { + UUID currentOwner = + purpose + == StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE + ? RESERVATION_OWNER_ID + : RECOVERY_OWNER_ID; + long currentFence = currentOwner.equals(RESERVATION_OWNER_ID) ? 1L : 3L; + when(reservationService.readCurrentClaimEvidence( + eq(REQUEST_ID), + eq(tuple), + eq(RESERVATION_OWNER_ID), + eq(1L), + eq(currentOwner), + eq(currentFence), + eq(toPurpose(purpose)))) + .thenReturn(Optional.of(evidence(tuple, currentOwner, currentFence, toPurpose(purpose)))); + + Observer observer = call(request(tuple, currentOwner, currentFence, purpose), ACCOUNT_URI); + + assertThat(observer.failure).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(observer.response.getControlPlaneRequestId()).isEqualTo(REQUEST_ID); + assertThat(observer.response.getPreAuthorizationTupleJson().toByteArray()) + .containsExactly(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8)); + assertThat(observer.response.getMutationDigest()).isEqualTo(tuple.mutationDigest()); + assertThat(observer.response.getReservationOwnerId()) + .isEqualTo(RESERVATION_OWNER_ID.toString()); + assertThat(observer.response.getReservationClaimFence()).isEqualTo(1L); + assertThat(observer.response.getClaimOwnerId()).isEqualTo(currentOwner.toString()); + assertThat(observer.response.getClaimFence()).isEqualTo(currentFence); + assertThat(observer.response.getClaimExpiresAtEpochMillis()).isEqualTo(OBSERVED_AT + 30_000L); + assertThat(observer.response.getObservedAtEpochMillis()).isEqualTo(OBSERVED_AT); + assertThat(observer.response.getPurpose()).isEqualTo(purpose); + verify(reservationService) + .readCurrentClaimEvidence( + REQUEST_ID, + tuple, + RESERVATION_OWNER_ID, + 1L, + currentOwner, + currentFence, + toPurpose(purpose)); + } + } + + @Test + void deniesMissingUnknownWrongServiceCrossNamespaceAndUnconfiguredPeersBeforeRead() { + StartSessionPreAuthorizationReservationTuple tuple = tuple(REQUEST_ID); + for (String peer : + new String[] { + null, + "spiffe://firemud/ns/other/sa/account-service", + "spiffe://firemud/ns/test/sa/game-session-service", + "spiffe://firemud/ns/test/sa/unknown-service" + }) { + assertThat(status(call(request(tuple, RESERVATION_OWNER_ID, 1L, issuePurpose()), peer))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } + + assertThat( + status( + call( + request(tuple, RESERVATION_OWNER_ID, 1L, issuePurpose()), + ACCOUNT_URI, + UNAPPROVED_LEAF_DER))) + .as("a same-URI certificate without leaf-instance approval must be denied") + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + status( + callWithoutCertificateEvidence( + request(tuple, RESERVATION_OWNER_ID, 1L, issuePurpose()), ACCOUNT_URI))) + .as("a URI principal without presented-leaf evidence must be denied") + .isEqualTo(Status.Code.PERMISSION_DENIED); + + StartSessionReservationEvidenceGrpcService unconfigured = + new StartSessionReservationEvidenceGrpcService( + reservationService, new StartSessionReservationEvidenceLeafApproval(""), ""); + Observer observer = new Observer(); + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(ACCOUNT_URI).orElseThrow(); + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .run( + () -> + unconfigured.readCurrentClaimEvidence( + request(tuple, RESERVATION_OWNER_ID, 1L, issuePurpose()), observer)); + assertThat(status(observer)).isEqualTo(Status.Code.PERMISSION_DENIED); + + StartSessionReservationEvidenceGrpcService missingApprovalFile = + new StartSessionReservationEvidenceGrpcService( + reservationService, + new StartSessionReservationEvidenceLeafApproval( + temporaryDirectory.resolve("missing-approval.txt").toString()), + "test"); + assertThat( + status( + call( + missingApprovalFile, + request(tuple, RESERVATION_OWNER_ID, 1L, issuePurpose()), + ACCOUNT_URI, + APPROVED_LEAF_DER))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(reservationService); + } + + @Test + void deniesHumanCallerContextBeforeOwnerRead() { + StartSessionPreAuthorizationReservationTuple tuple = tuple(REQUEST_ID); + SessionContext.setContext("account-uuid", List.of("player"), Map.of()); + + assertThat(status(call(request(tuple, RESERVATION_OWNER_ID, 1L, issuePurpose()), ACCOUNT_URI))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(reservationService); + } + + @Test + void acceptsCanonicalNfcUnicodeRequestIdAtExactUtf8ByteBound() { + String requestId = "é".repeat(64); + StartSessionPreAuthorizationReservationTuple tuple = tuple(requestId); + when(reservationService.readCurrentClaimEvidence( + eq(requestId), + eq(tuple), + eq(RESERVATION_OWNER_ID), + eq(1L), + eq(RESERVATION_OWNER_ID), + eq(1L), + eq(ReadPurpose.ISSUE))) + .thenReturn(Optional.of(evidence(tuple, RESERVATION_OWNER_ID, 1L, ReadPurpose.ISSUE))); + + Observer observer = call(request(tuple), ACCOUNT_URI); + + assertThat(observer.failure).isNull(); + assertThat(observer.response.getControlPlaneRequestId()).isEqualTo(requestId); + verify(reservationService) + .readCurrentClaimEvidence( + requestId, + tuple, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + ReadPurpose.ISSUE); + } + + @Test + void rejectsNonCanonicalOrTamperedRequestsBeforeOwnerRead() { + StartSessionPreAuthorizationReservationTuple tuple = tuple(REQUEST_ID); + List malformed = + List.of( + request(tuple).toBuilder() + .setControlPlaneRequestId("start-session/e\u0301vidence") + .build(), + request(tuple).toBuilder().setControlPlaneRequestId("").build(), + request(tuple).toBuilder().setReservationOwnerId("not-a-uuid").build(), + request(tuple).toBuilder().setReservationClaimFence(0L).build(), + request(tuple).toBuilder().setClaimFence(-1L).build(), + request(tuple).toBuilder() + .setPreAuthorizationTupleJson(ByteString.copyFrom(new byte[] {(byte) 0xc3, 0x28})) + .build(), + request(tuple).toBuilder() + .setPreAuthorizationTupleJson(ByteString.copyFromUtf8(tuple.canonicalJson() + " ")) + .build(), + request(tuple).toBuilder() + .setPurpose( + StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_UNSPECIFIED) + .build(), + request(tuple).toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build()); + malformed = new ArrayList<>(malformed); + String overLimitRequestId = "é".repeat(65); + String tupleLimitRequestId = "start-session/overlimit"; + StartSessionPreAuthorizationReservationTuple tupleForLimit = tuple(tupleLimitRequestId); + String overLimitTupleJson = + tupleForLimit + .canonicalJson() + .replace( + "\"requestId\":\"" + tupleLimitRequestId + "\"", + "\"requestId\":\"" + overLimitRequestId + "\""); + assertThat(overLimitTupleJson).isNotEqualTo(tupleForLimit.canonicalJson()); + malformed.add( + request(tupleForLimit).toBuilder() + .setPreAuthorizationTupleJson( + ByteString.copyFrom(overLimitTupleJson.getBytes(StandardCharsets.UTF_8))) + .build()); + malformed.add(request(tuple).toBuilder().setControlPlaneRequestId(overLimitRequestId).build()); + ReadCurrentClaimEvidenceRequest tupleKeyMismatch = + request(tuple).toBuilder().setControlPlaneRequestId("start-session/evidence/other").build(); + malformed.add(tupleKeyMismatch); + for (String nonObjectRoot : List.of("[]", "\"tuple\"", "1", "true", "null")) { + malformed.add( + request(tuple).toBuilder() + .setPreAuthorizationTupleJson(ByteString.copyFromUtf8(nonObjectRoot)) + .build()); + } + + for (ReadCurrentClaimEvidenceRequest request : malformed) { + assertThat(status(call(request, ACCOUNT_URI))).isEqualTo(Status.Code.INVALID_ARGUMENT); + } + verifyNoInteractions(reservationService); + } + + @Test + void failsClosedForAbsentStaleMismatchedOrUnavailableOwnerEvidence() { + StartSessionPreAuthorizationReservationTuple tuple = tuple(REQUEST_ID); + ReadCurrentClaimEvidenceRequest request = + request(tuple, RESERVATION_OWNER_ID, 1L, issuePurpose()); + when(reservationService.readCurrentClaimEvidence( + any(), any(), any(), anyLong(), any(), anyLong(), any())) + .thenReturn(Optional.empty()) + .thenThrow( + new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + REQUEST_ID)) + .thenThrow( + new StartSessionPreAuthorizationReservationService.IdempotencyConflictException( + REQUEST_ID)) + .thenThrow(new DataAccessResourceFailureException("offline")) + .thenThrow(new TransientDataAccessResourceException("retry the read")); + + assertThat(status(call(request, ACCOUNT_URI))).isEqualTo(Status.Code.NOT_FOUND); + assertThat(status(call(request, ACCOUNT_URI))).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(status(call(request, ACCOUNT_URI))).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(status(call(request, ACCOUNT_URI))).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(status(call(request, ACCOUNT_URI))).isEqualTo(Status.Code.UNAVAILABLE); + } + + @Test + void mapsOnlyConnectionAndTransientSqlFailuresToUnavailable() { + StartSessionPreAuthorizationReservationTuple tuple = tuple(REQUEST_ID); + ReadCurrentClaimEvidenceRequest request = request(tuple); + when(reservationService.readCurrentClaimEvidence( + any(), any(), any(), anyLong(), any(), anyLong(), any())) + .thenThrow( + new DataAccessException("connection failure", new SQLException("offline", "08006"))) + .thenThrow( + new DataAccessException( + "transient failure", new SQLTransientException("retry the transaction"))) + .thenThrow( + new DataAccessException("syntax failure", new SQLException("syntax error", "42601"))) + .thenThrow( + new DataAccessException( + "constraint failure", new SQLException("unique constraint", "23505"))) + .thenThrow( + new DataAccessException("type failure", new SQLException("type mismatch", "42804"))) + .thenThrow( + new DataAccessException( + "nested connection failure", + new IllegalStateException( + "driver wrapper", new SQLException("connection reset", "08001")))); + + assertThat(status(call(request, ACCOUNT_URI))).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(status(call(request, ACCOUNT_URI))).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(status(call(request, ACCOUNT_URI))).isEqualTo(Status.Code.INTERNAL); + assertThat(status(call(request, ACCOUNT_URI))).isEqualTo(Status.Code.INTERNAL); + assertThat(status(call(request, ACCOUNT_URI))).isEqualTo(Status.Code.INTERNAL); + assertThat(status(call(request, ACCOUNT_URI))).isEqualTo(Status.Code.UNAVAILABLE); + } + + @Test + void canonicalTupleTamperingReachesOwnerComparisonAndConflicts() { + StartSessionPreAuthorizationReservationTuple tamperedTuple = + tuple(REQUEST_ID, "changed audit reason"); + when(reservationService.readCurrentClaimEvidence( + eq(REQUEST_ID), + eq(tamperedTuple), + eq(RESERVATION_OWNER_ID), + eq(1L), + eq(RESERVATION_OWNER_ID), + eq(1L), + eq(ReadPurpose.ISSUE))) + .thenThrow( + new StartSessionPreAuthorizationReservationService.IdempotencyConflictException( + REQUEST_ID)); + + Observer observer = call(request(tamperedTuple), ACCOUNT_URI); + + assertThat(status(observer)).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(observer.response).isNull(); + verify(reservationService) + .readCurrentClaimEvidence( + REQUEST_ID, + tamperedTuple, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + ReadPurpose.ISSUE); + } + + @Test + void exactPublicMethodTraversesJwtAndPeerInterceptorsOverGrpcTransport() throws Exception { + String serverName = InProcessServerBuilder.generateName(); + Server server = + InProcessServerBuilder.forName(serverName) + .directExecutor() + .intercept( + new AuthTokenInterceptor( + new JwtUtil("a".repeat(64), 3_600_000L), + Set.of( + "logging_admin.v1.StartSessionReservationEvidenceService/" + + "ReadCurrentClaimEvidence"))) + .intercept(new GrpcPeerIdentityInterceptor()) + .addService(service) + .addService( + new LoggingAdminServiceGrpc.LoggingAdminServiceImplBase() { + @Override + public void ping(PingRequest request, StreamObserver observer) { + observer.onNext(PingResponse.newBuilder().setMessage("pong").build()); + observer.onCompleted(); + } + }) + .build() + .start(); + ManagedChannel channel = InProcessChannelBuilder.forName(serverName).directExecutor().build(); + try { + ReadCurrentClaimEvidenceRequest evidenceRequest = request(tuple(REQUEST_ID)); + assertThat( + transportStatus( + () -> + StartSessionReservationEvidenceServiceGrpc.newBlockingStub(channel) + .readCurrentClaimEvidence(evidenceRequest))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + + Metadata invalidJwtHeader = new Metadata(); + invalidJwtHeader.put( + Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER), + "Bearer deliberately-invalid"); + assertThat( + transportStatus( + () -> + StartSessionReservationEvidenceServiceGrpc.newBlockingStub(channel) + .withInterceptors( + MetadataUtils.newAttachHeadersInterceptor(invalidJwtHeader)) + .readCurrentClaimEvidence(evidenceRequest))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + + assertThat( + transportStatus( + () -> + LoggingAdminServiceGrpc.newBlockingStub(channel) + .ping(PingRequest.getDefaultInstance()))) + .isEqualTo(Status.Code.UNAUTHENTICATED); + verifyNoInteractions(reservationService); + } finally { + channel.shutdownNow(); + server.shutdownNow(); + } + } + + private Observer call(ReadCurrentClaimEvidenceRequest request, String peerUri) { + return call(service, request, peerUri, APPROVED_LEAF_DER); + } + + private Observer call( + ReadCurrentClaimEvidenceRequest request, String peerUri, byte[] leafCertificateDer) { + return call(service, request, peerUri, leafCertificateDer); + } + + private Observer call( + StartSessionReservationEvidenceGrpcService receiver, + ReadCurrentClaimEvidenceRequest request, + String peerUri, + byte[] leafCertificateDer) { + Observer observer = new Observer(); + Runnable invocation = () -> receiver.readCurrentClaimEvidence(request, observer); + Optional peer = + peerUri == null ? Optional.empty() : GrpcPeerIdentity.parseUri(peerUri); + if (peer.isEmpty()) { + invocation.run(); + } else { + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer.orElseThrow()) + .withValue( + GrpcPeerCertificateEvidence.CONTEXT_KEY, certificateEvidence(leafCertificateDer)) + .run(invocation); + } + return observer; + } + + private Observer callWithoutCertificateEvidence( + ReadCurrentClaimEvidenceRequest request, String peerUri) { + Observer observer = new Observer(); + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(peerUri).orElseThrow(); + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .run(() -> service.readCurrentClaimEvidence(request, observer)); + return observer; + } + + private static GrpcPeerCertificateEvidence certificateEvidence(byte[] certificateDer) { + X509Certificate leaf = mock(X509Certificate.class); + try { + when(leaf.getEncoded()).thenReturn(certificateDer); + } catch (CertificateEncodingException exception) { + throw new AssertionError(exception); + } + return GrpcPeerCertificateEvidence.fromCertificate(leaf).orElseThrow(); + } + + private static String sha256(byte[] value) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException exception) { + throw new AssertionError(exception); + } + } + + private static ReadCurrentClaimEvidenceRequest request( + StartSessionPreAuthorizationReservationTuple tuple, + UUID currentOwner, + long currentFence, + StartSessionReservationEvidencePurpose purpose) { + return ReadCurrentClaimEvidenceRequest.newBuilder() + .setControlPlaneRequestId(tuple.controlPlaneRequestId()) + .setPreAuthorizationTupleJson( + ByteString.copyFrom(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8))) + .setReservationOwnerId(RESERVATION_OWNER_ID.toString()) + .setReservationClaimFence(1L) + .setClaimOwnerId(currentOwner.toString()) + .setClaimFence(currentFence) + .setPurpose(purpose) + .build(); + } + + private static ReadCurrentClaimEvidenceRequest request( + StartSessionPreAuthorizationReservationTuple tuple) { + return request(tuple, RESERVATION_OWNER_ID, 1L, issuePurpose()); + } + + private static StartSessionReservationEvidencePurpose issuePurpose() { + return StartSessionReservationEvidencePurpose.START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE; + } + + private static ReadPurpose toPurpose(StartSessionReservationEvidencePurpose purpose) { + return switch (purpose) { + case START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE -> ReadPurpose.ISSUE; + case START_SESSION_RESERVATION_EVIDENCE_PURPOSE_RECOVER -> ReadPurpose.RECOVER; + default -> throw new IllegalArgumentException("unsupported purpose"); + }; + } + + private static CurrentClaimEvidence evidence( + StartSessionPreAuthorizationReservationTuple tuple, + UUID currentOwner, + long currentFence, + ReadPurpose purpose) { + Snapshot snapshot = + new Snapshot( + tuple, + tuple.mutationDigest(), + Phase.ACCOUNT_AUTHORIZATION, + State.AUTHORIZATION_PENDING, + 1L, + currentFence, + OBSERVED_AT + 30_000L, + ClaimState.ACTIVE, + currentFence == 1L ? ClaimPurpose.ORIGINAL : ClaimPurpose.AUTHORIZATION_RECOVERY); + return new CurrentClaimEvidence( + snapshot, RESERVATION_OWNER_ID, currentOwner, purpose, OBSERVED_AT); + } + + private static StartSessionPreAuthorizationReservationTuple tuple(String requestId) { + return tuple(requestId, "evidence read test"); + } + + private static StartSessionPreAuthorizationReservationTuple tuple( + String requestId, String auditReason) { + SessionContext.setContext( + "863843ee-f00a-4905-a9ad-11f706f1b693", + List.of(), + Map.of("3d3c5ca5-6d43-4db6-821d-8a0de883a467", List.of("tenantAdmin")), + false, + null, + null); + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope( + UUID.fromString("3d3c5ca5-6d43-4db6-821d-8a0de883a467"), "world-runtime"), + new StartSessionOperatorAction.Target( + 29L, UUID.fromString("be78a8de-a113-48c4-a247-39e3505aed8c")), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + auditReason); + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin(requestId, action); + SessionContext.clear(); + return tuple; + } + + private static Status.Code status(Observer observer) { + return observer.failure; + } + + private static Status.Code transportStatus(Runnable call) { + try { + call.run(); + return Status.Code.OK; + } catch (StatusRuntimeException ex) { + return ex.getStatus().getCode(); + } + } + + private static final class Observer implements StreamObserver { + private ReadCurrentClaimEvidenceResponse response; + private Status.Code failure; + private boolean completed; + + @Override + public void onNext(ReadCurrentClaimEvidenceResponse value) { + response = value; + } + + @Override + public void onError(Throwable throwable) { + failure = Status.fromThrowable(throwable).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceLeafApprovalTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceLeafApprovalTest.java new file mode 100644 index 0000000000..24d5e737c5 --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceLeafApprovalTest.java @@ -0,0 +1,151 @@ +package unit.net.firedevops.firemud.loggingadmin.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.cert.CertificateEncodingException; +import java.security.cert.X509Certificate; +import java.util.HexFormat; +import net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence; +import net.firedevops.firemud.loggingadmin.service.impl.StartSessionReservationEvidenceLeafApproval; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class StartSessionReservationEvidenceLeafApprovalTest { + private static final byte[] ACTIVE_LEAF_DER = + "active account leaf".getBytes(StandardCharsets.US_ASCII); + private static final byte[] OVERLAP_LEAF_DER = + "renewing account leaf".getBytes(StandardCharsets.US_ASCII); + private static final String ACTIVE_FINGERPRINT = sha256(ACTIVE_LEAF_DER); + private static final String OVERLAP_FINGERPRINT = sha256(OVERLAP_LEAF_DER); + + @TempDir Path temporaryDirectory; + + @Test + void matchesOnlyTheCurrentLeafAndReadsTrustedReplacementOnEachCall() throws Exception { + Path policy = temporaryDirectory.resolve("approved-leaves.txt"); + write(policy, "active=" + ACTIVE_FINGERPRINT + "\n"); + StartSessionReservationEvidenceLeafApproval approval = approval(policy); + + assertThat(approval.isApproved(evidence(ACTIVE_LEAF_DER))).isTrue(); + assertThat(approval.isApproved(evidence(OVERLAP_LEAF_DER))).isFalse(); + + write(policy, "active=" + OVERLAP_FINGERPRINT + "\n"); + + assertThat(approval.isApproved(evidence(ACTIVE_LEAF_DER))).isFalse(); + assertThat(approval.isApproved(evidence(OVERLAP_LEAF_DER))).isTrue(); + } + + @Test + void acceptsOneExplicitOverlapOnlyUntilItsAbsoluteExpiry() throws Exception { + Path policy = temporaryDirectory.resolve("approved-leaves.txt"); + long expiresAt = System.currentTimeMillis() + 60_000L; + write( + policy, + "active=" + + ACTIVE_FINGERPRINT + + "\noverlap=" + + OVERLAP_FINGERPRINT + + ";expires-at=" + + expiresAt + + "\n"); + StartSessionReservationEvidenceLeafApproval approval = approval(policy); + + assertThat(approval.isApproved(evidence(ACTIVE_LEAF_DER))).isTrue(); + assertThat(approval.isApproved(evidence(OVERLAP_LEAF_DER))).isTrue(); + + write( + policy, + "active=" + + ACTIVE_FINGERPRINT + + "\noverlap=" + + OVERLAP_FINGERPRINT + + ";expires-at=" + + (System.currentTimeMillis() - 1L) + + "\n"); + + assertThat(approval.isApproved(evidence(ACTIVE_LEAF_DER))).isTrue(); + assertThat(approval.isApproved(evidence(OVERLAP_LEAF_DER))).isFalse(); + } + + @Test + void missingUnreadableMalformedOrAmbiguousPolicyDenies() throws Exception { + Path missing = temporaryDirectory.resolve("missing.txt"); + assertThat(approval(missing).isApproved(evidence(ACTIVE_LEAF_DER))).isFalse(); + + Path directory = Files.createDirectory(temporaryDirectory.resolve("directory-policy")); + assertThat(approval(directory).isApproved(evidence(ACTIVE_LEAF_DER))).isFalse(); + + Path malformed = temporaryDirectory.resolve("malformed.txt"); + for (String content : + new String[] { + "", + "active=" + ACTIVE_FINGERPRINT.toUpperCase() + "\n", + "active=" + ACTIVE_FINGERPRINT + "\nactive=" + OVERLAP_FINGERPRINT + "\n", + "active=" + + ACTIVE_FINGERPRINT + + "\noverlap=" + + ACTIVE_FINGERPRINT + + ";expires-at=9999999999999\n", + "active=" + + ACTIVE_FINGERPRINT + + "\noverlap=" + + OVERLAP_FINGERPRINT + + ";expires-at=not-a-time\n", + "active=" + + ACTIVE_FINGERPRINT + + "\nactive=" + + OVERLAP_FINGERPRINT + + "\nactive=" + + ACTIVE_FINGERPRINT + + "\n" + }) { + write(malformed, content); + assertThat(approval(malformed).isApproved(evidence(ACTIVE_LEAF_DER))) + .as("policy content must fail closed: %s", content) + .isFalse(); + } + } + + @Test + void rejectsMissingEvidenceAndRelativePolicyPaths() throws Exception { + Path policy = temporaryDirectory.resolve("approved-leaves.txt"); + write(policy, "active=" + ACTIVE_FINGERPRINT + "\n"); + assertThat(approval(policy).isApproved(null)).isFalse(); + assertThat( + new StartSessionReservationEvidenceLeafApproval("relative-policy.txt") + .isApproved(evidence(ACTIVE_LEAF_DER))) + .isFalse(); + } + + private static StartSessionReservationEvidenceLeafApproval approval(Path path) { + return new StartSessionReservationEvidenceLeafApproval(path.toString()); + } + + private static GrpcPeerCertificateEvidence evidence(byte[] der) { + X509Certificate leaf = mock(X509Certificate.class); + try { + when(leaf.getEncoded()).thenReturn(der); + } catch (CertificateEncodingException exception) { + throw new AssertionError(exception); + } + return GrpcPeerCertificateEvidence.fromCertificate(leaf).orElseThrow(); + } + + private static String sha256(byte[] value) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException exception) { + throw new AssertionError(exception); + } + } + + private static void write(Path path, String value) throws Exception { + Files.writeString(path, value, StandardCharsets.US_ASCII); + } +} diff --git a/services/logging-admin-service/src/testFixtures/java/net/firedevops/firemud/loggingadmin/StartSessionReservationMutationTestFixtures.java b/services/logging-admin-service/src/testFixtures/java/net/firedevops/firemud/loggingadmin/StartSessionReservationMutationTestFixtures.java new file mode 100644 index 0000000000..6f4e357b00 --- /dev/null +++ b/services/logging-admin-service/src/testFixtures/java/net/firedevops/firemud/loggingadmin/StartSessionReservationMutationTestFixtures.java @@ -0,0 +1,159 @@ +package net.firedevops.firemud.loggingadmin; + +import java.lang.reflect.Constructor; +import java.sql.Connection; +import java.sql.SQLException; +import java.time.Clock; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService; +import net.firedevops.firemud.loggingadmin.repository.StartSessionPreAuthorizationReservationRepository; +import org.jooq.ConnectionProvider; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.mockito.Mockito; +import org.postgresql.ds.PGSimpleDataSource; +import org.testcontainers.containers.PostgreSQLContainer; + +/** Test-fixture-only constructors for isolated reservation mutation proofs. */ +public final class StartSessionReservationMutationTestFixtures { + private static final String MUTATION_CAPABILITY = "MutationCapability"; + private static final String DEFAULT_SCHEMA = "public"; + + private StartSessionReservationMutationTestFixtures() {} + + public static TestcontainersScope forRunOwnedPostgres(PostgreSQLContainer container) { + return forRunOwnedPostgres(container, DEFAULT_SCHEMA); + } + + public static TestcontainersScope forRunOwnedPostgres( + PostgreSQLContainer container, String schema) { + requireRunOwnedPostgres(container, schema); + String jdbcUrl = container.getJdbcUrl(); + String separator = jdbcUrl.contains("?") ? "&" : "?"; + PGSimpleDataSource dataSource = new PGSimpleDataSource(); + dataSource.setURL(jdbcUrl + separator + "currentSchema=" + schema); + dataSource.setUser(container.getUsername()); + dataSource.setPassword(container.getPassword()); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + verifyRunOwnedSchema(dsl, container, schema); + StartSessionPreAuthorizationReservationRepository repository = instantiateRepository(dsl); + StartSessionPreAuthorizationReservationService service = + instantiateService(repository, Clock.systemUTC()); + return new TestcontainersScope(repository, service); + } + + public static StartSessionPreAuthorizationReservationService forMockBackedUnitTest( + StartSessionPreAuthorizationReservationRepository repository, Clock clock) { + Objects.requireNonNull(repository, "repository is required"); + Objects.requireNonNull(clock, "clock is required"); + if (!Mockito.mockingDetails(repository).isMock()) { + throw new IllegalArgumentException("unit-test mutation scope requires a mocked repository"); + } + return instantiateService(repository, clock); + } + + private static void requireRunOwnedPostgres(PostgreSQLContainer container, String schema) { + Objects.requireNonNull(container, "run-owned PostgreSQL container is required"); + if (!container.isRunning()) { + throw new IllegalArgumentException("run-owned PostgreSQL container must already be running"); + } + if (schema == null || !schema.matches("[a-z][a-z0-9_]{0,62}")) { + throw new IllegalArgumentException("run-owned PostgreSQL schema name is invalid"); + } + } + + private static void verifyRunOwnedSchema( + DSLContext dsl, PostgreSQLContainer container, String expectedSchema) { + ConnectionProvider connectionProvider = + Objects.requireNonNull( + dsl.configuration().connectionProvider(), "DSLContext connection provider is required"); + try { + Connection connection = + Objects.requireNonNull( + connectionProvider.acquire(), "run-owned PostgreSQL connection is required"); + try { + String actualUrl = connection.getMetaData().getURL(); + if (!databaseEndpoint(actualUrl).equals(databaseEndpoint(container.getJdbcUrl()))) { + throw new IllegalArgumentException( + "mutation scope must use the exact run-owned PostgreSQL container database"); + } + } finally { + connectionProvider.release(connection); + } + String actualSchema = + dsl.select(DSL.field("current_schema()", String.class)).fetchOne(0, String.class); + if (!expectedSchema.equals(actualSchema)) { + throw new IllegalArgumentException( + "mutation scope must use the exact run-owned PostgreSQL schema"); + } + } catch (SQLException exception) { + throw new IllegalArgumentException( + "run-owned PostgreSQL mutation scope could not be verified", exception); + } + } + + private static String databaseEndpoint(String jdbcUrl) { + int queryStart = jdbcUrl.indexOf('?'); + return queryStart < 0 ? jdbcUrl : jdbcUrl.substring(0, queryStart); + } + + private static StartSessionPreAuthorizationReservationRepository instantiateRepository( + DSLContext dsl) { + Class capabilityType = + capabilityType(StartSessionPreAuthorizationReservationRepository.class); + Object capability = instantiateCapability(capabilityType); + return instantiate( + StartSessionPreAuthorizationReservationRepository.class, + new Class[] {DSLContext.class, capabilityType}, + dsl, + capability); + } + + private static StartSessionPreAuthorizationReservationService instantiateService( + StartSessionPreAuthorizationReservationRepository repository, Clock clock) { + Class capabilityType = capabilityType(StartSessionPreAuthorizationReservationService.class); + Object capability = instantiateCapability(capabilityType); + return instantiate( + StartSessionPreAuthorizationReservationService.class, + new Class[] { + StartSessionPreAuthorizationReservationRepository.class, Clock.class, capabilityType + }, + repository, + clock, + capability); + } + + private static Class capabilityType(Class owner) { + return Arrays.stream(owner.getDeclaredClasses()) + .filter(candidate -> candidate.getSimpleName().equals(MUTATION_CAPABILITY)) + .findFirst() + .orElseThrow( + () -> + new IllegalStateException("private mutation capability is missing from " + owner)); + } + + private static Object instantiateCapability(Class capabilityType) { + return instantiate(capabilityType, new Class[0]); + } + + private static T instantiate(Class type, Class[] parameterTypes, Object... arguments) { + try { + Constructor constructor = type.getDeclaredConstructor(parameterTypes); + constructor.setAccessible(true); + return constructor.newInstance(arguments); + } catch (ReflectiveOperationException exception) { + throw new IllegalStateException("test-only mutation fixture construction failed", exception); + } + } + + public record TestcontainersScope( + StartSessionPreAuthorizationReservationRepository repository, + StartSessionPreAuthorizationReservationService service) { + public TestcontainersScope { + Objects.requireNonNull(repository, "repository is required"); + Objects.requireNonNull(service, "service is required"); + } + } +}