diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e919d5382c..9b8ada9794 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,7 +4,6 @@ on: push: branches: [ main, develop ] pull_request: - branches: [ main, develop ] types: [opened, synchronize, reopened, edited] workflow_dispatch: @@ -1016,7 +1015,7 @@ jobs: contents: read pull-requests: write needs: [buf-check, docker-lint, shellcheck, python-script-validation, dev-tool-contract-checks, dev-tools-readme-contract, yaml-lint, metrics-cardinality-check, flyway-migration-sanity-checks, grpc-transport-config-sanity-checks, workflow-lint, helm-lint, helm-render-validation, helm-transaction-proof, docs-check, frontend-checks, build-and-test, validation-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 19c5fa387a..412f34e874 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -179,8 +179,8 @@ jobs: fail("source workflow run API id does not match the event") if source_run.get("workflow_id") != int(workflow_id_text): fail("source workflow identity changed between event and API") - if source_run.get("name") != source_title: - fail("source workflow API name differs from its exact run title") + if source_run.get("name") not in {"Build Runtime Images", source_title}: + fail("source workflow API name is neither its owning name nor exact run title") if source_run.get("path") != SOURCE_WORKFLOW_PATH: fail("source workflow API path is not the trusted runtime-images workflow") if source_run.get("event") != source_event: diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 67013db104..df21260621 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -113,6 +113,7 @@ jobs: uses: ./.github/actions/setup-trivy - name: 🔍 Run Trivy and Save Report + shell: bash run: | echo "::group::Run Trivy" trivy fs --config config/security/trivy.yaml . | tee trivy-report.txt @@ -207,7 +208,7 @@ jobs: contents: read pull-requests: write # Publishes the consolidated security result on the PR. needs: [changes, trivy-scan, secret-compliance, security-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index c65b36fb4f..b7e861e41a 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -88,6 +88,7 @@ jobs: ".github/actions/load-workflow-tool-versions/", ".github/actions/setup-python/", "dev-tools/smoke/", + "dev-tools/minio/", ]; const fullRelevantFiles = new Set([ "build.gradle.kts", @@ -145,7 +146,7 @@ jobs: contents: read pull-requests: write needs: [changes] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -198,6 +199,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -277,7 +298,7 @@ jobs: contents: read pull-requests: write needs: [changes, smoke-gate, smoke-summary-pending] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -334,6 +355,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -476,7 +517,11 @@ jobs: const eventMergeSha = context.sha; const prNumber = String(context.payload.pull_request.number); const started = Date.now(); - const timeoutMs = 25 * 60 * 1000; + // Contract-checked against pr-local-smoke; bounded overhead covers metadata, + // runner scheduling and API convergence, not unbounded queue delays. + const producerTimeoutMinutes = 45; + const prerequisiteAndQueueAllowanceMinutes = 45; + const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000; const cancelledReplacementTimeoutMs = 5 * 60 * 1000; const sleepMs = 15000; const pullRequestCheckInterval = 4; diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index 4a89119f45..b4c906f7b3 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -65,7 +65,8 @@ jobs: if ( currentPullRequest.state !== "open" || !sourceWorkflowName || - context.payload.workflow_run.name !== expectedSourceTitle || + (context.payload.workflow_run.name !== sourceWorkflowName && + context.payload.workflow_run.name !== expectedSourceTitle) || context.payload.workflow_run.display_title !== expectedSourceTitle ) { core.info("The source run is not bound to the current open pull-request base and head."); diff --git a/design/architecture/decisions/adr-0030-risk-based-active-session-revocation.md b/design/architecture/decisions/adr-0030-risk-based-active-session-revocation.md index 22ed63b094..be9f80d9a8 100644 --- a/design/architecture/decisions/adr-0030-risk-based-active-session-revocation.md +++ b/design/architecture/decisions/adr-0030-risk-based-active-session-revocation.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -No complete producer/consumer, monotonic issuer/membership versions, authority-generation workflow, bounded active-session index, or hard-cutoff proof exists. Current code principally rechecks membership and a limited entitlement response at `PLAY`; authority, grant, and billing changes do not revoke already-connected sessions. +Account has partial durable issuer/membership generations and a closed `account-auth-authority-event/v1` membership producer/codec, but no complete event delivery/consumer, same-snapshot carrier, bounded active-session index, or hard-cutoff proof. Current code principally rechecks membership and a limited entitlement response at `PLAY`; authority, grant, and billing changes do not revoke already-connected sessions. ## Decision Record @@ -36,7 +36,7 @@ Revocation-local admission decisions, exact-binding leases, and gameplay binding `membershipVersion` has one canonical durable and wire shape: the map `{tenantId: version}`. Account authority evidence, JWT claims, issued-token registry records, `resumeActivationLease`, Game Session binding/CAS records, Redis records, and membership-scoped events all retain that map. Each `version` is a JSON string in the canonical non-negative base-10 grammar `0` or `[1-9][0-9]*`; consumers validate and parse it as an arbitrary-precision integer and never compare alternate numeric spellings, JSON numbers, lexicographic strings, or IEEE-754 values. -For an exact `{accountId, tenantId}` binding, the map key set must be exactly `{tenantId}`. A validator may extract the value at that key into a process-local scalar only after validating the complete one-key map, but that scalar is not persisted, transmitted, digested, or used as a substitute carrier. A missing key, extra tenant key, wildcard, aggregate, first/last entry, or maximum value is invalid. Every lease, binding/CAS, Redis record, event, and proof compares the complete canonical map, and any event `accountId`/`tenantId` fields must equal the same exact binding identity. No producer or consumer may switch the carrier shape or infer the map from a different Account snapshot. +For an exact `{accountId, tenantId}` binding, the map key set must be exactly `{tenantId}`. A validator may extract the value at that key into a process-local scalar only after validating the complete one-key map; that scalar is not persisted, transmitted, digested, or used as a substitute **authority-evidence carrier**. This carrier rule does not prohibit Account's normalized, sole-writer SQL source row keyed by the exact `{accountId, tenantId}` from storing its membership-version counter as `BIGINT`. Account constructs the complete one-tenant map from that row in the same fenced snapshot as the applicable authority evidence, reads back and exact-compares the map in every persisted or transmitted evidence carrier, and fails closed before a source-counter overflow rather than wrapping or replacing the carrier with a scalar. A missing key, extra tenant key, wildcard, aggregate, first/last entry, or maximum value is invalid. Every lease, binding/CAS, Redis record, event, and proof compares the complete canonical map, and any event `accountId`/`tenantId` fields must equal the same exact binding identity. No producer or consumer may switch the carrier shape or infer the map from a different Account snapshot. ### Canonical `membershipBaseline` Carrier @@ -71,25 +71,8 @@ For every admission or replacement operation, `membershipBaseline` is one immuta - An issuer-generation cutoff is also an active-session revocation authority, not only a token-validation rule. Account advances the issuer generation and emits the committed outbox event with the issuer scope, new generation, `issuanceFence`, and cutoff checkpoint. Game Session owns only the derived consumer-local projection `session:game:auth:issuer-generation:v1:` and applies that event with set-if-greater semantics; it never writes or mutates Account's canonical `session:auth:generation:*` projection. Duplicate or older events are no-ops only when the exact source evidence rule below is satisfied; a generation-only match is insufficient. A gap or unavailable, stale, regressed, or ambiguous projection triggers authoritative reconciliation and fail-closed admission. Every active gameplay binding persists the issuer generation captured at admission, and the issuer cutoff is applied to all affected bindings across tenants. - Every new gameplay binding and every reconnect/resume admission must also use an Account-owned exact-binding admission lease. The lease contains the target `{accountId, tenantId}` binding identity, exact `authorityTuple`, unchanged `membershipBaseline`, `issuanceFence`, complete `outboxCheckpoints` set, a monotonic `leaseFence`, and a short expiry; grace resume uses the existing `resumeActivationLease` as this contract's exact-resume specialization. Game Session's binding CAS must include the expected old binding generation, exact lease identity, `leaseFence`, `issuanceFence`, and the same tuple, unchanged baseline, and checkpoint set and may publish only a non-admissible provisional record until Account durably finalizes the same lease as `COMMITTED`. Account authority advancement, membership-baseline changes, and lease finalization serialize through the same composite Account CAS across every applicable tuple and baseline member: if any issuer, account, tenant, membership, grant, billing, security, lifecycle, membership-version, or membership-generation value advances before finalization, the fence changes, finalization fails, and any provisional local binding is removed or remains blocked. A stale, missing, expired, ambiguous, or unfenced lease never becomes an admissible binding. This lease/fence predicate is the conditional authority checked by the Game Session binding CAS; it is an ordered idempotent protocol across stores, not a claimed cross-store transaction. - Game Session remains the owner of gameplay binding records, the binding CAS, all bounded active-binding indexes, and socket/admission termination. Account finalization commits only the Account-owned lease, decision, authority snapshot, complete `outboxCheckpoints` set, and idempotency evidence; it does not create, delete, or mutate a Game Session binding or index. If Account reconciliation finds a committed or abandoned lease with no matching admissible Game Session binding, Account emits durable orphan evidence and a fenced cleanup request keyed to the exact request, lease, binding, and fence. Gateway performs any matching edge-token deny/clear cleanup, and Game Session validates the cleanup fence before removing or quarantining the binding and its indexes. Account may reconcile the decision evidence and record cleanup acknowledgements, but local Account cleanup is not physical gameplay cleanup or proof of completion. -- Game Session consumes revocation events durably and idempotently. The canonical Account outbox payload is: - - ```text - { - schemaVersion, - eventId, - eventType, - outboxStreamKey, - outboxSequence, - sourceScope, - authorityTuple, - issuanceFence, - outboxCheckpoints, - eventDigest, - occurredAt - } - ``` - - `sourceScope` must decode to the scope encoded by `outboxStreamKey`; a mismatch is malformed evidence. `outboxCheckpoints` must be the complete canonical stream-key-ordered set, with exactly one `{outboxStreamKey, outboxSequence}` entry for every applicable authority stream, and the entry for `outboxStreamKey` must equal the event's `outboxSequence`; missing, extra, reordered-with-different-content, stale, regressed, or cross-scope entries are invalid. `eventDigest` is `sha256:` followed by 64 lowercase hexadecimal characters for SHA-256 over the UTF-8 bytes of the RFC 8785 JSON Canonicalization Scheme serialization of the complete canonical event object, excluding only the `eventDigest` field itself. The input includes every field in the payload above and every field declared by the exact `eventType` schema; it excludes transport headers, delivery metadata, and any undeclared or duplicate field. Account computes it from the authoritative snapshot before publishing, and the consumer recomputes it from the received object and compares the exact digest before applying or acknowledging the event. Canonical optional objects are omitted only when inapplicable; required maps/lists use their declared empty `{}`/`[]` forms, and `null`, empty-string, sentinel, alternate numeric, and alternate serialization forms are invalid. For a membership-scoped event, the event-type `membershipVersion` field is the complete exact one-tenant map defined above and must equal the map from the same Account snapshot. +- Game Session consumes revocation events durably and idempotently. Each event type has its own closed wire schema. [Authentication](../system-architecture-authentication.md#membership-event-digest) owns the exact `account-auth-authority-event/v1` membership-event fields and digest preimage; this ADR's revocation evidence requirements do not add `outboxCheckpoints`, `occurredAt`, or any other field to that event. Other revocation event types require a declared schema before emission. For the membership event, `sourceScope` must decode to the scope encoded by `outboxStreamKey`, and `membershipVersion` is the complete exact one-tenant map defined above. `eventDigest` is `sha256:` followed by 64 lowercase hexadecimal characters for SHA-256 over the UTF-8 bytes of the RFC 8785 JSON Canonicalization Scheme serialization of the exact declared event object, excluding only `eventDigest`. Account computes it from the authoritative snapshot before publishing; the consumer recomputes and compares it before applying or acknowledging the event. Undeclared, duplicate, missing, alternate-numeric, or alternate-serialization event fields are invalid. +- The complete `outboxCheckpoints` set is a separate Account-authenticated carrier from the same authority snapshot, not an event field or an implicit extension of its digest preimage. [ADR 0022](./adr-0022-account-authority-and-gameplay-session-ownership.md#canonical-checkpoint-and-source-evidence-binding) owns its checkpoint and source-evidence binding. The carrier binds the exact event ID and digest, source stream key and sequence, applicable `authorityTuple`, `issuanceFence`, unchanged `membershipBaseline` when membership applies, and the complete canonical stream-key-ordered checkpoint set. Each checkpoint has exactly `{outboxStreamKey, outboxSequence}`; the event's stream entry equals its committed sequence, and positive checkpoints have their separate same-snapshot event ID/digest source evidence. A missing, extra, stale, regressed, cross-scope, differently ordered, separately sourced, or mismatched carrier fails closed. The event alone, or its valid digest without the matching authenticated carrier, is insufficient for admission, duplicate acceptance, or projection advancement. A consumer stores one `lastAppliedSourceOutboxSequence` and a bounded per-sequence retained duplicate-evidence window using `{outboxStreamKey, outboxSequence, eventId, eventDigest, authorityTuple, issuanceFence, membershipBaseline, outboxCheckpoints}` when membership applies, never one global watermark. If `outboxSequence <= lastAppliedSourceOutboxSequence`, an older or duplicate event is a no-op only when retained evidence contains exact equality for the complete canonical schema, or an authoritative Account checkpoint returns that exact committed event evidence including the same digest; an evicted local entry, a generation-only match, or an event ID/digest pair alone is not proof. The same sequence with different evidence or digest is a reachable stream conflict, so the scope is quarantined and reconciled fail-closed. If the retained evidence has been evicted and the Account checkpoint is unavailable or timed out, the affected scope remains quarantined and the operation returns retryable `AUTH_UNAVAILABLE`. If `outboxSequence == lastAppliedSourceOutboxSequence + 1`, the consumer validates the recomputed `eventDigest`, full `authorityTuple`, `issuanceFence`, unchanged `membershipBaseline` where applicable, and complete `outboxCheckpoints` set against matching Account evidence, including that no applicable stream is missing or extra. An equal authority value is an idempotent accepted checkpoint and a higher value applies through set-if-greater before the watermark advances; a lower value is contradictory evidence that quarantines the scope and requires Account reconciliation before either value advances. If `outboxSequence > lastAppliedSourceOutboxSequence + 1`, it is a gap only for that same `outboxStreamKey`: the consumer stops admitting or reconnecting affected bindings, reconciles the exact scope from Account, and advances the watermark only after the Account checkpoint proves the missing range is covered. diff --git a/design/architecture/decisions/adr-0036-monotonic-authority-generations-for-bulk-token-revocation.md b/design/architecture/decisions/adr-0036-monotonic-authority-generations-for-bulk-token-revocation.md index e2e3a7d0af..6ec47623ff 100644 --- a/design/architecture/decisions/adr-0036-monotonic-authority-generations-for-bulk-token-revocation.md +++ b/design/architecture/decisions/adr-0036-monotonic-authority-generations-for-bulk-token-revocation.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -The monotonic generation contract is target state and is not fully implemented or proved. Current Account runtime documentation records legacy Account session keys and incomplete issued-token/auth-generation enforcement; durable generation records and projections, transactional issuance/revocation ordering, and cross-scope validation proof remain outstanding. +The monotonic generation contract is target state and is not fully implemented or proved. The current Unit 1B draft adds durable generation-storage primitives, initializes the Account UUID scope for newly registered global accounts, idempotently enrolls the exact Account JWT issuer at startup, and enrolls retained Account and approved tenant UUID scopes without resetting advanced state. Account V33 adds separately sequenced, immutable authority-outbox storage, and the current explicit first-JOIN candidate emits one canonical membership event with its committed membership, role snapshot, audit, receipt, and operation in an Account transaction. That candidate still needs executed PostgreSQL proof; retained inactive reactivation denies without a canonical current INACTIVE event. Event delivery and Redis projections, the fenced runtime membership snapshot and Game Session consumer, complete authority-mutation composition, transactional token issuance/revocation ordering, and cross-scope validation proof remain outstanding. Account runtime still uses legacy session keys and incomplete issued-token/auth-generation enforcement; the runtime membership RPC remains denied. ## Decision Record diff --git a/design/architecture/infrastructure/environment-and-secrets-overview.md b/design/architecture/infrastructure/environment-and-secrets-overview.md index 6c162d5237..46df488036 100644 --- a/design/architecture/infrastructure/environment-and-secrets-overview.md +++ b/design/architecture/infrastructure/environment-and-secrets-overview.md @@ -210,6 +210,20 @@ Each credential record must point to content-addressed output generated by the a The pre-release authority is a dedicated authenticated handoff store/API owned by the environment/secrets provisioning, rotation, or rebinding controller. Its publisher uses an identity scoped to one environment’s compliance path and content-addressed evidence. Before a recovery or release transition, the owner supplies one complete immutable handoff containing the target environment, applicable event kind and identity, exact credential-class keys, evidence references and digests, selected freshness field/value and previous field/value, retained material-lineage identity when applicable, exact target binding when applicable, and canonical parent-record digest. Recovery handoffs use the recovery controller's existing canonical operation identity: `operationId` for the general recovery workflow, or the branch-specific `restoreOperationId` for the ADR 0155 handoff below. That identity binds only the matching recovery event and is absent from ordinary release, promotion, and other transition handoffs. Ordinary release and transition identity uses the existing event-scoped tuple `{deploymentRef, deploymentEventId, trafficOpenEvent}` from the preflight contract. A production promotion additionally retains the existing promotion lineage `{stagingOverlayCommitSha, stagingDeploymentEventId, productionOverlayRef}`; these canonical identifiers are not replaced by a fabricated generic release or promotion operation ID. A rebinding handoff also carries the exact new target binding. The handoff publisher validates and atomically publishes that exact tuple; a retry is allowed only when every field and digest matches, while a partial, conflicting, or ambiguous owner, publisher, or dereferenced-evidence result fails closed. The owner handoff and dereferenced evidence are the sole pre-release authority. A separate authenticated Git exporter projects the finalized record for retention and reporting; Git authorship, branch protection, commit timestamps, file paths, and process exit codes are not publisher authority, and the Git projection is never read back to authorize the same recovery or release. +The Account response-envelope ring uses this same authenticated, content-addressed environment/secrets channel with a distinct `account-response-envelope-ring-materialization-v1` receipt, not a `jwt-signing-keys-jwks` credential record or JWT evidence shape. The typed receipt binds the exact protected source generation and predecessor, source manifest digest, environment and namespace, server-authenticated sole materializer identity, canonical Secret name, and the Secret UID and resourceVersion obtained by post-write readback. It carries only non-secret source and resource metadata; its `immutableArtifactId` is the canonical SHA-256 digest with that field omitted from the preimage. The environment/secrets owner must publish and authenticate the exact typed receipt and reject a missing, conflicting, wrong-writer, wrong-generation, or wrong-Secret result. A local materializer return value, checked-in projection, or digest-shaped string is not that handoff. The separate deployment readback must match the published generation, Secret identity and mounted content binding; live freshness and Account readiness are independently proved before the ring mount or either envelope purpose is activated. Neither a receipt nor the shared channel grants Account permission to replace its own Secret. + +### Account ring materializer target-cluster binding + +The ring materializer must authenticate its destination independently of the caller's environment name, namespace, service-account name, source record and ambient kubeconfig. The environment/secrets owner supplies an immutable, authenticated cluster-binding handoff through its protected channel, separately from the key-bearing source. The verifier's publisher trust anchor is provisioned by the platform owner outside candidate code and caller inputs; a source-file digest, Git projection or caller-provided public key cannot establish that trust. + +The handoff pins the exact environment, HTTPS API endpoint and TLS server name, approved API serving trust anchors, the observed `kube-system` Namespace UID as the Kubernetes cluster-incarnation identity, the target Namespace UID, and the dedicated server-authenticated materializer principal. It binds these observations to the owner-authorized operation, immutable binding identity/digest, current generation and predecessor, and validity window. The UID is meaningful only when read from the API authenticated against the independently trusted endpoint and serving pins; repeated names or a copied UID presented by an untrusted server are not evidence. The platform owner records those pins and initial UIDs from independently authenticated provisioning/readback, not from the materializer's current context. Recreating either namespace or the cluster changes the binding and requires owner-authorized recovery, not an automatic name-based match. + +Before any Secret access, the materializer verifies the authenticated handoff, its current operation/generation and validity, API endpoint/TLS trust, both live Namespace UIDs and its server-reported principal. Every identity check, Secret read, CAS mutation and exact readback uses the same frozen verified endpoint, trust configuration and credential snapshot; rereading a mutable kubeconfig or silently switching context is forbidden. Missing, stale, ambiguous or conflicting bindings fail before cluster mutation and cannot produce a live materialization receipt. The published materialization handoff and deployment readback must bind this exact verified cluster-binding identity/digest as well as the source generation and Secret identity. This contract does not change the existing local receipt schema or make its structural verifier a live destination verifier. + +API certificate/CA rollover requires an authenticated owner operation compare-and-set against the exact prior binding generation/digest, explicit old/new serving pins and unchanged cluster/target Namespace UIDs. Any bounded overlap is explicitly authorized by that operation, not inferred from a server response; old pins are retired only after exact new-binding readback. Lost trust, cluster restoration, or a changed UID stays blocked until the owner publishes a separately authenticated recovery binding from authoritative provisioning evidence. Such recovery preserves retained source generations, decrypt-only keys and encrypted evidence; it never regenerates keys, invents continuity or rewrites an old receipt to claim a new destination. + +**Implementation status:** the independently trusted binding verifier, authenticated publication and live rollover/recovery proof are not implemented. Real Account-ring materializer transport is therefore denied in code. Protected offline source preparation and explicitly simulated read/write/readback tests remain available, but their local receipts and passing checks are insufficient for live delivery. This containment authorizes no workload mount, credential activation or runtime release. + For the ADR 0155 same-boundary PostgreSQL-only rewind branch, the credential event kind for `verified_not_restored` is exactly `recovery-trust-verification`. It is a `secretComplianceRefresh` handoff event, not a second recovery owner or release state; the recovery controller and the detailed [post-restore hardening handoff](../system-architecture-post-restore-hardening.md#5-secret-compliance-evidence-refresh) remain authoritative. Its immutable per-class tuple is exactly `{restoreOperationId, credentialEventKind, credentialOperationId, targetEnvironment, credentialClass, disposition, freshness, materialLineageIdentity, targetBinding, restoreArtifact, evidenceRef, evidenceKey, immutableArtifactId, parentRecordDigest, jwtEvidence}`; `jwtEvidence` is present only for `jwt-signing-keys-jwks`. Here `freshness` is exactly `{lineage, field, value, previousField, previousValue}` and, for this disposition, retains the existing `lineage=existing` and exact `lastProvisionedAt` or `lastRotationAt` field/value pair; `materialLineageIdentity` is the retained current-material lineage; `targetBinding` is the exact environment-owned binding identity declared by expected bindings (`bindingRef` or `fingerprint`, using that manifest’s canonical form); `restoreArtifact` is exactly `{artifactRef, artifactDigest, artifactLineage}` for the selected PostgreSQL restore artifact; and `evidenceRef` plus `evidenceKey` dereference the evidence object whose `immutableArtifactId` is the complete `sha256:<64 lowercase hex>` digest of its UTF-8 RFC 8785 canonical bytes with only that `immutableArtifactId` member omitted from the preimage. `parentRecordDigest` is the same canonical digest relationship applied to the parent compliance record. The evidence must prove the current material and binding were outside the restore artifact, with the artifact identity, digest, and lineage exact-matching the recovery controller’s selected restore artifact; no path, timestamp, mutable reference, or Git projection substitutes for this tuple. For `jwt-signing-keys-jwks`, `jwtEvidence` is exactly `{accountSignerGeneration, accountJwksGeneration, currentKeyset, validatorAcceptance}`: it records the current Account signer generation, Account-published JWKS generation, intact current keyset/`kid` set, and one validator-convergence result per authoritative validator proving acceptance of that unchanged current set. The outer immutable per-class tuple carries the exact environment-owned `targetBinding`; `targetBinding` is not a member of `jwtEvidence` and must not be duplicated inside that exact schema. The Account authority/delegation and Game Session invalidations remain universal rewind controls. The recovery controller accepts `verified_not_restored` only when it atomically compare-and-set exact-matches the complete tuple, dereferenced evidence digest, restore-artifact lineage, retained freshness pair, and JWT evidence where applicable; missing, extra, stale, conflicting, or ambiguous fields fail closed. This is target-state validation: the current static compliance validator remains a post-publication retention check and cannot authorize the current recovery from a Git record alone. diff --git a/design/architecture/microservices/account-service/configuration.md b/design/architecture/microservices/account-service/configuration.md index 3e5345d5e8..8a45394394 100644 --- a/design/architecture/microservices/account-service/configuration.md +++ b/design/architecture/microservices/account-service/configuration.md @@ -22,10 +22,16 @@ In player-facing environments, the interim `jwt-signing-keys` private bundle is The configurable cleanup margin controls issued-token registry retention only. Gameplay continuity is a separate Game Session policy documented in [Reconnection](../../system-architecture-reconnection.md); Account configuration does not derive or widen that lifetime. +### Response-Envelope Key Delivery + +The Account-owned response-envelope ring is separate from JWT signing, JWKS, and request-digest material. Account alone reads its versioned key manifest from a read-only mounted Secret at the configured path; no inline key or JWT-key fallback is permitted. The manifest has one active write key ID and distinct AEAD material for connect-token issuance and bare first-party `LOGIN` under each retained ID. Rotation replaces the mounted projection atomically, moves prior IDs to decrypt-only use, and retains them until Account proves that no retained response envelope needing recovery references them. [Account Runtime and Data](./runtime-and-data.md#connect-token-issuance-persistence-and-retention) owns the exact-operation and fail-closed recovery contract. Deployment and producer/consumer proof remain required before either envelope path is enabled. + ## Implementation Status The current runtime still uses the shared-HMAC compatibility profile for issuance and validation and has no asymmetric non-exportable signer delegation. Any Secret-backed asymmetric materialization is the explicit interim fallback/drift, not canonical target custody; the current preflight/manifests still treat signing paths and `jwt-signing-keys` mounts as shared workload configuration rather than enforcing Account as the sole private-material consumer, and the classpath fallback remains permitted when the configured JWKS file is absent. The runtime also retains the legacy creator-share percentage setting and provider-mutating code paths; they are unsupported implementation drift, not an accepted fee policy or product capability. These target-state requirements are not proof of current startup, custody, mount enforcement, or creator-commerce disablement; runtime, preflight, and manifest alignment is outside this documentation slice. +The local Account response-envelope crypto primitive parses the separate mounted ring format. An unactivated trusted-operator helper can create an initial protected source record exactly once with distinct random purpose keys in an operator-selected owner-only custody directory. Its explicit rotation action reads the protected prior record, retains every old decrypt key, adds distinct active purpose keys, and writes a new predecessor-bound source record without overwriting either file. Ordinary deployment must never run either key-generation action, and owner-only files alone are not durable backed-up custody proof. An unactivated materializer candidate reads the source's exact manifest bytes, environment, namespace, generation/predecessor, immutable source-created freshness anchor, and expiry, then writes the canonical Secret with bounded freshness metadata, exact readback, retry-stable generation handling, and retained decrypt-only keys. No actual protected environment source, trusted writer identity/RBAC, deployment readback, freshness-enforcing readiness actor, or mounted Secret is established yet; the proposed mount remains unpublished. V35 stores an unwired connect-token issuance operation and encrypted envelope, but neither credential producer consumes it. This is local format, storage, bootstrap, rotation-source, and materializer-contract proof only, not response-loss recovery or an enabled credential path. + ## Service-Specific Variables Additional variables configure outbound email delivery, payment behavior, and Account's JOIN reconciliation. The reconciliation environment-variable names, defaults, and bounds are maintained in the central [Environment Variables & Secrets Catalog: Account JOIN Reconciliation](../../infrastructure/environment-and-secrets-catalog.md#account-join-reconciliation); the local properties and runtime consequences are summarized below. @@ -44,6 +50,7 @@ Additional variables configure outbound email delivery, payment behavior, and Ac | `FIREMUD_AUTH_JWT_SECRET` | Inline JWT signing key material for local/dev or explicitly ephemeral stacks only (legacy compatibility; not for player-facing environments) | *(none)* | | `FIREMUD_AUTH_JWT_SECRET_PATH` | Account-only path to the interim versioned asymmetric signing bundle (fallback while delegated non-exportable signer custody is unavailable; mounted read-only from `jwt-signing-keys`) | *(none)* | | `FIREMUD_AUTH_JWKS_PATH` | Path to the Account-published public `jwks.json` file used by Account and JWT validators (required for player-facing environments; mounted read-only from `jwt-jwks`, normally `/var/run/secrets/firemud/jwks/jwks.json`) | *(none)* | +| `FIREMUD_AUTH_RESPONSE_ENVELOPE_KEY_RING_PATH` | Account-only read-only mounted versioned AEAD ring manifest for connect-token and bare-`LOGIN` response envelopes; no inline or JWT-key fallback | *(none; required before either response-envelope path is enabled)* | | `FIREMUD_AUTH_JWT_EXPIRATION_MS` | Lifetime of newly issued JWTs for profiles using the global setting (target `control-ui` and receiver-specific private player-delegation profiles); Account-specific player-bootstrap and gameplay-connect lifetimes are configured separately below | `3600000` | | `FIREMUD_ACCOUNT_TOKENS_SESSION_EXPIRATION_MS` | Current default legacy Account authentication-session record TTL when `SessionService.storeSession(tenantId, accountId, token)` is called without an explicit lifetime (currently gameplay text/delegation paths); control-ui and player-bootstrap account rows currently pass their corresponding JWT lifetimes directly, while connect-token rows pass the connect-token lifetime directly. It is not JWT `exp`, gameplay-continuity, or issued-token-registry retention | `3600000` | | `FIREMUD_ACCOUNT_TOKENS_PLAYER_BOOTSTRAP_EXPIRATION_MS` | `player-bootstrap` JWT lifetime; target ceiling is `300000` ms (five minutes). Current runtime consumes this override, but target startup/preflight bound validation remains incomplete | `300000` | diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 220ac6d239..837d9c4df5 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -26,9 +26,13 @@ Account V25 enforces the live tenant-scoped profile identity `(tenantId, account Account V29 keeps the numeric `accounts.id` primary key and adds an immutable canonical `account_uuid` per Account. Retained rows receive `ACCOUNT_V29_MIGRATION` provenance and a source numeric row equal to their unchanged primary key; an Account insert trigger binds new rows to their numeric key, while `AccountRepository` assigns UUIDs with `ACCOUNT_REPOSITORY_INSERT` provenance and verifies exact persisted identity readback. Database uniqueness constraints prevent duplicate UUID/source mappings. This is an Account persistence bridge only: REST/gRPC DTOs, JWT identities, and external callers remain numeric, and this migration does not create or infer tenant UUID mappings. The focused repository/migration integration class compiled successfully, but all 13 cases were skipped because Docker was unavailable; V29 PostgreSQL migration and immutability behavior therefore remains unexecuted runtime proof. +The current Unit 1B authority and membership candidates build on distinct migrations: V31 positive authority-generation rows and an Account-local issuance fence; V32 membership role snapshots; V33 immutable, independently sequenced authority events; V34 retained Account authority enrollment; V35 connect-token issuance/envelope storage; and V36 durable authority for verified Account/tenant pairs. The v1 event preserves the exact one-tenant `membershipVersion` map, complete committed event and role evidence, and immutable history; a producer may derive a local numeric value only after validating the canonical map. A never-joined pair may expose a positive version/generation baseline at sequence zero only after same-fence provenance and row/receipt/event absence proof, and that baseline never admits gameplay. JOIN advances version and event sequence from the baseline, advances generation only when caller-bound authority was invalidated, and commits membership, role snapshot, event, receipt, audit, and terminal operation evidence together. Retained positive history is never renumbered; inactive reactivation remains denied without the exact current INACTIVE event and writer. Runtime RPCs, event delivery/projections, Game Session consumption, fresh-tenant UUID handoff, old-issuer fencing, and complete token issuance remain unproved. Detailed capability status belongs in the [player access and session tracker](../../../project-management/implementation-tracking/player-access-and-session.md). + +The local AES-256-GCM response-envelope primitive and V35 issuance/envelope storage candidate are not wired into production issuance. The offline materializer simulations, per-access principal checks, and local receipt verifier do not authenticate target-cluster identity or prove Secret delivery. Real Kubernetes operations remain denied until the [canonical target-cluster binding gate](../../infrastructure/environment-and-secrets-overview.md#account-ring-materializer-target-cluster-binding), protected custody, trusted writer, deployment readback, and readiness proof are implemented. An unavailable key or uncertain result never authorizes reminting. + Account implements bounded owner-local cleanup of expired password-reset, email-verification, and email-login-challenge SQL rows, with per-family deleted-row counts and oldest-expired-row lag metrics. The cleanup uses the same process-local wall-clock basis as current credential issuance and validation against timezone-less SQL timestamps; cross-node timezone normalization and existing-row migration are not established by this cleanup. Six focused unit cases in `ExpiredCredentialCleanupJobTest` executed locally; seven PostgreSQL integration cases in `CredentialCleanupRepositoryIntegrationTest` passed in hosted CI, while local execution compiles but skips them when Docker is unavailable. This cleanup does not claim atomic token consumption, session revocation, or completion of the full [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) retention contract; shared retention classes, dependency horizons, blockers, holds, and cross-service proof remain outstanding. -The current public registration path creates only a global Account row and a platform-scoped audit outbox record; it does not create a tenant membership or profile, and a legacy caller-supplied `tenantId` does not establish tenant authority. Explicit `JoinPublicProductionMembership` is the only public-production membership writer. It first commits a policy-independent `PENDING` intent containing the global request ID, verified caller binding, exact retained connect-scope evidence, and a version-1 intent digest. Only after authoritative entitlement evaluation succeeds does a separate Account transaction bind `allowPublicJoin`, the positive `entitlementVersion`, and the version-1 policy digest; that transaction revalidates the exact policy at the membership commit gate and atomically commits any membership transition, tenant-scoped audit outbox event, and terminal operation outcome. If entitlement authority is unavailable, the row remains `PENDING` with a typed last-attempt failure and availability but null policy values and null policy digest; an exact request retry may reconcile it after authority recovers. For a retained `PENDING` operation, an expired scope currently records retryable `AUTH_UNAVAILABLE` without entitlement evaluation or membership mutation; the bounded worker can terminalize only exact positive prior-commit evidence. A malformed or missing bearer is rejected without inventing a terminal operation result. An exact caller retry cannot rerun JOIN with the expired scope. Definitive pre-policy failures retain the intent digest and a durable terminal outcome rather than fabricating policy evidence. A definitive mismatch between the freshly evaluated policy digest and an already-bound digest fails terminally as `IDEMPOTENCY_CONFLICT`, retaining the original request digest, policy version, and policy result without membership or transition audit/outbox mutation; this applies both on a retry and at the immediate commit-gate reread. Unavailable or unsafe authority and uncertain commit outcomes remain `PENDING`. A post-transaction readback returns a stored terminal outcome when present; otherwise Account returns retryable `AUTH_UNAVAILABLE` and the caller must retry the same request ID. A bounded Account-owned worker now revisits due `PENDING` intents, locks and reads back exact operation and scope, membership, exact JOIN transition receipt, and matching version-1 COMMITTED audit receipt/projection evidence, and records capped diagnostics with a reason and backoff when evidence is incomplete. It terminalizes JOINED only from that exact prior-transition evidence, or ALREADY_ACTIVE only from matching positive retained receipt history with no new event; unresolved rows remain visible and caller-retryable, and due readbacks continue after the configured diagnostic threshold. Exact PostgreSQL concurrency and unknown-outcome proof remains open until executed. Successful repeated JOINs replay the stored operation result; `ACTIVE` membership is idempotent, while only missing or inactive membership transitions to `ACTIVE`. PostgreSQL repository proof covers independent intent insertion and atomic policy-binding/membership/outbox/outcome persistence, while the service unit proof covers the separate transaction commit/rollback boundary; all PostgreSQL cases are skipped locally without Docker, so no live PostgreSQL execution is claimed. No direct text-client end-to-end proof is claimed. Legacy Account migrations still assign tenant defaults/backfills and retain prior memberships as unverified, non-admitting evidence. This remains a retained-data deployment blocker: before any affected deployment, Account must record either a verified no-data boundary or an explicit retained-row disposition/mapping, including exact readback and admission-isolation evidence. No recovery is implied for already-applied irreversible migrations, and this status does not choose a tenant-identity migration design. +Registration creates only a global Account row and platform-scoped audit evidence; a legacy caller-supplied `tenantId` establishes neither membership nor profile authority. Explicit `JoinPublicProductionMembership` is the only public-production membership writer. It first commits a policy-independent `PENDING` intent bound to the verified caller, exact retained connect scope, request ID, and intent digest. After authoritative entitlement evaluation, a separate transaction binds the policy result/digest and revalidates it at the membership commit gate. Unavailable policy authority leaves policy values unset and the operation pending; expiry, attempt exhaustion, absent rows, and uncertainty never prove a terminal result or permit resubmission of the expired bearer-bound request. Exact retries remain bound to caller, target, intent, and stored policy digest. Readback-only reconciliation terminalizes `JOINED` only from exact committed operation, scope, membership, role, transition-receipt, authority-event, and matching version-1 `COMMITTED` audit receipt/projection evidence; `ALREADY_ACTIVE` requires exact positive retained receipt history and no new event. Incomplete or contradictory proof remains pending or fails closed with capped diagnostics; it never invents provenance. V40 stores membership transition receipts and does not replace the separate V31–V36 authority/envelope migrations or claim the complete authority tuple. PostgreSQL unknown-outcome/concurrency and direct text-to-Logging proof remain open. Retained legacy memberships remain unverified and non-admitting; affected deployment requires a verified no-data boundary or explicit retained-row disposition/mapping with exact readback and admission-isolation evidence. See the [player access and session tracker](../../../project-management/implementation-tracking/player-access-and-session.md) for proof and rollout gates. Hosted Creator Party/operator identity, terms catalog, acceptance/currentness evidence, changed-term status, and future financial-reconciliation boundaries are target-only. No current party/signer or terms storage, acceptance/transfer route, creator UI, or Game Design evidence binding is implemented or proved; the local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner contract is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled rather than implied by this data model. @@ -194,8 +198,9 @@ Membership freshness evidence contract: `GetTenantMembershipForRuntime` requires `authorityAvailability=AVAILABLE` before its snapshot can authorize admission; `UNAVAILABLE` is an authority failure, not missing or `INACTIVE` membership and cannot produce `JOIN_REQUIRED`. The generated proto and Account producer emit `membershipLifecycleState` and `membershipAuthorityGeneration`. Game Session validates lifecycle consistency, membership version, positive authority generation, identity, freshness, admission, and evaluation time on supplied-authority paths. The target authority tuple and outbox checkpoints remain absent, and the live Account RPC still rejects before data access, so these consumer checks do not establish a fresh atomic target snapshot or composed admission proof. Detailed status is tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). - Account reads the membership state, `membershipVersion`, the complete applicable `authorityTuple` (including the Account-owned membership authority generation), `evaluatedAt`, and the applicable committed `outboxCheckpoints` set from one authoritative snapshot/transaction or equivalent Account-owned fence. It returns those values together, or returns Account-authenticated evidence over exactly those values; callers must not assemble them from separate membership, generation, projection, or event reads. -- The target membership response minimum therefore includes `accountId`, `tenantId`, `roles[]`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, `authorityTuple`, `evaluatedAt`, and `outboxCheckpoints[]`. The checkpoint set uses `{outboxStreamKey, outboxSequence, sourceEventId, sourceEventDigest}` for every positive sequence and must contain the exact entry for `account:auth-authority:v1:membership//` that covers the returned membership and tuple snapshot. `membershipAuthorityGeneration` is the explicit membership member of that tuple; any separately carried value must authenticate the same value and is not an independent authority. -- A sequence-zero checkpoint is permitted only for an exact account/tenant membership stream that has never committed. Account must prove that condition under the same fenced snapshot as the no-row read and explicitly authenticate the tuple, membership generation, and version; a missing row cannot supply or imply those values. Sequence zero carries neither `sourceEventId` nor `sourceEventDigest` and cannot authorize admission. The first committed `JOIN` is sequence one, and a previously joined or left stream retains its positive sequence history even if no current membership row exists. +- The target membership response minimum therefore includes `accountId`, `tenantId`, `roles[]`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, `authorityTuple`, `evaluatedAt`, and `outboxCheckpoints[]`. Each checkpoint entry has exactly `{outboxStreamKey, outboxSequence}` and the set must contain the exact entry for `account:auth-authority:v1:membership//` that covers the returned membership and tuple snapshot. For every positive sequence, separate same-snapshot source evidence binds the event ID and canonical digest to that checkpoint, tuple, issuance fence, and complete checkpoint set under [ADR 0022](../../decisions/adr-0022-account-authority-and-gameplay-session-ownership.md). `membershipAuthorityGeneration` is the explicit membership member of that tuple; any separately carried value must authenticate the same value and is not an independent authority. +- A sequence-zero checkpoint is permitted only for an exact account/tenant membership stream that has never committed. Account must prove that condition under the same fenced snapshot as the no-row read and explicitly authenticate the tuple, membership generation, and version; a missing row cannot supply or imply those values. Sequence zero has no event ID or digest in separate source evidence and cannot authorize admission. The first committed `JOIN` is sequence one, and a previously joined or left stream retains its positive sequence history even if no current membership row exists. +- Account persists one authority baseline for each verified account/tenant pair before returning a never-joined snapshot. That record carries positive generation and independent version while membership is absent; the same Account fence must bind it to the verified UUID association, no-row read, and no-committed-event/history proof. The first JOIN advances the version from this durable absence baseline and emits sequence one; it advances the generation only when the transition records caller-bound authority invalidation. Retained rows keep their provable version and stream history without a manufactured absence baseline. The current V36/JOIN candidate creates and consumes the pair baseline for a verified never-joined pair, but the runtime RPC remains denied until its authenticated response and Game Session consumer proof are complete. - `evaluatedAt` is the UTC evaluation time of that complete authoritative snapshot and is not restamped when an older projection or cached row is read. A response is invalid when any required field or checkpoint is absent, when the checkpoint does not cover the tuple and membership version, or when the values cannot be proven to come from the same snapshot. Reachable contradictory, stale, regressed, or mismatched evidence is denied; an unavailable or timed-out Account evidence dependency remains retryable `AUTH_UNAVAILABLE`. A distinct authorization outcome may be defined only by the owning API contract for a different operation, not as an alternative code for this runtime membership dependency. Runtime caller contract: @@ -209,7 +214,7 @@ Runtime caller contract: - Minimum request fields: `tenantId`, `requestId`. - For target player-admission calls only, the minimum request additionally carries `callerAccountId`, `verifiedConnectScopeId`, and the exact resolved target bundle. Game Session supplies these fields as trusted typed execution/request context; the private `game-session-account-delegation` JWT carries its declared Account authority but does not carry `verifiedConnectScopeId` or the complete runtime target bundle. Account requires `callerAccountId` to equal the authenticated delegation JWT's `accountId`/`sub` and the exact bound Game Session subject, then verifies the scope and target fields against the signed connect scope and current exact target before returning the already-declared caller/target-bound evidence. World Management's tenant/operation-bound lifecycle calls retain their separate operation context and do not fabricate player-binding fields. - Minimum response fields: `tenantId`, nullable `subscriptionStatus`, nullable `provisioningStatus`, `gameplayAvailable`, `allowPublicJoin`, `allowNewGameplayBindings`, `allowNewInstanceStarts`, `quotas { ... }`, `evaluatedAt`, `entitlementVersion`, `tenantBillingSequence`, opaque `tenantAuthorityGeneration`, positive `bundleVersion`, opaque `snapshotIdentity`, opaque `evaluationIdentity`, the complete applicable `authorityTuple`, the separate exact `tenantBillingCutoff[tenantId]` entry when billing evidence applies, and the complete applicable `outboxCheckpoints[]` set. For player admission, the response additionally requires `callerAccountId`, `verifiedConnectScopeId`, and the exact resolved target bundle. While `provisioningStatus` is `pending` or `provisioning`, `subscriptionStatus` is null and every gameplay/admission/instance-start flag is false; after provisioning resolves, `provisioningStatus` is null and `subscriptionStatus` carries the canonical subscription state. - - The entitlement values, caller/target binding when applicable, bundle metadata and identities, complete tuple, applicable billing cutoff, and checkpoint set are one Account-authenticated `account-auth-evidence-bundle/v1` result from the same authoritative transaction or Account-owned fence. `snapshotIdentity` names the committed authority snapshot and `evaluationIdentity` names this evaluation of it. The applicable billing cutoff carries the exact `tenantBillingSequence`, `outboxStreamKey`, and `outboxSequence`; every positive matching checkpoint also carries `sourceEventId` and `sourceEventDigest` and must cover that same stream and sequence. Callers must reject missing, extra, contradictory, or separately sourced evidence and must not reconstruct either identity or treat the flat `tenantBillingSequence` as a substitute for the cutoff or checkpoint. A tenant-only runtime bundle cannot authorize player admission; the caller-bound `verifiedConnectScopeId` and target must match the server-verified scope exactly. + - The entitlement values, caller/target binding when applicable, bundle metadata and identities, complete tuple, applicable billing cutoff, and checkpoint set are one Account-authenticated `account-auth-evidence-bundle/v1` result from the same authoritative transaction or Account-owned fence. `snapshotIdentity` names the committed authority snapshot and `evaluationIdentity` names this evaluation of it. The applicable billing cutoff carries the exact `tenantBillingSequence`, `outboxStreamKey`, and `outboxSequence`; every positive matching checkpoint has separate same-snapshot event ID and canonical digest evidence and must cover that same stream and sequence. Callers must reject missing, extra, contradictory, or separately sourced evidence and must not reconstruct either identity or treat the flat `tenantBillingSequence` as a substitute for the cutoff or checkpoint. A tenant-only runtime bundle cannot authorize player admission; the caller-bound `verifiedConnectScopeId` and target must match the server-verified scope exactly. - `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` is the runtime-served gameplay-admissible-instance lookup for the canonical realm-catalog/admission-pointer contract owned by Multi-Tenancy. The current implementation is `game_session.v1.GameSessionService/GetAdmissionPointer`; Game Session persists and serves the pointer, while Account calls it through `GameSessionClient` and receives either a `GameplayAdmissionPointer` or an application error. - Current proto/producer fields are `tenantId`, `worldSlug`, `realmSlug`, `gameInstanceId`, `pointerVersion`, `requiresCharacterSelection`, `visible`, `stateScope`, `characterCreationPolicy`, and `publicProductionRealm`, plus display names. The current persisted pointer requires a positive runtime target and does not expose `admissionState`, `updatedAt`, or an explicit `CLOSED` response. - Target minimum response fields: `tenantId`, `worldSlug`, `realmSlug`, `admissionState`, `catalogRevision`, `pointerVersion`, `updatedAt`; `admissibleGameInstanceId` is present if and only if `admissionState` is `OPEN`. These target-only fields must not be reported as current proto/runtime behavior. @@ -246,7 +251,9 @@ Runtime caller contract: ### Connect-token issuance persistence and retention -The target Account persistence shape is not current implementation: one Account-schema `connect_token_issuance_operation` record owns the exact `(accountId, tenantId, connectScopeId, requestId)` identity, Account-computed versioned request digest, lifecycle (`PENDING`, `COMMITTED`, deterministic `FAILED`, or `ABORTED`), token identity/hash and authority/postcondition evidence, and reconciliation metadata; it never stores a raw JWT. A separate bounded `connect_token_response_envelope` record is keyed to that operation and stores the exact success credential or deterministic failure only as an Account-encrypted envelope with its key/version and authenticated binding to the operation identity, digest, authority tuple, issuance fence, and applicable postconditions. Both records are Account-owned service-schema objects introduced and accessed through the service-local Flyway/jOOQ lineage; Redis remains only the reset-sensitive exact-result projection/cache. +The target Account persistence shape is not current implementation: one Account-schema `connect_token_issuance_operation` record owns the exact `(accountId, tenantId, connectScopeId, requestId)` identity, Account-computed versioned request digest, lifecycle (`PENDING`, `COMMITTED`, deterministic `FAILED`, or `ABORTED`), token identity/hash and authority/postcondition evidence, and reconciliation metadata; it never stores a raw JWT. A separate bounded `connect_token_response_envelope` record is keyed to that operation and stores the exact success credential or deterministic failure only as an Account-encrypted envelope with its key/version and authenticated binding to the operation identity, digest, authority tuple, Account-local issuance CAS fence, and applicable postconditions. That Account-local fence serializes the durable operation; it is not an `issuanceFence` claim in the `gameplay-connect` token or a substitute for Gateway's distinct `replayAdmissionFence`. Both records are Account-owned service-schema objects introduced and accessed through the service-local Flyway/jOOQ lineage; Redis remains only the reset-sensitive exact-result projection/cache. + +Account owns one versioned, mounted-secret key ring and rotation procedure for both connect-token issuance and bare first-party `LOGIN` response envelopes. The ring contains distinct AEAD keys for the two purposes; an envelope records its purpose and key ID, and a key for one purpose must never decrypt the other. These encryption keys are separate from JWT signing and request-digest keys. New envelopes use the current write key for their purpose. Rotation makes older keys decrypt-only, and Account retains each old key until no retained envelope requiring exact-result recovery references it; removal is an evidence-backed cleanup decision, not a fixed timer. Decryption authenticates the exact durable operation identity, request digest and applicable authority/postcondition binding. Recovery first reads back that operation and its exact envelope, then checks the recorded purpose, key ID and binding before returning the original result. A missing key, failed authentication, missing or mismatched operation or envelope, or binding mismatch fails closed and never mints a replacement credential. Neither envelope purpose is enabled until rotation, wrong-purpose and wrong-operation rejection, and lost-response recovery are proved for its producer and consumer. The operation identity is claimed by a serializable transaction or equivalent Account-owned CAS: one matching digest wins, a concurrent matching request waits for and reads the same operation, and any changed digest returns `IDEMPOTENCY_CONFLICT` without minting or mutating. Account records the durable operation before exposing a result, accepts and reads back the required registry/admission postconditions before `COMMITTED`, and exact retries revalidate current authority and all applicable registry/admission postconditions before decrypting and returning a successful credential envelope. If that revalidation fails, the retry returns the applicable canonical denial and leaves the committed operation and envelope unchanged; it does not remint or replace the credential. A deterministic `FAILED` result, such as `JOIN_REQUIRED`, replays its stored failure envelope directly after the exact operation identity and digest match, without rerunning authority or membership checks, while that failure envelope remains retained. If the matching compact receipt remains after its response envelope has been removed at the declared response-recovery horizon, an exact digest match returns `RESPONSE_RECOVERY_EXPIRED`; a changed digest still returns `IDEMPOTENCY_CONFLICT`. That outcome is terminal for the original issuance attempt and callers must use a new `requestId` for a fresh authorized request. Missing, ambiguous, or unreconciled durable state fails closed; no retry reconstructs or silently remints a JWT. The response envelope must not be removed while the operation is pending, ambiguous, or otherwise blocked on reconciliation. This target persistence/CAS/readback path is unimplemented and must not be inferred from the current Redis map. @@ -260,6 +267,8 @@ Membership-change producer contract: - The target Account producer commits the membership change, applicable `authorityTuple`/`issuanceFence`, `membershipVersion`, and the outbox row in one Account transaction or composite CAS/fence. It emits membership-change events with `schemaVersion`, `eventId`, `eventType`, `outboxStreamKey`, `outboxSequence`, `sourceScope`, `accountId`, `tenantId`, `membershipVersion`, the Account-committed opaque `membershipAuthorityGeneration` for that exact `{accountId, tenantId}` scope, the complete applicable `authorityTuple`, `issuanceFence`, changed roles, a flag indicating whether gameplay admission remains allowed, and the Account-committed boolean `callerBoundAuthorityInvalidated` from that same snapshot/checkpoint. - The membership event stream is exactly `account:auth-authority:v1:membership//`. Its `sourceScope` is exactly `membership//` and must decode to the scope encoded by `outboxStreamKey`; a mismatch is malformed evidence. `outboxSequence` starts at `1` independently for this exact stream and is allocated in the same Account commit as the membership authority change. `membershipVersion` remains the separate monotonic membership projection version and is never substituted for `outboxSequence` or `membershipAuthorityGeneration`. +- The Account producer and Game Session consumer share the closed `account-auth-authority-event/v1` membership-event preimage and verification rules owned by [Authentication & Authorization](../../system-architecture-authentication.md#contract-decisions-normative). Account must calculate the digest only after the exact stream sequence and complete same-transaction tuple/fence/payload have been selected; neither a pre-sequence template nor a later projection read is valid source evidence. The current JOIN candidate produces and reads back the canonical committed event; the outbox repository by itself stores immutable bytes and digest but does not prove Game Session's runtime consumption or the complete same-snapshot membership response. The gameplay membership RPC therefore remains denied. +- The closed `account-auth-authority-event/v1` stores and digests `membershipVersion` as the exact one-tenant `{tenantId: version}` map from the committed membership snapshot, with the event's canonical tenant ID as its only key and a canonical positive decimal string as its value. Account's exact retry and readback compare the complete map. A numeric scalar is only a process-local value after validating that map, never the event field or a persisted substitute. - `membershipVersion` must advance on any membership or role change that can affect gameplay admission or caller-bound tenant authority. - When a membership or tenant-role change invalidates existing caller-bound tenant authorization, the Account Service must also advance the `{accountId, tenantId}` membership authority generation and project `session:auth:generation:membership::` so previously issued control-plane tokens lose tenant authority immediately rather than waiting for expiry. - Each consumer keeps a `watermark` (`lastAppliedOutboxSequence`) and the applied event identity/digest per exact `outboxStreamKey`, never one global watermark. `contiguous` is true only when `outboxSequence == watermark + 1`; a first event is initialized from the matching Account checkpoint and is not treated as a false gap. A sequence at or below the watermark is a no-op only when its event identity/digest and all authority evidence match. The same sequence with conflicting identity, digest, `sourceScope`, `authorityTuple`, `issuanceFence`, `membershipVersion`, or membership payload is a stream conflict and must quarantine the affected scope and fail closed. A higher sequence is a gap only for that same stream; an unrelated account, tenant, issuer, or grant stream never creates a membership gap. On a gap, non-contiguous delivery, or conflict, consumers stop affected admission and reconnect/validation, reconcile the exact Account snapshot/checkpoint, and advance the watermark only after the missing range or conflict is proven resolved. Unavailable reconciliation is retryable unavailable; reachable contradictory or revoked evidence remains denied. @@ -276,7 +285,7 @@ Entitlement producer contract: - positive `bundleVersion`, opaque `snapshotIdentity`, and opaque `evaluationIdentity`, - the complete applicable `authorityTuple`, - the separate exact `tenantBillingCutoff[tenantId]` entry with `{tenantBillingSequence, outboxStreamKey, outboxSequence}`, and - - the complete applicable `outboxCheckpoints[]` set, including the matching entry that covers the cutoff stream and sequence; every positive checkpoint carries its `sourceEventId` and canonical `sourceEventDigest`. + - the complete applicable `outboxCheckpoints[]` set, including the matching entry that covers the cutoff stream and sequence; every positive checkpoint has separate same-snapshot event ID and canonical digest evidence. - `evaluatedAt` records evaluation of authoritative committed input and must not be restamped merely because an older projection was read. - `tenantBillingSequence` must be monotonic for each tenant and must advance whenever billing-state transitions can affect availability/quotas. - `provisioningStatus` is `pending`, `provisioning`, or null; while non-null, `subscriptionStatus` is null and all new gameplay/admission/instance-start flags are false. `tenantAuthorityGeneration` is opaque and may be compared only for exact equality, never ordered or used as an event identity. diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index a2dc9b1acb..f340bc16a2 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -10,9 +10,11 @@ For REST endpoints, the authoritative request/response schema source is [openapi Game Design is the canonical issuer of opaque UUID `tenantId` values and the owner of stable `tenantSlug` selectors under [Multi-Tenancy](../../system-architecture-multi-tenancy.md#canonical-identity-and-retained-key-bridge). A retained Game Design game row may receive a UUID with exact owner-local provenance naming its row and former `game.tenant_id`; that binding is immutable and read back exactly. A newly created tenant receives a fresh persisted UUID rather than a numeric-key conversion. Selector assignment is explicit and unique; a game name, row key, former tenant string, or guessed slug is not a selector. Resolving a selector requires the current authoritative binding and does not authorize the caller by itself. +The fresh-tenant Account handoff is distinct from both retained-key reads below. Game Design must durably bind the exact creation request to its issued UUID and return authenticated operation-bound creation/readback evidence to Account under the [canonical identity contract](../../system-architecture-multi-tenancy.md#canonical-identity-and-retained-key-bridge). The current tenant-identity proto has no such method, and the current new-game repository path has no stable creation operation identity; neither the smoke seeder nor a legacy-manifest read supplies this handoff. + The separate `TenantIdentityService.ResolveLegacyGameTenantIdentity` read is limited to the verified Account workload peer. It accepts only an exact former Game Design tenant key and returns the persisted UUID, source key, source game row, and provenance kind together. A missing source returns `NOT_FOUND`; malformed input, missing peer, changed provenance, and ambiguous owner data fail closed before returning content. This read does **not** attest that an Account-retained numeric tenant key has the same identity as a numerically similar Game Design key. The separate `ResolveLegacyAccountTenantAssociation` read returns that cross-owner association only when a signed, owner-approved migration manifest has been applied and its exact source tuple still reads back. It is limited to the verified, same-namespace `account-tenant-migrator` workload identity; ordinary Account and other service peers are denied. It returns the immutable operation, approval, signature, digest, and retained-source evidence with the mapping, and denies absent or contradictory rows. Account's own retained-row verification and mapping readback are still required before it may use the UUID, and neither read itself grants membership admission. The [multi-tenancy identity bridge](../../system-architecture-multi-tenancy.md#canonical-identity-and-retained-key-bridge) owns the target contract; [Game Design operations](./operations.md#legacy-tenant-association-migration) records the controlled migration sequence and current proof limits. -**Implementation status:** Current Game Design data does not include a stable tenant slug or a proved cross-owner Account legacy-key association, and no current player-facing selector resolution is claimed. The owner-local UUID source/read is being introduced as a bounded prerequisite; it does not make the Account runtime membership snapshot RPC safe to enable. Live retained-row migration, mounted-certificate acceptance, and Account/Game Session consumer proof must be reported separately from schema and unit tests. +**Implementation status:** Current Game Design data does not include a stable tenant slug, a normal operation-bound fresh-tenant handoff to Account, or a proved cross-owner Account legacy-key association, and no current player-facing selector resolution is claimed. The owner-local UUID source/read is a bounded prerequisite; it does not make the Account runtime membership snapshot RPC safe to enable. Live retained-row migration, mounted-certificate acceptance, and Account/Game Session consumer proof must be reported separately from schema and unit tests. ## Official Hosted Creator Mutation Gate diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index 969bf1d6a8..022715dffc 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -43,13 +43,17 @@ For every private/playtest grant consequence, the exact Account target is `{acco The following contract decisions are mandatory and resolve cross-document ambiguity: +For the closed `account-auth-authority-event/v1` membership event, `membershipVersion` is the exact one-tenant map `{tenantId: version}` required by [ADR 0030](./decisions/adr-0030-risk-based-active-session-revocation.md), not a scalar field. Its sole key is the event's canonical `tenantId`; its value is a canonical positive decimal string from the same Account snapshot. The map is included unchanged in the canonical digest preimage, durable event, exact retry and readback comparisons, and consumer evidence. The decimal-string rule below applies to numeric values inside maps as well as standalone numeric fields. A consumer may extract a process-local scalar only after validating the complete map; no event producer or consumer transmits or persists that scalar as `membershipVersion`. + - **Authority-generation writer** – The Account Service owns durable issuer, account, tenant, and `{accountId, tenantId}` membership authority generations and is the sole writer of every applicable canonical `authorityTuple` field, cutoff, and `issuanceFence`, plus their canonical `session:auth:generation:*` projections. Account commits the durable tuple/fence, applicable account-security or tenant-billing cutoff, and monotonic outbox event together; the projection is an asynchronous outbox output, not part of that atomic durable transaction. Consumers fail closed while the projection or its freshness/source evidence is missing, stale, malformed, regressed, or ambiguous. Other services must publish billing/security events and must not write canonical authority-generation state or projection keys; Game Session may write only its distinct derived issuer projection under the ADR 0022 schema. - **Issuer projection checkpoint** – The Redis issuer-generation projections use `lastAppliedSourceOutboxSequence`, `lastAppliedSourceEventId`, and `lastAppliedSourceEventDigest` for the exact Account authority outbox stream. Sequence `0` is permitted only when that stream has no committed event; at that baseline, `lastAppliedSourceEventId` and `lastAppliedSourceEventDigest` are omitted from the projection, never serialized as `null`, an empty string, a zero digest, or another sentinel. For every positive sequence, both source-event fields are required non-null values in their canonical formats, and the projection advances only on the next contiguous sequence after exact checkpoint validation. These are projection-local replay/checkpoint fields, not JWT claims; JWT claims carry only the applicable authority tuple, including `issuerAuthGeneration`. - **Authority outbox stream** – Account emits each revocation payload on exactly `account:auth-authority:v1:`, where `scopeId` is `issuer/`, `account/`, `tenant/`, `membership//`, or the lifecycle-bound playtest grant scope produced by the [canonical grant authority-stream scope codec](./system-architecture-redis.md#canonical-grant-authority-stream-scope-codec). `outboxSequence` starts at `1` independently for each exact stream key; `tenantBillingSequence` remains the separate tenant billing sequence. Consumers keep watermarks per exact stream key: duplicates with matching evidence at or below the watermark are no-ops, the next sequence is contiguous, a higher sequence is a gap only within that same key, and an unrelated scope never creates a gap. Conflicting duplicate evidence or a same-key gap stops affected validation/admission until Account reconciliation proves the exact checkpoint. - **Playtest grant stream identity** – The grant stream's scope, `sourceScope`, and `outboxStreamKey` are lifecycle-bound and must be produced and parsed only by the [canonical grant authority-stream scope codec](./system-architecture-redis.md#canonical-grant-authority-stream-scope-codec). Any grant revision, tombstone, lookup, or admission evidence that omits `playtestLifecycleId` is incomplete and fails closed; a realm slug alone cannot select a grant. - **Authority replay evidence** – Consumers retain only a finite, deployment-configured replay-evidence window per exact `outboxStreamKey`, with a maximum sequence count and retention TTL, keyed by `outboxSequence`; each retained entry includes `eventId`, the canonical event digest, `sourceScope`, the complete applicable `authorityTuple`/`issuanceFence`, and the relevant event payload evidence. When a duplicate at or below the watermark falls outside that window, the consumer must use an Account-owned authoritative lookup for the exact `(outboxStreamKey, outboxSequence)` and compare the supplied evidence for exact equality. Matching evidence is accepted as a no-op; unavailable lookup is retryable `AUTH_UNAVAILABLE` and keeps the affected scope fail closed; reachable missing or conflicting evidence is quarantined for reconciliation and fails closed. Advancing a watermark never makes an unverified older duplicate acceptable. -- **Membership freshness evidence** – Any authoritative Account membership response/evidence used for billing-safe checks, gameplay admission, reconnect, or revocation must carry or authenticate the complete applicable `authorityTuple`, exact `membershipLifecycleState`, separate `membershipVersion`, `evaluatedAt`, and the matching `outboxCheckpoints` entry from one authoritative Account snapshot/transaction or equivalent Account-owned fence. The target response fields are `accountId`, `tenantId`, `membershipExists`, `membershipLifecycleState`, `roles[]`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, `authorityTuple`, `evaluatedAt`, and `outboxCheckpoints[]`; `membershipAuthorityGeneration` is the tuple's membership member, and a separately carried copy must authenticate the same value. For a committed stream, the matching checkpoint is `{outboxStreamKey: account:auth-authority:v1:membership//, outboxSequence: , sourceEventId, sourceEventDigest}`. Account may instead return sequence `0` only when the exact account/tenant membership stream has never committed and the same fenced snapshot proves no membership row together with the authenticated tuple, generation, and version. A sequence-zero checkpoint omits event ID and digest, grants no admission, and is followed by the first committed `JOIN` event at sequence `1`. A formerly joined or left stream never resets to zero. `evaluatedAt` describes that complete snapshot and is not restamped from a projection or cache. Missing fields, a checkpoint that does not cover the tuple, lifecycle state, or membership version, or values assembled from different checkpoints are invalid and fail closed. +- **Membership freshness evidence** – Any authoritative Account membership response/evidence used for billing-safe checks, gameplay admission, reconnect, or revocation must carry or authenticate the complete applicable `authorityTuple`, exact `membershipLifecycleState`, separate `membershipVersion`, `evaluatedAt`, and the matching `outboxCheckpoints` entry from one authoritative Account snapshot/transaction or equivalent Account-owned fence. The target response fields are `accountId`, `tenantId`, `membershipExists`, `membershipLifecycleState`, `roles[]`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, `authorityTuple`, `evaluatedAt`, and `outboxCheckpoints[]`; `membershipAuthorityGeneration` is the tuple's membership member, and a separately carried copy must authenticate the same value. For a committed stream, the matching checkpoint is exactly `{outboxStreamKey: account:auth-authority:v1:membership//, outboxSequence: }`. Separate same-snapshot source evidence binds event ID and canonical digest to that checkpoint, tuple, issuance fence, and complete checkpoint set under [ADR 0022](./decisions/adr-0022-account-authority-and-gameplay-session-ownership.md). Account may instead return sequence `0` only when the exact account/tenant membership stream has never committed and the same fenced snapshot proves no membership row together with the authenticated tuple, generation, and version. A sequence-zero checkpoint has no event ID or digest, grants no admission, and is followed by the first committed `JOIN` event at sequence `1`. A formerly joined or left stream never resets to zero. `evaluatedAt` describes that complete snapshot and is not restamped from a projection or cache. Missing fields, a checkpoint that does not cover the tuple, lifecycle state, or membership version, or values assembled from different checkpoints are invalid and fail closed. +- **Never-joined pair baseline** – For each verified account/tenant pair, Account owns a durable pair-authority record with a positive membership generation and independent positive membership version even while membership is absent. A sequence-zero response requires one Account-fenced snapshot that proves this exact record, the verified pair identity, no current membership, and no committed membership event or retained contradictory history; absence of a row alone is never a generation, version, or checkpoint. The first explicit `JOIN` commits event sequence `1` and advances `membershipVersion` from that recorded absence baseline. It advances `membershipAuthorityGeneration` independently only if the transition records `callerBoundAuthorityInvalidated=true`. Existing retained membership versions and positive event sequences are preserved rather than assigned a synthetic absence baseline or renumbered. Unmapped or contradictory pairs remain denied, and sequence zero never authorizes admission. - **Membership event continuity** – Membership changes use only `account:auth-authority:v1:membership//`. Each event names `outboxStreamKey`, `sourceScope` (`membership//`), `outboxSequence`, `eventId`, the complete applicable `authorityTuple`/`issuanceFence`, and the Account snapshot's `accountId`, `tenantId`, `membershipVersion`, membership payload, admission flag, and `callerBoundAuthorityInvalidated` result. `sourceScope` must decode to `outboxStreamKey`; each consumer stores a `watermark` and event identity/digest per exact stream and marks delivery `contiguous` only when the next sequence is `watermark + 1` (with first-stream initialization from the Account checkpoint). A duplicate at or below the watermark is valid only when all evidence matches; a same-sequence conflict quarantines the affected scope. A higher sequence is a gap only within that same stream; unrelated streams do not advance or gap this watermark. Conflicts, non-contiguous delivery, missing or mismatched tuple/checkpoint evidence, or an unresolved membership-version/generation pair stop affected admission and reconnect/validation until exact Account reconciliation proves coverage; unavailable reconciliation returns retryable `AUTH_UNAVAILABLE`, while reachable contradictory or revoked evidence is denied/revoked. +- **Membership event digest** – `account-auth-authority-event/v1` is the closed wire/preimage schema for a committed Account membership-change event; other event types, including a deletion/tombstone, require their own declared schema before emission. Its required top-level fields are `schemaVersion` (exactly `account-auth-authority-event/v1`), `eventType` (exactly `MEMBERSHIP_CHANGED`), `eventId`, `requestId`, `outboxStreamKey`, `outboxSequence`, `sourceScope`, `accountId`, `tenantId`, `membershipExists` (exactly `true`), `membershipLifecycleState` (`ACTIVE` or `INACTIVE`), `membershipVersion`, `membershipAuthorityGeneration`, `authorityTuple`, `issuanceFence`, `roles`, `gameplayAdmissionAllowed`, and `callerBoundAuthorityInvalidated`. The sole additional wire field is `eventDigest`; the digest preimage excludes **only** that field. No undeclared field may be emitted or accepted, and a changed declared field changes the digest. `accountId` and `tenantId` are canonical lowercase UUID strings; `sourceScope` and stream key encode those exact IDs. `gameplayAdmissionAllowed` is false for `INACTIVE`; a missing row is not an event. `roles` is a required, duplicate-free array of canonical role names sorted by Unicode code-point order; its empty value is `[]`, not omission. The complete applicable `authorityTuple` uses the field names and presence rules in [JWT and Token Contracts](./system-architecture-jwt-and-token-contracts.md#canonical-authority-tuple): `issuerAuthGeneration`, `accountAuthorityGeneration`, `tenantAuthorityGeneration`, `membershipAuthorityGeneration`, and `privateRealmGrantVersions` are always present; `accountSecurityCutoff` and `tenantBillingCutoff` are omitted only when inapplicable. Both generation maps have exactly the event's `tenantId` key, and the membership-map value equals the separately carried `membershipAuthorityGeneration`; no unrelated tenant entry is applicable to this one-member event. The optional `tenantBillingCutoff` map, when present, likewise has exactly that tenant key, and every private-realm grant entry, when present, belongs to that tenant. Maps are keyed by exact canonical tenant UUID; private-realm grant entries contain all five canonical fields and are sorted lexicographically by `(tenantId, worldSlug, realmSlug, playtestLifecycleId)`, with duplicate identities rejected. All generations, versions, sequences, cutoffs, grant versions, and `issuanceFence` in this event are canonical unsigned decimal **strings** (`0` only where the owning field permits it; no sign, leading zero, exponent, whitespace, or JSON number), preserving values above JavaScript's exact-integer range. `null` never substitutes for omission or an empty list/map. The producer serializes this complete event without `eventDigest` as RFC 8785 canonical JSON UTF-8 and sets `eventDigest` to lowercase `sha256:` plus the SHA-256 hex of those bytes; receivers validate the closed shape, field types, scope coherence, canonical collection rules, and recomputed digest before applying or acknowledging it. This digest binds immutable source evidence; it does not substitute for Account authentication, source sequencing, or current-authority comparison. - **Authority validation outcomes** – A registry, lease, gameplay binding, token-identity fence, Account authority source, or authority-projection freshness fence that cannot be reached or times out is a retryable `AUTH_UNAVAILABLE` / HTTP 503 condition; this includes runtime membership-authority reads. It does not revoke the client's authentication and no cached authority may authorize the failed operation. Reachable missing, malformed, expired, revoked, stale, regressed, or mismatched evidence is an authentication failure (`AUTH_SESSION_REVOKED` or the specific invalid-token outcome) and requires reauthentication. Registry presence or absence never overrides this classification; membership-authority failures use these same availability-versus-denial rules and do not introduce a second canonical error. - **Tenant authority-generation scope** – `session:auth:generation:tenant:` applies by default to tenant-scoped regular and gameplay-affecting operations. Only the closed route-class allowlist in [JWT and Token Contracts](./system-architecture-jwt-and-token-contracts.md#explicit-route-class-generation-allowlist) may omit the target tenant generation. The `billing_safe_tenant` class intentionally omits that target-tenant generation only under this closed exception; it still requires issuer/account and caller-bound membership generations plus a live `tenantAdmin` check. `cross_tenant_support_safe` requires issuer/account generations, a live `support` role without elevation or an explicitly allowed `platformAdmin` role with `privileged_control` backed by independent TOTP, and global token scope; and `cross_tenant_billing_safe` requires issuer/account generations, a live `billingAdmin` or explicitly allowed `platformAdmin` role, global token scope, and `privileged_control`. None of these routes may use cached authorization, and no newly named route class inherits the allowlist. - **Membership authority-generation scope** – `session:auth:generation:membership::` applies to caller-bound tenant authorization for one account in one tenant and advances when membership or tenant roles change without triggering a tenant-wide billing cutoff. diff --git a/design/architecture/system-architecture-multi-tenancy.md b/design/architecture/system-architecture-multi-tenancy.md index c919b08e8a..a357dbf576 100644 --- a/design/architecture/system-architecture-multi-tenancy.md +++ b/design/architecture/system-architecture-multi-tenancy.md @@ -47,6 +47,8 @@ Current Game Session bootstrap/reconnect context remains on the implementation-l Game Design issues and persists the canonical opaque UUID `tenantId` and owns its stable `tenantSlug` selector. Issuance is a durable owner transaction, not a conversion of a numeric key, an interpretation of UUID bits, or a slug-derived value. An exact owner read must return the same persisted UUID and the source/selector provenance; absence, ambiguity, or changed source binding is not a tenant identity. A retained Game Design game row can be assigned a UUID with provenance naming that exact row and its former Game Design tenant key. That assignment by itself does not prove that a numerically similar Account tenant key denotes the same tenant. +For a newly created tenant, Game Design binds a stable creation-request identity to the persisted opaque UUID and creation provenance in its owner transaction. A distinct Game Design-authenticated creation/readback handoff returns that exact operation, UUID, and persisted source evidence to Account; an exact retry returns the same binding, while a changed, absent, ambiguous, or conflicting operation fails closed. Account stores and reads back the fresh association under its own identity authority before membership work. This path does not use the retained-row migration manifest, infer a UUID or Account association from a numeric key or selector, or grant membership or admission by itself. + Account issues and persists a separate canonical UUID `accountId` for each global account while retaining private numeric row keys. Its retained account mapping is one-to-one and records the exact Account row and assignment provenance. For retained membership, JOIN, receipt, and audit rows, Account preserves the original numeric evidence and adds a separate one-to-one bridge to the Game Design-issued tenant UUID only after an authenticated Game Design owner assertion establishes the exact legacy Account tenant-key association and its provenance. Neither a matching decimal string, a game row ID, a default tenant value, nor a guessed slug is that assertion. The owner assertion and Account bridge must be durably readable back and must reject duplicate UUID claims, one legacy key mapped to multiple UUIDs, one UUID mapped to multiple legacy keys, and evidence changes on retry. Unmapped or ambiguous retained rows remain non-admitting and may not be resolved by selecting an arbitrary candidate. For retained rows without another authoritative association source, that owner assertion is an explicit, one-time, audited migration manifest. Game Design's tenant owner signs a versioned, length-framed manifest binding the exact deployment namespace, stable operation identity, owner approval/reference, former Game Design tenant key, Game Design source row, issued UUID, Account numeric tenant key, and Account's retained-source evidence digest. Game Design verifies the trusted signer and exact former-key-to-UUID source before storing an immutable, one-to-one assertion; Account obtains it only from the authenticated Game Design workload read, recomputes its own retained-row evidence, then stores and reads back its immutable local mapping. Exact retries must return the same evidence, while missing, conflicting, duplicate, changed, or ambiguous pairs fail closed. Manifest approval establishes identity association only: it does not activate a legacy membership, create an authority stream, grant admission, or relax the disabled runtime membership RPC. diff --git a/design/architecture/system-architecture-session-behavior.md b/design/architecture/system-architecture-session-behavior.md index 0035e12956..fe5e6d5c16 100644 --- a/design/architecture/system-architecture-session-behavior.md +++ b/design/architecture/system-architecture-session-behavior.md @@ -26,11 +26,11 @@ Retained per-sequence duplicate evidence is a separate same-snapshot carrier, no ## Canonical Monotonic Integer Strings -`outboxSequence` is a scalar JSON string containing a canonical non-negative base-10 integer. `membershipVersion` is not a scalar in this contract: it is the exact map `{tenantId: version}`, and the grammar below applies independently to each map value. The only accepted value grammar is `0` or a nonzero digit sequence with no leading zero (`[1-9][0-9]*`). Values must be JSON strings; empty values, signs, decimal points, exponents, nonfinite values such as `NaN` or `Infinity`, other numeric types, and any alternate spelling are rejected. Consumers validate the complete membership map and exact tenant key, then may parse a value as a process-local arbitrary-precision integer before high-water comparisons. They must never compare strings lexicographically or convert values through IEEE-754 numbers. For `outboxSequence`, the existing sequence-0 baseline and positive-sequence checkpoint rules still apply. +`outboxSequence` is a scalar JSON string containing a canonical non-negative base-10 integer. The canonical membership event and the local `membershipBaseline` both retain their exact one-tenant `membershipVersion` maps; Session does not translate the event to a scalar carrier. Each map value is a JSON string in the canonical grammar `0` or `[1-9][0-9]*`; the committed membership event requires a positive value, while an owning baseline may permit zero only where its contract explicitly does. Empty values, signs, decimal points, exponents, nonfinite values such as `NaN` or `Infinity`, JSON numbers, and alternate spellings are rejected. Consumers validate the complete carrier and exact tenant key before parsing a value as a process-local arbitrary-precision integer for high-water comparisons. They never compare strings lexicographically or convert values through IEEE-754 numbers. For `outboxSequence`, the existing sequence-0 baseline and positive-sequence checkpoint rules still apply. ## Implementation Status -Membership-change event delivery and generation-aware session consumption are not yet live. The current `GetTenantMembershipForRuntimeResponse` and `AccountGrpcService` producer expose `accountId`, `tenantId`, `membershipExists`, `membershipLifecycleState`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, `evaluatedAt`, and `error`; the current Game Session text `PLAY` path validates this lifecycle and generation evidence before admission. Roles, the target exact one-tenant `membershipVersion` map carrier, `authorityTuple`, `outboxCheckpoints`, Account event delivery, generation-aware event consumers, same-stream reconciliation, remaining player-facing legacy mapping, and complete proof across admission/reconnect paths remain gaps; the bounded text `PLAY` checks do not establish those broader guarantees. The versioned Account-owned token-registry rules and binding schema below are target state, not current runtime behavior: the current fallback uses the legacy Account session key rather than the canonical issued-token registry. Game Session must not treat the contract below as fully implemented until those fields, consumers, and proofs converge. The target Account-durable-intent-before-Gateway-marker logout ordering and final Account token-fence invalidation are also not currently proven; for an authenticated session, text `LOGOUT` currently returns `LOGOUT_UNAVAILABLE` before logout side effects, without invoking Account logout or performing local cleanup. The durable logout fence and its end-to-end proof remain gaps. +Membership-change delivery and generation-aware session consumption are not live. Account's runtime membership RPC fails closed before reading because its request cannot authenticate the player and target binding; Game Session `PLAY` calls that denied route and does not receive an admitting Account snapshot. Supplied-authority unit-path checks do not prove composed live admission. Game Session remains a consumer of Account-owned authority: roles, the exact one-tenant `membershipVersion` map, complete `authorityTuple`, `outboxCheckpoints`, authenticated caller/target context, exact binding `membershipBaseline`, event delivery, generation-aware consumption, same-stream reconciliation, and admission/reconnect proof remain open. The versioned token registry and binding schema below are target state; the current fallback still uses the legacy Account session key. Target durable-intent-before-Gateway-marker logout ordering and Account token-fence invalidation are unproved; authenticated text `LOGOUT` currently returns `LOGOUT_UNAVAILABLE` before side effects. The target logout fence and end-to-end proof remain gaps. Account's membership, outbox, and recovery contract is owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority) and its implementation proof by [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md). Account Service is the sole writer of account authority-generation advances and all canonical `session:auth:generation:*` projections, including `session:auth:generation:account:`. Account commits every applicable canonical tuple field, cutoff, `issuanceFence`, and monotonic outbox event together; the generation projection is an asynchronous outbox output, not an atomically committed part of that durable generation/event transaction. Game Session and other downstream services consume Account-owned generation events and projections; they must not advance canonical authority or write canonical projections directly, and they fail closed while projection or freshness/source evidence is missing, stale, malformed, regressed, or ambiguous. Game Session's only generation projection write is its derived `session:game:auth:issuer-generation:v1:` consumer-local record under the ADR 0022 schema. @@ -92,7 +92,7 @@ This is backend role-context maintenance only. It does not prompt for another ga Membership changes that affect tenant access follow a stricter target contract than ordinary role refresh: -1. The Account Service emits a membership-change event containing `accountId`, `tenantId`, `membershipLifecycleState`, `membershipVersion`, complete applicable `authorityTuple`, positive `issuanceFence`, `outboxStreamKey`, `outboxSequence`, the complete stream-key-ordered `outboxCheckpoints`, `changedRoleSet` as the complete post-change role snapshot represented by a sorted array of unique ASCII role identifiers under the canonical bytewise comparator, whether gameplay admission remains allowed, the Account-committed boolean `callerBoundAuthorityInvalidated`, and `eventDigest` from that same authoritative snapshot/checkpoint. +1. The Account Service emits the canonical `account-auth-authority-event/v1` membership-change event defined in [Authentication & Authorization](./system-architecture-authentication.md#membership-event-digest), including its exact one-tenant `membershipVersion` map, complete applicable `authorityTuple`, positive `issuanceFence`, `roles`, gameplay-admission flag, and `callerBoundAuthorityInvalidated` result. Session obtains the event's separate same-snapshot checkpoint and source evidence through the canonical authority-event contract; checkpoints are not fields in the event. 2. Game Session compares the event against active gameplay bindings for `{accountId, tenantId}`. 3. Losing tenant membership or losing gameplay-admission authority (for example removal of `player` or a required private-realm grant) immediately revokes the affected gameplay sessions. Planned realm or playtest closure uses the owning close-and-drain workflow before grants are revoked; grant revocation itself is not a graceful-drain mechanism. 4. For caller-bound tenant control-plane access, the Account Service must also advance the `{accountId, tenantId}` membership authority generation when membership or tenant-role changes invalidate previously issued tenant authority for that caller. @@ -102,13 +102,11 @@ Membership changes that affect tenant access follow a stricter target contract t Target membership-change event delivery semantics are required, not best-effort folklore: -- Every event must include `schemaVersion`, a stable `eventId`, `eventType`, exact `outboxStreamKey`, `outboxSequence`, `sourceScope`, `occurredAt`, `eventDigest`, and the complete payload tuple `{accountId, tenantId, membershipLifecycleState, membershipVersion, authorityTuple, issuanceFence, changedRoleSet, gameplayAdmissionAllowed, callerBoundAuthorityInvalidated, outboxCheckpoints}`; `outboxCheckpoints` is the complete stream-key-ordered checkpoint set from the same Account snapshot, not a latest-only or aggregate value. -- A role identifier is an ASCII string matching `[A-Za-z][A-Za-z0-9_-]*`; its bytes are used exactly as supplied, so case variants are distinct and whitespace, non-ASCII characters, Unicode escapes that decode to non-ASCII, and other spellings are invalid. `compareRoleIdentifierBytes(a, b)` is the one canonical comparator: compare the unsigned identifier bytes lexicographically, with the shorter identifier first when one is a prefix. Producers validate every identifier, reject bytewise duplicates, and sort `changedRoleSet` with this comparator without Unicode normalization, locale collation, case folding, or other transformation. Consumers apply the same validation and comparator and reject an unsorted, duplicated, malformed, or differently normalized array; `[]` is the only empty representation. -- `eventDigest` has one canonical meaning: it is `sha256:` followed by 64 lowercase hexadecimal characters for SHA-256 over UTF-8 RFC 8785 JSON Canonicalization Scheme bytes of the complete membership-event envelope and payload, excluding only the `eventDigest` field itself. The canonical schema field set is exactly `schemaVersion`, `eventId`, `eventType`, `outboxStreamKey`, `outboxSequence`, `sourceScope`, `accountId`, `tenantId`, `membershipLifecycleState`, `membershipVersion`, `authorityTuple`, `issuanceFence`, `changedRoleSet`, `gameplayAdmissionAllowed`, `callerBoundAuthorityInvalidated`, `outboxCheckpoints`, and `occurredAt`. Every field in that emitted envelope, including `eventDigest`, is required and non-null; `changedRoleSet` is the complete post-change role snapshot as a sorted array of unique role identifiers and uses `[]` when empty, not an added/removed delta or an unordered set. `outboxCheckpoints` is complete, canonicalized in stream-key order, and comes from the same authoritative snapshot as the payload tuple. Any optional members nested inside `authorityTuple` use the canonical authority-tuple presence rules rather than a new event-specific encoding. An absent optional nested member is represented by omission, never by JSON `null`, an empty string, or a sentinel. `outboxSequence` is a canonical unsigned base-10 JSON string. `membershipVersion` uses the canonical exact one-tenant map `{tenantId: version}`; its sole value uses that same unsigned-string grammar. This preserves values beyond IEEE-754 exact-integer range and the shared carrier shape across implementations. RFC 8785 preserves string data as supplied; producers perform no Unicode normalization before canonicalization. No envelope field may be omitted, added, or serialized through an alternate grammar. Account computes the digest and consumers recompute and compare it before applying or acknowledging the event. -- The sole value in the validated exact one-tenant `membershipVersion` map must be monotonic per `{accountId, tenantId}` and must advance on any role or membership change that can affect gameplay or tenant-safe control-plane authority. A consumer may extract that value only as a process-local arbitrary-precision integer after validating the complete map and exact tenant key; the event, digest, projection, and binding retain the map. `membershipAuthorityGeneration` is a separate authority fence that advances only when `callerBoundAuthorityInvalidated=true`, meaning the change invalidates previously issued caller-bound tenant authority. A non-revoking change must carry `callerBoundAuthorityInvalidated=false`, the current unchanged opaque generation, and complete same-snapshot `authorityTuple`/`issuanceFence`/checkpoint evidence proving that no prior caller-bound authority was invalidated. Missing or mismatched proof fails closed. Consumers must not substitute `membershipVersion` for the generation or use either field as the other's proof. -- Consumers maintain two independent high-water marks per `{accountId, tenantId}`. `membershipVersion` orders membership projection state, and the membership projection payload, including the complete `changedRoleSet` snapshot, changes only when the event's version is newer than the stored membership version. `membershipAuthorityGeneration` is an independent set-if-greater revocation fence. An event with a newer authority generation and an equal or older membership version advances only that separate authority fence and triggers authoritative membership reconciliation; it must not apply its role set, `changedRoleSet`, `gameplayAdmissionAllowed`, or other membership payload over the newer projection and must not downgrade projection state. An event with a newer membership version updates membership state from that event's complete post-change role snapshot even when the authority generation is unchanged, subject to the complete Account evidence check. Only an event that is not newer on either dimension is a duplicate/no-op. -- Consumers maintain `lastAppliedSourceOutboxSequence` per exact `outboxStreamKey` plus bounded retained duplicate evidence using the canonical separate schema `{outboxStreamKey, outboxSequence, eventId, eventDigest, authorityTuple, issuanceFence, membershipBaseline, outboxCheckpoints}` when membership applies. For sequence `0`, permitted only when the Account-owned stream has no committed event, `lastAppliedSourceEventId` and `lastAppliedSourceEventDigest` are omitted from the projection, and there is no duplicate-evidence entry; JSON `null`, an empty string, a zero digest, or another sentinel is invalid. For every positive sequence, `lastAppliedSourceEventId`, `lastAppliedSourceEventDigest`, and every applicable duplicate-evidence field are required non-null values in their canonical formats. An event at or below `lastAppliedSourceOutboxSequence` is a no-op only when the complete retained evidence matches or an authoritative Account lookup for the exact `(outboxStreamKey, outboxSequence)` proves the same event identity, complete payload including `membershipLifecycleState` where applicable, `authorityTuple`, `issuanceFence`, `membershipBaseline` where applicable, complete `outboxCheckpoints`, and `eventDigest`; a watermark or event ID/digest pair alone is never duplicate proof. For a new event above the watermark, the next sequence must be contiguous; a higher sequence is a gap only within that same stream, and an unrelated issuer, account, tenant, membership, or grant stream never creates a gap. If older evidence has aged out, the lookup is unavailable, or the same sequence has different authoritative evidence or digest, the consumer quarantines the stream and stops affected admission/reconnect until exact Account reconciliation succeeds. A same-key gap or same-sequence mismatch, including any invalid absent/null representation, stops affected admission/reconnect and requires Account reconciliation of the exact checkpoint before processing resumes; it must never be accepted as an idempotent duplicate. -- An event whose `membershipAuthorityGeneration` is lower than the current consumer or Account value must not apply its payload, even when its `membershipVersion` is newer. The consumer rejects that payload, quarantines the affected stream/scope, and reconciles one complete Account snapshot containing the authority generation, membership map, full `outboxCheckpoints`, and same-snapshot event evidence before resuming; it must not choose the newer membership version or silently preserve the lower-generation event. +- The canonical event shape, field presence, role ordering, decimal-string grammar for map values and standalone counters, and digest preimage are defined by [Authentication & Authorization](./system-architecture-authentication.md#membership-event-digest). Session consumes the validated `roles` snapshot and does not add event fields or redefine the wire preimage. The event does not contain `outboxCheckpoints`; Session binds the complete checkpoint set and its same-snapshot source evidence separately, as required by the canonical authority-event contract. +- The exact one-tenant `membershipVersion` map must carry a version monotonic per `{accountId, tenantId}` and advance on any role or membership change that can affect gameplay or tenant-safe control-plane authority. A consumer may parse its value as a process-local arbitrary-precision integer only after validating the complete canonical map; the event, projection, and binding retain the map. `membershipAuthorityGeneration` is a separate authority fence that advances only when `callerBoundAuthorityInvalidated=true`, meaning the change invalidates previously issued caller-bound tenant authority. A non-revoking change must carry `callerBoundAuthorityInvalidated=false`, the current unchanged opaque generation, and complete same-snapshot `authorityTuple`/`issuanceFence`/checkpoint evidence proving that no prior caller-bound authority was invalidated. Missing or mismatched proof fails closed. Consumers must not substitute `membershipVersion` for the generation or use either field as the other's proof. +- Consumers maintain two independent high-water marks per `{accountId, tenantId}`. `membershipVersion` orders membership projection state, and the membership projection payload, including the canonical `roles` snapshot, changes only when the event's version is newer than the stored membership version. `membershipAuthorityGeneration` is an independent set-if-greater revocation fence. An event with a newer authority generation and an equal or older membership version advances only that separate authority fence and triggers authoritative membership reconciliation; it must not apply its roles, `gameplayAdmissionAllowed`, or other membership payload over the newer projection and must not downgrade projection state. An event with a newer membership version updates membership state from that event's `roles` snapshot even when the authority generation is unchanged, subject to the complete Account evidence check. Only an event that is not newer on either dimension is a duplicate/no-op. +- Consumers maintain `lastAppliedSourceOutboxSequence` per exact `outboxStreamKey` plus bounded retained duplicate evidence using the canonical separate schema `{outboxStreamKey, outboxSequence, eventId, eventDigest, authorityTuple, issuanceFence, membershipBaseline, outboxCheckpoints}` when membership applies. For sequence `0`, permitted only when the Account-owned stream has no committed event, `lastAppliedSourceEventId` and `lastAppliedSourceEventDigest` are omitted from the projection, and there is no duplicate-evidence entry; JSON `null`, an empty string, a zero digest, or another sentinel is invalid. For every positive sequence, `lastAppliedSourceEventId`, `lastAppliedSourceEventDigest`, and every applicable duplicate-evidence field are required non-null values in their canonical formats. An event at or below `lastAppliedSourceOutboxSequence` is a no-op only when the complete retained evidence matches or an authoritative Account lookup for the exact `(outboxStreamKey, outboxSequence)` proves the same event identity and canonical payload, together with the separately bound same-snapshot `authorityTuple`, `issuanceFence`, `membershipBaseline`, checkpoint set, and source evidence; a watermark or event ID/digest pair alone is never duplicate proof. For a new event above the watermark, the next sequence must be contiguous; a higher sequence is a gap only within that same stream, and an unrelated issuer, account, tenant, membership, or grant stream never creates a gap. If older evidence has aged out, the lookup is unavailable, or the same sequence has different authoritative evidence or digest, the consumer quarantines the stream and stops affected admission/reconnect until exact Account reconciliation succeeds. A same-key gap or same-sequence mismatch, including any invalid absent/null representation, stops affected admission/reconnect and requires Account reconciliation of the exact checkpoint before processing resumes; it must never be accepted as an idempotent duplicate. +- An event whose `membershipAuthorityGeneration` is lower than the current consumer or Account value must not apply its payload, even when its `membershipVersion` map carries a newer version. The consumer rejects that payload, quarantines the affected stream/scope, and reconciles one complete Account snapshot containing the authority generation, exact one-tenant membership-version map, full `outboxCheckpoints`, and same-snapshot event evidence before resuming; it must not choose the newer membership version or silently preserve the lower-generation event. - If Game Session detects a version gap or has no prior version for an active binding, it must reconcile immediately via the authoritative internal membership API before deciding whether the session remains valid. - Account Service owns the version increment rules; other services must not synthesize membership versions locally. - The two high-waters have independent meanings and must be stored independently per `{accountId, tenantId}`: `membershipVersionHighWater` orders the Account membership projection, while `membershipAuthorityGenerationHighWater` is the set-if-greater revocation fence for previously issued caller-bound authority. `lastAppliedSourceOutboxSequence` is a separate exact-stream delivery watermark and is never replaced by either membership high-water. A newer generation with an equal or older membership version is valid ordering, advances the separate revocation fence without applying or downgrading the membership projection payload, and requires authoritative membership reconciliation before affected gameplay is retained or admitted. A newer membership version with an unchanged generation is valid only when the Account snapshot proves that the change did not invalidate previously issued tenant authority; it updates membership state but does not imply revocation. A membership-version advance that removes gameplay authority without the corresponding Account generation evidence, a generation value that regresses relative to the Account snapshot, or any pair assembled from different checkpoints is inconsistent. @@ -116,7 +114,7 @@ Target membership-change event delivery semantics are required, not best-effort - Focused proof must show that Account emits the event's `membershipAuthorityGeneration` from the same committed snapshot: advanced when `callerBoundAuthorityInvalidated=true`, or unchanged when that flag is false. Game Session rejects missing or mismatched generation evidence rather than substituting `membershipVersion`. Target transaction and consumer contract: once implemented, Account commits each security, membership, grant, or billing authority change, the corresponding durable Account-owned authority-generation or grant-version advance, every applicable cutoff and `issuanceFence`, and its monotonic outbox event in one database transaction or composite CAS/fence. Redis and other downstream projections then idempotently reflect the committed authority state. The cutoff workflow does not report enforcement complete until the required projection and consumer convergence succeeds. Game Session consumes the durable events through an idempotent consumer and maintains the canonical bounded active-binding indexes listed below; correctness must not depend on wildcard Redis scans. -The downstream generation projection uses set-if-greater semantics and may not move authority backward. For a membership or authority-generation event, the Account authority-generation commit atomically includes the exact one-tenant `membershipVersion` map, complete applicable `authorityTuple`, `issuanceFence`, full stream-key-ordered `outboxCheckpoints`, and the event payload/digest from that same durable snapshot; a consumer must reject any event assembled from different snapshots. +The downstream generation projection uses set-if-greater semantics and may not move authority backward. For a membership or authority-generation event, the Account authority-generation commit atomically includes the exact applicable `membershipVersion` map, complete applicable `authorityTuple`, `issuanceFence`, and event payload/digest from one durable snapshot; the separate stream checkpoint set and source evidence are bound to that event and retained by consumers under the canonical authority-event contract. A consumer must reject any event or evidence assembled from different snapshots. For every registry, lease or lease-fence, binding or binding-index, token-identity fence, non-entitlement Account evidence, lease commit, token issuance dependency, outbox/checkpoint delivery, issuer-generation projection, or required Account reconciliation dependency, an unavailable or timed-out dependency returns retryable `AUTH_UNAVAILABLE`. The distinct ADR 0028 entitlement-only path returns `ENTITLEMENT_UNAVAILABLE` when entitlement evaluation alone is unavailable and no eligible same-binding LKG entitlement value supplies that input; it never covers a failed lease, binding, token-identity fence, non-entitlement authority read, lease commit, token issuance dependency, outbox/checkpoint delivery, projection, or reconciliation dependency. Separately, ADR 0037 bounded active-binding continuity may keep an already-admitted connected binding operating only under its prior-positive, unexpired authority-freshness lease and live coordination-health predicate. That continuity does not authorize new admission, reconnect/resume/rebind, scope expansion, lease renewal, token issuance/refresh, or extension or recreation of the lease. A reachable missing, malformed, stale, regressed, expired, or mismatched value is invalid/revoked. No cache, empty projection, Redis presence/absence, or local binding may override that classification. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index fc50fb9212..904c5e54fb 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -78,6 +78,14 @@ Entry format: - Context: #2873's Account tenant-association PostgreSQL test passed local compilation but skipped without Docker. Its first hosted run could not find an inserted table because a new `?currentSchema=` was appended to a Testcontainers JDBC URL that already carried a query string. After preserving the existing separator, the next run reached the later saga migration and failed because the standalone Flyway invocation omitted `${serviceSchema}`. - Expected pattern: preserve existing JDBC URL parameters when adding a schema selector, and supply the same Flyway placeholders for both target-version setup and subsequent full migration. Treat each hosted failure as fixture evidence until the exact database case executes and passes; local compilation is not that proof. +- `2026-09-26`: Indexed PostgreSQL `TEXT` migrations may fail the jOOQ/H2 schema model + - Context: Account's new authority-outbox stream key used an indexed `TEXT` column; PostgreSQL accepts that shape, but the configured jOOQ DDL interpreter mapped it to an H2 CLOB and rejected the primary-key index before Java compilation. + - Expected pattern: use an explicit bounded `VARCHAR` for indexed identity fields with matching application validation, run the owning service's `generateJooq`, and still prove the migration and concurrency behavior separately against PostgreSQL. Parser success does not establish runtime database proof. + +- `2026-09-27`: RFC 3339 fractional-second parsing needs all permitted precisions + - Context: the Account response-envelope Secret materializer emitted canonical UTC timestamps with trailing fractional zeroes removed. A broad developer-tool run intermittently failed its CLI readback although focused tests using whole-second timestamps passed. + - Observation: this runner's Python `datetime.fromisoformat` rejected a valid five-digit fractional-second timestamp such as `.00101Z` after offset normalization. A timestamp round-trip sweep reproduced the defect, and the parser was changed to accept the contract's one-to-six fractional digits explicitly; the full 112-test developer-tool suite then passed. + - Expected pattern: test exact writer-to-reader timestamp round trips across fractional precisions, including live-clock output, before treating a source-generation/freshness readback as reliable. - `2026-09-26`: Necessary procedural migration preflights may use jOOQ ignore markers - Context: Account V25's duplicate-detection preflight requires a PostgreSQL `DO` block and wraps it in `-- [jooq ignore start]` and `-- [jooq ignore stop]` markers. - Observation: this qualifies the 2026-09-20 expected pattern: declarative constraints remain preferred when sufficient, but a necessary procedural preflight can be excluded from jOOQ parsing while retaining separate PostgreSQL migration proof. @@ -241,3 +249,8 @@ Entry format: - Context: #2873 was reconciled in a local preparation branch whose name differed from the PR head branch; an initial push mistakenly named #2880's branch as its destination. - Observation: Git rejected that push as non-fast-forward, so no remote branch changed. The local commit was then pushed to #2873's verified `headRefName`. - Expected pattern: read the live PR `headRefName` and exact remote head immediately before each push from an isolated branch; use the verified destination, and treat a non-fast-forward rejection as a stop-and-recheck signal rather than forcing it. + +- `2026-09-30`: Await publication readback before dispatching exact-head CI + - Context: a #2881 push yielded asynchronously and later returned a generic remote rejection. Dependent PR-body and CI operations were issued before consuming that result, so CI run `36703184951` targeted the old published head instead of the prepared correction. + - Observation: the rejection's cause was not reported. Fresh remote readback confirmed no head change; a non-force retry then published the correction. The stale-head run was explicitly cancelled and excluded from proof. + - Expected pattern: finish the push, verify the exact published SHA, and only then describe it as published or dispatch its CI. Independent operations may run concurrently; operations depending on publication must remain ordered even when tool calls yield. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 6d534ed630..4f4d2bc1cb 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,19 +6,15 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -The Account JOIN worker's positive audit evidence now includes an explicit version-1 COMMITTED receipt/projection marker and nonblank receiver identities from the locked scoped outbox row. The composed Logging & Admin child supplies local typed receipt/projection and readback capability, but retained legacy IDs without that marker remain unresolved and are never promoted by deploying the receiver. Exact receipt/readback and guarded Account evidence recording, retained-evidence disposition, and runtime/retention proof remain gates for recovery. Account JOIN audit/reconciliation containment is tracked under #2848; Logging & Admin receiver persistence/readback proof remains tracked under #2940. +The resumed Account runtime-authority candidate adds an Account-fenced pair-preparation boundary: a verified never-joined pair reuses durable absence enrollment and exact readback, while retained active membership requires its existing receipt/event proof and preserved counters. Unmapped tenants, inactive membership, and absent rows with retained history remain denied; preparation and exact retry create neither membership nor authority events. #2880 owns composing the preparation with a complete typed same-snapshot response. `:account-service:check -PfullCheck --no-configuration-cache` passed with 389 unit cases executed; all 83 integration cases compiled/discovered but skipped without Docker. This is not authenticated RPC, database execution, or admission proof; runtime membership reads, credential paths, and the Account ring mount remain disabled. -Live `CreateLogEvent` returns non-OK `UNAVAILABLE` after exact Account workload authentication and before storage. `ReadLogEventReceipt` remains available, but Account audit delivery is unscheduled, so new and outstanding registration/JOIN outbox rows stay `PENDING`. Producer-side typed receipt validation and verified-projection markers, plus the composed Logging & Admin receiver/readback, exist locally; positive receiver, projection, and delivery behavior has only offline fixture proof. Historical rows with unknown projection provenance are not upgraded by fixture markers. Retention, safe-watermark, cleanup, and positive delivery activation remain unproved. +The #2876 `account-auth-authority-event/v1` correction uses the exact one-tenant `membershipVersion` map, strict shared codec, canonical digest vectors, immutable evidence, and exact Account retry/readback comparisons. Local codec and Account/Game Session vectors execute; PostgreSQL JOIN/reconciliation tests compile but skip without Docker. V31–V36 authority, role, event, enrollment, issuance-envelope, and pair-authority migrations remain distinct from the current V40 transition-receipt migration. The V40 receipt is not a complete authority tuple or a replacement for event/source evidence. Runtime event delivery/projection and Game Session consumption remain open. The local AES-GCM envelope and ring materializer remain offline candidates: per-access principal checks and receipt shape validation do not authenticate target-cluster identity, and local receipts do not prove Secret delivery. Normal Kubernetes operations remain denied pending the [canonical target-cluster binding gate](../../architecture/infrastructure/environment-and-secrets-overview.md#account-ring-materializer-target-cluster-binding), protected custody, trusted writer, deployment readback, and readiness proof. -Implemented seams span Account, Common Security, TCP Proxy, Gateway, Game Session, and gameplay runtimes, including tenantless bootstrap, global-only registration, explicit public-production JOIN, owner-local Account audit outbox, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Account's `/auth/bootstrap/join` operation and Game Session direct-text `JOIN` dispatch exist locally, but Gateway blocks external route exposure and first-party browser `Join & Play` remains unavailable. Local implementation does not establish live audit delivery or complete admission. +Implemented seams span Account, Common Security, TCP Proxy, Gateway, Game Session, and gameplay runtimes, including account-first tenantless bootstrap, global-only registration, explicit public-production JOIN, owner-local audit outbox, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Account's bounded JOIN worker is readback-only: expired scopes, attempt limits, absent evidence, and uncertainty do not terminalize or trigger resubmission. JOINED requires exact positive operation, scope, membership, transition-receipt, authority-event, and version-1 COMMITTED audit receipt/projection evidence, including the explicit marker and nonblank receiver identities read from the locked scoped outbox row; ALREADY_ACTIVE requires matching positive retained receipt history with no new event. Legacy rows without that marker remain unresolved and are never promoted by deploying the receiver. Incomplete evidence remains pending with capped diagnostics. PostgreSQL lost-acknowledgement/concurrency and direct text-client-to-Logging end-to-end proof remain open. Gateway blocks external exposure of Account JOIN, so first-party browser `Join & Play` remains unavailable. -The Account JOIN worker is readback-only. An expired scope on a retained `PENDING` intent returns retryable `AUTH_UNAVAILABLE`; the worker cannot resubmit the expired bearer-bound request and can terminalize only exact positive prior-commit evidence. Expiry, attempt limits, absent evidence, and uncertainty never terminalize; unresolved intents remain pending with capped diagnostics and backoff. Terminal retry is fenced to the authenticated caller, target, intent, and retained policy digest; terminal storage alone is not replay authority. PostgreSQL lost-acknowledgement/concurrency and direct text-client-to-Logging end-to-end proof remain open. +Account's live membership, entitlement, and realm-grant handlers fail closed before data reads, including for Game Session. Supplied-authority local `PLAY` classification is not composed admission proof; live text `PLAY` maps Account `FAILED_PRECONDITION` to `WORLD_ACCESS_DENIED`, and direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity. The current Game Session presence classifier has no fresh Account-authenticated gameplay-grant carrier and records `PLAYER` for new presence; JWT role claims do not confer gameplay elevation. Existing Redis presence reads project `PLAYER` without writes or TTL refresh, and activity updates demote cached elevated roles without changing identity or activity fields. The catalog and `GetAdmissionPointer` fail closed unless a tenant has exactly one visible public-production realm; direct-text Account scope issuance checks current entitlement and denies missing, ambiguous, unavailable, or gameplay-blocked authority before retaining scope. Reconnect and continuity remain partial: private retained-context replay is suppressed fail-closed, safe eligible first-party replay remains incomplete, and accepted `PLAY` renders a fresh `LOOK`; namespace-aware binding, effective resume-window enforcement, exactly-one-prompt proof, and durable post-logout episode fencing are incomplete. Authenticated text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects, does not clear the active binding, and does not prove the generation fence. TCP Proxy's bounded ordered input remains connection-local and is not durable replay. Broader manual end-to-end and continuity proof remain open; canonical target behavior is linked below rather than restated. -Account's live membership, entitlement, and realm-grant handlers fail closed before data reads, including for Game Session. Supplied-authority local `PLAY` classification is not composed admission proof; live text `PLAY` maps Account `FAILED_PRECONDITION` to `WORLD_ACCESS_DENIED`, and direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity, so roster access is not live or proven. The current Game Session presence classifier has no fresh Account-authenticated gameplay-grant carrier and records `PLAYER` for new presence; JWT role claims do not confer gameplay elevation. Existing Redis presence reads project `PLAYER` without writes or TTL refresh, and activity updates demote cached elevated roles without changing identity/activity fields. Positive gameplay-grant elevation proof remains open. - -The catalog and `GetAdmissionPointer` fail closed unless the tenant has exactly one visible public-production realm. Existing duplicates remain a data-decision and activation gap; focused local cardinality proof does not claim PostgreSQL/concurrency when Docker-gated runs skip. Direct-text Account scope issuance checks current entitlement and denies missing, ambiguous, unavailable, or gameplay-blocked authority before retaining scope. These bounded corrections do not establish complete live admission or `PLAY`. Namespace-aware binding, effective resume-window enforcement, exactly-one-prompt proof, and broader cross-transport continuity remain incomplete; TCP Proxy's bounded ordered input is connection-local memory for the retained connection, not durable replay of input/bytes/frames. - -Reconnect/context persistence is partial: private retained-context replay is currently suppressed fail-closed, safe eligible first-party replay remains incomplete, and accepted `PLAY` renders fresh `LOOK`. `LOGOUT_UNAVAILABLE` does not clear the active binding or prove logout; exact current `resumeContextGeneration` and durable terminal-episode/binding evidence are absent, so the post-logout generation fence remains incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift. Account lifecycle, Stripe follow-through, entitlement enforcement, safety-restriction/appeal workflows, prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal paths, but manual end-to-end QA and broader continuity proof remain open; canonical target behavior is linked below rather than restated. +Live `CreateLogEvent` returns `UNAVAILABLE`, and Account audit delivery is unscheduled, so new and outstanding outbox rows remain `PENDING`. Producer-side typed receipt validation and the composed Logging & Admin receiver/readback exist locally, but positive receiver, projection, and delivery behavior has only offline fixture proof. Historical rows without verified projection provenance are not upgraded. Retention, safe-watermark, cleanup, and positive delivery activation remain unproved. Account lifecycle, Stripe follow-through, entitlement enforcement, safety-restriction/appeal workflows, prompt login, and full control-plane revocation/logout remain partial. Official-hosted creator-content acceptance remains an unimplemented target gap; see [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). It is outside player-admission and session authority. Future managed creator commerce remains outside player access and session authority; its canonical boundary is [ADR 0179](../../architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md); no marketplace or purchase-entitlement implementation is present. @@ -26,11 +22,21 @@ The current Unit 1B draft adds Account-owned provisional JOIN/reactivation trans Account runtime admission reads remain a capability/proof blocker. `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` are no longer on the public bearer-bypass list, and these two methods plus `GetRealmAccessGrantForRuntime` now deny even the exact Game Session peer with `FAILED_PRECONDITION` before Account data reads because the current requests lack a verified player/tenant or lifecycle target. Missing or wrong peers are denied separately. Unit 1B must implement the typed caller/target contract and consumer propagation before these reads can be enabled; the target boundary is canonical in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md) and the [authorization route matrix](../../architecture/system-architecture-authz-route-matrix.md). -The in-progress #2873 tenant bridge now has a signed Game Design migration-manifest verifier, immutable owner assertion storage/read, an exact dedicated Account-tenant-migrator gRPC read, and an Account import boundary that recomputes retained V26 source evidence before storing an immutable local mapping. Neither migration auto-creates a pair; both chart Jobs are opt-in and require distinct verified workload certificates, and the runtime membership RPC remains denied. Local focused manifest, gRPC, certificate/admission, Helm-render and Account negative tests executed; Game Design's new V31 PostgreSQL case executed and passed in hosted CI, while Account's new V30 import case has reached Flyway fixture setup but lacks a passing hosted database run after its latest correction. No real signed manifest, live data association, composed owner/consumer snapshot, or runtime admission proof has been completed. Missing/conflicting rows remain denied; this is not a completed membership authority stream or Unit 1B closure. +The #2876 draft adds Account V31 durable issuer, Account UUID, tenant UUID, and membership generations plus an account-local issuance fence. New global registration initializes its persisted Account UUID pair; startup enrolls the exact issuer; approved retained-tenant association enrolls the canonical tenant generation; V34 enrolls retained Account UUID pairs without resetting advanced values and aborts on a half-pair. V33 adds immutable independently sequenced authority events and a shared strict `account-auth-authority-event/v1` Account/Game Session codec with executed positive/negative, ordering, and large-counter vectors. The first-JOIN candidate composes approved retained tenant UUID, V31 membership generation/fence, version-bound roles, V33 event, receipt, audit, and terminal operation in one Account transaction. Replay and abandoned-`PENDING` reconciliation require exact event readback; retained inactive reactivation remains fail-closed without a canonical INACTIVE writer/event. V35 and V36 migrated in hosted PostgreSQL CI; all four V36 repository cases passed in the earlier run, while two V35 timestamp-bind and two JOIN transaction-diagnostic cases failed among 80 Account integration cases. The corrected exact-head Account job subsequently ran `:account-service:integrationTest` and passed, but its success artifact did not include per-test XML, so exact case and skip counts cannot be independently read back for that run; local Docker remains unavailable. Event delivery, Redis projections, Account runtime response, Game Session consumer, fresh-tenant UUID handoff, mixed-version issuer cutover, and complete token issuance remain open. No issued token or runtime response consumes the new state; the membership RPC stays denied and Unit 1B remains provisional. + +The same draft now includes a bounded Ed25519 compact-JWS signing and verification primitive for the dedicated Gateway connect-context key namespace. It is not wired to Gateway issuance, Game Session or Account verification, key publication/rotation, or the complete context-field checks; the current HMAC context path remains partial implementation drift. The primitive's local unit proof is not a signed-context handoff or gameplay admission proof. + +Account V32 holds version-bound tenant-role snapshots without backfilling retained memberships. First explicit public JOIN writes `player` with the membership and audit transaction; active membership and abandoned-`PENDING` reconciliation require exact current role and authority-event readback. The earlier reactivation role-update code is not a proved capability: it now fails closed before mutation unless a canonical current INACTIVE event exists, and no such writer is implemented. Prior CI executed 12 PostgreSQL JOIN cases and V32 migration; the corrected-head Account integration task passed, though its success artifact lacks per-test XML for exact method-level counts. Account runtime snapshot and Game Session consumption remain open. + +The in-progress #2873 tenant bridge now has a signed Game Design migration-manifest verifier, immutable owner assertion storage/read, an exact dedicated Account-tenant-migrator gRPC read, and an Account import boundary that recomputes retained V26 source evidence before storing an immutable local mapping. Neither migration auto-creates a pair; both chart Jobs are opt-in and require distinct verified workload certificates, and the runtime membership RPC remains denied. Game Design persists and reads back fresh opaque tenant UUIDs in its new-row repository, but no normal creation-to-Account handoff carries that UUID into Account membership; current JOIN still stores the retained numeric tenant key. The retained manifest path must not be reused to infer a fresh mapping. Local focused manifest, gRPC, certificate/admission, Helm-render and Account negative tests executed; Game Design's new V31 PostgreSQL case executed and passed in hosted CI, while Account's new V30 import case has reached Flyway fixture setup but lacks a passing hosted database run after its latest correction. No real signed manifest, live data association, composed owner/consumer snapshot, or runtime admission proof has been completed. Missing/conflicting rows remain denied; this is not a completed membership authority stream or Unit 1B closure. The current Unit 1B draft's conditional Game Session `PLAY` branch now distinguishes coherent missing/`INACTIVE` public membership from `ACTIVE` denial, requires existing `ACTIVE` membership before a non-public grant read, and records missing non-public grant internally as `REALM_ACCESS_DENIED`; hidden/non-public definitive denials remain externally projected to generic selection guidance rather than revealing the target. Mocked-response unit tests cover these outcomes and contradictory lifecycle evidence. The Account gRPC precondition still prevents these branches from becoming live admission proof. -The approved first-party bare-`LOGIN` private-delegation exchange is not implemented. Account's current connect issuance relies on legacy Redis replay/session records rather than a durable committed issuance, bootstrap-subject and authority-fence proof, and Account does not independently verify the current Gateway-signed connect context. An Account-owned one-use/idempotent exchange must establish those producer facts and exact Game Session caller binding before Game Session can receive a private delegation JWT; a forwarded context or token `jti` alone cannot authorize the exchange. The approved never-joined sequence-zero membership checkpoint likewise requires Account to prove the exact canonical authority stream never committed under the same fenced snapshot as the no-row read and authenticated tuple/generation/version; the provisional transition receipt does not prove that condition, and no current response or consumer provides it. Formerly joined or left streams retain positive sequence history. Both paths remain unavailable while the runtime RPCs deny. +The approved first-party bare-`LOGIN` private-delegation exchange is not implemented. Account's current connect issuance relies on legacy Redis replay/session records rather than a durable committed issuance, bootstrap-subject and authority-fence proof, and Account does not independently verify the current Gateway-signed connect context. V35 adds an unwired first-writer issuance operation and encrypted response-envelope storage candidate, not production issuance, key-ring deployment, or exact-result recovery. An Account-owned one-use/idempotent exchange must establish those producer facts and exact Game Session caller binding before Game Session can receive a private delegation JWT; a forwarded context or token `jti` alone cannot authorize the exchange. V36 creates a durable positive version/generation pair baseline only for a verified never-joined Account/tenant pair, proves row/receipt/event absence under the Account fence, and returns non-admitting sequence zero with no event identity; first JOIN advances version from one to two and event sequence from zero to one without advancing generation. A formerly joined or left stream never resets to zero, and retained positive counters enroll only from exact readback. The local never-joined evidence constructor now rejects noncanonical IDs, counters, tuple members, and stream keys; the full local Account check passed with 373 unit tests executed, while all 76 integration tests skipped without Docker. V36's repository proof executed and passed in an earlier hosted PostgreSQL run, and the corrected-head Account integration task subsequently passed without exact per-test XML readback. This is not yet a live Account runtime response or a proved Game Session consumer. Both paths remain unavailable while the runtime RPCs deny. + +The #2876 candidate also adds a local AES-256-GCM response-envelope primitive backed by one Account-only versioned mounted-file ring, with separate connect-token and bare-`LOGIN` purpose keys, key IDs, current-write/older-decrypt rotation, and length-framed exact-operation evidence. Local unit tests execute both-purpose round trips, old-key recovery/removal, wrong-purpose and wrong-operation rejection, and missing/malformed-ring denial. V35 adds an unwired connect-token issuance operation/envelope table with exact identity, digest, pending/terminal state and encrypted-envelope readback; its six PostgreSQL cases reached execution in a prior hosted run, four passed and two failed on a timestamp bind. The corrected-head Account integration task passed, but its success artifact lacks per-test XML. An operator bootstrap candidate creates a protected initial source record once in an owner-only directory and provides an explicit separate rotation action that retains every old purpose key, adds new distinct write keys, and binds a new generation to the previous one without overwriting either source. A separate materializer candidate consumes exact manifest bytes, environment, namespace, generation/predecessor, immutable source-created freshness anchor, and expiry; it verifies retry-stable Secret readback and preserves old decrypt-only keys. The 28 focused materializer tests and combined 139-test developer-tool suite, Ruff, and syntax checks pass locally. Exact-head CI run `36254410583` passed Account Build/Test; its integration task ran and its coverage artifact lists 20 integration classes, but the absent per-case XML prevents an exact executed/skipped count. The aggregate CI gate is red from unchanged Game Session Friends assertions, hosted smoke-tool lint, and an EA-3.1 proof-link check outside #2876's unique diff. Actual protected durable custody, source backup and writer RBAC, deployment/readiness wiring, a live mounted Secret, executed rotation, and proven safe decrypt-only key retirement are still absent. There is no corresponding bare-`LOGIN` operation, wired producer/consumer, or lost-response/live rollout proof. Neither credential path is enabled by the primitive, tool candidates, or V35, and an unavailable key may never authorize reminting. The separately specified credential-bearing `Authenticate` exact-retry envelope is also unimplemented; this two-purpose primitive does not supply its key or enable that operation. + +At published #2876 head `774356d5a66846a535726f680aa54ce85669160b`, manual CI run `36257232596` passed Account Build/Test, but `:account-service:integrationTest` was `FROM-CACHE`; it does not demonstrate fresh PostgreSQL execution. The gate failed on seven of 39 Game Session Friends/WebSocket cross-service cases, ten hosted smoke-tool Ruff errors, and the EA-3.1 executable-proof-link check. The failing paths are outside #2876's unique diff, but CI alone does not establish the Game Session root cause or merge readiness. The proposed required Account Secret mount remains unpublished: its rendered-manifest contract passes locally, but no environment source, trusted-writer receipt, or readiness proof exists, and deployment cannot safely require the absent Secret. A Game Session sequence-only event-consumer draft was discarded because the accepted contract requires authenticated same-snapshot tuple, fence, membership baseline, complete checkpoints, and source evidence; the current wire does not provide those fields. Runtime RPCs remain denied. Account's credential-granting gameplay gRPC methods enforce the exact Game Session mTLS peer before authentication or email-code work, with local negative proof. Legacy profile GET/PUT now require the exact Social Groups peer and matching non-internal caller-account subject; presence-policy batch reads require the exact Social Groups peer and remain scoped to tenant profiles. Direct account-ID export, external-link, and verification gRPC methods deny before reads or mutation because no authorized internal caller is configured. These guards do not make the broader target method/caller authority complete or restore the disabled runtime reads. Deferred virtual-currency `GetBalance`, `AddCurrency`, and `SpendCurrency` gRPC calls fail with `FAILED_PRECONDITION` before stored balance access or mutation; this does not implement a supported economy or marketplace. diff --git a/dev-tools/deploy/README.md b/dev-tools/deploy/README.md index 45fb581e4d..53e6c64938 100644 --- a/dev-tools/deploy/README.md +++ b/dev-tools/deploy/README.md @@ -9,6 +9,8 @@ These scripts answer two different questions: They are not generic CI utilities. They enforce the deployment contract for player-facing and self-hosted environments. +The unactivated Account response-envelope materializer now fails closed before starting any real Kubernetes subprocess until the independently trusted target-cluster binding verifier is implemented. Fake-kubectl tests retain offline operation, rotation, readback, and receipt-shape proof only; those simulations and local receipts do not prove live delivery. The [environment and secrets owner contract](../../design/architecture/infrastructure/environment-and-secrets-overview.md#account-ring-materializer-target-cluster-binding) defines the missing binding gate. The Account mount remains unpublished until that gate and the other custody, handoff, deployment-readback, and live freshness/readiness proofs are complete. + ## Script Map - `preflight.py` @@ -19,6 +21,13 @@ They are not generic CI utilities. They enforce the deployment contract for play - Its `hosted-bridge ` form applies the same `PREFLIGHT-BRIDGE-001` validator to preview/dev-demo Helm output; optional `--expected-hosted-telnet-node-port ` requires the exact expected rendered Telnet NodePort and rejects any other explicit `nodePort`; operator context additionally checks that the controller-projected `-gateway-internal-ws` and `-tcp-proxy-bridge` Secrets exist with `tls.crt`, `tls.key`, and `ca.crt`, and that `-telnet-tls` exists with `tls.crt` and `tls.key`. - The ordinary environment form is used by operator deployment workflows and CI static-policy validation; hosted workflow integration for the `hosted-bridge` form is tracked separately from the validator capability. +- `materialize-account-response-envelope-ring.py` + - Unactivated offline materializer candidate for the Account-only `account-response-envelope-key-ring` Secret. It reads an already-created owner-only protected source record (`--source-record`) binding version 1, canonical Base64 for exact `manifest.v1` bytes, an opaque `sourceGeneration`, an immutable `sourceCreatedAt` freshness anchor, `sourceExpiresAt`, exact `environmentId` and `targetNamespace`, and a nullable `previousSourceGeneration`. The caller supplies the independently expected `--environment-id`, `--namespace`, and credential-class `--class-max-age-seconds`; the tool generates no key material. The source-created anchor conservatively bounds the age of retained bytes even if a first-generation Secret is lost and recreated; a retry cannot obtain a fresh age window. Offline fake-kubectl proofs cover read-only exact-generation retry, rotation CAS, byte preservation, and typed receipt construction. Real Kubernetes access is unconditionally denied until the [canonical target-cluster binding gate](../../design/architecture/infrastructure/environment-and-secrets-overview.md#account-ring-materializer-target-cluster-binding) is implemented; local receipts are not live delivery evidence. + - This tool is not wired into preview, dev-demo, or player-facing deployment and does not itself establish protected source custody, sole-writer RBAC, deployment readback, a freshness-enforcing workload readiness actor, or live rotation/rollout proof. Do not publish the Account Secret mount or enable either credential-envelope producer until those gates are complete; a missing source or Secret is an activation failure, not a reason to generate fresh keys during deployment. + +- `bootstrap-account-response-envelope-ring.py` + - Unactivated source-bootstrap candidate for a trusted operator, not a normal deploy or PR job. The initial action requires an absolute output file outside this checkout in a pre-existing operator-owned `0700` custody directory, an exact environment and namespace, and an explicit approved `--source-ttl-seconds`; it creates one `0600` source record with distinct random purpose keys, a random key ID and generation, and an immutable source-created freshness anchor. The explicit `rotate` action additionally requires `--previous-source-record` in protected owner-only custody, retains every prior key for decryption, adds distinct new active purpose keys, and binds the new generation to the prior one. Both actions refuse an existing output rather than regenerating on retry and print no key bytes. The custody operator must separately establish durable protected storage, backup, access control, and audit; this helper alone does not prove them. Actual rotation rollout and proven safe retirement of decrypt-only keys still need separate owner evidence. + - `write-traffic-open-evidence.py` - Canonical writer for hobby traffic-open projection records. - It does not write production traffic-open evidence. Production projection export belongs to the durable environment-wide recovery controller after finalization, and the pre-release gate cannot use a checked-in projection or caller-supplied evidence. diff --git a/dev-tools/deploy/bootstrap-account-response-envelope-ring.py b/dev-tools/deploy/bootstrap-account-response-envelope-ring.py new file mode 100644 index 0000000000..9b2a45c54f --- /dev/null +++ b/dev-tools/deploy/bootstrap-account-response-envelope-ring.py @@ -0,0 +1,540 @@ +#!/usr/bin/env python3 +"""Create initial or explicitly rotated Account response-envelope ring source records. + +This is an unactivated operator bootstrap helper. It creates one version-1 source +record for the Account response-envelope materializer in an operator-supplied, +owner-only directory outside this repository. The initial record binds the exact +dedicated materializer service-account username for its environment and namespace; +explicit rotation retains that identity. The source record is intended for +protected durable custody; creating this local file does not prove that custody, +sole-writer RBAC, Kubernetes deployment, or workload readiness exists. + +The output is create-once. Existing output is never opened for writing, replaced, +or regenerated. Key material and the source-record JSON are never printed. +""" + +from __future__ import annotations + +import argparse +import base64 +import datetime as dt +import importlib.util +import json +import os +import re +import secrets +import stat +import sys +from collections.abc import Sequence +from pathlib import Path + +SOURCE_RECORD_VERSION = 1 +KEY_BYTES = 32 +OWNER_DIRECTORY_MODE = 0o700 +OWNER_FILE_MODE = 0o600 +KEY_ID_PATTERN = re.compile(r"[A-Za-z0-9_-]{1,64}\Z") +NAMESPACE_PATTERN = re.compile(r"[a-z0-9]([-a-z0-9]*[a-z0-9])?\Z") +SERVICE_ACCOUNT_NAME_PATTERN = re.compile( + r"[a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?)*\Z" +) +RFC3339_UTC_PATTERN = re.compile( + r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,6})?Z\Z" +) + + +class BootstrapError(Exception): + """A safe, non-secret-bearing bootstrap failure.""" + + +def format_timestamp(value: dt.datetime) -> str: + """Render the materializer's canonical UTC timestamp format.""" + + if value.tzinfo is None or value.utcoffset() is None: + raise BootstrapError("timestamp must be timezone-aware") + rendered = value.astimezone(dt.timezone.utc).isoformat(timespec="microseconds") + rendered = rendered.replace("+00:00", "Z") + if "." in rendered: + rendered = rendered.replace("Z", "").rstrip("0").rstrip(".") + "Z" + if not RFC3339_UTC_PATTERN.fullmatch(rendered): + raise BootstrapError("timestamp is outside the canonical RFC 3339 UTC format") + return rendered + + +def _validate_environment_id(value: str) -> str: + if not isinstance(value, str): + raise BootstrapError("environment ID must be a string") + try: + encoded = value.encode("utf-8") + except UnicodeError as exc: + raise BootstrapError("environment ID must be valid UTF-8") from exc + if not value or len(encoded) > 4096: + raise BootstrapError("environment ID must be a non-empty opaque value") + if any(ord(character) < 0x20 or ord(character) == 0x7F for character in value): + raise BootstrapError("environment ID must not contain control characters") + return value + + +def _validate_namespace(value: str) -> str: + if not isinstance(value, str) or len(value) > 63 or not NAMESPACE_PATTERN.fullmatch(value): + raise BootstrapError("target namespace must be a Kubernetes namespace name") + return value + + +def _validate_materializer_username(value: str, namespace: str) -> str: + prefix = f"system:serviceaccount:{namespace}:" + if not isinstance(value, str) or not value.startswith(prefix): + raise BootstrapError( + "materializer username must be a Kubernetes service-account username in the target namespace" + ) + service_account_name = value[len(prefix) :] + if ( + not service_account_name + or len(service_account_name) > 253 + or not SERVICE_ACCOUNT_NAME_PATTERN.fullmatch(service_account_name) + ): + raise BootstrapError( + "materializer username must be a Kubernetes service-account username in the target namespace" + ) + return value + + +def _validate_source_ttl(source_ttl_seconds: int) -> int: + if type(source_ttl_seconds) is not int or source_ttl_seconds <= 0: + raise BootstrapError("source TTL must be a positive number of seconds") + return source_ttl_seconds + + +def _random_identifier(byte_count: int) -> str: + identifier = secrets.token_urlsafe(byte_count) + if not KEY_ID_PATTERN.fullmatch(identifier): + raise BootstrapError("secure random identifier did not match the source-record contract") + return identifier + + +def _manifest() -> bytes: + key_id = _random_identifier(16) + bare_login_key = secrets.token_bytes(KEY_BYTES) + connect_token_key = secrets.token_bytes(KEY_BYTES) + while connect_token_key == bare_login_key: + connect_token_key = secrets.token_bytes(KEY_BYTES) + bare_login_encoded = base64.urlsafe_b64encode(bare_login_key).rstrip(b"=").decode("ascii") + connect_token_encoded = base64.urlsafe_b64encode(connect_token_key).rstrip(b"=").decode("ascii") + return ( + f"version=1\nactiveKeyId={key_id}\n" + f"key:{key_id}:bare-login={bare_login_encoded}\n" + f"key:{key_id}:connect-token={connect_token_encoded}\n" + ).encode("ascii") + + +def _source_record_bytes( + environment_id: str, + namespace: str, + materializer_username: str, + source_ttl_seconds: int, + now: dt.datetime, + manifest: bytes, + previous_source_generation: str | None, + source_generation: str | None = None, +) -> bytes: + environment_id = _validate_environment_id(environment_id) + namespace = _validate_namespace(namespace) + materializer_username = _validate_materializer_username(materializer_username, namespace) + source_ttl_seconds = _validate_source_ttl(source_ttl_seconds) + if now.tzinfo is None or now.utcoffset() is None: + raise BootstrapError("bootstrap clock must be timezone-aware") + current_time = now.astimezone(dt.timezone.utc) + try: + expiry = current_time + dt.timedelta(seconds=source_ttl_seconds) + except OverflowError as exc: + raise BootstrapError("source TTL is out of range") from exc + created_at = format_timestamp(current_time) + expires_at = format_timestamp(expiry) + record = { + "version": SOURCE_RECORD_VERSION, + "manifestBase64": base64.b64encode(manifest).decode("ascii"), + "sourceGeneration": source_generation or _random_identifier(32), + "sourceExpiresAt": expires_at, + "sourceCreatedAt": created_at, + "environmentId": environment_id, + "targetNamespace": namespace, + "materializerUsername": materializer_username, + "previousSourceGeneration": previous_source_generation, + } + return (json.dumps(record, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n").encode( + "utf-8" + ) + + +def build_source_record( + environment_id: str, + namespace: str, + materializer_username: str, + source_ttl_seconds: int, + now: dt.datetime | None = None, +) -> bytes: + """Build one canonical initial source record without writing or printing it.""" + + environment_id = _validate_environment_id(environment_id) + namespace = _validate_namespace(namespace) + materializer_username = _validate_materializer_username(materializer_username, namespace) + source_ttl_seconds = _validate_source_ttl(source_ttl_seconds) + current_time = now or dt.datetime.now(dt.timezone.utc) + return _source_record_bytes( + environment_id, + namespace, + materializer_username, + source_ttl_seconds, + current_time, + _manifest(), + None, + ) + + +def _is_within(path: Path, directory: Path) -> bool: + try: + return os.path.commonpath((str(path), str(directory))) == str(directory) + except ValueError: + return False + + +def _repository_root() -> Path: + return Path(__file__).resolve().parents[2] + + +def _load_materializer(): + materializer_path = Path(__file__).with_name("materialize-account-response-envelope-ring.py") + spec = importlib.util.spec_from_file_location( + "account_response_envelope_materializer_for_bootstrap", materializer_path + ) + if spec is None or spec.loader is None: + raise BootstrapError("response-envelope materializer is unavailable") + materializer = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = materializer + try: + spec.loader.exec_module(materializer) + except (ImportError, OSError, SyntaxError) as exc: + raise BootstrapError("response-envelope materializer is unavailable") from exc + return materializer + + +def _read_previous_source_record(path: Path, repository_root: Path): + if not path.is_absolute(): + raise BootstrapError("previous source record must be an absolute path") + try: + resolved_path = path.resolve(strict=True) + resolved_repository = repository_root.resolve(strict=True) + metadata = os.lstat(path) + directory_metadata = os.lstat(path.parent) + except OSError as exc: + raise BootstrapError("previous source record is missing or unreadable") from exc + if _is_within(resolved_path, resolved_repository): + raise BootstrapError("previous source record must be outside the repository") + if not stat.S_ISDIR(directory_metadata.st_mode) or stat.S_IMODE(directory_metadata.st_mode) != OWNER_DIRECTORY_MODE: + raise BootstrapError("previous source directory must be owner-only mode 0700") + if not hasattr(os, "getuid") or directory_metadata.st_uid != os.getuid(): + raise BootstrapError("previous source directory must be owned by the operator") + if not stat.S_ISREG(metadata.st_mode) or stat.S_IMODE(metadata.st_mode) & 0o077: + raise BootstrapError("previous source record must be a regular owner-only file") + if metadata.st_uid != os.getuid(): + raise BootstrapError("previous source record must be owned by the operator") + materializer = _load_materializer() + try: + previous = materializer.read_source_record(path) + except materializer.MaterializationError as exc: + raise BootstrapError("previous source record is invalid or unreadable") from exc + return materializer, previous + + +def _rotation_manifest(materializer, previous_manifest: bytes) -> bytes: + previous = materializer.parse_manifest(previous_manifest) + previous_material = { + key_material + for purposes in previous.keys.values() + for key_material in purposes.values() + } + previous_key_ids = set(previous.keys) + while True: + active_key_id = _random_identifier(16) + if active_key_id not in previous_key_ids: + break + + def fresh_key() -> bytes: + while True: + candidate = secrets.token_bytes(KEY_BYTES) + if candidate not in previous_material: + return candidate + + bare_login_key = fresh_key() + connect_token_key = fresh_key() + while connect_token_key == bare_login_key: + connect_token_key = fresh_key() + lines = ["version=1", f"activeKeyId={active_key_id}"] + for key_id, purposes in previous.keys.items(): + for purpose in ("bare-login", "connect-token"): + encoded = base64.urlsafe_b64encode(purposes[purpose]).rstrip(b"=").decode("ascii") + lines.append(f"key:{key_id}:{purpose}={encoded}") + for purpose, key_material in ( + ("bare-login", bare_login_key), + ("connect-token", connect_token_key), + ): + encoded = base64.urlsafe_b64encode(key_material).rstrip(b"=").decode("ascii") + lines.append(f"key:{active_key_id}:{purpose}={encoded}") + return ("\n".join(lines) + "\n").encode("ascii") + + +def build_rotated_source_record( + previous_source_record: Path, + environment_id: str, + namespace: str, + source_ttl_seconds: int, + now: dt.datetime | None = None, + repository_root: Path | None = None, +) -> bytes: + """Build a rotation record while retaining every prior decrypt-only key.""" + + repository_root = repository_root or _repository_root() + environment_id = _validate_environment_id(environment_id) + namespace = _validate_namespace(namespace) + source_ttl_seconds = _validate_source_ttl(source_ttl_seconds) + materializer, previous = _read_previous_source_record(Path(previous_source_record), repository_root) + if previous.environment_id != environment_id: + raise BootstrapError("previous source record environment does not match the requested environment") + if previous.target_namespace != namespace: + raise BootstrapError("previous source record namespace does not match the requested namespace") + current_time = now or dt.datetime.now(dt.timezone.utc) + if current_time.tzinfo is None or current_time.utcoffset() is None: + raise BootstrapError("bootstrap clock must be timezone-aware") + current_time = current_time.astimezone(dt.timezone.utc) + if current_time <= previous.source_created_at: + raise BootstrapError("rotation source creation time must follow the previous source creation time") + while True: + source_generation = _random_identifier(32) + if source_generation != previous.source_generation: + break + source_record = _source_record_bytes( + environment_id, + namespace, + previous.materializer_username, + source_ttl_seconds, + current_time, + _rotation_manifest(materializer, previous.manifest_bytes), + previous.source_generation, + source_generation, + ) + if len(source_record) > materializer.MAX_SOURCE_RECORD_BYTES: + raise BootstrapError("rotated source record exceeds the materializer size limit") + return source_record + + +def _open_owner_directory(output_path: Path, repository_root: Path) -> tuple[int, str]: + if not output_path.is_absolute(): + raise BootstrapError("output must be an absolute path") + try: + os.lstat(output_path) + except FileNotFoundError: + pass + except OSError as exc: + raise BootstrapError("output path cannot be inspected") from exc + else: + raise BootstrapError("output already exists; refusing to overwrite or regenerate") + try: + resolved_output = output_path.resolve(strict=False) + resolved_repository = repository_root.resolve(strict=True) + except OSError as exc: + raise BootstrapError("output path cannot be resolved") from exc + if _is_within(resolved_output, resolved_repository): + raise BootstrapError("output must be outside the repository") + + parent = resolved_output.parent + output_name = resolved_output.name + if not output_name or output_name in {".", ".."}: + raise BootstrapError("output must name a file") + nofollow = getattr(os, "O_NOFOLLOW", None) + if nofollow is None: + raise BootstrapError("platform cannot enforce no-follow output creation") + directory_flag = getattr(os, "O_DIRECTORY", 0) + try: + directory_fd = os.open(parent, os.O_RDONLY | directory_flag | nofollow) + except OSError as exc: + raise BootstrapError("output parent directory must already exist") from exc + try: + metadata = os.fstat(directory_fd) + if not stat.S_ISDIR(metadata.st_mode): + raise BootstrapError("output parent must be a directory") + if stat.S_IMODE(metadata.st_mode) != OWNER_DIRECTORY_MODE: + raise BootstrapError("output parent directory must be owner-only mode 0700") + if not hasattr(os, "getuid"): + raise BootstrapError("platform cannot verify operator ownership") + if metadata.st_uid != os.getuid(): + raise BootstrapError("output parent directory must be owned by the operator") + try: + os.stat(output_name, dir_fd=directory_fd, follow_symlinks=False) + except FileNotFoundError: + pass + except OSError as exc: + raise BootstrapError("output path cannot be inspected") from exc + else: + raise BootstrapError("output already exists; refusing to overwrite or regenerate") + return directory_fd, output_name + except Exception: + os.close(directory_fd) + raise + + +def _write_once(directory_fd: int, output_name: str, source_record: bytes) -> None: + nofollow = getattr(os, "O_NOFOLLOW", None) + if nofollow is None: + raise BootstrapError("platform cannot enforce no-follow output creation") + close_on_exec = getattr(os, "O_CLOEXEC", 0) + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | nofollow | close_on_exec + output_fd: int | None = None + try: + try: + output_fd = os.open(output_name, flags, OWNER_FILE_MODE, dir_fd=directory_fd) + except FileExistsError as exc: + raise BootstrapError("output already exists; refusing to overwrite or regenerate") from exc + os.fchmod(output_fd, OWNER_FILE_MODE) + view = memoryview(source_record) + while view: + written = os.write(output_fd, view) + if written <= 0: + raise OSError("source record write made no progress") + view = view[written:] + os.fsync(output_fd) + metadata = os.fstat(output_fd) + if stat.S_IMODE(metadata.st_mode) != OWNER_FILE_MODE: + raise BootstrapError("created source record does not have owner-only mode 0600") + finally: + if output_fd is not None: + os.close(output_fd) + os.fsync(directory_fd) + + +def create_initial_source_record( + output: Path, + environment_id: str, + namespace: str, + materializer_username: str, + source_ttl_seconds: int, + now: dt.datetime | None = None, + repository_root: Path | None = None, +) -> None: + """Create an initial source record exactly once in protected operator custody.""" + + output = Path(output) + directory_fd, output_name = _open_owner_directory(output, repository_root or _repository_root()) + try: + source_record = build_source_record( + environment_id, + namespace, + materializer_username, + source_ttl_seconds, + now, + ) + _write_once(directory_fd, output_name, source_record) + finally: + os.close(directory_fd) + + +def create_rotated_source_record( + output: Path, + previous_source_record: Path, + environment_id: str, + namespace: str, + source_ttl_seconds: int, + now: dt.datetime | None = None, + repository_root: Path | None = None, +) -> None: + """Create one explicit rotation record without retiring any prior key.""" + + repository_root = repository_root or _repository_root() + directory_fd, output_name = _open_owner_directory(Path(output), repository_root) + try: + source_record = build_rotated_source_record( + previous_source_record=previous_source_record, + environment_id=environment_id, + namespace=namespace, + source_ttl_seconds=source_ttl_seconds, + now=now, + repository_root=repository_root, + ) + _write_once(directory_fd, output_name, source_record) + finally: + os.close(directory_fd) + + +def _positive_seconds(value: str) -> int: + try: + parsed = int(value) + except ValueError as exc: + raise argparse.ArgumentTypeError("must be a positive integer") from exc + if parsed <= 0: + raise argparse.ArgumentTypeError("must be a positive integer") + return parsed + + +def _parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", nargs="?", choices=("create", "rotate"), default=None) + parser.add_argument("--output", required=True, type=Path, help="absolute owner-only custody output file") + parser.add_argument("--environment-id", required=True) + parser.add_argument("--namespace", required=True) + parser.add_argument( + "--materializer-username", + help="dedicated Kubernetes service-account username; required for initial creation", + ) + parser.add_argument( + "--previous-source-record", + type=Path, + help="protected prior source record; required only for explicit rotation", + ) + parser.add_argument( + "--source-ttl-seconds", + required=True, + type=_positive_seconds, + help="approved credential-class lifetime for sourceExpiresAt", + ) + return parser.parse_args(argv) + + +def main(argv: Sequence[str] | None = None) -> int: + try: + args = _parse_args(argv) + if args.action != "rotate" and args.previous_source_record is not None: + raise BootstrapError("create action cannot specify a previous source record") + if args.action == "rotate" and args.previous_source_record is None: + raise BootstrapError("rotate action requires a previous source record") + if args.action == "rotate": + if args.materializer_username is not None: + raise BootstrapError("rotation must retain the prior materializer username") + create_rotated_source_record( + output=args.output, + previous_source_record=args.previous_source_record, + environment_id=args.environment_id, + namespace=args.namespace, + source_ttl_seconds=args.source_ttl_seconds, + ) + success_message = "created rotated Account response-envelope source record" + else: + if args.materializer_username is None: + raise BootstrapError("create action requires --materializer-username") + create_initial_source_record( + output=args.output, + environment_id=args.environment_id, + namespace=args.namespace, + materializer_username=args.materializer_username, + source_ttl_seconds=args.source_ttl_seconds, + ) + success_message = "created initial Account response-envelope source record" + except BootstrapError as exc: + print(f"bootstrap failed: {exc}", file=sys.stderr) + return 1 + except (OSError, OverflowError, TypeError, ValueError): + print("bootstrap failed: unable to create protected source record", file=sys.stderr) + return 1 + print(success_message) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/dev-tools/deploy/materialize-account-response-envelope-ring.py b/dev-tools/deploy/materialize-account-response-envelope-ring.py new file mode 100644 index 0000000000..37b2a9170a --- /dev/null +++ b/dev-tools/deploy/materialize-account-response-envelope-ring.py @@ -0,0 +1,1094 @@ +#!/usr/bin/env python3 +"""Materialize an externally custodied Account response-envelope ring into Kubernetes. + +This tool accepts an owner-only source record containing version=1, canonical Base64 for the +exact manifest bytes, an opaque source generation, source expiry, target environment and +namespace, the exact dedicated materializer service-account username, predecessor generation, +and an immutable source-created timestamp. That timestamp is a conservative age anchor for the +Secret's materialized-at and expiry metadata, not a claim of the later Kubernetes write time. +The source record must come from protected durable custody. Real Kubernetes subprocesses are +currently denied until the independently trusted target-cluster binding verifier is implemented. +With that gate satisfied, the materializer verifies the server-reported kubectl identity before +each Secret operation and never creates or rotates key material. The caller supplies the trusted +class maximum age separately. Re-running an exact generation is read-only and preserves its +timestamps. +""" + +from __future__ import annotations + +import argparse +import base64 +import binascii +import datetime as dt +import hashlib +import json +import os +import re +import stat +import subprocess +import sys +from collections.abc import Sequence +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +DEV_TOOLS_DIR = Path(__file__).resolve().parents[1] +if str(DEV_TOOLS_DIR) not in sys.path: + sys.path.insert(0, str(DEV_TOOLS_DIR)) + +from evidence_digest import canonical_evidence_digest + +SECRET_NAME = "account-response-envelope-key-ring" +SECRET_KEY = "manifest.v1" +MAX_MANIFEST_BYTES = 64 * 1024 +MAX_SOURCE_RECORD_BYTES = 2 * MAX_MANIFEST_BYTES +OWNER_DIRECTORY_MODE = 0o700 +MAX_RECEIPT_BYTES = 64 * 1024 +KUBECTL_TIMEOUT_SECONDS = 30 +RECEIPT_VERSION = 1 +RECEIPT_TYPE = "account-response-envelope-ring-materialization-v1" +ANNOTATION_MATERIALIZED_AT = "firemud.io/materialized-at" +ANNOTATION_EXPIRES_AT = "firemud.io/expires-at" +ANNOTATION_SOURCE_GENERATION = "firemud.io/source-generation" +ANNOTATION_ENVIRONMENT_ID = "firemud.io/environment-id" +ANNOTATION_TARGET_NAMESPACE = "firemud.io/target-namespace" +ANNOTATION_PREVIOUS_SOURCE_GENERATION = "firemud.io/previous-source-generation" +REQUIRED_ANNOTATIONS = ( + ANNOTATION_MATERIALIZED_AT, + ANNOTATION_EXPIRES_AT, + ANNOTATION_SOURCE_GENERATION, + ANNOTATION_ENVIRONMENT_ID, + ANNOTATION_TARGET_NAMESPACE, + ANNOTATION_PREVIOUS_SOURCE_GENERATION, +) +KEY_ID_PATTERN = re.compile(r"[A-Za-z0-9_-]{1,64}\Z") +KEY_BYTES_PATTERN = re.compile(rb"[A-Za-z0-9_-]{43}\Z") +RFC3339_UTC_PATTERN = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,6})?Z\Z") +KUBERNETES_METADATA_VALUE_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,127}\Z") +SERVICE_ACCOUNT_NAME_PATTERN = re.compile( + r"[a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?)*\Z" +) + + +class MaterializationError(Exception): + """A safe, non-secret-bearing error suitable for command-line output.""" + + +@dataclass(frozen=True) +class ParsedManifest: + active_key_id: str + keys: dict[str, dict[str, bytes]] + + @property + def key_ids(self) -> frozenset[str]: + return frozenset(self.keys) + + +@dataclass(frozen=True) +class ExistingSecret: + manifest_bytes: bytes + manifest: ParsedManifest + materialized_at: dt.datetime + materialized_at_text: str + expires_at: dt.datetime + expires_at_text: str + source_generation: str + previous_source_generation: str | None + environment_id: str + target_namespace: str + uid: str + resource_version: str + labels: dict[str, str] + annotations: dict[str, str] + + +@dataclass(frozen=True) +class SourceRecord: + manifest_bytes: bytes + source_generation: str + source_expires_at: dt.datetime + source_expires_at_text: str + source_created_at: dt.datetime + source_created_at_text: str + environment_id: str + target_namespace: str + materializer_username: str + previous_source_generation: str | None + + +@dataclass(frozen=True) +class MaterializationReceipt: + """Bounded non-authorizing evidence returned by one materializer invocation. + + The canonical record is deliberately stored as immutable JSON text. Callers can obtain a + decoded copy for an authenticated owner handoff, but mutating that copy cannot change the + receipt or its digest. This object is evidence of one Secret operation only; it is not an + authorization result, a readiness result, or a publication to the environment handoff API. + """ + + changed: bool + _canonical_record: str + + def __bool__(self) -> bool: + """Retain the materializer's historical changed/not-changed truthiness contract.""" + + return self.changed + + @property + def canonical_bytes(self) -> bytes: + """Return the bounded canonical receipt bytes without any Secret content.""" + + return self._canonical_record.encode("utf-8") + + def as_dict(self) -> dict[str, Any]: + """Return a fresh decoded receipt copy for a caller-owned handoff envelope.""" + + decoded = json.loads(self._canonical_record) + if not isinstance(decoded, dict): + raise MaterializationError("materialization receipt is internally malformed") + return decoded + + # These aliases make the handoff candidate convenient for callers while keeping one shape. + to_dict = as_dict + + def __getitem__(self, key: str) -> Any: + return self.as_dict()[key] + + @property + def content_digest(self) -> str: + return self["immutableArtifactId"] + + +def parse_rfc3339_utc(value: str, field_name: str) -> dt.datetime: + if not isinstance(value, str) or not RFC3339_UTC_PATTERN.fullmatch(value): + raise MaterializationError(f"{field_name} must be an RFC 3339 UTC timestamp ending in Z") + try: + timestamp_format = "%Y-%m-%dT%H:%M:%S.%fZ" if "." in value else "%Y-%m-%dT%H:%M:%SZ" + parsed = dt.datetime.strptime(value, timestamp_format).replace(tzinfo=dt.timezone.utc) + except ValueError as exc: + raise MaterializationError(f"{field_name} is not a valid RFC 3339 UTC timestamp") from exc + if format_timestamp(parsed) != value: + raise MaterializationError(f"{field_name} must use canonical RFC 3339 UTC formatting") + return parsed + + +def format_timestamp(value: dt.datetime) -> str: + normalized = value.astimezone(dt.timezone.utc) + rendered = normalized.isoformat(timespec="microseconds") + rendered = rendered.replace("+00:00", "Z") + if "." in rendered: + rendered = rendered.replace("Z", "").rstrip("0").rstrip(".") + "Z" + return rendered + + +def validate_source_generation(value: str) -> str: + try: + encoded = value.encode("utf-8") + except UnicodeError as exc: + raise MaterializationError("source generation must be valid UTF-8") from exc + if not value or len(encoded) > 4096: + raise MaterializationError("source generation must be a non-empty opaque annotation value") + if any(ord(char) < 0x20 or ord(char) == 0x7F for char in value): + raise MaterializationError("source generation must not contain control characters") + return value + + +def validate_environment_id(value: str) -> str: + try: + encoded = value.encode("utf-8") + except UnicodeError as exc: + raise MaterializationError("environment ID must be valid UTF-8") from exc + if not value or len(encoded) > 4096: + raise MaterializationError("environment ID must be a non-empty opaque value") + if any(ord(char) < 0x20 or ord(char) == 0x7F for char in value): + raise MaterializationError("environment ID must not contain control characters") + return value + + +def validate_namespace(value: str) -> str: + if not isinstance(value, str) or len(value) > 63 or not re.fullmatch(r"[a-z0-9]([-a-z0-9]*[a-z0-9])?", value): + raise MaterializationError("target namespace must be a Kubernetes namespace name") + return value + + +def validate_kubernetes_metadata_value(value: str, field_name: str) -> str: + """Validate an opaque Kubernetes UID/resourceVersion readback value. + + Kubernetes treats both values as opaque strings. The materializer therefore requires a + bounded, printable token rather than assuming either one is numeric or inventing a UUID + grammar that a server implementation may not use. + """ + + if not isinstance(value, str) or not KUBERNETES_METADATA_VALUE_PATTERN.fullmatch(value): + raise MaterializationError(f"existing Secret {field_name} is missing or malformed") + return value + + +def validate_materializer_username(value: str, namespace: str) -> str: + prefix = f"system:serviceaccount:{namespace}:" + if not isinstance(value, str) or not value.startswith(prefix): + raise MaterializationError( + "materializer username must be a Kubernetes service-account username in the target namespace" + ) + service_account_name = value[len(prefix) :] + if ( + not service_account_name + or len(service_account_name) > 253 + or not SERVICE_ACCOUNT_NAME_PATTERN.fullmatch(service_account_name) + ): + raise MaterializationError( + "materializer username must be a Kubernetes service-account username in the target namespace" + ) + return value + + +def _is_within(path: Path, directory: Path) -> bool: + try: + return os.path.commonpath((str(path), str(directory))) == str(directory) + except ValueError: + return False + + +def _repository_root() -> Path: + return Path(__file__).resolve().parents[2] + + +def read_protected_source_record(path: Path) -> bytes: + path = Path(path) + if not path.is_absolute(): + raise MaterializationError("source record path must be absolute") + nofollow = getattr(os, "O_NOFOLLOW", None) + directory_flag = getattr(os, "O_DIRECTORY", None) + if nofollow is None or nofollow == 0 or directory_flag is None or directory_flag == 0: + raise MaterializationError("platform cannot enforce protected source custody") + try: + source_metadata = os.lstat(path) + if not stat.S_ISREG(source_metadata.st_mode): + raise MaterializationError("source record must be a regular owner-only file") + resolved_path = path.resolve(strict=True) + resolved_repository = _repository_root().resolve(strict=True) + except OSError as exc: + raise MaterializationError("source record is missing or unreadable") from exc + if _is_within(resolved_path, resolved_repository): + raise MaterializationError("source record must be outside the repository") + if not hasattr(os, "getuid"): + raise MaterializationError("platform cannot verify operator ownership") + + directory_fd: int | None = None + descriptor: int | None = None + try: + directory_fd = os.open( + resolved_path.parent, + os.O_RDONLY | directory_flag | nofollow | getattr(os, "O_CLOEXEC", 0), + ) + directory_metadata = os.fstat(directory_fd) + if not stat.S_ISDIR(directory_metadata.st_mode): + raise MaterializationError("source directory must be an owner-only directory") + if stat.S_IMODE(directory_metadata.st_mode) != OWNER_DIRECTORY_MODE: + raise MaterializationError("source directory must be owner-only mode 0700") + if directory_metadata.st_uid != os.getuid(): + raise MaterializationError("source directory must be owned by the operator") + descriptor = os.open( + resolved_path.name, + os.O_RDONLY | nofollow | getattr(os, "O_CLOEXEC", 0), + dir_fd=directory_fd, + ) + metadata = os.fstat(descriptor) + if not stat.S_ISREG(metadata.st_mode) or metadata.st_mode & 0o077: + raise MaterializationError("source record must be a regular file with owner-only permissions") + if metadata.st_uid != os.getuid(): + raise MaterializationError("source record must be owned by the operator") + with os.fdopen(descriptor, "rb", closefd=False) as source: + source_record = source.read(MAX_SOURCE_RECORD_BYTES + 1) + if not source_record or len(source_record) > MAX_SOURCE_RECORD_BYTES: + raise MaterializationError("source record is empty or exceeds the format size limit") + return source_record + except MaterializationError: + raise + except OSError as exc: + raise MaterializationError("source record is missing or unreadable") from exc + finally: + if descriptor is not None: + os.close(descriptor) + if directory_fd is not None: + os.close(directory_fd) + + +def _unique_json_members(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + raise MaterializationError("source record contains duplicate JSON fields") + result[key] = value + return result + + +def _reject_json_constant(value: str) -> None: + raise MaterializationError("source record contains a non-standard JSON value") + + +def read_source_record(path: Path) -> SourceRecord: + source_record_bytes = read_protected_source_record(path) + try: + source_record_text = source_record_bytes.decode("utf-8") + record = json.loads( + source_record_text, + object_pairs_hook=_unique_json_members, + parse_constant=_reject_json_constant, + ) + except (UnicodeDecodeError, json.JSONDecodeError, RecursionError) as exc: + raise MaterializationError("source record must be valid UTF-8 JSON") from exc + expected_fields = { + "version", + "manifestBase64", + "sourceGeneration", + "sourceExpiresAt", + "sourceCreatedAt", + "environmentId", + "targetNamespace", + "materializerUsername", + "previousSourceGeneration", + } + if not isinstance(record, dict) or set(record) != expected_fields: + raise MaterializationError("source record fields do not match the version 1 contract") + if type(record["version"]) is not int or record["version"] != 1: + raise MaterializationError("source record version must be the integer 1") + if not isinstance(record["manifestBase64"], str): + raise MaterializationError("source record manifestBase64 must be a string") + if not isinstance(record["sourceGeneration"], str): + raise MaterializationError("source record sourceGeneration must be a string") + if not isinstance(record["sourceExpiresAt"], str): + raise MaterializationError("source record sourceExpiresAt must be a string") + if not isinstance(record["sourceCreatedAt"], str): + raise MaterializationError("source record sourceCreatedAt must be a string") + if not isinstance(record["environmentId"], str): + raise MaterializationError("source record environmentId must be a string") + if not isinstance(record["targetNamespace"], str): + raise MaterializationError("source record targetNamespace must be a string") + if not isinstance(record["materializerUsername"], str): + raise MaterializationError("source record materializerUsername must be a string") + if record["previousSourceGeneration"] is not None and not isinstance(record["previousSourceGeneration"], str): + raise MaterializationError("source record previousSourceGeneration must be a string or null") + try: + canonical_record = ( + json.dumps(record, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n" + ).encode("utf-8") + encoded_manifest = record["manifestBase64"].encode("ascii") + except (UnicodeEncodeError, TypeError, ValueError) as exc: + raise MaterializationError("source record contains invalid text") from exc + if source_record_bytes != canonical_record: + raise MaterializationError("source record must use canonical JSON encoding and one trailing LF") + try: + manifest_bytes = base64.b64decode(encoded_manifest, validate=True) + except (binascii.Error, ValueError) as exc: + raise MaterializationError("source record manifestBase64 is malformed") from exc + if base64.b64encode(manifest_bytes) != encoded_manifest: + raise MaterializationError("source record manifestBase64 is not canonical") + if not manifest_bytes or len(manifest_bytes) > MAX_MANIFEST_BYTES: + raise MaterializationError("source record manifest is empty or exceeds the format size limit") + source_generation = validate_source_generation(record["sourceGeneration"]) + environment_id = validate_environment_id(record["environmentId"]) + target_namespace = validate_namespace(record["targetNamespace"]) + materializer_username = validate_materializer_username(record["materializerUsername"], target_namespace) + previous_source_generation = record["previousSourceGeneration"] + if previous_source_generation is not None: + previous_source_generation = validate_source_generation(previous_source_generation) + source_expires_at_text = record["sourceExpiresAt"] + source_expires_at = parse_rfc3339_utc(source_expires_at_text, "source expiry") + source_created_at_text = record["sourceCreatedAt"] + source_created_at = parse_rfc3339_utc(source_created_at_text, "source creation time") + if source_expires_at <= source_created_at: + raise MaterializationError("source expiry must follow source creation time") + return SourceRecord( + manifest_bytes=manifest_bytes, + source_generation=source_generation, + source_expires_at=source_expires_at, + source_expires_at_text=source_expires_at_text, + source_created_at=source_created_at, + source_created_at_text=source_created_at_text, + environment_id=environment_id, + target_namespace=target_namespace, + materializer_username=materializer_username, + previous_source_generation=previous_source_generation, + ) + + +def parse_manifest(manifest: bytes) -> ParsedManifest: + if not manifest or len(manifest) > MAX_MANIFEST_BYTES or not manifest.endswith(b"\n"): + raise MaterializationError("source manifest does not match Account manifest v1 framing") + if any(value == 0x0D or value > 0x7E or (value < 0x21 and value != 0x0A) for value in manifest): + raise MaterializationError("source manifest is not strict printable ASCII") + try: + lines = manifest[:-1].decode("ascii").split("\n") + except UnicodeDecodeError as exc: + raise MaterializationError("source manifest is not ASCII") from exc + if len(lines) < 4 or any(not line for line in lines): + raise MaterializationError("source manifest has missing or empty lines") + if lines[0] != "version=1" or not lines[1].startswith("activeKeyId="): + raise MaterializationError("source manifest does not match Account manifest v1 headers") + active_key_id = lines[1][len("activeKeyId=") :] + if not KEY_ID_PATTERN.fullmatch(active_key_id): + raise MaterializationError("source manifest has an invalid active key ID") + + keys: dict[str, dict[str, bytes]] = {} + seen_material: set[bytes] = set() + allowed_purposes = {"bare-login", "connect-token"} + for line in lines[2:]: + if line.count("=") != 1: + raise MaterializationError("source manifest contains a malformed key line") + identity, encoded_text = line.split("=", 1) + parts = identity.split(":") + if len(parts) != 3 or parts[0] != "key": + raise MaterializationError("source manifest contains a malformed key line") + _, key_id, purpose = parts + if not KEY_ID_PATTERN.fullmatch(key_id) or purpose not in allowed_purposes: + raise MaterializationError("source manifest contains an invalid key identity") + encoded = encoded_text.encode("ascii") + if not KEY_BYTES_PATTERN.fullmatch(encoded): + raise MaterializationError("source manifest contains invalid encoded key material") + try: + key_bytes = base64.urlsafe_b64decode(encoded + b"=") + except (binascii.Error, ValueError) as exc: + raise MaterializationError("source manifest contains invalid encoded key material") from exc + if len(key_bytes) != 32 or base64.urlsafe_b64encode(key_bytes).rstrip(b"=") != encoded: + raise MaterializationError("source manifest key material is not a canonical 32-byte value") + if key_bytes in seen_material: + raise MaterializationError("source manifest reuses key material") + by_purpose = keys.setdefault(key_id, {}) + if purpose in by_purpose: + raise MaterializationError("source manifest repeats a key identity") + by_purpose[purpose] = key_bytes + seen_material.add(key_bytes) + + if not keys or active_key_id not in keys: + raise MaterializationError("source manifest does not contain its active key ID") + if any(set(by_purpose) != allowed_purposes for by_purpose in keys.values()): + raise MaterializationError("every retained key ID must contain both Account purposes") + return ParsedManifest(active_key_id, keys) + + +def _decode_secret_manifest(secret: dict[str, Any], namespace: str) -> tuple[bytes, dict[str, Any]]: + metadata = secret.get("metadata") + if not isinstance(metadata, dict): + raise MaterializationError("existing Secret metadata is missing or malformed") + if metadata.get("name") != SECRET_NAME or metadata.get("namespace") != namespace: + raise MaterializationError("existing Secret identity is inconsistent") + if secret.get("apiVersion") != "v1" or secret.get("kind") != "Secret" or secret.get("type") != "Opaque": + raise MaterializationError("existing Secret type or API identity is inconsistent") + data = secret.get("data") + if not isinstance(data, dict) or set(data) != {SECRET_KEY} or not isinstance(data.get(SECRET_KEY), str): + raise MaterializationError("existing Secret must contain exactly the canonical manifest key") + try: + encoded = data[SECRET_KEY].encode("ascii", errors="strict") + manifest_bytes = base64.b64decode(encoded, validate=True) + except (binascii.Error, UnicodeEncodeError, ValueError) as exc: + raise MaterializationError("existing Secret manifest encoding is malformed") from exc + if base64.b64encode(manifest_bytes) != encoded: + raise MaterializationError("existing Secret manifest encoding is not canonical") + return manifest_bytes, metadata + + +def _load_existing_secret(secret: dict[str, Any], namespace: str, expected_environment_id: str) -> ExistingSecret: + manifest_bytes, metadata = _decode_secret_manifest(secret, namespace) + parsed_manifest = parse_manifest(manifest_bytes) + annotations = metadata.get("annotations") + labels = metadata.get("labels", {}) + uid = metadata.get("uid") + resource_version = metadata.get("resourceVersion") + if not isinstance(annotations, dict) or not isinstance(labels, dict): + raise MaterializationError("existing Secret annotations or labels are malformed") + uid = validate_kubernetes_metadata_value(uid, "UID") + resource_version = validate_kubernetes_metadata_value(resource_version, "resource version") + if any(key not in annotations or not isinstance(annotations[key], str) for key in REQUIRED_ANNOTATIONS): + raise MaterializationError("existing Secret freshness metadata is missing") + generation = validate_source_generation(annotations[ANNOTATION_SOURCE_GENERATION]) + environment_id = validate_environment_id(annotations[ANNOTATION_ENVIRONMENT_ID]) + target_namespace = validate_namespace(annotations[ANNOTATION_TARGET_NAMESPACE]) + previous_generation_text = annotations[ANNOTATION_PREVIOUS_SOURCE_GENERATION] + previous_generation = ( + None if previous_generation_text == "" else validate_source_generation(previous_generation_text) + ) + if environment_id != expected_environment_id or target_namespace != namespace: + raise MaterializationError("existing Secret environment or target namespace is inconsistent") + materialized_text = annotations[ANNOTATION_MATERIALIZED_AT] + expires_text = annotations[ANNOTATION_EXPIRES_AT] + materialized_at = parse_rfc3339_utc(materialized_text, "existing materialized-at") + expires_at = parse_rfc3339_utc(expires_text, "existing expires-at") + if expires_at <= materialized_at: + raise MaterializationError("existing Secret expiry does not follow materialization") + if any(not isinstance(key, str) or not isinstance(value, str) for key, value in labels.items()): + raise MaterializationError("existing Secret labels are malformed") + if any(not isinstance(key, str) or not isinstance(value, str) for key, value in annotations.items()): + raise MaterializationError("existing Secret annotations are malformed") + return ExistingSecret( + manifest_bytes=manifest_bytes, + manifest=parsed_manifest, + materialized_at=materialized_at, + materialized_at_text=materialized_text, + expires_at=expires_at, + expires_at_text=expires_text, + source_generation=generation, + previous_source_generation=previous_generation, + environment_id=environment_id, + target_namespace=target_namespace, + uid=uid, + resource_version=resource_version, + labels=dict(labels), + annotations=dict(annotations), + ) + + +def _run_kubectl( + command: Sequence[str], + request_object: dict[str, Any] | None = None, + *, + failure_message: str = "Kubernetes operation failed; existing Secret was left for diagnosis", +) -> str: + _require_target_cluster_binding() + try: + completed = subprocess.run( + list(command), + input=None if request_object is None else json.dumps(request_object, separators=(",", ":")), + capture_output=True, + text=True, + check=False, + timeout=KUBECTL_TIMEOUT_SECONDS, + ) + except subprocess.TimeoutExpired as exc: + raise MaterializationError("Kubernetes operation timed out") from exc + except UnicodeError as exc: + raise MaterializationError("Kubernetes operation returned invalid text") from exc + except OSError as exc: + raise MaterializationError("kubectl could not be started") from exc + if completed.returncode != 0: + raise MaterializationError(failure_message) + return completed.stdout + + +def _require_target_cluster_binding() -> None: + """Fail closed until the trusted target-cluster binding verifier exists.""" + + raise MaterializationError( + "target-cluster binding verification is unavailable; Kubernetes access is disabled" + ) + + +def _verify_materializer_identity(kubectl: str, expected_username: str) -> str: + output = _run_kubectl( + [kubectl, "auth", "whoami", "-o", "json"], + failure_message="server-authenticated materializer identity verification failed", + ) + try: + identity = json.loads(output, object_pairs_hook=_unique_json_members) + except (json.JSONDecodeError, MaterializationError, RecursionError) as exc: + raise MaterializationError("kubectl auth whoami returned malformed identity") from exc + status = identity.get("status") if isinstance(identity, dict) else None + user_info = status.get("userInfo") if isinstance(status, dict) else None + username = user_info.get("username") if isinstance(user_info, dict) else None + if not isinstance(username, str): + raise MaterializationError("kubectl auth whoami did not return an authenticated username") + if username != expected_username: + raise MaterializationError("authenticated username does not match the protected source record") + return username + + +def _read_secret(kubectl: str, namespace: str) -> dict[str, Any] | None: + output = _run_kubectl( + [ + kubectl, + "get", + "secret", + SECRET_NAME, + "--namespace", + namespace, + "--ignore-not-found=true", + "--output=json", + ] + ) + if not output.strip(): + return None + try: + secret = json.loads(output) + except json.JSONDecodeError as exc: + raise MaterializationError("Kubernetes returned malformed Secret readback") from exc + if not isinstance(secret, dict): + raise MaterializationError("Kubernetes returned malformed Secret readback") + return secret + + +def _bounded_expiry(source_expires_at: dt.datetime, materialized_at: dt.datetime, max_age_seconds: int) -> dt.datetime: + return min(source_expires_at, _class_age_deadline(materialized_at, max_age_seconds)) + + +def _class_age_deadline(materialized_at: dt.datetime, max_age_seconds: int) -> dt.datetime: + try: + return materialized_at + dt.timedelta(seconds=max_age_seconds) + except OverflowError as exc: + raise MaterializationError("class maximum age is out of range") from exc + + +def _secret_for_write( + manifest_bytes: bytes, + namespace: str, + source_generation: str, + environment_id: str, + previous_source_generation: str | None, + materialized_at: dt.datetime, + expires_at: dt.datetime, + existing: ExistingSecret | None, +) -> dict[str, Any]: + metadata: dict[str, Any] = {"name": SECRET_NAME, "namespace": namespace} + if existing is not None: + metadata["resourceVersion"] = existing.resource_version + if existing.labels: + metadata["labels"] = existing.labels + annotations = existing.annotations + else: + annotations = {} + annotations = dict(annotations) + annotations.update( + { + ANNOTATION_MATERIALIZED_AT: format_timestamp(materialized_at), + ANNOTATION_EXPIRES_AT: format_timestamp(expires_at), + ANNOTATION_SOURCE_GENERATION: source_generation, + ANNOTATION_ENVIRONMENT_ID: environment_id, + ANNOTATION_TARGET_NAMESPACE: namespace, + ANNOTATION_PREVIOUS_SOURCE_GENERATION: previous_source_generation or "", + } + ) + metadata["annotations"] = annotations + return { + "apiVersion": "v1", + "kind": "Secret", + "metadata": metadata, + "type": "Opaque", + "data": {SECRET_KEY: base64.b64encode(manifest_bytes).decode("ascii")}, + } + + +def _verify_readback( + secret: dict[str, Any] | None, + namespace: str, + environment_id: str, + manifest_bytes: bytes, + source_generation: str, + materialized_at_text: str, + expires_at_text: str, + expected_labels: dict[str, str], + expected_annotations: dict[str, str], + expected_uid: str | None = None, + expected_resource_version: str | None = None, +) -> ExistingSecret: + if secret is None: + raise MaterializationError("Secret readback is missing") + observed_manifest, _ = _decode_secret_manifest(secret, namespace) + if observed_manifest != manifest_bytes: + raise MaterializationError("Secret readback manifest bytes do not match the source") + current = _load_existing_secret(secret, namespace, environment_id) + if expected_uid is not None and current.uid != expected_uid: + raise MaterializationError("Secret readback UID does not match the existing Secret") + if expected_resource_version is not None and current.resource_version == expected_resource_version: + raise MaterializationError("Secret readback resource version did not advance") + if current.source_generation != source_generation: + raise MaterializationError("Secret readback source generation does not match") + if current.materialized_at_text != materialized_at_text or current.expires_at_text != expires_at_text: + raise MaterializationError("Secret readback freshness metadata does not match") + if current.labels != expected_labels or current.annotations != expected_annotations: + raise MaterializationError("Secret readback metadata does not match the materialized object") + return current + + +def _sha256_digest(value: bytes) -> str: + return f"sha256:{hashlib.sha256(value).hexdigest()}" + + +def _receipt_json_members(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + raise MaterializationError("materialization receipt contains duplicate JSON fields") + result[key] = value + return result + + +def verify_materialization_receipt( + canonical_bytes: bytes, + *, + expected_environment_id: str, + expected_namespace: str, + expected_source_generation: str, + expected_predecessor_generation: str | None, + expected_manifest_digest: str, + expected_materializer_username: str, + expected_secret_name: str = SECRET_NAME, + expected_secret_uid: str, + expected_secret_resource_version: str, +) -> dict[str, Any]: + """Strictly parse and compare local receipt bytes against caller-supplied bindings. + + This verifies receipt structure and consistency only. It does not authenticate a transport, + prove who published the bytes, or establish Secret freshness/readiness. + """ + + if not isinstance(canonical_bytes, bytes) or not canonical_bytes: + raise MaterializationError("materialization receipt must be non-empty bytes") + if len(canonical_bytes) > MAX_RECEIPT_BYTES: + raise MaterializationError("materialization receipt exceeds the format size limit") + try: + text = canonical_bytes.decode("utf-8") + record = json.loads(text, object_pairs_hook=_receipt_json_members) + except MaterializationError: + raise + except (UnicodeDecodeError, json.JSONDecodeError, ValueError) as exc: + raise MaterializationError("materialization receipt is not valid UTF-8 JSON") from exc + if not isinstance(record, dict): + raise MaterializationError("materialization receipt must be a JSON object") + + expected_fields = { + "version", + "receiptType", + "operation", + "source", + "environmentId", + "targetNamespace", + "secret", + "materializerUsername", + "freshnessAnnotations", + "immutableArtifactId", + } + if set(record) != expected_fields: + raise MaterializationError("materialization receipt fields do not match the typed format") + if type(record["version"]) is not int or record["version"] != RECEIPT_VERSION: + raise MaterializationError("materialization receipt version is unsupported") + if record["receiptType"] != RECEIPT_TYPE: + raise MaterializationError("materialization receipt type is not the Account ring format") + if not isinstance(record["operation"], str) or record["operation"] not in { + "create", + "rotate", + "retry", + }: + raise MaterializationError("materialization receipt operation is invalid") + + source = record["source"] + secret = record["secret"] + freshness = record["freshnessAnnotations"] + if not isinstance(source, dict) or set(source) != { + "generation", + "predecessorGeneration", + "manifestDigest", + }: + raise MaterializationError("materialization receipt source fields do not match the typed format") + if not isinstance(secret, dict) or set(secret) != { + "apiVersion", + "kind", + "name", + "namespace", + "uid", + "resourceVersion", + }: + raise MaterializationError("materialization receipt Secret fields do not match the typed format") + if not isinstance(freshness, dict) or set(freshness) != set(REQUIRED_ANNOTATIONS): + raise MaterializationError("materialization receipt freshness fields do not match the typed format") + for name in ("environmentId", "targetNamespace", "materializerUsername", "immutableArtifactId"): + if not isinstance(record[name], str): + raise MaterializationError("materialization receipt contains an invalid field value") + try: + validate_environment_id(record["environmentId"]) + validate_namespace(record["targetNamespace"]) + validate_source_generation(source["generation"]) + if source["predecessorGeneration"] is not None: + validate_source_generation(source["predecessorGeneration"]) + except (MaterializationError, AttributeError) as exc: + raise MaterializationError("materialization receipt source or target binding is invalid") from exc + if not isinstance(source["manifestDigest"], str) or not re.fullmatch( + r"sha256:[0-9a-f]{64}", source["manifestDigest"] + ): + raise MaterializationError("materialization receipt manifest digest is invalid") + if any(not isinstance(value, str) for value in secret.values()): + raise MaterializationError("materialization receipt Secret identity is invalid") + if any(not isinstance(value, str) for value in freshness.values()): + raise MaterializationError("materialization receipt freshness annotation is invalid") + parse_rfc3339_utc(freshness[ANNOTATION_MATERIALIZED_AT], "receipt materialized-at") + parse_rfc3339_utc(freshness[ANNOTATION_EXPIRES_AT], "receipt expires-at") + + digest = record["immutableArtifactId"] + if not re.fullmatch(r"sha256:[0-9a-f]{64}", digest): + raise MaterializationError("materialization receipt immutable digest is invalid") + try: + calculated_digest = canonical_evidence_digest(record) + except (TypeError, ValueError, UnicodeEncodeError) as exc: + raise MaterializationError("materialization receipt digest preimage is invalid") from exc + if digest != calculated_digest: + raise MaterializationError("materialization receipt immutable digest does not match") + + try: + validate_environment_id(expected_environment_id) + validate_namespace(expected_namespace) + validate_source_generation(expected_source_generation) + if expected_predecessor_generation is not None: + validate_source_generation(expected_predecessor_generation) + validate_materializer_username(expected_materializer_username, expected_namespace) + validate_kubernetes_metadata_value(expected_secret_uid, "UID") + validate_kubernetes_metadata_value(expected_secret_resource_version, "resource version") + except (MaterializationError, AttributeError) as exc: + raise MaterializationError("expected materialization receipt binding is invalid") from exc + if expected_secret_name != SECRET_NAME: + raise MaterializationError("expected materialization receipt Secret name is not canonical") + + exact_bindings = ( + (record["environmentId"], expected_environment_id, "environment"), + (record["targetNamespace"], expected_namespace, "namespace"), + (source["generation"], expected_source_generation, "source generation"), + (source["predecessorGeneration"], expected_predecessor_generation, "predecessor generation"), + (source["manifestDigest"], expected_manifest_digest, "manifest digest"), + (record["materializerUsername"], expected_materializer_username, "materializer identity"), + (secret["apiVersion"], "v1", "Secret apiVersion"), + (secret["kind"], "Secret", "Secret kind"), + (secret["name"], SECRET_NAME, "Secret name"), + (secret["namespace"], expected_namespace, "Secret namespace"), + (secret["uid"], expected_secret_uid, "Secret UID"), + (secret["resourceVersion"], expected_secret_resource_version, "Secret resource version"), + (freshness[ANNOTATION_SOURCE_GENERATION], expected_source_generation, "freshness generation"), + ( + freshness[ANNOTATION_ENVIRONMENT_ID], + expected_environment_id, + "freshness environment", + ), + ( + freshness[ANNOTATION_TARGET_NAMESPACE], + expected_namespace, + "freshness namespace", + ), + ( + freshness[ANNOTATION_PREVIOUS_SOURCE_GENERATION], + expected_predecessor_generation or "", + "freshness predecessor", + ), + ) + for actual, expected, label in exact_bindings: + if actual != expected: + raise MaterializationError(f"materialization receipt {label} does not match expected value") + + canonical_text = json.dumps(record, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n" + if canonical_text.encode("utf-8") != canonical_bytes: + raise MaterializationError("materialization receipt bytes are not canonical") + return record + + +def _materialization_receipt( + *, + changed: bool, + operation: str, + source: SourceRecord, + source_manifest_digest: str, + authenticated_materializer_username: str, + current: ExistingSecret, +) -> MaterializationReceipt: + if operation not in {"create", "rotate", "retry"}: + raise MaterializationError("materialization receipt operation is invalid") + if current.source_generation != source.source_generation: + raise MaterializationError("materialization receipt source generation is inconsistent") + if current.previous_source_generation != source.previous_source_generation: + raise MaterializationError("materialization receipt predecessor is inconsistent") + if current.environment_id != source.environment_id or current.target_namespace != source.target_namespace: + raise MaterializationError("materialization receipt environment binding is inconsistent") + freshness_annotations = {annotation: current.annotations[annotation] for annotation in REQUIRED_ANNOTATIONS} + record: dict[str, Any] = { + "version": RECEIPT_VERSION, + "receiptType": RECEIPT_TYPE, + "operation": operation, + "source": { + "generation": source.source_generation, + "predecessorGeneration": source.previous_source_generation, + "manifestDigest": source_manifest_digest, + }, + "environmentId": source.environment_id, + "targetNamespace": source.target_namespace, + "secret": { + "apiVersion": "v1", + "kind": "Secret", + "name": SECRET_NAME, + "namespace": current.target_namespace, + "uid": current.uid, + "resourceVersion": current.resource_version, + }, + "materializerUsername": authenticated_materializer_username, + "freshnessAnnotations": freshness_annotations, + } + record["immutableArtifactId"] = canonical_evidence_digest(record) + try: + canonical_record = ( + json.dumps(record, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n" + ).encode("utf-8") + except (TypeError, UnicodeEncodeError, ValueError) as exc: + raise MaterializationError("materialization receipt contains invalid evidence values") from exc + if len(canonical_record) > MAX_RECEIPT_BYTES: + raise MaterializationError("materialization receipt exceeds the format size limit") + return MaterializationReceipt(changed=changed, _canonical_record=canonical_record.decode("utf-8")) + + +def materialize( + source_record_path: Path, + environment_id: str, + namespace: str, + class_max_age_seconds: int, + kubectl: str = "kubectl", + now: dt.datetime | None = None, +) -> MaterializationReceipt: + environment_id = validate_environment_id(environment_id) + namespace = validate_namespace(namespace) + if class_max_age_seconds <= 0: + raise MaterializationError("class maximum age must be a positive number of seconds") + source_record = read_source_record(source_record_path) + if source_record.environment_id != environment_id: + raise MaterializationError("source record environment ID does not match the expected environment") + if source_record.target_namespace != namespace: + raise MaterializationError("source record target namespace does not match the expected namespace") + expected_materializer_username = source_record.materializer_username + source_generation = source_record.source_generation + source_expires_at = source_record.source_expires_at + source_created_at = source_record.source_created_at + source_bytes = source_record.manifest_bytes + source_manifest = parse_manifest(source_bytes) + current_time = now or dt.datetime.now(dt.timezone.utc) + if current_time.tzinfo is None: + raise MaterializationError("materializer clock must be timezone-aware") + current_time = current_time.astimezone(dt.timezone.utc) + if source_expires_at <= current_time: + raise MaterializationError("source expiry must be in the future") + if source_created_at > current_time: + raise MaterializationError("source creation time must not be in the future") + expires_at = _bounded_expiry(source_expires_at, source_created_at, class_max_age_seconds) + if expires_at <= current_time: + raise MaterializationError("source generation has expired under the class maximum age") + + # Verify the server-reported principal immediately before every Kubernetes + # Secret operation; kubectl context or credentials may change between calls. + authenticated_materializer_username = _verify_materializer_identity(kubectl, expected_materializer_username) + secret = _read_secret(kubectl, namespace) + existing: ExistingSecret | None = None + if secret is not None: + existing = _load_existing_secret(secret, namespace, environment_id) + if existing.materialized_at > current_time: + raise MaterializationError("existing Secret materialized-at timestamp is in the future") + if existing.source_generation == source_generation: + if source_record.previous_source_generation != existing.previous_source_generation: + raise MaterializationError("same-generation predecessor does not match materialization lineage") + if ( + existing.materialized_at_text != source_record.source_created_at_text + or existing.expires_at != expires_at + ): + raise MaterializationError("same-generation freshness metadata does not match the source record") + if existing.manifest_bytes != source_bytes: + raise MaterializationError("same source generation has different manifest bytes") + return _materialization_receipt( + changed=False, + operation="retry", + source=source_record, + source_manifest_digest=_sha256_digest(source_bytes), + authenticated_materializer_username=authenticated_materializer_username, + current=existing, + ) + if source_record.previous_source_generation != existing.source_generation: + raise MaterializationError("source predecessor does not match the current Secret generation") + if source_created_at < existing.materialized_at: + raise MaterializationError("source creation time regresses the current Secret generation") + previous_age_deadline = _class_age_deadline(existing.materialized_at, class_max_age_seconds) + if existing.expires_at > previous_age_deadline: + raise MaterializationError("existing Secret expiry exceeds the supplied class maximum age") + if existing.manifest_bytes == source_bytes: + raise MaterializationError("source generation cannot advance while manifest bytes stay unchanged") + if source_manifest.active_key_id in existing.manifest.key_ids: + raise MaterializationError("replacement must introduce a new active key ID") + if not existing.manifest.key_ids.issubset(source_manifest.key_ids): + raise MaterializationError("replacement removes a prior key ID needed for decryption") + for key_id in existing.manifest.key_ids: + if source_manifest.keys[key_id] != existing.manifest.keys[key_id]: + raise MaterializationError("replacement changes material for a retained prior key ID") + elif source_record.previous_source_generation is not None: + raise MaterializationError("source predecessor requires an existing Secret generation") + + materialized_at = source_created_at + if expires_at <= materialized_at: + raise MaterializationError("bounded Secret expiry must follow source creation time") + manifest_object = _secret_for_write( + source_bytes, + namespace, + source_generation, + environment_id, + source_record.previous_source_generation, + materialized_at, + expires_at, + existing, + ) + expected_annotations = dict(manifest_object["metadata"]["annotations"]) + expected_labels = dict(manifest_object["metadata"].get("labels", {})) + write_command = [ + kubectl, + "create" if existing is None else "replace", + "--namespace", + namespace, + "--filename", + "-", + "--output=json", + ] + authenticated_materializer_username = _verify_materializer_identity(kubectl, expected_materializer_username) + _run_kubectl(write_command, manifest_object) + authenticated_materializer_username = _verify_materializer_identity(kubectl, expected_materializer_username) + readback = _read_secret(kubectl, namespace) + readback_secret = _verify_readback( + readback, + namespace, + environment_id, + source_bytes, + source_generation, + format_timestamp(materialized_at), + format_timestamp(expires_at), + expected_labels, + expected_annotations, + expected_uid=existing.uid if existing is not None else None, + expected_resource_version=existing.resource_version if existing is not None else None, + ) + return _materialization_receipt( + changed=True, + operation="create" if existing is None else "rotate", + source=source_record, + source_manifest_digest=_sha256_digest(source_bytes), + authenticated_materializer_username=authenticated_materializer_username, + current=readback_secret, + ) + + +def _parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--source-record", required=True, type=Path) + parser.add_argument("--environment-id", required=True) + parser.add_argument("--namespace", required=True) + parser.add_argument("--class-max-age-seconds", required=True, type=int) + parser.add_argument("--kubectl", default="kubectl") + return parser.parse_args(argv) + + +def main(argv: Sequence[str] | None = None) -> int: + try: + args = _parse_args(argv) + changed = materialize( + source_record_path=args.source_record, + environment_id=args.environment_id, + namespace=args.namespace, + class_max_age_seconds=args.class_max_age_seconds, + kubectl=args.kubectl, + ) + except MaterializationError as exc: + print(f"materialization failed: {exc}", file=sys.stderr) + return 1 + except (OSError, ValueError, TypeError): + print("materialization failed: invalid input or unavailable dependency", file=sys.stderr) + return 1 + action = "materialized" if changed else "already materialized" + print(f"{action} {SECRET_NAME} in namespace {args.namespace}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/dev-tools/hosted/preview/resolve-preview-image-tag.sh b/dev-tools/hosted/preview/resolve-preview-image-tag.sh index f9d00f5fd6..442eb9e33c 100644 --- a/dev-tools/hosted/preview/resolve-preview-image-tag.sh +++ b/dev-tools/hosted/preview/resolve-preview-image-tag.sh @@ -33,7 +33,7 @@ runtime_relevant() { .github/workflows/runtime-images.yml | .github/workflows/publish-pr-runtime-images.yml | .github/workflows/smoke.yml | .github/workflows/smoke-full.yml | .dockerignore) return 0 ;; - .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/*) + .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/* | dev-tools/minio/*) return 0 ;; config/python/smoke-requirements.txt | config/python/smoke-requirements.in | \ diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index fdb265d732..3bf11d75f7 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -41,6 +41,18 @@ if script.index("github.rest.pulls.get") > script.index("github.paginate(github. raise SystemExit("validation-summary must verify the current PR before listing comments") PY +python3 - "$ROOT_DIR/.github/workflows/ci.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["validation-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + script_b64="$({ python3 - "$CI_WORKFLOW" <<'PY' import base64 diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 926cb684a4..fd063f377b 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -498,6 +498,89 @@ grep -Fq "name: \${{ github.event_name == 'pull_request' && github.event.action tmp_dir="$(mktemp -d)" trap 'rm -rf "$tmp_dir"' EXIT + +# The Smoke consumer must outlive its producer and still terminate fail closed. +smoke_clock_fixture="$tmp_dir/smoke-clock.js" +python3 - "$ROOT_DIR" "$smoke_clock_fixture" <<'PY' +from pathlib import Path +import re +import sys +import yaml + +root = Path(sys.argv[1]) +smoke = yaml.load((root / ".github/workflows/smoke.yml").read_text(), Loader=yaml.BaseLoader) +producer = yaml.load((root / ".github/workflows/runtime-images.yml").read_text(), Loader=yaml.BaseLoader) +job = smoke["jobs"]["smoke-gate"] +script = next(step["with"]["script"] for step in job["steps"] if step.get("name") == "Track full-stack smoke result from Build Runtime Images") +producer_minutes = int(re.search(r"const producerTimeoutMinutes = ([0-9]+);", script)[1]) +overhead_minutes = int(re.search(r"const prerequisiteAndQueueAllowanceMinutes = ([0-9]+);", script)[1]) +if producer_minutes != int(producer["jobs"]["pr-local-smoke"]["timeout-minutes"]): + raise SystemExit("Smoke polling producer budget must match the actual full-stack producer timeout") +if overhead_minutes != 45 or int(job["timeout-minutes"]) < producer_minutes + overhead_minutes + 5: + raise SystemExit("Smoke polling must retain bounded scheduling overhead and five-minute job margin") +if "const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000;" not in script: + raise SystemExit("Smoke polling deadline must use the checked producer and overhead authorities") +Path(sys.argv[2]).write_text(script) +PY + +node - "$smoke_clock_fixture" <<'NODE' +const assert = require("node:assert/strict"); +const script = require("node:fs").readFileSync(process.argv[2], "utf8"); +const head = "a".repeat(40), base = "b".repeat(40), merge = "c".repeat(40); +const title = `Build Runtime Images secure-pr-artifact pr-42 base-${base} head-${head} merge-${merge} mode-required`; +const context = { repo: { owner: "example", repo: "firemud" }, sha: merge, + payload: { pull_request: { number: 42, head: { sha: head }, base: { ref: "develop", sha: base }, created_at: "2026-09-01T00:00:00Z" } } }; +const execute = new Function("github", "context", "core", "Date", "setTimeout", `return (async () => {\n${script}\n})()`); +async function scenario(outcome, completedAtMinutes) { + let now = 1000; + const start = now; + const failures = []; + const listRuns = async () => {}, listJobs = async () => {}; + const github = { rest: { + pulls: { get: async () => ({ data: { state: "open", head: { sha: head }, base: { ref: "develop", sha: base }, merge_commit_sha: merge } }) }, + repos: { getCommit: async () => ({ data: { sha: merge, parents: [{ sha: base }, { sha: head }] } }) }, + actions: { listWorkflowRuns: listRuns, listJobsForWorkflowRun: listJobs }, + }, paginate: async (method, input) => { + assert.equal(method, listJobs); + assert.equal(input.run_id, 42); + return [{ name: "PR Full-Stack Smoke", status: "completed", conclusion: "success", + steps: [{ name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success" }] }]; + } }; + github.paginate.iterator = async function* (method, input) { + assert.equal(method, listRuns); + assert.equal(input.workflow_id, "runtime-images.yml"); + if (input.event === "repository_dispatch") { yield { data: [] }; return; } + assert.equal(input.head_sha, head); + const complete = now - start >= completedAtMinutes * 60 * 1000; + yield { data: [{ id: 42, event: "pull_request", head_sha: head, display_title: title, pull_requests: [], + status: complete ? "completed" : "in_progress", conclusion: complete ? outcome : null }] }; + }; + const core = { info: () => {}, warning: () => {}, setFailed: message => failures.push(message) }; + const clock = { now: () => now, parse: Date.parse }; + const sleep = (callback, duration) => { now += duration; queueMicrotask(callback); }; + await execute(github, context, core, clock, sleep); + return { failures, minutes: (now - start) / 60000 }; +} +(async () => { + const success = await scenario("success", 30); + assert.deepEqual(success.failures, [], "exact producer success after 25 minutes must be admitted"); + assert.equal(success.minutes, 30); + const failed = await scenario("failure", 30); + assert.equal(failed.failures.length, 1); + assert.match(failed.failures[0], /did not complete successfully/); + assert.equal(failed.minutes, 30, "terminal failure must stop polling promptly"); + const cancelled = await scenario("cancelled", 0); + assert.equal(cancelled.failures.length, 1); + assert.match(cancelled.failures[0], /cancelled/i); + assert.ok(cancelled.minutes <= 5.25, "cancelled source without an exact replacement remains bounded"); + const deadline = await scenario("success", Infinity); + assert.equal(deadline.failures.length, 1); + assert.match(deadline.failures[0], /Timed out waiting for the exact/); + assert.equal(deadline.minutes, 90, "active producers cannot escape the total deadline"); + console.log("Smoke clock contract passed: late success, prompt failure, bounded cancellation and deadline"); +})().catch(error => { console.error(error); process.exitCode = 1; }); +NODE + cat >"$tmp_dir/gh" <<'EOF' #!/usr/bin/env bash set -euo pipefail diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index e27cbf79e0..affc4ae136 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -334,6 +334,44 @@ for path in "$ci_path" "$security_path" "$smoke_path"; do require_contains "$path" 'types: [opened, synchronize, reopened, edited]' done +# Optional native-PR comments cannot delay cancellation or require fork/bot write tokens. +python3 - "$ROOT_DIR" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +root = Path(sys.argv[1]) +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +for filename, jobs in { + "ci.yml": ("validation-summary",), + "security.yml": ("security-summary",), + "smoke.yml": ("smoke-summary-pending", "smoke-summary"), +}.items(): + workflow = yaml.load((root / ".github/workflows" / filename).read_text(), Loader=yaml.BaseLoader) + for job in jobs: + condition = workflow["jobs"][job]["if"] + if condition != expected: + raise SystemExit(f"{filename}/{job} must retain the cancellation, trust and substantive-event condition") + def eligible(cancelled=False, event="pull_request", head_repo="example/repo", actor="contributor", action="synchronize", base_ref=None): + expression = condition[3:-3].replace("!cancelled()", str(not cancelled)) + values = { + "github.event.pull_request.head.repo.full_name": head_repo, + "github.event.changes.base.ref": base_ref, + "github.event_name": event, + "github.repository": "example/repo", + "github.actor": actor, + "github.event.action": action, + } + for key, value in values.items(): + expression = expression.replace(key, repr(value)) + return eval(expression.replace("&&", "and").replace("||", "or").replace("null", "None"), {"__builtins__": {}}) + if not eligible() or not eligible(action="edited", base_ref="develop"): + raise SystemExit(f"{job} must report ordinary results and base retargets") + for arguments in ({"cancelled": True}, {"head_repo": "fork/repo"}, {"actor": "dependabot[bot]"}, {"action": "edited"}, {"event": "push"}): + if eligible(**arguments): + raise SystemExit(f"{job} permits an ineligible comment mutation: {arguments}") +PYTHON + # Metadata-only edits get distinct optional summary contexts; substantive events # retain each summary's canonical name. # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. @@ -1503,6 +1541,15 @@ runtime_service = "services/account-service/src/Main.java" assert run_scope([controller_service]) == {"run_smoke_full": "false"} assert run_scope([controller_smoke_script]) == {"run_smoke_full": "false"} +# Source-built MinIO helpers must require runtime proof even when no Dockerfile changes. +root = Path(sys.argv[1]).resolve().parents[2] +preview_resolver = (root / "dev-tools/hosted/preview/resolve-preview-image-tag.sh").read_text() +preview_predicate = preview_resolver[preview_resolver.index("runtime_relevant() {"):preview_resolver.index('\nif [[ -n "${pr_number}"')] +for helper in ("dev-tools/minio/base_image_refs.py", "dev-tools/minio/build-and-smoke-images.sh"): + assert run_scope([helper]) == {"run_smoke_full": "true"}, helper + preview = subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", helper], check=False) + assert preview.returncode == 0, helper +assert subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", "design/example.md"], check=False).returncode != 0 assert run_scope([runtime_service]) == {"run_smoke_full": "true"} assert run_scope([controller_service, runtime_service]) == {"run_smoke_full": "true"} PY @@ -1973,6 +2020,7 @@ const scripts = JSON.parse(process.env.SMOKE_SUMMARY_SCRIPTS); const context = { repo: { owner: "example", repo: "firemud" }, issue: { number: 42 }, + payload: { pull_request: { head: { sha: "h" }, base: { ref: "develop", sha: "b" } } }, }; async function checkSummary(jobName, script) { @@ -2005,13 +2053,16 @@ async function checkSummary(jobName, script) { created_at: "2026-08-01T00:00:00Z", }, ]; - const calls = { paginate: [], operations: [], creates: [] }; + const calls = { paginate: [], operations: [], creates: [], bodies: [] }; + let currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + let readError = null; const listComments = async () => undefined; const github = { rest: { + pulls: { get: async () => { if (readError) throw readError; return { data: currentPullRequest }; } }, issues: { listComments, - updateComment: async ({ comment_id }) => calls.operations.push(`update:${comment_id}`), + updateComment: async ({ comment_id, body }) => { calls.operations.push(`update:${comment_id}`); calls.bodies.push(body); }, deleteComment: async ({ comment_id }) => calls.operations.push(`delete:${comment_id}`), createComment: async (request) => calls.creates.push(request), }, @@ -2025,8 +2076,24 @@ async function checkSummary(jobName, script) { process.env.CHANGES_RESULT = "success"; process.env.RUN_SMOKE_FULL = "true"; process.env.SMOKE_GATE_RESULT = "success"; - const run = new Function("github", "context", `return (async () => {\n${script}\n})()`); - await run(github, context); + const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); + const core = { info: () => {} }; + for (const changed of [ + { state: "closed" }, { head: { sha: "new" } }, + { base: { ref: "main", sha: "b" } }, { base: { ref: "develop", sha: "new" } }, + ]) { + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request), ...changed }; + await run(github, context, core); + assert.deepEqual(calls.paginate, [], `${jobName} must not list stale comments`); + assert.deepEqual(calls.operations, [], `${jobName} must not mutate stale comments`); + assert.deepEqual(calls.creates, [], `${jobName} must not create stale comments`); + } + readError = new Error("PR guard unavailable"); + await assert.rejects(run(github, context, core), /PR guard unavailable/); + assert.deepEqual(calls.paginate, [], `${jobName} guard errors must fail closed`); + readError = null; + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + await run(github, context, core); assert.equal(calls.paginate.length, 1, `${jobName} must paginate once`); assert.equal(calls.paginate[0].method, listComments, `${jobName} must paginate issue comments`); @@ -2037,6 +2104,10 @@ async function checkSummary(jobName, script) { `${jobName} must update the oldest bot summary before deleting later duplicates`, ); assert.deepEqual(calls.creates, [], `${jobName} must not create another summary`); + process.env.CHANGES_RESULT = "failure"; + process.env.SMOKE_GATE_RESULT = "failure"; + await run(github, context, core); + assert.ok(calls.bodies.at(-1).includes("failure"), `${jobName} must report failed dependencies`); } (async () => { diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 1bbb114fab..c8a2009a3c 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -159,7 +159,7 @@ cat > "$artifact_dir/pr-runtime-provenance.json" < "$fixture_dir/source-run.json" < "$fixture_dir/pull-request.json" <&2 + exit 1 + fi + python3 - "$fixture_dir/source-run.json" "$source_title" <<'PY' +import json +import sys +from pathlib import Path +p = Path(sys.argv[1]); data = json.loads(p.read_text()); data["name"] = "Build Runtime Images"; data["display_title"] = sys.argv[2]; p.write_text(json.dumps(data)) +PY +done run_validation grep -Fxq "IMAGE_TAG=pr-merge-$merge_sha" "$fixture_dir/github-env" grep -Fxq "PR_RUNTIME_ARTIFACT_DIR=$artifact_dir" "$fixture_dir/github-env" diff --git a/dev-tools/tests/security-summary-contract.sh b/dev-tools/tests/security-summary-contract.sh index 1164ed55ee..56120dc56b 100644 --- a/dev-tools/tests/security-summary-contract.sh +++ b/dev-tools/tests/security-summary-contract.sh @@ -15,6 +15,18 @@ grep -Fq 'currentPullRequest.head.sha !== expectedHeadSha' "$workflow" grep -Fq 'currentPullRequest.base.ref !== expectedBaseRef' "$workflow" grep -Fq 'currentPullRequest.base.sha !== expectedBaseSha' "$workflow" +python3 - "$repo_root/.github/workflows/security.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["security-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + test_root="$(mktemp -d)" trap 'rm -rf -- "$test_root"' EXIT script_path="$test_root/security-summary.js" @@ -164,4 +176,43 @@ run(github, context, core).then(async () => { }); NODE +# Execute the checked-in scanner step using the explicit Actions Bash shell. +# The fake scanner and reports stay in one disposable directory; no scan/network occurs. +python3 - "$workflow" "$repo_root/config/security/trivy.yaml" <<'PYTHON' +from pathlib import Path +import os +import subprocess +import sys +import tempfile +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +steps = workflow["jobs"]["trivy-scan"]["steps"] +scanner = next(step for step in steps if step.get("name") == "🔍 Run Trivy and Save Report") +upload = next(step for step in steps if step.get("name") == "📤 Upload Trivy Report") +if scanner.get("shell") != "bash" or upload.get("if") != "always()": + raise SystemExit("Trivy must use explicit pipefail Bash and retain always-uploaded reports") +settings = yaml.safe_load(Path(sys.argv[2]).read_text()) +if settings.get("exit-code") != 1 or settings.get("severity") != ["CRITICAL", "HIGH"] or settings.get("ignore-unfixed") is not True: + raise SystemExit("Trivy failure policy and filters must remain intact") +with tempfile.TemporaryDirectory(prefix="firemud-trivy-pipeline-") as directory: + root = Path(directory) + scanner_path = root / "trivy" + scanner_path.write_text('#!/bin/sh\nprintf "scanner-result-%s\\n" "$FAKE_TRIVY_EXIT"\nexit "$FAKE_TRIVY_EXIT"\n') + scanner_path.chmod(0o755) + for exit_status in (0, 1, 2): + environment = dict(os.environ, PATH=str(root) + os.pathsep + os.environ["PATH"], FAKE_TRIVY_EXIT=str(exit_status)) + # actions/runner explicit shell:bash -> bash --noprofile --norc -e -o pipefail {0}. + script = root / "step.sh" + script.write_text(scanner["run"]) + result = subprocess.run(["bash", "--noprofile", "--norc", "-e", "-o", "pipefail", str(script)], cwd=root, env=environment, capture_output=True, text=True) + if result.returncode != exit_status: + raise SystemExit(f"Trivy exit {exit_status} was masked: {result.returncode}") + if (root / "trivy-report.txt").read_text() != f"scanner-result-{exit_status}\n": + raise SystemExit("tee must retain the report even when the scanner fails") + if ("::endgroup::" in result.stdout) != (exit_status == 0): + raise SystemExit("Failed scanner pipelines must stop the step") +print("Trivy pipeline contract passed: scanner success/vulnerability/error with reports retained") +PYTHON + echo "security summary contract passed" diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 14165090c5..17edc16a3a 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -262,7 +262,7 @@ const context = { payload: { workflow_run: { event: "pull_request", - name: `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`, + name: "CodeQL Analysis", path: ".github/workflows/codeql.yml", head_sha: headSha, head_branch: "feature", @@ -273,7 +273,7 @@ const context = { }; const core = { info: () => {} }; const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); -run(github, context, core).then(() => { +run(github, context, core).then(async () => { if (calls.paginate.length !== 4) throw new Error(`expected four paginated calls, got ${calls.paginate.length}`); if (!calls.paginate.every(({ input }) => input.per_page === 100)) throw new Error("all API listings must request page size 100"); if (calls.updated.length !== 1 || calls.updated[0].comment_id !== 2) throw new Error("oldest bot summary was not updated"); @@ -281,6 +281,12 @@ run(github, context, core).then(() => { if (calls.created.length !== 0) throw new Error("existing bot summary should be updated"); if (!calls.updated[0].body.includes("❌ Static analysis checks failed")) throw new Error("new failure was masked by the older success"); if (!calls.updated[0].body.includes("CodeQL gate: `failure`")) throw new Error("latest CodeQL gate result was not selected"); + context.payload.workflow_run.name = "Forged workflow name"; + await run(github, context, core); + if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { + throw new Error("unrelated source names must not query runs or alter comments"); + } + context.payload.workflow_run.name = "CodeQL Analysis"; currentHeadSha = "d".repeat(40); return run(github, context, core).then(() => { if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { @@ -316,6 +322,7 @@ run(github, context, core).then(() => { calls.deleted.length = 0; calls.updated.length = 0; calls.created.length = 0; + context.payload.workflow_run.name = `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`; deleteStatus = 404; return run(github, context, core).then(() => { if (calls.deleted.length !== 1 || calls.deleted[0] !== 3) { diff --git a/dev-tools/tests/test_account_response_envelope_bootstrap.py b/dev-tools/tests/test_account_response_envelope_bootstrap.py new file mode 100644 index 0000000000..f8acc78c9e --- /dev/null +++ b/dev-tools/tests/test_account_response_envelope_bootstrap.py @@ -0,0 +1,536 @@ +from __future__ import annotations + +import contextlib +import datetime as dt +import importlib.util +import io +import json +import os +import stat +import sys +import tempfile +import unittest +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import patch + +SCRIPT_PATH = ( + Path(__file__).resolve().parents[1] + / "deploy" + / "bootstrap-account-response-envelope-ring.py" +) +SPEC = importlib.util.spec_from_file_location("account_response_envelope_bootstrap", SCRIPT_PATH) +assert SPEC is not None and SPEC.loader is not None +BOOTSTRAP = importlib.util.module_from_spec(SPEC) +sys.modules[SPEC.name] = BOOTSTRAP +SPEC.loader.exec_module(BOOTSTRAP) + +MATERIALIZER_PATH = ( + Path(__file__).resolve().parents[1] + / "deploy" + / "materialize-account-response-envelope-ring.py" +) +MATERIALIZER_SPEC = importlib.util.spec_from_file_location("account_response_envelope_materializer", MATERIALIZER_PATH) +assert MATERIALIZER_SPEC is not None and MATERIALIZER_SPEC.loader is not None +MATERIALIZER = importlib.util.module_from_spec(MATERIALIZER_SPEC) +sys.modules[MATERIALIZER_SPEC.name] = MATERIALIZER +MATERIALIZER_SPEC.loader.exec_module(MATERIALIZER) + + +NOW = dt.datetime(2026, 9, 27, 12, 0, 0, 123400, tzinfo=dt.timezone.utc) +ENVIRONMENT_ID = "player-facing-prod" +TARGET_NAMESPACE = "account-prod" +MATERIALIZER_USERNAME = ( + "system:serviceaccount:account-prod:firemud-secret-materializer" +) + + +class FakeKubectl: + def __init__(self) -> None: + self.secret: dict | None = None + self.username = MATERIALIZER_USERNAME + self.operations: list[str] = [] + self.mutations: list[str] = [] + self.uid = "secret-uid-account-ring-1" + + def __call__(self, command: list[str], **kwargs: object) -> SimpleNamespace: + operation = command[1] + self.operations.append(operation) + if operation == "auth": + return SimpleNamespace( + returncode=0, + stdout=json.dumps( + {"status": {"userInfo": {"username": self.username}}} + ), + stderr="", + ) + if operation == "get": + return SimpleNamespace( + returncode=0, + stdout="" if self.secret is None else json.dumps(self.secret), + stderr="", + ) + request = json.loads(kwargs["input"]) + if operation == "create": + if self.secret is not None: + return SimpleNamespace(returncode=1, stdout="", stderr="already exists") + resource_version = "1" + elif operation == "replace": + if self.secret is None: + return SimpleNamespace(returncode=1, stdout="", stderr="not found") + if request["metadata"].get("resourceVersion") != self.secret["metadata"]["resourceVersion"]: + return SimpleNamespace(returncode=1, stdout="", stderr="conflict") + resource_version = str(int(self.secret["metadata"]["resourceVersion"]) + 1) + else: + raise AssertionError(f"unexpected kubectl operation: {operation}") + self.mutations.append(operation) + if operation == "create": + request["metadata"]["uid"] = self.uid + else: + request["metadata"]["uid"] = self.secret["metadata"]["uid"] + request["metadata"]["resourceVersion"] = resource_version + self.secret = request + return SimpleNamespace(returncode=0, stdout=json.dumps(self.secret), stderr="") + + +class AccountResponseEnvelopeBootstrapTest(unittest.TestCase): + def setUp(self) -> None: + self.temporary_directory = tempfile.TemporaryDirectory() + self.addCleanup(self.temporary_directory.cleanup) + self.custody_directory = Path(self.temporary_directory.name) + os.chmod(self.custody_directory, 0o700) + self.output = self.custody_directory / "source-record.json" + + def create(self, **kwargs: object) -> None: + values = { + "output": self.output, + "environment_id": ENVIRONMENT_ID, + "namespace": TARGET_NAMESPACE, + "materializer_username": MATERIALIZER_USERNAME, + "source_ttl_seconds": 3600, + "now": NOW, + } + values.update(kwargs) + BOOTSTRAP.create_initial_source_record(**values) + + def test_output_is_materializer_compatible_with_valid_timestamps_and_null_predecessor(self) -> None: + self.create() + + source = MATERIALIZER.read_source_record(self.output) + self.assertEqual(ENVIRONMENT_ID, source.environment_id) + self.assertEqual(TARGET_NAMESPACE, source.target_namespace) + self.assertEqual(MATERIALIZER_USERNAME, source.materializer_username) + self.assertIsNone(source.previous_source_generation) + self.assertEqual("2026-09-27T12:00:00.1234Z", source.source_created_at_text) + self.assertEqual("2026-09-27T13:00:00.1234Z", source.source_expires_at_text) + self.assertGreater(source.source_expires_at, source.source_created_at) + self.assertEqual(source.source_created_at, NOW) + + manifest = MATERIALIZER.parse_manifest(source.manifest_bytes) + self.assertEqual(manifest.active_key_id, next(iter(manifest.keys))) + self.assertEqual({"bare-login", "connect-token"}, set(manifest.keys[manifest.active_key_id])) + + def test_purpose_keys_are_distinct_random_32_byte_values(self) -> None: + self.create() + + source = MATERIALIZER.read_source_record(self.output) + manifest = MATERIALIZER.parse_manifest(source.manifest_bytes) + keys = manifest.keys[manifest.active_key_id] + self.assertEqual(32, len(keys["bare-login"])) + self.assertEqual(32, len(keys["connect-token"])) + self.assertNotEqual(keys["bare-login"], keys["connect-token"]) + self.assertNotEqual("key-id", manifest.active_key_id) + self.assertNotEqual("source-generation", source.source_generation) + + def test_rotation_is_parser_and_materializer_compatible_and_retains_old_keys(self) -> None: + self.create() + previous = MATERIALIZER.read_source_record(self.output) + rotated_output = self.custody_directory / "rotated-source-record.json" + rotation_time = NOW + dt.timedelta(minutes=10) + + BOOTSTRAP.create_rotated_source_record( + output=rotated_output, + previous_source_record=self.output, + environment_id=ENVIRONMENT_ID, + namespace=TARGET_NAMESPACE, + source_ttl_seconds=3600, + now=rotation_time, + ) + + rotated = MATERIALIZER.read_source_record(rotated_output) + self.assertEqual(previous.source_generation, rotated.previous_source_generation) + self.assertGreater(rotated.source_created_at, previous.source_created_at) + self.assertEqual(ENVIRONMENT_ID, rotated.environment_id) + self.assertEqual(TARGET_NAMESPACE, rotated.target_namespace) + self.assertEqual(previous.materializer_username, rotated.materializer_username) + previous_manifest = MATERIALIZER.parse_manifest(previous.manifest_bytes) + rotated_manifest = MATERIALIZER.parse_manifest(rotated.manifest_bytes) + self.assertNotEqual(previous_manifest.active_key_id, rotated_manifest.active_key_id) + self.assertTrue(previous_manifest.key_ids < rotated_manifest.key_ids) + for key_id, purposes in previous_manifest.keys.items(): + self.assertEqual(purposes, rotated_manifest.keys[key_id]) + self.assertEqual({"bare-login", "connect-token"}, set(rotated_manifest.keys[rotated_manifest.active_key_id])) + + fake_kubectl = FakeKubectl() + # These fake Kubernetes transcripts prove offline behavior only; they + # do not authorize or establish live target-cluster delivery. + with ( + patch.object(MATERIALIZER, "_require_target_cluster_binding", return_value=None), + patch.object(MATERIALIZER.subprocess, "run", side_effect=fake_kubectl), + ): + self.assertTrue( + MATERIALIZER.materialize( + self.output, + ENVIRONMENT_ID, + TARGET_NAMESPACE, + 7200, + now=NOW + dt.timedelta(minutes=1), + ) + ) + self.assertTrue( + MATERIALIZER.materialize( + rotated_output, + ENVIRONMENT_ID, + TARGET_NAMESPACE, + 7200, + now=rotation_time + dt.timedelta(minutes=1), + ) + ) + + def test_rotation_rejects_wrong_environment_or_namespace_without_output(self) -> None: + self.create() + wrong_environment_output = self.custody_directory / "wrong-environment.json" + with self.assertRaisesRegex(BOOTSTRAP.BootstrapError, "environment"): + BOOTSTRAP.create_rotated_source_record( + output=wrong_environment_output, + previous_source_record=self.output, + environment_id="other-environment", + namespace=TARGET_NAMESPACE, + source_ttl_seconds=3600, + now=NOW + dt.timedelta(minutes=1), + ) + self.assertFalse(wrong_environment_output.exists()) + + wrong_namespace_output = self.custody_directory / "wrong-namespace.json" + with self.assertRaisesRegex(BOOTSTRAP.BootstrapError, "namespace"): + BOOTSTRAP.create_rotated_source_record( + output=wrong_namespace_output, + previous_source_record=self.output, + environment_id=ENVIRONMENT_ID, + namespace="other-namespace", + source_ttl_seconds=3600, + now=NOW + dt.timedelta(minutes=1), + ) + self.assertFalse(wrong_namespace_output.exists()) + + def test_rotation_keeps_the_bound_identity_and_rejects_a_changed_caller(self) -> None: + self.create() + rotated_output = self.custody_directory / "rotated-source-record.json" + BOOTSTRAP.create_rotated_source_record( + output=rotated_output, + previous_source_record=self.output, + environment_id=ENVIRONMENT_ID, + namespace=TARGET_NAMESPACE, + source_ttl_seconds=3600, + now=NOW + dt.timedelta(minutes=10), + ) + initial = MATERIALIZER.read_source_record(self.output) + rotated = MATERIALIZER.read_source_record(rotated_output) + self.assertEqual(initial.materializer_username, rotated.materializer_username) + + fake_kubectl = FakeKubectl() + # These fake Kubernetes transcripts prove offline behavior only; they + # do not authorize or establish live target-cluster delivery. + with ( + patch.object(MATERIALIZER, "_require_target_cluster_binding", return_value=None), + patch.object(MATERIALIZER.subprocess, "run", side_effect=fake_kubectl), + ): + self.assertTrue( + MATERIALIZER.materialize( + self.output, + ENVIRONMENT_ID, + TARGET_NAMESPACE, + 7200, + now=NOW + dt.timedelta(minutes=1), + ) + ) + fake_kubectl.username = "system:serviceaccount:account-prod:account-service" + fake_kubectl.operations.clear() + + with self.assertRaisesRegex( + MATERIALIZER.MaterializationError, + "does not match the protected source record", + ): + MATERIALIZER.materialize( + rotated_output, + ENVIRONMENT_ID, + TARGET_NAMESPACE, + 7200, + now=NOW + dt.timedelta(minutes=11), + ) + + self.assertEqual(["auth"], fake_kubectl.operations) + self.assertEqual(["create"], fake_kubectl.mutations) + + def test_rotation_rejects_unprotected_previous_directory(self) -> None: + self.create() + protected_output_directory = self.custody_directory / "protected-output" + protected_output_directory.mkdir(mode=0o700) + rotated_output = protected_output_directory / "rotated-source-record.json" + os.chmod(self.custody_directory, 0o750) + with self.assertRaisesRegex(BOOTSTRAP.BootstrapError, "directory must be owner-only"): + BOOTSTRAP.create_rotated_source_record( + output=rotated_output, + previous_source_record=self.output, + environment_id=ENVIRONMENT_ID, + namespace=TARGET_NAMESPACE, + source_ttl_seconds=3600, + now=NOW + dt.timedelta(minutes=1), + ) + self.assertFalse(rotated_output.exists()) + + def test_rotation_rejects_oversized_record_before_writing(self) -> None: + self.create() + rotated_output = self.custody_directory / "rotated-source-record.json" + size_limited_materializer = SimpleNamespace( + read_source_record=MATERIALIZER.read_source_record, + parse_manifest=MATERIALIZER.parse_manifest, + MaterializationError=MATERIALIZER.MaterializationError, + MAX_SOURCE_RECORD_BYTES=1, + ) + with patch.object(BOOTSTRAP, "_load_materializer", return_value=size_limited_materializer), self.assertRaisesRegex( + BOOTSTRAP.BootstrapError, "size limit" + ): + BOOTSTRAP.create_rotated_source_record( + output=rotated_output, + previous_source_record=self.output, + environment_id=ENVIRONMENT_ID, + namespace=TARGET_NAMESPACE, + source_ttl_seconds=3600, + now=NOW + dt.timedelta(minutes=1), + ) + self.assertFalse(rotated_output.exists()) + + def test_rotation_refuses_same_output_without_overwrite_or_regeneration(self) -> None: + self.create() + first_bytes = self.output.read_bytes() + with patch.object(BOOTSTRAP.secrets, "token_bytes", side_effect=AssertionError("regenerated")), patch.object( + BOOTSTRAP.secrets, "token_urlsafe", side_effect=AssertionError("regenerated") + ), self.assertRaisesRegex(BOOTSTRAP.BootstrapError, "already exists"): + BOOTSTRAP.create_rotated_source_record( + output=self.output, + previous_source_record=self.output, + environment_id=ENVIRONMENT_ID, + namespace=TARGET_NAMESPACE, + source_ttl_seconds=3600, + now=NOW + dt.timedelta(minutes=1), + ) + self.assertEqual(first_bytes, self.output.read_bytes()) + + def test_rotation_cli_does_not_print_source_material(self) -> None: + previous_output = self.custody_directory / "previous-source-record.json" + self.create(output=previous_output, now=dt.datetime.now(dt.timezone.utc) - dt.timedelta(minutes=1)) + rotated_output = self.custody_directory / "rotated-source-record.json" + stdout = io.StringIO() + stderr = io.StringIO() + with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr): + result = BOOTSTRAP.main( + [ + "rotate", + "--output", + str(rotated_output), + "--previous-source-record", + str(previous_output), + "--environment-id", + ENVIRONMENT_ID, + "--namespace", + TARGET_NAMESPACE, + "--source-ttl-seconds", + "3600", + ] + ) + self.assertEqual(0, result) + self.assertIn("created rotated Account response-envelope source record", stdout.getvalue()) + self.assertEqual("", stderr.getvalue()) + output_text = stdout.getvalue() + stderr.getvalue() + rotated_text = rotated_output.read_text(encoding="utf-8") + self.assertNotIn(rotated_text, output_text) + self.assertNotIn(MATERIALIZER.read_source_record(rotated_output).manifest_bytes.decode("ascii"), output_text) + + def test_rotation_cli_rejects_materializer_identity_override(self) -> None: + previous_output = self.custody_directory / "previous-source-record.json" + self.create(output=previous_output) + rotated_output = self.custody_directory / "rotated-source-record.json" + stderr = io.StringIO() + + with contextlib.redirect_stderr(stderr): + result = BOOTSTRAP.main( + [ + "rotate", + "--output", + str(rotated_output), + "--previous-source-record", + str(previous_output), + "--environment-id", + ENVIRONMENT_ID, + "--namespace", + TARGET_NAMESPACE, + "--materializer-username", + "system:serviceaccount:account-prod:alternate-materializer", + "--source-ttl-seconds", + "3600", + ] + ) + + self.assertEqual(1, result) + self.assertIn("must retain the prior materializer username", stderr.getvalue()) + self.assertFalse(rotated_output.exists()) + + def test_output_is_created_once_and_retry_preserves_bytes_without_regeneration(self) -> None: + self.create() + first_bytes = self.output.read_bytes() + + with patch.object(BOOTSTRAP.secrets, "token_bytes", side_effect=AssertionError("regenerated")), patch.object( + BOOTSTRAP.secrets, "token_urlsafe", side_effect=AssertionError("regenerated") + ), self.assertRaisesRegex(BOOTSTRAP.BootstrapError, "already exists"): + self.create() + + self.assertEqual(first_bytes, self.output.read_bytes()) + + def test_existing_output_symlink_cannot_replace_its_target(self) -> None: + retained = self.custody_directory / "retained-source" + retained.write_bytes(b"retain") + self.output.symlink_to(retained) + + with self.assertRaisesRegex(BOOTSTRAP.BootstrapError, "already exists"): + self.create() + + self.assertEqual(b"retain", retained.read_bytes()) + + def test_dangling_output_symlink_cannot_redirect_creation(self) -> None: + target = self.custody_directory / "absent-target" + self.output.symlink_to(target) + + with self.assertRaisesRegex(BOOTSTRAP.BootstrapError, "already exists"): + self.create() + + self.assertFalse(target.exists()) + + def test_file_and_parent_permissions_are_owner_only(self) -> None: + self.create() + + self.assertEqual(0o700, stat.S_IMODE(self.custody_directory.stat().st_mode)) + self.assertEqual(0o600, stat.S_IMODE(self.output.stat().st_mode)) + + def test_missing_parent_is_rejected_without_creating_output(self) -> None: + missing_parent = self.custody_directory / "missing" + output = missing_parent / "source-record.json" + + with self.assertRaisesRegex(BOOTSTRAP.BootstrapError, "must already exist"): + self.create(output=output) + + self.assertFalse(output.exists()) + self.assertFalse(missing_parent.exists()) + + def test_parent_with_group_access_is_rejected(self) -> None: + os.chmod(self.custody_directory, 0o750) + with self.assertRaisesRegex(BOOTSTRAP.BootstrapError, "owner-only mode 0700"): + self.create() + self.assertFalse(self.output.exists()) + + def test_repository_output_is_rejected(self) -> None: + repository_root = Path(__file__).resolve().parents[2] + output = repository_root / "bootstrap-source-record-test.json" + + with self.assertRaisesRegex(BOOTSTRAP.BootstrapError, "outside the repository"): + self.create(output=output) + + self.assertFalse(output.exists()) + + def test_cli_requires_explicit_output_and_does_not_print_material(self) -> None: + stdout = io.StringIO() + stderr = io.StringIO() + with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr): + result = BOOTSTRAP.main( + [ + "--output", + str(self.output), + "--environment-id", + ENVIRONMENT_ID, + "--namespace", + TARGET_NAMESPACE, + "--materializer-username", + MATERIALIZER_USERNAME, + "--source-ttl-seconds", + "3600", + ] + ) + + self.assertEqual(0, result) + self.assertIn("created initial Account response-envelope source record", stdout.getvalue()) + self.assertEqual("", stderr.getvalue()) + output_text = stdout.getvalue() + stderr.getvalue() + source_text = self.output.read_text(encoding="utf-8") + source = json.loads(source_text) + manifest = MATERIALIZER.read_source_record(self.output).manifest_bytes.decode("ascii") + self.assertNotIn(source_text, output_text) + self.assertNotIn(manifest, output_text) + self.assertNotIn(source["manifestBase64"], output_text) + + def test_cli_rejects_missing_output_argument(self) -> None: + with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit) as raised: + BOOTSTRAP.main( + ["--environment-id", ENVIRONMENT_ID, "--namespace", TARGET_NAMESPACE, "--source-ttl-seconds", "3600"] + ) + self.assertEqual(2, raised.exception.code) + + def test_cli_requires_explicit_credential_class_lifetime(self) -> None: + with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit) as raised: + BOOTSTRAP.main(["--output", str(self.output), "--environment-id", ENVIRONMENT_ID, "--namespace", TARGET_NAMESPACE]) + self.assertEqual(2, raised.exception.code) + self.assertFalse(self.output.exists()) + + def test_cli_requires_materializer_username_for_initial_creation(self) -> None: + stdout = io.StringIO() + stderr = io.StringIO() + with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr): + result = BOOTSTRAP.main( + [ + "--output", + str(self.output), + "--environment-id", + ENVIRONMENT_ID, + "--namespace", + TARGET_NAMESPACE, + "--source-ttl-seconds", + "3600", + ] + ) + + self.assertEqual(1, result) + self.assertIn("requires --materializer-username", stderr.getvalue()) + self.assertFalse(self.output.exists()) + + def test_initial_creation_rejects_non_target_or_malformed_service_account(self) -> None: + for index, username in enumerate( + ( + "system:serviceaccount:account-preview:firemud-secret-materializer", + "system:serviceaccount:account-prod:", + "account-prod:firemud-secret-materializer", + ) + ): + with self.subTest(username=username): + output = self.custody_directory / f"invalid-source-{index}.json" + with self.assertRaisesRegex( + BOOTSTRAP.BootstrapError, "service-account username" + ): + self.create(output=output, materializer_username=username) + self.assertFalse(output.exists()) + + def test_relative_output_is_rejected(self) -> None: + with self.assertRaisesRegex(BOOTSTRAP.BootstrapError, "absolute path"): + self.create(output=Path("source-record.json")) + + +if __name__ == "__main__": + unittest.main() diff --git a/dev-tools/tests/test_account_response_envelope_materializer.py b/dev-tools/tests/test_account_response_envelope_materializer.py new file mode 100644 index 0000000000..d4930218b6 --- /dev/null +++ b/dev-tools/tests/test_account_response_envelope_materializer.py @@ -0,0 +1,1121 @@ +from __future__ import annotations + +import base64 +import contextlib +import copy +import datetime as dt +import importlib.util +import io +import json +import os +import sys +import tempfile +import unittest +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import patch + +SCRIPT_PATH = Path(__file__).resolve().parents[1] / "deploy" / "materialize-account-response-envelope-ring.py" +SPEC = importlib.util.spec_from_file_location("account_response_envelope_materializer", SCRIPT_PATH) +assert SPEC is not None and SPEC.loader is not None +MATERIALIZER = importlib.util.module_from_spec(SPEC) +sys.modules[SPEC.name] = MATERIALIZER +SPEC.loader.exec_module(MATERIALIZER) + + +NOW = dt.datetime(2026, 9, 27, 12, 0, 0, tzinfo=dt.timezone.utc) +SOURCE_EXPIRY = "2030-01-01T00:00:00Z" +SOURCE_CREATED_AT = "2026-09-27T11:00:00Z" +NEXT_SOURCE_CREATED_AT = "2026-09-27T12:00:00Z" +MAX_AGE_SECONDS = 86_400 +ENVIRONMENT_ID = "player-facing-prod" +TARGET_NAMESPACE = "account-prod" +MATERIALIZER_USERNAME = "system:serviceaccount:account-prod:firemud-secret-materializer" +UNSET = object() + + +def manifest_for(*, active: str, ids: tuple[str, ...], first_material_number: int = 1) -> bytes: + lines = ["version=1", f"activeKeyId={active}"] + material_number = first_material_number + for key_id in ids: + for purpose in ("bare-login", "connect-token"): + material = bytes([material_number]) * 32 + material_number += 1 + encoded = base64.urlsafe_b64encode(material).rstrip(b"=").decode("ascii") + lines.append(f"key:{key_id}:{purpose}={encoded}") + return ("\n".join(lines) + "\n").encode("ascii") + + +def source_record_for( + manifest: bytes, + generation: str, + expires_at: str, + created_at: str, + environment_id: str, + target_namespace: str, + previous_generation: str | None, + materializer_username: str = MATERIALIZER_USERNAME, +) -> bytes: + record = { + "version": 1, + "manifestBase64": base64.b64encode(manifest).decode("ascii"), + "sourceGeneration": generation, + "sourceExpiresAt": expires_at, + "sourceCreatedAt": created_at, + "environmentId": environment_id, + "targetNamespace": target_namespace, + "materializerUsername": materializer_username, + "previousSourceGeneration": previous_generation, + } + encoded = json.dumps(record, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + return (encoded + "\n").encode("utf-8") + + +class FakeKubectl: + def __init__(self) -> None: + self.secret: dict | None = None + self.mutations: list[tuple[str, dict]] = [] + self.operations: list[str] = [] + self.commands: list[str] = [] + self.identity_commands: list[list[str]] = [] + self.attempts: list[tuple[str, dict]] = [] + self.reads = 0 + self.mutate_readback = False + self.fail_operation: str | None = None + self.raise_timeout = False + self.raise_unicode_error = False + self.identity_username = MATERIALIZER_USERNAME + self.identity_usernames: list[str] = [] + self.identity_calls = 0 + self.identity_output: str | None = None + self.identity_returncode = 0 + self.timeouts: list[int | None] = [] + self.uid = "secret-uid-account-ring-1" + self.readback_uid: str | None = None + self.readback_resource_version: str | None = None + + def __call__(self, command: list[str], **kwargs) -> SimpleNamespace: + operation = command[1] + self.commands.append(operation) + self.timeouts.append(kwargs.get("timeout")) + if self.raise_timeout: + raise MATERIALIZER.subprocess.TimeoutExpired(command, kwargs.get("timeout"), output="sensitive output") + if self.raise_unicode_error: + raise UnicodeDecodeError("utf-8", b"\xff", 0, 1, "invalid test output") + if operation == "auth": + self.identity_commands.append(list(command)) + identity_username = ( + self.identity_usernames[self.identity_calls] + if self.identity_calls < len(self.identity_usernames) + else self.identity_username + ) + self.identity_calls += 1 + return SimpleNamespace( + returncode=self.identity_returncode, + stdout=self.identity_output + if self.identity_output is not None + else json.dumps({"status": {"userInfo": {"username": identity_username}}}), + stderr="identity provider error", + ) + self.operations.append(operation) + if operation == "get": + self.reads += 1 + return SimpleNamespace( + returncode=0, + stdout="" if self.secret is None else json.dumps(self.secret), + stderr="", + ) + request_object = json.loads(kwargs["input"]) + self.attempts.append((operation, copy.deepcopy(request_object))) + if operation == self.fail_operation: + return SimpleNamespace(returncode=1, stdout="", stderr="provider error") + if operation == "create": + if self.secret is not None: + return SimpleNamespace(returncode=1, stdout="", stderr="already exists") + resource_version = "1" + elif operation == "replace": + if self.secret is None: + return SimpleNamespace(returncode=1, stdout="", stderr="not found") + expected_resource_version = self.secret["metadata"]["resourceVersion"] + if request_object["metadata"].get("resourceVersion") != expected_resource_version: + return SimpleNamespace(returncode=1, stdout="", stderr="conflict") + resource_version = str(int(expected_resource_version) + 1) + else: + raise AssertionError(f"unexpected kubectl operation: {operation}") + self.mutations.append((operation, copy.deepcopy(request_object))) + if operation == "create": + request_object["metadata"]["uid"] = self.uid + else: + request_object["metadata"]["uid"] = self.secret["metadata"]["uid"] + request_object["metadata"]["resourceVersion"] = resource_version + self.secret = request_object + if self.mutate_readback: + self.secret["data"][MATERIALIZER.SECRET_KEY] = base64.b64encode(b"tampered").decode("ascii") + if self.readback_uid is not None: + self.secret["metadata"]["uid"] = self.readback_uid + if self.readback_resource_version is not None: + self.secret["metadata"]["resourceVersion"] = self.readback_resource_version + return SimpleNamespace(returncode=0, stdout=json.dumps(self.secret), stderr="") + + +class AccountResponseEnvelopeMaterializerTest(unittest.TestCase): + def setUp(self) -> None: + self.temporary_directory = tempfile.TemporaryDirectory() + self.addCleanup(self.temporary_directory.cleanup) + self.source_path = Path(self.temporary_directory.name) / "source-record.json" + self.source_manifest = manifest_for(active="k1", ids=("k1",)) + self.source_generation = "custody-generation-1" + self.source_expires_at = SOURCE_EXPIRY + self.source_created_at = SOURCE_CREATED_AT + self.environment_id = ENVIRONMENT_ID + self.target_namespace = TARGET_NAMESPACE + self.materializer_username = MATERIALIZER_USERNAME + self.previous_generation: str | None = None + self.write_source_record() + self.fake_kubectl = FakeKubectl() + self.kubectl_patch = patch.object(MATERIALIZER.subprocess, "run", side_effect=self.fake_kubectl) + self.subprocess_run_mock = self.kubectl_patch.start() + self.addCleanup(self.kubectl_patch.stop) + # Permit only this test fixture's fake Kubernetes transcripts. This is + # offline behavior proof, not authorization for live materialization. + self.target_binding_patch = patch.object( + MATERIALIZER, "_require_target_cluster_binding", return_value=None + ) + self.target_binding_patch.start() + self.addCleanup(self.target_binding_patch.stop) + + def write_source_record( + self, + *, + manifest: bytes | None = None, + generation: str | None = None, + expires_at: str | None = None, + created_at: str | None = None, + environment_id: str | None = None, + target_namespace: str | None = None, + materializer_username: str | None = None, + previous_generation: str | None | object = UNSET, + raw: bytes | None = None, + ) -> None: + if manifest is not None: + self.source_manifest = manifest + if generation is not None: + self.source_generation = generation + if expires_at is not None: + self.source_expires_at = expires_at + if created_at is not None: + self.source_created_at = created_at + if environment_id is not None: + self.environment_id = environment_id + if target_namespace is not None: + self.target_namespace = target_namespace + if materializer_username is not None: + self.materializer_username = materializer_username + if previous_generation is not UNSET: + self.previous_generation = previous_generation + source_record = raw or source_record_for( + self.source_manifest, + self.source_generation, + self.source_expires_at, + self.source_created_at, + self.environment_id, + self.target_namespace, + self.previous_generation, + self.materializer_username, + ) + self.source_path.write_bytes(source_record) + os.chmod(self.source_path, 0o600) + + def run_materializer( + self, + *, + now: dt.datetime = NOW, + expected_environment_id: str = ENVIRONMENT_ID, + expected_namespace: str = TARGET_NAMESPACE, + ) -> bool: + return MATERIALIZER.materialize( + source_record_path=self.source_path, + environment_id=expected_environment_id, + namespace=expected_namespace, + class_max_age_seconds=MAX_AGE_SECONDS, + kubectl="kubectl-test-double", + now=now, + ) + + def test_rfc3339_utc_accepts_canonical_fractional_precision(self) -> None: + timestamp = "2026-09-27T12:00:00.00101Z" + parsed = MATERIALIZER.parse_rfc3339_utc(timestamp, "source expiry") + + self.assertEqual(1010, parsed.microsecond) + self.assertEqual(timestamp, MATERIALIZER.format_timestamp(parsed)) + + def test_create_then_exact_retry_preserves_bytes_and_timestamps_without_write(self) -> None: + created_receipt = self.run_materializer() + self.assertTrue(created_receipt) + self.assertEqual(MATERIALIZER_USERNAME, created_receipt["materializerUsername"]) + created = json.loads(json.dumps(self.fake_kubectl.secret)) + self.assertEqual(["create"], [operation for operation, _ in self.fake_kubectl.mutations]) + self.assertEqual([30], self.fake_kubectl.timeouts[:1]) + self.assertEqual( + ["auth", "get", "auth", "create", "auth", "get"], + self.fake_kubectl.commands, + ) + self.assertEqual( + [["kubectl-test-double", "auth", "whoami", "-o", "json"]] * 3, + self.fake_kubectl.identity_commands, + ) + annotations = created["metadata"]["annotations"] + self.assertEqual("custody-generation-1", annotations[MATERIALIZER.ANNOTATION_SOURCE_GENERATION]) + self.assertEqual(SOURCE_CREATED_AT, annotations[MATERIALIZER.ANNOTATION_MATERIALIZED_AT]) + self.assertEqual("2026-09-28T11:00:00Z", annotations[MATERIALIZER.ANNOTATION_EXPIRES_AT]) + self.assertEqual( + base64.b64encode(self.source_manifest).decode("ascii"), + created["data"][MATERIALIZER.SECRET_KEY], + ) + + retry_receipt = self.run_materializer(now=NOW + dt.timedelta(hours=1)) + self.assertFalse(retry_receipt) + self.assertEqual(["create"], [operation for operation, _ in self.fake_kubectl.mutations]) + self.assertEqual(created, self.fake_kubectl.secret) + self.assertEqual("create", created_receipt["operation"]) + self.assertEqual("retry", retry_receipt["operation"]) + self.assertEqual( + created_receipt["source"]["generation"], + retry_receipt["source"]["generation"], + ) + self.assertEqual( + ["auth", "get", "auth", "create", "auth", "get", "auth", "get"], + self.fake_kubectl.commands, + ) + self.assertEqual(4, len(self.fake_kubectl.identity_commands)) + self.assertEqual(3, self.fake_kubectl.reads) + self.assertEqual(created["metadata"]["uid"], retry_receipt["secret"]["uid"]) + self.assertEqual(created["metadata"]["resourceVersion"], retry_receipt["secret"]["resourceVersion"]) + self.assertNotIn(self.source_manifest.decode("ascii"), json.dumps(retry_receipt.as_dict())) + + def test_exact_retry_receipt_is_stable_and_canonical_digest_changes_with_a_field(self) -> None: + self.run_materializer() + first_retry = self.run_materializer(now=NOW + dt.timedelta(minutes=1)) + second_retry = self.run_materializer(now=NOW + dt.timedelta(minutes=2)) + + self.assertEqual(first_retry.as_dict(), second_retry.as_dict()) + self.assertEqual( + first_retry["immutableArtifactId"], + MATERIALIZER.canonical_evidence_digest(first_retry.as_dict()), + ) + changed = first_retry.as_dict() + changed["secret"]["resourceVersion"] = "99" + self.assertNotEqual( + first_retry["immutableArtifactId"], + MATERIALIZER.canonical_evidence_digest(changed), + ) + + def test_receipt_contains_no_secret_bytes(self) -> None: + receipt = self.run_materializer() + rendered = json.dumps(receipt.as_dict(), sort_keys=True) + self.assertNotIn(self.source_manifest.decode("ascii"), rendered) + for line in self.source_manifest.decode("ascii").splitlines()[2:]: + self.assertNotIn(line.split("=", 1)[1], rendered) + self.assertLessEqual(len(receipt.canonical_bytes), MATERIALIZER.MAX_RECEIPT_BYTES) + + def verify_receipt(self, receipt_bytes: bytes, **expected_overrides) -> dict: + receipt = self.run_materializer() + expected = { + "expected_environment_id": ENVIRONMENT_ID, + "expected_namespace": TARGET_NAMESPACE, + "expected_source_generation": "custody-generation-1", + "expected_predecessor_generation": None, + "expected_manifest_digest": MATERIALIZER._sha256_digest(self.source_manifest), + "expected_materializer_username": MATERIALIZER_USERNAME, + "expected_secret_name": MATERIALIZER.SECRET_NAME, + "expected_secret_uid": receipt["secret"]["uid"], + "expected_secret_resource_version": receipt["secret"]["resourceVersion"], + } + expected.update(expected_overrides) + return MATERIALIZER.verify_materialization_receipt(receipt_bytes, **expected) + + @staticmethod + def canonical_receipt(record: dict) -> bytes: + record["immutableArtifactId"] = MATERIALIZER.canonical_evidence_digest(record) + return (json.dumps(record, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n").encode("utf-8") + + def test_read_side_receipt_verifier_accepts_exact_canonical_receipt(self) -> None: + receipt = self.run_materializer() + parsed = self.verify_receipt(receipt.canonical_bytes) + + self.assertEqual(receipt.as_dict(), parsed) + self.assertEqual(receipt.content_digest, parsed["immutableArtifactId"]) + + def test_read_side_receipt_verifier_rejects_duplicate_wrong_shape_and_jwt_shape(self) -> None: + receipt = self.run_materializer() + duplicate_member = receipt.canonical_bytes.replace( + b'"environmentId":', b'"environmentId":"duplicate","environmentId":', 1 + ) + jwt_shape = json.dumps( + {"credentialClass": "jwt-signing-keys-jwks", "immutableArtifactId": "sha256:" + "0" * 64} + ).encode("utf-8") + malformed = ( + duplicate_member, + b'{"receiptType":"account-response-envelope-ring-materialization-v1"}\n', + jwt_shape, + ) + for evidence in malformed: + with self.subTest(evidence=evidence[:48]), self.assertRaises(MATERIALIZER.MaterializationError): + self.verify_receipt(evidence) + + def test_read_side_receipt_verifier_rejects_tampered_digest_and_noncanonical_bytes(self) -> None: + receipt = self.run_materializer() + tampered = receipt.as_dict() + tampered["secret"]["resourceVersion"] = "999" + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "digest does not match"): + self.verify_receipt(json.dumps(tampered, sort_keys=True, separators=(",", ":")).encode("utf-8")) + + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "not canonical"): + self.verify_receipt(receipt.canonical_bytes + b" ") + + def test_read_side_receipt_verifier_rejects_wrong_writer_generation_and_secret_bindings(self) -> None: + receipt = self.run_materializer() + mutations = ( + ("materializerUsername", "system:serviceaccount:account-prod:other-writer"), + ("environmentId", "different-environment"), + ("targetNamespace", "different-namespace"), + ) + for field, wrong_value in mutations: + with self.subTest(field=field): + changed = receipt.as_dict() + changed[field] = wrong_value + with self.assertRaises(MATERIALIZER.MaterializationError): + self.verify_receipt(self.canonical_receipt(changed)) + + for field, wrong_value in ( + ("generation", "different-generation"), + ("predecessorGeneration", "unexpected-predecessor"), + ("manifestDigest", "sha256:" + "0" * 64), + ): + with self.subTest(source_field=field): + changed = receipt.as_dict() + changed["source"][field] = wrong_value + with self.assertRaises(MATERIALIZER.MaterializationError): + self.verify_receipt(self.canonical_receipt(changed)) + + for field, wrong_value in ( + ("name", "other-secret"), + ("uid", "other-secret-uid"), + ("resourceVersion", "99"), + ): + with self.subTest(secret_field=field): + changed = receipt.as_dict() + changed["secret"][field] = wrong_value + with self.assertRaises(MATERIALIZER.MaterializationError): + self.verify_receipt(self.canonical_receipt(changed)) + + def test_read_side_receipt_verifier_rejects_matching_malformed_expected_bindings(self) -> None: + receipt = self.run_materializer() + cases = ( + ( + "source generation", + "expected_source_generation", + "generation\ninvalid", + lambda changed, value: changed["source"].update(generation=value), + ), + ( + "environment", + "expected_environment_id", + "environment\ninvalid", + lambda changed, value: changed.update(environmentId=value), + ), + ( + "namespace", + "expected_namespace", + "Invalid_Namespace", + lambda changed, value: ( + changed.update(targetNamespace=value), + changed["secret"].update(namespace=value), + changed["freshnessAnnotations"].update({MATERIALIZER.ANNOTATION_TARGET_NAMESPACE: value}), + ), + ), + ( + "predecessor generation", + "expected_predecessor_generation", + "predecessor\ninvalid", + lambda changed, value: ( + changed["source"].update(predecessorGeneration=value), + changed["freshnessAnnotations"].update({MATERIALIZER.ANNOTATION_PREVIOUS_SOURCE_GENERATION: value}), + ), + ), + ) + for label, expected_name, malformed_value, update_record in cases: + with self.subTest(binding=label): + changed = receipt.as_dict() + update_record(changed, malformed_value) + evidence = self.canonical_receipt(changed) + with self.assertRaises(MATERIALIZER.MaterializationError): + self.verify_receipt(evidence, **{expected_name: malformed_value}) + + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "Secret name is not canonical"): + self.verify_receipt( + receipt.canonical_bytes, + expected_secret_name="jwt-signing-keys", + ) + + def test_existing_secret_requires_valid_uid_and_resource_version(self) -> None: + self.run_materializer() + for field, invalid_value, expected_message in ( + ("uid", None, "UID"), + ("uid", "contains whitespace", "UID"), + ("resourceVersion", None, "resource version"), + ("resourceVersion", "contains whitespace", "resource version"), + ): + with self.subTest(field=field, invalid_value=invalid_value): + original = self.fake_kubectl.secret["metadata"].get(field) + if invalid_value is None: + self.fake_kubectl.secret["metadata"].pop(field, None) + else: + self.fake_kubectl.secret["metadata"][field] = invalid_value + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, expected_message): + self.run_materializer() + self.fake_kubectl.secret["metadata"][field] = original + + def test_post_write_readback_requires_uid_and_resource_version(self) -> None: + for field, invalid_value, expected_message in ( + ("uid", "", "UID"), + ("resourceVersion", "", "resource version"), + ): + with self.subTest(field=field): + if field == "uid": + self.fake_kubectl.readback_uid = invalid_value + else: + self.fake_kubectl.readback_resource_version = invalid_value + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, expected_message): + self.run_materializer() + self.fake_kubectl.readback_uid = None + self.fake_kubectl.readback_resource_version = None + self.fake_kubectl.secret = None + self.fake_kubectl.mutations.clear() + self.fake_kubectl.attempts.clear() + + def test_rotation_rejects_secret_identity_or_resource_version_mismatch_after_write(self) -> None: + self.run_materializer() + prior_secret = copy.deepcopy(self.fake_kubectl.secret) + prior_uid = self.fake_kubectl.secret["metadata"]["uid"] + prior_resource_version = self.fake_kubectl.secret["metadata"]["resourceVersion"] + self.write_source_record( + manifest=manifest_for(active="k2", ids=("k1", "k2")), + generation="custody-generation-2", + created_at=NEXT_SOURCE_CREATED_AT, + previous_generation="custody-generation-1", + ) + self.fake_kubectl.readback_uid = "different-secret-uid" + + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "UID does not match"): + self.run_materializer(now=NOW + dt.timedelta(hours=2)) + + self.fake_kubectl.readback_uid = None + self.fake_kubectl.secret = prior_secret + self.fake_kubectl.mutations.clear() + self.fake_kubectl.attempts.clear() + self.fake_kubectl.readback_resource_version = prior_resource_version + + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "resource version did not advance"): + self.run_materializer(now=NOW + dt.timedelta(hours=2)) + + self.assertEqual(prior_uid, self.fake_kubectl.uid) + + def test_lost_first_generation_secret_does_not_extend_freshness(self) -> None: + self.run_materializer() + original_annotations = copy.deepcopy(self.fake_kubectl.secret["metadata"]["annotations"]) + self.fake_kubectl.secret = None + + self.assertTrue(self.run_materializer(now=NOW + dt.timedelta(hours=6))) + + recreated_annotations = self.fake_kubectl.secret["metadata"]["annotations"] + self.assertEqual( + original_annotations[MATERIALIZER.ANNOTATION_MATERIALIZED_AT], + recreated_annotations[MATERIALIZER.ANNOTATION_MATERIALIZED_AT], + ) + self.assertEqual( + original_annotations[MATERIALIZER.ANNOTATION_EXPIRES_AT], + recreated_annotations[MATERIALIZER.ANNOTATION_EXPIRES_AT], + ) + self.assertEqual(["create", "create"], [operation for operation, _ in self.fake_kubectl.mutations]) + + def test_cross_environment_record_is_rejected_before_kubernetes_access(self) -> None: + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "environment ID"): + self.run_materializer(expected_environment_id="preview") + + self.assertEqual([], self.fake_kubectl.operations) + + def test_wrong_target_namespace_record_is_rejected_before_kubernetes_access(self) -> None: + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "target namespace"): + self.run_materializer(expected_namespace="account-preview") + + self.assertEqual([], self.fake_kubectl.operations) + + def test_malformed_bound_materializer_username_is_rejected_before_kubernetes_access(self) -> None: + self.write_source_record( + materializer_username=("system:serviceaccount:account-preview:firemud-secret-materializer") + ) + + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "service-account username"): + self.run_materializer() + + self.assertEqual([], self.fake_kubectl.commands) + self.assertEqual([], self.fake_kubectl.operations) + + def test_wrong_server_authenticated_account_or_deploy_identity_fails_before_secret_access(self) -> None: + for username in ( + "system:serviceaccount:account-prod:account-service", + "system:serviceaccount:account-prod:deployment", + ): + with self.subTest(username=username): + self.fake_kubectl.identity_username = username + + with self.assertRaisesRegex( + MATERIALIZER.MaterializationError, + "does not match the protected source record", + ): + self.run_materializer() + + self.assertEqual(["auth"], self.fake_kubectl.commands) + self.assertEqual([], self.fake_kubectl.operations) + self.fake_kubectl.commands.clear() + + def test_missing_malformed_or_failed_whoami_fails_before_secret_access(self) -> None: + for response, returncode, expected_message in ( + ("{}", 0, "did not return an authenticated username"), + ("not-json", 0, "malformed identity"), + ( + '{"status":{"userInfo":{"username":"one","username":"two"}}}', + 0, + "malformed identity", + ), + ("", 1, "identity verification failed"), + ): + with self.subTest(response=response, returncode=returncode): + self.fake_kubectl.identity_output = response + self.fake_kubectl.identity_returncode = returncode + + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, expected_message): + self.run_materializer() + + self.assertEqual(["auth"], self.fake_kubectl.commands) + self.assertEqual([], self.fake_kubectl.operations) + self.fake_kubectl.commands.clear() + self.fake_kubectl.identity_output = None + self.fake_kubectl.identity_returncode = 0 + + def test_identity_is_rechecked_before_each_exact_generation_retry(self) -> None: + self.run_materializer() + self.assertEqual( + ["auth", "get", "auth", "create", "auth", "get"], + self.fake_kubectl.commands, + ) + self.fake_kubectl.commands.clear() + self.fake_kubectl.identity_commands.clear() + self.fake_kubectl.identity_username = "system:serviceaccount:account-prod:account-service" + + with self.assertRaisesRegex( + MATERIALIZER.MaterializationError, + "does not match the protected source record", + ): + self.run_materializer() + + self.assertEqual(["auth"], self.fake_kubectl.commands) + self.assertEqual(1, len(self.fake_kubectl.identity_commands)) + self.assertEqual(["get", "create", "get"], self.fake_kubectl.operations) + + def test_identity_drift_after_initial_read_prevents_secret_mutation(self) -> None: + self.fake_kubectl.identity_usernames = [ + MATERIALIZER_USERNAME, + "system:serviceaccount:account-prod:account-service", + ] + + with self.assertRaisesRegex( + MATERIALIZER.MaterializationError, + "does not match the protected source record", + ): + self.run_materializer() + + self.assertEqual(["auth", "get", "auth"], self.fake_kubectl.commands) + self.assertEqual(["get"], self.fake_kubectl.operations) + self.assertEqual(1, self.fake_kubectl.reads) + self.assertEqual([], self.fake_kubectl.mutations) + self.assertIsNone(self.fake_kubectl.secret) + + def test_identity_drift_after_write_prevents_readback_and_receipt(self) -> None: + self.fake_kubectl.identity_usernames = [ + MATERIALIZER_USERNAME, + MATERIALIZER_USERNAME, + "system:serviceaccount:account-prod:account-service", + ] + + with self.assertRaisesRegex( + MATERIALIZER.MaterializationError, + "does not match the protected source record", + ): + self.run_materializer() + + self.assertEqual( + ["auth", "get", "auth", "create", "auth"], + self.fake_kubectl.commands, + ) + self.assertEqual(["get", "create"], self.fake_kubectl.operations) + self.assertEqual(1, self.fake_kubectl.reads) + self.assertEqual(1, len(self.fake_kubectl.mutations)) + self.assertIsNotNone(self.fake_kubectl.secret) + + def test_normal_python_and_cli_materialization_fail_before_kubectl_without_cluster_binding(self) -> None: + current_time = dt.datetime.now(dt.timezone.utc) + self.write_source_record( + created_at=MATERIALIZER.format_timestamp(current_time - dt.timedelta(minutes=1)), + expires_at=MATERIALIZER.format_timestamp(current_time + dt.timedelta(hours=1)), + ) + source_record = MATERIALIZER.read_source_record(self.source_path) + self.assertEqual(ENVIRONMENT_ID, source_record.environment_id) + self.assertEqual(TARGET_NAMESPACE, source_record.target_namespace) + self.assertEqual(MATERIALIZER_USERNAME, source_record.materializer_username) + self.fake_kubectl.identity_username = MATERIALIZER_USERNAME + self.target_binding_patch.stop() + self.subprocess_run_mock.reset_mock() + + with patch.object( + MATERIALIZER, + "_materialization_receipt", + wraps=MATERIALIZER._materialization_receipt, + ) as receipt_factory: + with self.assertRaisesRegex( + MATERIALIZER.MaterializationError, + "target-cluster binding verification is unavailable", + ): + self.run_materializer(now=current_time) + + error_output = io.StringIO() + with contextlib.redirect_stderr(error_output): + result = MATERIALIZER.main( + [ + "--source-record", + str(self.source_path), + "--environment-id", + ENVIRONMENT_ID, + "--namespace", + TARGET_NAMESPACE, + "--class-max-age-seconds", + str(MAX_AGE_SECONDS), + "--kubectl", + "kubectl-test-double", + ] + ) + + self.assertEqual(1, result) + self.assertIn("target-cluster binding verification is unavailable", error_output.getvalue()) + receipt_factory.assert_not_called() + + self.subprocess_run_mock.assert_not_called() + self.assertEqual([], self.fake_kubectl.commands) + self.assertEqual([], self.fake_kubectl.operations) + self.assertEqual(0, self.fake_kubectl.reads) + self.assertEqual([], self.fake_kubectl.mutations) + self.assertIsNone(self.fake_kubectl.secret) + + def test_same_generation_with_different_bytes_fails_without_write(self) -> None: + self.run_materializer() + self.write_source_record(manifest=manifest_for(active="k2", ids=("k2",))) + + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "same source generation"): + self.run_materializer() + + self.assertEqual(1, len(self.fake_kubectl.mutations)) + + def test_changed_generation_with_identical_bytes_fails_without_write(self) -> None: + self.run_materializer() + self.write_source_record( + generation="custody-generation-2", + created_at=NEXT_SOURCE_CREATED_AT, + previous_generation="custody-generation-1", + ) + + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "generation cannot advance"): + self.run_materializer() + + self.assertEqual(["get", "create", "get", "get"], self.fake_kubectl.operations) + self.assertEqual(1, len(self.fake_kubectl.mutations)) + + def test_same_generation_retry_requires_the_recorded_predecessor(self) -> None: + self.run_materializer() + self.write_source_record(previous_generation="stale-generation") + + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "same-generation predecessor"): + self.run_materializer() + + self.assertEqual(["get", "create", "get", "get"], self.fake_kubectl.operations) + self.assertEqual(1, len(self.fake_kubectl.mutations)) + + def test_rotation_requires_current_generation_as_predecessor(self) -> None: + self.run_materializer() + self.write_source_record( + manifest=manifest_for(active="k2", ids=("k1", "k2")), + generation="custody-generation-2", + created_at=NEXT_SOURCE_CREATED_AT, + previous_generation="forked-generation", + ) + + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "predecessor does not match"): + self.run_materializer() + + self.assertEqual(["get", "create", "get", "get"], self.fake_kubectl.operations) + self.assertEqual(1, len(self.fake_kubectl.mutations)) + + def test_missing_secret_requires_null_first_materialization_predecessor(self) -> None: + self.write_source_record( + generation="custody-generation-2", + created_at=NEXT_SOURCE_CREATED_AT, + previous_generation="custody-generation-1", + ) + + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "requires an existing Secret"): + self.run_materializer() + + self.assertEqual(["get"], self.fake_kubectl.operations) + self.assertEqual([], self.fake_kubectl.mutations) + + def test_rotation_uses_resource_version_and_retains_prior_ids_and_material(self) -> None: + self.run_materializer() + previous = copy.deepcopy(self.fake_kubectl.secret) + self.write_source_record( + manifest=manifest_for(active="k2", ids=("k1", "k2")), + generation="custody-generation-2", + created_at=NEXT_SOURCE_CREATED_AT, + previous_generation="custody-generation-1", + ) + + rotation_receipt = self.run_materializer(now=NOW + dt.timedelta(hours=2)) + self.assertTrue(rotation_receipt) + + self.assertEqual(["create", "replace"], [op for op, _ in self.fake_kubectl.mutations]) + replacement = self.fake_kubectl.mutations[-1][1] + self.assertEqual(previous["metadata"]["resourceVersion"], replacement["metadata"]["resourceVersion"]) + self.assertEqual({"k1", "k2"}, MATERIALIZER.parse_manifest(self.source_manifest).key_ids) + self.assertEqual( + "custody-generation-2", + self.fake_kubectl.secret["metadata"]["annotations"][MATERIALIZER.ANNOTATION_SOURCE_GENERATION], + ) + self.assertEqual("rotate", rotation_receipt["operation"]) + self.assertEqual("custody-generation-1", rotation_receipt["source"]["predecessorGeneration"]) + self.assertEqual(self.fake_kubectl.secret["metadata"]["uid"], rotation_receipt["secret"]["uid"]) + self.assertEqual( + self.fake_kubectl.secret["metadata"]["resourceVersion"], + rotation_receipt["secret"]["resourceVersion"], + ) + rotated = copy.deepcopy(self.fake_kubectl.secret) + + retry_receipt = self.run_materializer(now=NOW + dt.timedelta(hours=3)) + self.assertFalse(retry_receipt) + self.assertEqual("retry", retry_receipt["operation"]) + + self.assertEqual(2, len(self.fake_kubectl.mutations)) + self.assertEqual(rotated, self.fake_kubectl.secret) + + def test_rotation_cannot_drop_prior_decrypt_key(self) -> None: + self.run_materializer() + self.write_source_record( + manifest=manifest_for(active="k2", ids=("k2",)), + generation="custody-generation-2", + created_at=NEXT_SOURCE_CREATED_AT, + previous_generation="custody-generation-1", + ) + + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "removes a prior key ID"): + self.run_materializer() + + self.assertEqual(1, len(self.fake_kubectl.mutations)) + + def test_rotation_cannot_reactivate_old_decrypt_key(self) -> None: + self.run_materializer() + self.write_source_record( + manifest=manifest_for(active="k2", ids=("k1", "k2")), + generation="custody-generation-2", + created_at=NEXT_SOURCE_CREATED_AT, + previous_generation="custody-generation-1", + ) + self.run_materializer() + self.write_source_record( + manifest=manifest_for(active="k1", ids=("k1", "k2")), + generation="custody-generation-3", + created_at=NEXT_SOURCE_CREATED_AT, + previous_generation="custody-generation-2", + ) + + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "new active key ID"): + self.run_materializer() + + self.assertEqual(2, len(self.fake_kubectl.mutations)) + + def test_rotation_cannot_change_retained_key_bytes(self) -> None: + self.run_materializer() + self.write_source_record( + manifest=manifest_for(active="k2", ids=("k1", "k2"), first_material_number=10), + generation="custody-generation-2", + created_at=NEXT_SOURCE_CREATED_AT, + previous_generation="custody-generation-1", + ) + + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "changes material"): + self.run_materializer() + + self.assertEqual(["get", "create", "get", "get"], self.fake_kubectl.operations) + self.assertEqual(1, len(self.fake_kubectl.mutations)) + + def test_same_generation_metadata_mismatch_fails_closed(self) -> None: + self.run_materializer() + self.fake_kubectl.secret["metadata"]["annotations"][MATERIALIZER.ANNOTATION_MATERIALIZED_AT] = ( + "2026-09-27T10:00:00Z" + ) + + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "freshness metadata"): + self.run_materializer() + + self.assertEqual(1, len(self.fake_kubectl.mutations)) + + def test_post_write_readback_mismatch_fails_without_exposing_bytes(self) -> None: + self.fake_kubectl.mutate_readback = True + + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "readback manifest bytes"): + self.run_materializer() + + self.assertEqual(1, len(self.fake_kubectl.mutations)) + self.assertEqual(["get", "create", "get"], self.fake_kubectl.operations) + self.assertNotIn("delete", self.fake_kubectl.operations) + self.assertEqual(1, len(self.fake_kubectl.attempts)) + + def test_failed_create_does_not_delete_retry_or_change_source_bytes(self) -> None: + self.fake_kubectl.fail_operation = "create" + source_record_bytes = self.source_path.read_bytes() + + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "Kubernetes operation failed"): + self.run_materializer() + + self.assertEqual(["get", "create"], self.fake_kubectl.operations) + self.assertNotIn("delete", self.fake_kubectl.operations) + self.assertEqual(1, len(self.fake_kubectl.attempts)) + attempted_manifest = base64.b64decode(self.fake_kubectl.attempts[0][1]["data"][MATERIALIZER.SECRET_KEY]) + self.assertEqual(self.source_manifest, attempted_manifest) + self.assertEqual(source_record_bytes, self.source_path.read_bytes()) + + def test_failed_replace_does_not_delete_retry_or_change_source_bytes(self) -> None: + self.run_materializer() + self.fake_kubectl.fail_operation = "replace" + replacement_bytes = manifest_for(active="k2", ids=("k1", "k2")) + self.write_source_record( + manifest=replacement_bytes, + generation="custody-generation-2", + created_at=NEXT_SOURCE_CREATED_AT, + previous_generation="custody-generation-1", + ) + + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "Kubernetes operation failed"): + self.run_materializer() + + self.assertEqual(["get", "create", "get", "get", "replace"], self.fake_kubectl.operations) + self.assertNotIn("delete", self.fake_kubectl.operations) + self.assertEqual(["create", "replace"], [operation for operation, _ in self.fake_kubectl.attempts]) + attempted_manifest = base64.b64decode(self.fake_kubectl.attempts[-1][1]["data"][MATERIALIZER.SECRET_KEY]) + self.assertEqual(replacement_bytes, attempted_manifest) + self.assertEqual(replacement_bytes, self.source_manifest) + + def test_kubectl_timeout_fails_closed_without_leaking_output_or_retry(self) -> None: + self.fake_kubectl.raise_timeout = True + + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "timed out") as raised: + self.run_materializer() + + self.assertNotIn("sensitive output", str(raised.exception)) + self.assertEqual(["auth"], self.fake_kubectl.commands) + self.assertEqual([], self.fake_kubectl.operations) + self.assertEqual([30], self.fake_kubectl.timeouts) + self.assertEqual([], self.fake_kubectl.attempts) + + def test_kubectl_invalid_text_fails_closed_without_leaking_output_or_retry(self) -> None: + self.fake_kubectl.raise_unicode_error = True + + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "invalid text") as raised: + self.run_materializer() + + self.assertNotIn("invalid test output", str(raised.exception)) + self.assertEqual(["auth"], self.fake_kubectl.commands) + self.assertEqual([], self.fake_kubectl.operations) + self.assertEqual([], self.fake_kubectl.attempts) + + def test_missing_source_fails_before_kubernetes_access(self) -> None: + self.source_path.unlink() + + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "source record"): + self.run_materializer() + + self.assertEqual(0, self.fake_kubectl.reads) + self.assertEqual([], self.fake_kubectl.mutations) + + def test_source_record_rejects_duplicate_metadata_fields(self) -> None: + encoded_manifest = base64.b64encode(self.source_manifest).decode("ascii") + raw_record = ( + '{"version":1,"manifestBase64":"' + encoded_manifest + '","sourceGeneration":"custody-generation-1",' + '"sourceGeneration":"custody-generation-2",' + '"environmentId":"player-facing-prod",' + '"targetNamespace":"account-prod",' + '"previousSourceGeneration":null,' + '"sourceCreatedAt":"2026-09-27T11:00:00Z",' + '"sourceExpiresAt":"2030-01-01T00:00:00Z"}\n' + ).encode("utf-8") + self.write_source_record(raw=raw_record) + + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "duplicate JSON fields"): + self.run_materializer() + + self.assertEqual(0, self.fake_kubectl.reads) + + def test_source_record_rejects_contradictory_version(self) -> None: + source_record = { + "version": 2, + "manifestBase64": base64.b64encode(self.source_manifest).decode("ascii"), + "sourceGeneration": self.source_generation, + "sourceExpiresAt": self.source_expires_at, + "sourceCreatedAt": self.source_created_at, + "environmentId": self.environment_id, + "targetNamespace": self.target_namespace, + "materializerUsername": self.materializer_username, + "previousSourceGeneration": self.previous_generation, + } + raw_record = ( + json.dumps(source_record, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n" + ).encode("utf-8") + self.write_source_record(raw=raw_record) + + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "version must be the integer 1"): + self.run_materializer() + + self.assertEqual(0, self.fake_kubectl.reads) + + def test_source_record_rejects_expired_source_metadata(self) -> None: + self.write_source_record(expires_at="2026-09-27T11:59:59Z") + + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "source expiry must be in the future"): + self.run_materializer() + + self.assertEqual(0, self.fake_kubectl.reads) + + def test_source_record_rejects_creation_anchor_aged_out_by_class_max_age(self) -> None: + self.write_source_record(created_at="2026-09-26T10:00:00Z") + + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "expired under the class maximum age"): + self.run_materializer() + + self.assertEqual([], self.fake_kubectl.operations) + + def test_source_record_rejects_future_creation_anchor(self) -> None: + self.write_source_record(created_at="2026-09-27T13:00:00Z") + + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "must not be in the future"): + self.run_materializer() + + self.assertEqual([], self.fake_kubectl.operations) + + def test_source_file_with_group_or_world_access_is_rejected(self) -> None: + os.chmod(self.source_path, 0o640) + + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "owner-only permissions"): + self.run_materializer() + + self.assertEqual(0, self.fake_kubectl.reads) + + def test_safe_source_read_preserves_exact_bytes(self) -> None: + expected = self.source_path.read_bytes() + + self.assertEqual(expected, MATERIALIZER.read_protected_source_record(self.source_path)) + + def test_source_read_rejects_platform_without_no_follow_support(self) -> None: + with ( + patch.object(MATERIALIZER.os, "O_NOFOLLOW", None), + self.assertRaisesRegex( + MATERIALIZER.MaterializationError, + "cannot enforce protected source custody", + ), + ): + self.run_materializer() + + self.assertEqual(0, self.fake_kubectl.reads) + self.assertEqual([], self.fake_kubectl.mutations) + + def test_source_read_rejects_symlink_source(self) -> None: + target = self.source_path.with_name("source-record-target.json") + target.write_bytes(self.source_path.read_bytes()) + os.chmod(target, 0o600) + self.source_path.unlink() + self.source_path.symlink_to(target) + + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "regular owner-only file"): + self.run_materializer() + + self.assertEqual(0, self.fake_kubectl.reads) + + def test_source_read_rejects_unprotected_or_unowned_directory(self) -> None: + custody_directory = self.source_path.parent + os.chmod(custody_directory, 0o750) + try: + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "mode 0700"): + self.run_materializer() + finally: + os.chmod(custody_directory, 0o700) + + with ( + patch.object(MATERIALIZER.os, "getuid", return_value=os.getuid() + 1), + self.assertRaisesRegex(MATERIALIZER.MaterializationError, "directory must be owned"), + ): + self.run_materializer() + + with ( + patch.object( + MATERIALIZER.os, + "getuid", + side_effect=(os.getuid(), os.getuid() + 1), + ), + self.assertRaisesRegex(MATERIALIZER.MaterializationError, "source record must be owned"), + ): + self.run_materializer() + + self.assertEqual(0, self.fake_kubectl.reads) + self.assertEqual([], self.fake_kubectl.mutations) + + def test_cli_uses_protected_source_record_without_printing_material(self) -> None: + current_time = dt.datetime.now(dt.timezone.utc) + self.write_source_record( + created_at=MATERIALIZER.format_timestamp(current_time - dt.timedelta(minutes=1)), + expires_at=MATERIALIZER.format_timestamp(current_time + dt.timedelta(hours=1)), + ) + output = io.StringIO() + with contextlib.redirect_stdout(output): + result = MATERIALIZER.main( + [ + "--source-record", + str(self.source_path), + "--environment-id", + ENVIRONMENT_ID, + "--namespace", + "account-prod", + "--class-max-age-seconds", + str(MAX_AGE_SECONDS), + "--kubectl", + "kubectl-test-double", + ] + ) + + self.assertEqual(0, result) + self.assertEqual(1, len(self.fake_kubectl.mutations)) + self.assertEqual( + "materialized account-response-envelope-key-ring in namespace account-prod\n", + output.getvalue(), + ) + self.assertNotIn(self.source_generation, output.getvalue()) + self.assertNotIn(self.source_manifest.decode("ascii"), output.getvalue()) + + +if __name__ == "__main__": + unittest.main() diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 246cffd8af..a027b767eb 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -27,6 +27,7 @@ fabric8-kubernetes-client = "7.9.0" # Keep these pins split: bcprov-jdk18on has 1.85.2, but bcpkix-jdk18on and bcutil-jdk18on 1.85.2 artifacts are unpublished. bcprov = "1.86" bcpkix = "1.86" +java-json-canonicalization = "1.1" [libraries] # Spring Boot Starters @@ -100,6 +101,7 @@ java-operator-sdk-spring-boot-starter = { module = "io.javaoperatorsdk:operator- fabric8-kubernetes-client = { module = "io.fabric8:kubernetes-client", version.ref = "fabric8-kubernetes-client" } bouncycastle = { module = "org.bouncycastle:bcprov-jdk18on", version.ref = "bcprov" } bouncycastle-pkix = { module = "org.bouncycastle:bcpkix-jdk18on", version.ref = "bcpkix" } +java-json-canonicalization = { module = "io.github.erdtman:java-json-canonicalization", version.ref = "java-json-canonicalization" } testcontainers = { module = "org.testcontainers:testcontainers", version.ref = "testcontainers" } testcontainers-junit-jupiter = { module = "org.testcontainers:testcontainers-junit-jupiter", version.ref = "testcontainers" } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/maintenance/AccountAuthorityGenerationEnrollmentRunner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/maintenance/AccountAuthorityGenerationEnrollmentRunner.java new file mode 100644 index 0000000000..b34628248a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/maintenance/AccountAuthorityGenerationEnrollmentRunner.java @@ -0,0 +1,38 @@ +package net.firedevops.firemud.accountservice.maintenance; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +/** Enrolls and reads back Account's exact JWT issuer generation before the service starts. */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected AccountAuthorityGenerationRepository is an internal Spring collaborator.") +@Component +public class AccountAuthorityGenerationEnrollmentRunner implements ApplicationRunner { + private final AccountAuthorityGenerationRepository authorityGenerationRepository; + + public AccountAuthorityGenerationEnrollmentRunner( + AccountAuthorityGenerationRepository authorityGenerationRepository) { + this.authorityGenerationRepository = authorityGenerationRepository; + } + + @Override + @Transactional + public void run(ApplicationArguments args) { + String issuerId = AccountServiceImpl.ACCOUNT_JWT_ISSUER; + AuthorityScope expectedScope = AuthorityScope.issuer(issuerId); + ScopeState persisted = authorityGenerationRepository.initializeIssuerIfAbsent(issuerId); + if (persisted == null || !expectedScope.equals(persisted.scope())) { + throw new IllegalStateException( + "Account issuer authority readback did not match exact issuer"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java new file mode 100644 index 0000000000..51fe20b086 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java @@ -0,0 +1,469 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +/** + * Stores Account-owned authority generations and their transaction-local issuance fence inputs. + * + *

This is a persistence primitive only. Callers must compose applicable generation rows, this + * account-local fence, authority mutations, and any canonical outbox evidence in their own + * transaction. The account-local scalar is not by itself the composite fence for issuer or tenant + * changes; {@link #readCompositeSnapshot(String, UUID, Collection, Collection)} locks and returns + * the exact scope rows selected by the caller. This repository does not create projections, issue + * tokens, or enable runtime reads. + */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class AccountAuthorityGenerationRepository { + private static final String GENERATION_TABLE = "account_authority_generations"; + + private final DSLContext dsl; + + public AccountAuthorityGenerationRepository(DSLContext dsl) { + this.dsl = dsl; + } + + /** Explicitly initializes one exact authority scope. Reads never initialize missing state. */ + @Transactional(propagation = Propagation.MANDATORY) + public ScopeState initialize(AuthorityScope scope) { + validateScope(scope); + if (scope.kind() == ScopeKind.MEMBERSHIP) { + requireAccountState(scope.accountId(), true); + readScopeState(AuthorityScope.tenant(scope.tenantId()), true); + // Establishing a never-joined pair does not invalidate existing callers. Only an + // explicit authority advance may change the account-local issuance fence. + } + insertGeneration(scope); + if (scope.kind() == ScopeKind.ACCOUNT) { + dsl.execute( + "INSERT INTO account_authority_issuance_fences " + + "(account_uuid, issuance_fence, source_version) VALUES (?, 1, 1)", + scope.accountId()); + } + return readScopeState(scope, true); + } + + /** + * Enrolls the exact Account JWT issuer scope once, preserving any existing durable values. + * + *

The partial unique index arbitrates concurrent Account startups. The subsequent locked + * readback returns the exact persisted issuer row and rejects missing or malformed state. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ScopeState initializeIssuerIfAbsent(String exactIssuerId) { + AuthorityScope scope = AuthorityScope.issuer(exactIssuerId); + int inserted = + dsl.execute( + "INSERT INTO " + + GENERATION_TABLE + + " (scope_kind, issuer_id, account_uuid, tenant_uuid, generation, source_version) " + + "VALUES ('ISSUER', ?, NULL, NULL, 1, 1) " + + "ON CONFLICT (issuer_id) WHERE scope_kind = 'ISSUER' DO NOTHING", + exactIssuerId); + if (inserted < 0 || inserted > 1) { + throw new IllegalStateException("Account issuer authority enrollment was ambiguous"); + } + return readScopeState(scope, true); + } + + /** + * Enrolls one exact canonical tenant scope once, preserving any existing durable generation. + * + *

This is used only after Account has stored and exactly read back its approved tenant + * identity association in the caller's transaction. Numeric retained tenant keys are not accepted + * by this method. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ScopeState initializeTenantIfAbsent(UUID canonicalTenantId) { + AuthorityScope scope = AuthorityScope.tenant(canonicalTenantId); + validateScope(scope); + int inserted = + dsl.execute( + "INSERT INTO " + + GENERATION_TABLE + + " (scope_kind, issuer_id, account_uuid, tenant_uuid, generation, source_version) " + + "VALUES ('TENANT', NULL, NULL, ?, 1, 1) " + + "ON CONFLICT (tenant_uuid) WHERE scope_kind = 'TENANT' DO NOTHING", + canonicalTenantId); + if (inserted < 0 || inserted > 1) { + throw new IllegalStateException("Account tenant authority enrollment was ambiguous"); + } + return readScopeState(scope, true); + } + + /** Reads one initialized exact scope and fails closed for absent or malformed state. */ + @Transactional(propagation = Propagation.MANDATORY) + public ScopeState read(AuthorityScope scope) { + validateScope(scope); + return readScopeState(scope, true); + } + + /** + * Locks one exact generation scope and compare-and-advances it by one. + * + *

Account and membership advances also require and advance the account-local issuance fence. + * Issuer and tenant advances are fenced by their exact generation row; a composite token issuance + * must lock and compare every applicable scope row in the same caller transaction. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ScopeState advance(ScopeState expectedState, IssuanceFence expectedIssuanceFence) { + if (expectedState == null) { + throw new IllegalArgumentException("Expected Account authority state is required"); + } + AuthorityScope scope = expectedState.scope(); + validateScope(scope); + boolean accountFenced = + scope.kind() == ScopeKind.ACCOUNT || scope.kind() == ScopeKind.MEMBERSHIP; + if (accountFenced != (expectedIssuanceFence != null)) { + throw new IllegalArgumentException( + "Account and membership advances require the matching Account issuance fence"); + } + if (!Objects.equals(expectedState.issuanceFence(), expectedIssuanceFence)) { + throw new IllegalArgumentException( + "Expected scope state and Account issuance fence must match exactly"); + } + + if (accountFenced) { + requireAccountState(scope.accountId(), true); + IssuanceFence currentFence = readIssuanceFence(scope.accountId(), true); + requireExpectedFence(expectedIssuanceFence, currentFence); + } + + Record changed = + updateGeneration(scope, expectedState.generation(), expectedState.sourceVersion()); + if (changed == null) { + throw new IllegalStateException("Stale or missing Account authority generation"); + } + + IssuanceFence nextFence = + accountFenced ? advanceIssuanceFence(scope.accountId(), expectedIssuanceFence) : null; + return state(scope, changed, nextFence); + } + + /** + * Locks one exact requested authority tuple in stable scope order at the caller's linearization + * point. Tenant and membership scope lists are independent because their canonical tuple maps can + * have different key sets. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CompositeSnapshot readCompositeSnapshot( + String issuerId, + UUID accountId, + Collection tenantIds, + Collection membershipTenantIds) { + AuthorityScope issuerScope = AuthorityScope.issuer(issuerId); + AuthorityScope accountScope = AuthorityScope.account(accountId); + List tenants = sortedDistinct(tenantIds, "tenant authority scopes"); + List memberships = sortedDistinct(membershipTenantIds, "membership authority scopes"); + + ScopeState issuer = readScopeState(issuerScope, true); + ScopeState account = readScopeState(accountScope, true); + IssuanceFence fence = requireIssuanceFence(accountId, true); + List tenantStates = new ArrayList<>(); + for (UUID tenantId : tenants) { + tenantStates.add(readScopeState(AuthorityScope.tenant(tenantId), true)); + } + List membershipStates = new ArrayList<>(); + for (UUID tenantId : memberships) { + membershipStates.add(readScopeState(AuthorityScope.membership(accountId, tenantId), true)); + } + return new CompositeSnapshot(issuer, account, tenantStates, membershipStates, fence); + } + + private void insertGeneration(AuthorityScope scope) { + int inserted = + dsl.execute( + "INSERT INTO " + + GENERATION_TABLE + + " (scope_kind, issuer_id, account_uuid, tenant_uuid, generation, source_version) " + + "VALUES (?, ?, ?, ?, 1, 1)", + scope.kind().name(), + scope.issuerId(), + scope.accountId(), + scope.tenantId()); + if (inserted != 1) { + throw new IllegalStateException("Account authority generation was not initialized"); + } + } + + private ScopeState readScopeState(AuthorityScope scope, boolean lock) { + if (scope.kind() == ScopeKind.MEMBERSHIP) { + requireAccountState(scope.accountId(), lock); + readScopeState(AuthorityScope.tenant(scope.tenantId()), lock); + } + String suffix = lock ? " FOR UPDATE" : ""; + Record row = + dsl.fetchOne( + "SELECT generation, source_version FROM " + + GENERATION_TABLE + + " WHERE scope_kind = ? AND issuer_id IS NOT DISTINCT FROM ? " + + "AND account_uuid IS NOT DISTINCT FROM ? " + + "AND tenant_uuid IS NOT DISTINCT FROM ?" + + suffix, + scope.kind().name(), + scope.issuerId(), + scope.accountId(), + scope.tenantId()); + if (row == null) { + throw new IllegalStateException("Account authority generation is missing"); + } + long generation = requiredPositive(row.get("generation", Long.class), "generation"); + long sourceVersion = requiredPositive(row.get("source_version", Long.class), "source version"); + IssuanceFence fence = + scope.kind() == ScopeKind.ACCOUNT || scope.kind() == ScopeKind.MEMBERSHIP + ? requireIssuanceFence(scope.accountId(), lock) + : null; + return new ScopeState(scope, generation, sourceVersion, fence); + } + + private Record updateGeneration( + AuthorityScope scope, long expectedGeneration, long expectedVersion) { + if (expectedGeneration <= 0L || expectedVersion <= 0L) { + throw new IllegalArgumentException("Expected Account authority values must be positive"); + } + return dsl.fetchOne( + "UPDATE " + + GENERATION_TABLE + + " SET generation = generation + 1, source_version = source_version + 1, " + + "updated_at = CURRENT_TIMESTAMP WHERE scope_kind = ? " + + "AND issuer_id IS NOT DISTINCT FROM ? AND account_uuid IS NOT DISTINCT FROM ? " + + "AND tenant_uuid IS NOT DISTINCT FROM ? AND generation = ? AND source_version = ? " + + "RETURNING generation, source_version", + scope.kind().name(), + scope.issuerId(), + scope.accountId(), + scope.tenantId(), + expectedGeneration, + expectedVersion); + } + + private IssuanceFence advanceIssuanceFence(UUID accountId, IssuanceFence expected) { + Record row; + if (expected == null) { + row = + dsl.fetchOne( + "UPDATE account_authority_issuance_fences " + + "SET issuance_fence = issuance_fence + 1, " + + "source_version = source_version + 1, updated_at = CURRENT_TIMESTAMP " + + "WHERE account_uuid = ? RETURNING issuance_fence, source_version", + accountId); + } else { + requireFenceOwner(expected, accountId); + row = + dsl.fetchOne( + "UPDATE account_authority_issuance_fences " + + "SET issuance_fence = issuance_fence + 1, " + + "source_version = source_version + 1, updated_at = CURRENT_TIMESTAMP " + + "WHERE account_uuid = ? AND issuance_fence = ? AND source_version = ? " + + "RETURNING issuance_fence, source_version", + accountId, + expected.value(), + expected.sourceVersion()); + } + if (row == null) { + throw new IllegalStateException("Stale or missing Account authority issuance fence"); + } + return new IssuanceFence( + accountId, + requiredPositive(row.get("issuance_fence", Long.class), "issuance fence"), + requiredPositive(row.get("source_version", Long.class), "issuance-fence source version")); + } + + private IssuanceFence readIssuanceFence(UUID accountId, boolean lock) { + String suffix = lock ? " FOR UPDATE" : ""; + Record row = + dsl.fetchOne( + "SELECT issuance_fence, source_version FROM account_authority_issuance_fences " + + "WHERE account_uuid = ?" + + suffix, + accountId); + if (row == null) { + throw new IllegalStateException("Account authority issuance fence is missing"); + } + return new IssuanceFence( + accountId, + requiredPositive(row.get("issuance_fence", Long.class), "issuance fence"), + requiredPositive(row.get("source_version", Long.class), "issuance-fence source version")); + } + + private IssuanceFence requireIssuanceFence(UUID accountId, boolean lock) { + return readIssuanceFence(accountId, lock); + } + + private void requireAccountState(UUID accountId, boolean lock) { + readScopeState(AuthorityScope.account(accountId), lock); + } + + private void requireExpectedFence(IssuanceFence expected, IssuanceFence current) { + requireFenceOwner(expected, current.accountId()); + if (!expected.equals(current)) { + throw new IllegalStateException("Stale Account authority issuance fence"); + } + } + + private void requireFenceOwner(IssuanceFence fence, UUID accountId) { + if (fence == null || !accountId.equals(fence.accountId()) || fence.value() <= 0L) { + throw new IllegalArgumentException("Matching positive Account issuance fence is required"); + } + } + + private ScopeState state(AuthorityScope scope, Record row, IssuanceFence fence) { + return new ScopeState( + scope, + requiredPositive(row.get("generation", Long.class), "generation"), + requiredPositive(row.get("source_version", Long.class), "source version"), + fence); + } + + private List sortedDistinct(Collection values, String label) { + if (values == null) { + throw new IllegalArgumentException(label + " are required"); + } + List result = new ArrayList<>(); + Set seen = new HashSet<>(); + for (UUID value : values) { + if (value == null || !seen.add(value)) { + throw new IllegalArgumentException(label + " must contain unique canonical UUIDs"); + } + result.add(value); + } + result.sort(Comparator.naturalOrder()); + return List.copyOf(result); + } + + private void validateScope(AuthorityScope scope) { + Objects.requireNonNull(scope, "authority scope is required"); + switch (scope.kind()) { + case ISSUER -> requireNonBlank(scope.issuerId(), "issuer ID"); + case ACCOUNT -> + Objects.requireNonNull(scope.accountId(), "canonical Account UUID is required"); + case TENANT -> Objects.requireNonNull(scope.tenantId(), "canonical tenant UUID is required"); + case MEMBERSHIP -> { + Objects.requireNonNull(scope.accountId(), "canonical Account UUID is required"); + Objects.requireNonNull(scope.tenantId(), "canonical tenant UUID is required"); + } + } + } + + private void requireNonBlank(String value, String field) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(field + " is required"); + } + } + + private long requiredPositive(Long value, String field) { + if (value == null || value <= 0L) { + throw new IllegalStateException("Account authority " + field + " is missing or malformed"); + } + return value; + } + + public enum ScopeKind { + ISSUER, + ACCOUNT, + TENANT, + MEMBERSHIP + } + + /** Exact owner scope. UUID fields are canonical identities; retained numeric IDs are excluded. */ + public record AuthorityScope(ScopeKind kind, String issuerId, UUID accountId, UUID tenantId) { + public AuthorityScope { + Objects.requireNonNull(kind, "authority scope kind is required"); + switch (kind) { + case ISSUER -> { + if (issuerId == null || issuerId.isBlank() || accountId != null || tenantId != null) { + throw new IllegalArgumentException( + "Issuer authority scope must contain only exact issuer ID"); + } + } + case ACCOUNT -> { + if (issuerId != null || accountId == null || tenantId != null) { + throw new IllegalArgumentException( + "Account authority scope requires only Account UUID"); + } + } + case TENANT -> { + if (issuerId != null || accountId != null || tenantId == null) { + throw new IllegalArgumentException("Tenant authority scope requires only tenant UUID"); + } + } + case MEMBERSHIP -> { + if (issuerId != null || accountId == null || tenantId == null) { + throw new IllegalArgumentException("Membership authority scope requires both UUIDs"); + } + } + } + } + + public static AuthorityScope issuer(String exactIssuerId) { + return new AuthorityScope(ScopeKind.ISSUER, exactIssuerId, null, null); + } + + public static AuthorityScope account(UUID accountId) { + return new AuthorityScope(ScopeKind.ACCOUNT, null, accountId, null); + } + + public static AuthorityScope tenant(UUID tenantId) { + return new AuthorityScope(ScopeKind.TENANT, null, null, tenantId); + } + + public static AuthorityScope membership(UUID accountId, UUID tenantId) { + return new AuthorityScope(ScopeKind.MEMBERSHIP, null, accountId, tenantId); + } + } + + /** Positive generation and independently monotonic durable source version for one exact scope. */ + public record ScopeState( + AuthorityScope scope, long generation, long sourceVersion, IssuanceFence issuanceFence) { + public ScopeState { + Objects.requireNonNull(scope, "authority scope is required"); + if (generation <= 0L || sourceVersion <= 0L) { + throw new IllegalArgumentException( + "Authority generation and source version must be positive"); + } + } + } + + /** Account-local issuance serialization value; it is one component of a composite snapshot. */ + public record IssuanceFence(UUID accountId, long value, long sourceVersion) { + public IssuanceFence { + Objects.requireNonNull(accountId, "canonical Account UUID is required"); + if (value <= 0L || sourceVersion <= 0L) { + throw new IllegalArgumentException("Account issuance fence values must be positive"); + } + } + } + + /** + * Exact issuer/account and caller-selected tenant/membership generation rows plus Account fence. + */ + public record CompositeSnapshot( + ScopeState issuer, + ScopeState account, + List tenants, + List memberships, + IssuanceFence issuanceFence) { + public CompositeSnapshot { + Objects.requireNonNull(issuer, "issuer authority state is required"); + Objects.requireNonNull(account, "Account authority state is required"); + tenants = List.copyOf(tenants); + memberships = List.copyOf(memberships); + Objects.requireNonNull(issuanceFence, "Account issuance fence is required"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepository.java new file mode 100644 index 0000000000..037db96b19 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepository.java @@ -0,0 +1,404 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.function.LongFunction; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +/** + * Stores immutable Account authority-event evidence in independently sequenced SQL streams. + * + *

The caller owns the transaction that composes authority changes with this outbox. The digest + * is supplied by the producer's canonical event contract and is persisted and compared exactly; + * this repository does not define or recompute its preimage. An absent checkpoint is uninitialized + * storage evidence, not a sequence-zero authority proof. A caller may report zero only after its + * own same-transaction membership and retained-history checks prove that the exact scope has never + * committed an authority event. The repository checks the stream-key prefix and preserves its exact + * value; callers must validate the scope ID with its owning issuer, account, tenant, membership, or + * grant-scope rule before calling it. + */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class AccountAuthorityOutboxRepository { + private static final String STREAM_PREFIX = "account:auth-authority:v1:"; + private static final int MAX_STREAM_KEY_LENGTH = 2048; + private static final int MAX_REQUEST_ID_LENGTH = 512; + private static final int MAX_EVENT_ID_LENGTH = 512; + private static final int MAX_EVENT_DIGEST_LENGTH = 512; + + private final DSLContext dsl; + + public AccountAuthorityOutboxRepository(DSLContext dsl) { + this.dsl = dsl; + } + + /** + * Appends one immutable event or returns the committed event for an exact retry. + * + *

A request ID is unique within its exact stream. Retrying that ID with any changed event ID, + * digest, or payload is denied as an idempotency conflict. Sequence allocation, event insertion, + * and stream-head advancement participate in the caller's transaction. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Event append( + String outboxStreamKey, + String requestId, + String eventId, + String eventDigest, + byte[] payload) { + validateStreamKey(outboxStreamKey); + requireBoundedNonBlank(requestId, "request ID", MAX_REQUEST_ID_LENGTH); + EventEvidence evidence = new EventEvidence(eventId, eventDigest, payload); + return append(outboxStreamKey, requestId, ignoredSequence -> evidence); + } + + /** + * Appends one event whose immutable evidence is produced after the exact stream is locked. + * + *

The factory receives the next sequence for a new request, or the committed sequence for an + * exact-request retry. Its payload is the complete producer wire payload (including its {@code + * eventDigest} field). The producer must ensure that field matches the separate digest; this + * repository treats both as opaque evidence and does not interpret the payload or validate that + * equality. The factory may run again for an exact-request retry, so it must be deterministic and + * side-effect-free for the same request and sequence. It is invoked before the stream head is + * advanced, so a failed factory cannot advance the head. The caller must let a factory failure + * escape its transaction if it also needs the initial zero-sequence stream row rolled back. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Event append( + String outboxStreamKey, String requestId, LongFunction evidenceFactory) { + validateStreamKey(outboxStreamKey); + requireBoundedNonBlank(requestId, "request ID", MAX_REQUEST_ID_LENGTH); + if (evidenceFactory == null) { + throw new IllegalArgumentException("Account authority outbox evidence factory is required"); + } + + dsl.execute( + "INSERT INTO account_authority_outbox_streams (outbox_stream_key, last_sequence) " + + "VALUES (?, 0) ON CONFLICT (outbox_stream_key) DO NOTHING", + outboxStreamKey); + Record stream = lockStream(outboxStreamKey); + long currentSequence = requiredNonnegative(stream, "last_sequence"); + + Record priorRequest = + dsl.fetchOne( + "SELECT outbox_sequence, event_id, event_digest, payload " + + "FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ? AND request_id = ?", + outboxStreamKey, + requestId); + if (priorRequest != null) { + Event committed = toEvent(outboxStreamKey, requestId, priorRequest); + EventEvidence candidate = produceEvidence(evidenceFactory, committed.outboxSequence()); + if (!committed.matches(candidate)) { + throw new IdempotencyConflictException( + "Account authority outbox request was reused with different event evidence"); + } + if (currentSequence < committed.outboxSequence()) { + throw new IllegalStateException("Account authority outbox stream head regressed"); + } + return committed; + } + + long nextSequence = nextSequence(currentSequence); + EventEvidence evidence = produceEvidence(evidenceFactory, nextSequence); + Record priorEventId = + dsl.fetchOne( + "SELECT request_id FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ? AND event_id = ?", + outboxStreamKey, + evidence.eventId()); + if (priorEventId != null) { + throw new IdempotencyConflictException( + "Account authority outbox event ID is already bound to another request"); + } + + Record advancedHead = + dsl.fetchOne( + "UPDATE account_authority_outbox_streams SET last_sequence = ? " + + "WHERE outbox_stream_key = ? AND last_sequence = ? " + + "RETURNING last_sequence", + nextSequence, + outboxStreamKey, + currentSequence); + if (advancedHead == null) { + throw new IllegalStateException("Account authority outbox stream changed concurrently"); + } + + int inserted = + dsl.execute( + "INSERT INTO account_authority_outbox_events " + + "(outbox_stream_key, outbox_sequence, request_id, event_id, event_digest, payload) " + + "VALUES (?, ?, ?, ?, ?, ?)", + outboxStreamKey, + nextSequence, + requestId, + evidence.eventId(), + evidence.eventDigest(), + evidence.payload()); + if (inserted != 1) { + throw new IllegalStateException("Account authority outbox event was not appended"); + } + return new Event( + outboxStreamKey, + requestId, + nextSequence, + evidence.eventId(), + evidence.eventDigest(), + evidence.payload()); + } + + private static long nextSequence(long currentSequence) { + try { + return Math.addExact(currentSequence, 1L); + } catch (ArithmeticException overflow) { + throw new IllegalStateException("Account authority outbox sequence is exhausted", overflow); + } + } + + private static EventEvidence produceEvidence( + LongFunction evidenceFactory, long sequence) { + EventEvidence produced = evidenceFactory.apply(sequence); + if (produced == null) { + throw new IllegalArgumentException("Account authority outbox evidence factory returned null"); + } + return new EventEvidence(produced.eventId(), produced.eventDigest(), produced.payload()); + } + + /** Exact event readback for a positive sequence; sequence zero is not an event identity. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findEvent(String outboxStreamKey, long outboxSequence) { + validateStreamKey(outboxStreamKey); + if (outboxSequence <= 0) { + throw new IllegalArgumentException("Authority outbox event sequence must be positive"); + } + Record row = + dsl.fetchOne( + "SELECT outbox_sequence, request_id, event_id, event_digest, payload " + + "FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ? AND outbox_sequence = ?", + outboxStreamKey, + outboxSequence); + return row == null + ? Optional.empty() + : Optional.of(toEvent(outboxStreamKey, row.get("request_id", String.class), row)); + } + + /** Exact immutable event lookup for a request in one stream, including superseded events. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findEvent(String outboxStreamKey, String requestId) { + validateStreamKey(outboxStreamKey); + requireBoundedNonBlank(requestId, "request ID", MAX_REQUEST_ID_LENGTH); + Record row = + dsl.fetchOne( + "SELECT outbox_sequence, request_id, event_id, event_digest, payload " + + "FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ? AND request_id = ?", + outboxStreamKey, + requestId); + return row == null + ? Optional.empty() + : Optional.of(toEvent(outboxStreamKey, row.get("request_id", String.class), row)); + } + + /** + * Reads the exact latest positive checkpoint for a stream, or empty when no canonical event has + * ever been committed to that stream. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readCheckpoint(String outboxStreamKey) { + validateStreamKey(outboxStreamKey); + Record stream = + dsl.fetchOne( + "SELECT last_sequence FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ? FOR SHARE", + outboxStreamKey); + if (stream == null) { + return Optional.empty(); + } + long sequence = requiredPositive(stream, "last_sequence"); + Event event = + findEvent(outboxStreamKey, sequence) + .orElseThrow( + () -> + new IllegalStateException( + "Account authority outbox checkpoint has no matching event evidence")); + return Optional.of( + new Checkpoint( + outboxStreamKey, event.outboxSequence(), event.eventId(), event.eventDigest())); + } + + private Record lockStream(String outboxStreamKey) { + Record stream = + dsl.fetchOne( + "SELECT last_sequence FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ? FOR UPDATE", + outboxStreamKey); + if (stream == null) { + throw new IllegalStateException("Account authority outbox stream could not be locked"); + } + return stream; + } + + private Event toEvent(String outboxStreamKey, String requestId, Record row) { + return new Event( + outboxStreamKey, + requestId, + requiredPositive(row, "outbox_sequence"), + requiredText(row, "event_id"), + requiredText(row, "event_digest"), + row.get("payload", byte[].class)); + } + + private static long requiredNonnegative(Record row, String field) { + Long value = row.get(field, Long.class); + if (value == null || value < 0L) { + throw new IllegalStateException("Malformed Account authority outbox " + field); + } + return value; + } + + private static long requiredPositive(Record row, String field) { + Long value = row.get(field, Long.class); + if (value == null || value <= 0L) { + throw new IllegalStateException("Malformed Account authority outbox " + field); + } + return value; + } + + private static String requiredText(Record row, String field) { + String value = row.get(field, String.class); + requireNonBlank(value, field); + return value; + } + + private static void validateStreamKey(String outboxStreamKey) { + if (outboxStreamKey == null + || !outboxStreamKey.startsWith(STREAM_PREFIX) + || outboxStreamKey.length() == STREAM_PREFIX.length() + || outboxStreamKey.length() > MAX_STREAM_KEY_LENGTH + || outboxStreamKey.substring(STREAM_PREFIX.length()).isBlank() + || !outboxStreamKey.equals(outboxStreamKey.strip()) + || outboxStreamKey.indexOf('\n') >= 0 + || outboxStreamKey.indexOf('\r') >= 0) { + throw new IllegalArgumentException( + "Account authority outbox key with canonical prefix and exact scope is required"); + } + } + + private static void requireNonBlank(String value, String field) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException("Account authority outbox " + field + " is required"); + } + } + + private static void requireBoundedNonBlank(String value, String field, int maxLength) { + requireNonBlank(value, field); + if (value.length() > maxLength) { + throw new IllegalArgumentException( + "Account authority outbox " + field + " exceeds its maximum length"); + } + } + + private static byte[] copyPayload(byte[] payload) { + if (payload == null || payload.length == 0) { + throw new IllegalArgumentException("Account authority outbox payload is required"); + } + return payload.clone(); + } + + /** Immutable producer evidence; payload contains the complete canonical wire bytes. */ + public record EventEvidence(String eventId, String eventDigest, byte[] payload) { + public EventEvidence { + requireBoundedNonBlank(eventId, "event ID", MAX_EVENT_ID_LENGTH); + requireBoundedNonBlank(eventDigest, "event digest", MAX_EVENT_DIGEST_LENGTH); + payload = copyPayload(payload); + } + + @Override + public byte[] payload() { + return payload.clone(); + } + } + + /** Immutable event evidence returned by append and exact readback. */ + public record Event( + String outboxStreamKey, + String requestId, + long outboxSequence, + String eventId, + String eventDigest, + byte[] payload) { + public Event { + validateStreamKey(outboxStreamKey); + requireBoundedNonBlank(requestId, "request ID", MAX_REQUEST_ID_LENGTH); + requireBoundedNonBlank(eventId, "event ID", MAX_EVENT_ID_LENGTH); + requireBoundedNonBlank(eventDigest, "event digest", MAX_EVENT_DIGEST_LENGTH); + if (outboxSequence <= 0) { + throw new IllegalArgumentException("Authority outbox event sequence must be positive"); + } + payload = copyPayload(payload); + } + + @Override + public byte[] payload() { + return payload.clone(); + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof Event event)) { + return false; + } + return outboxSequence == event.outboxSequence + && Objects.equals(outboxStreamKey, event.outboxStreamKey) + && Objects.equals(requestId, event.requestId) + && Objects.equals(eventId, event.eventId) + && Objects.equals(eventDigest, event.eventDigest) + && Arrays.equals(payload, event.payload); + } + + @Override + public int hashCode() { + int result = Objects.hash(outboxStreamKey, requestId, outboxSequence, eventId, eventDigest); + return 31 * result + Arrays.hashCode(payload); + } + + private boolean matches(EventEvidence candidate) { + return Objects.equals(eventId, candidate.eventId()) + && Objects.equals(eventDigest, candidate.eventDigest()) + && Arrays.equals(payload, candidate.payload()); + } + } + + /** Positive Account checkpoint; an absent checkpoint must not be serialized as sequence zero. */ + public record Checkpoint( + String outboxStreamKey, long outboxSequence, String sourceEventId, String sourceEventDigest) { + public Checkpoint { + validateStreamKey(outboxStreamKey); + if (outboxSequence <= 0) { + throw new IllegalArgumentException("Authority outbox checkpoint sequence must be positive"); + } + requireNonBlank(sourceEventId, "checkpoint source event ID"); + requireNonBlank(sourceEventDigest, "checkpoint source event digest"); + } + } + + /** A stable request identity was reused with different event evidence. */ + public static final class IdempotencyConflictException extends IllegalStateException { + public IdempotencyConflictException(String message) { + super(message); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceIdentity.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceIdentity.java new file mode 100644 index 0000000000..2648fdb7b9 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceIdentity.java @@ -0,0 +1,64 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.nio.charset.StandardCharsets; +import java.util.Objects; + +/** Exact caller-supplied identity for one durable connect-token issuance attempt. */ +public record AccountConnectTokenIssuanceIdentity( + long accountId, long tenantId, String connectScopeId, String requestId) { + + public static final int MAX_CONNECT_SCOPE_ID_UTF8_BYTES = 2048; + public static final int MAX_REQUEST_ID_LENGTH = 128; + + public AccountConnectTokenIssuanceIdentity { + if (accountId <= 0 || tenantId <= 0) { + throw new IllegalArgumentException("Connect-token account and tenant IDs must be positive"); + } + connectScopeId = requireText(connectScopeId, "connectScopeId"); + requestId = requireText(requestId, "requestId"); + if (connectScopeId.getBytes(StandardCharsets.UTF_8).length > MAX_CONNECT_SCOPE_ID_UTF8_BYTES) { + throw new IllegalArgumentException("Connect-token scope ID exceeds its storage bound"); + } + if (requestId.length() > MAX_REQUEST_ID_LENGTH) { + throw new IllegalArgumentException("Connect-token request ID exceeds its storage bound"); + } + } + + String connectScopeHash() { + return net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash(connectScopeId); + } + + @Override + public String toString() { + return "AccountConnectTokenIssuanceIdentity{accountId=" + + accountId + + ", tenantId=" + + tenantId + + ", connectScopeId=, requestId='" + + requestId + + "'}"; + } + + private static String requireText(String value, String fieldName) { + Objects.requireNonNull(value, fieldName); + if (value.isBlank() || value.indexOf('\0') >= 0 || hasUnpairedSurrogate(value)) { + throw new IllegalArgumentException("Invalid " + fieldName); + } + return value; + } + + private static boolean hasUnpairedSurrogate(String value) { + 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))) { + return true; + } + index++; + } else if (Character.isLowSurrogate(current)) { + return true; + } + } + return false; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceOperation.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceOperation.java new file mode 100644 index 0000000000..ebd9b1ab66 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceOperation.java @@ -0,0 +1,189 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.time.Instant; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; + +/** Readback-only view of the non-secret durable issuance operation row. */ +public record AccountConnectTokenIssuanceOperation( + UUID operationId, + long accountId, + long tenantId, + String connectScopeHash, + String requestId, + int requestDigestVersion, + byte[] requestDigest, + Lifecycle lifecycle, + String outcomeCode, + String tokenIdentity, + byte[] tokenHash, + byte[] contextEvidenceDigest, + byte[] authorityTupleDigest, + byte[] issuanceFenceDigest, + byte[] postconditionDigest, + int reconciliationAttemptCount, + Instant lastReconciliationAttemptAt, + String lastReconciliationAttemptReason, + Instant nextReconciliationAttemptAt, + Instant createdAt, + Instant updatedAt) { + + public enum Lifecycle { + PENDING, + COMMITTED, + FAILED, + ABORTED; + + static Lifecycle fromDatabase(String value) { + try { + return Lifecycle.valueOf(value); + } catch (RuntimeException exception) { + throw new IllegalStateException("Stored connect-token issuance lifecycle is invalid"); + } + } + } + + public AccountConnectTokenIssuanceOperation { + if (operationId == null + || accountId <= 0 + || tenantId <= 0 + || connectScopeHash == null + || requestId == null + || requestDigestVersion != 1 + || lifecycle == null + || reconciliationAttemptCount < 0 + || nextReconciliationAttemptAt == null + || createdAt == null + || updatedAt == null) { + throw new IllegalArgumentException("Stored connect-token issuance operation is malformed"); + } + requestDigest = copyDigest(requestDigest, "request digest", false); + tokenHash = copyDigest(tokenHash, "token hash", true); + contextEvidenceDigest = copyDigest(contextEvidenceDigest, "context digest", true); + authorityTupleDigest = copyDigest(authorityTupleDigest, "authority tuple digest", true); + issuanceFenceDigest = copyDigest(issuanceFenceDigest, "issuance-fence digest", true); + postconditionDigest = copyDigest(postconditionDigest, "postcondition digest", true); + } + + @Override + public byte[] requestDigest() { + return requestDigest.clone(); + } + + @Override + public byte[] tokenHash() { + return copyNullable(tokenHash); + } + + @Override + public byte[] contextEvidenceDigest() { + return copyNullable(contextEvidenceDigest); + } + + @Override + public byte[] authorityTupleDigest() { + return copyNullable(authorityTupleDigest); + } + + @Override + public byte[] issuanceFenceDigest() { + return copyNullable(issuanceFenceDigest); + } + + @Override + public byte[] postconditionDigest() { + return copyNullable(postconditionDigest); + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof AccountConnectTokenIssuanceOperation that)) { + return false; + } + return accountId == that.accountId + && tenantId == that.tenantId + && requestDigestVersion == that.requestDigestVersion + && reconciliationAttemptCount == that.reconciliationAttemptCount + && operationId.equals(that.operationId) + && connectScopeHash.equals(that.connectScopeHash) + && requestId.equals(that.requestId) + && Arrays.equals(requestDigest, that.requestDigest) + && lifecycle == that.lifecycle + && Objects.equals(outcomeCode, that.outcomeCode) + && Objects.equals(tokenIdentity, that.tokenIdentity) + && Arrays.equals(tokenHash, that.tokenHash) + && Arrays.equals(contextEvidenceDigest, that.contextEvidenceDigest) + && Arrays.equals(authorityTupleDigest, that.authorityTupleDigest) + && Arrays.equals(issuanceFenceDigest, that.issuanceFenceDigest) + && Arrays.equals(postconditionDigest, that.postconditionDigest) + && Objects.equals(lastReconciliationAttemptAt, that.lastReconciliationAttemptAt) + && Objects.equals(lastReconciliationAttemptReason, that.lastReconciliationAttemptReason) + && Objects.equals(nextReconciliationAttemptAt, that.nextReconciliationAttemptAt) + && Objects.equals(createdAt, that.createdAt) + && Objects.equals(updatedAt, that.updatedAt); + } + + @Override + public int hashCode() { + int result = + Objects.hash( + operationId, + accountId, + tenantId, + connectScopeHash, + requestId, + requestDigestVersion, + lifecycle, + outcomeCode, + tokenIdentity, + reconciliationAttemptCount, + lastReconciliationAttemptAt, + lastReconciliationAttemptReason, + nextReconciliationAttemptAt, + createdAt, + updatedAt); + result = 31 * result + Arrays.hashCode(requestDigest); + result = 31 * result + Arrays.hashCode(tokenHash); + result = 31 * result + Arrays.hashCode(contextEvidenceDigest); + result = 31 * result + Arrays.hashCode(authorityTupleDigest); + result = 31 * result + Arrays.hashCode(issuanceFenceDigest); + result = 31 * result + Arrays.hashCode(postconditionDigest); + return result; + } + + @Override + public String toString() { + return "AccountConnectTokenIssuanceOperation{operationId=" + + operationId + + ", accountId=" + + accountId + + ", tenantId=" + + tenantId + + ", requestId='" + + requestId + + "', lifecycle=" + + lifecycle + + ", secretEvidence=}"; + } + + private static byte[] copyDigest(byte[] value, String fieldName, boolean nullable) { + if (value == null) { + if (nullable) { + return null; + } + throw new IllegalArgumentException(fieldName + " is required"); + } + if (value.length != 32) { + throw new IllegalArgumentException(fieldName + " must be 32 bytes"); + } + return Arrays.copyOf(value, value.length); + } + + private static byte[] copyNullable(byte[] value) { + return value == null ? null : value.clone(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceRepository.java new file mode 100644 index 0000000000..9ef48d7f71 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceRepository.java @@ -0,0 +1,917 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.security.MessageDigest; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceOperation.Lifecycle; +import net.firedevops.firemud.accountservice.security.AccountEncryptedEnvelope; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeBinding; +import net.firedevops.firemud.accountservice.security.AccountEnvelopePurpose; +import net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +/** Account-owned first-writer-wins storage and exact readback for connect-token issuance. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class AccountConnectTokenIssuanceRepository { + private static final String OPERATION_TABLE = "account_connect_token_issuance_operations"; + private static final String ENVELOPE_TABLE = "account_connect_token_response_envelopes"; + private static final int REQUEST_DIGEST_VERSION = 1; + private static final int DIGEST_LENGTH_BYTES = 32; + private static final int MAX_TOKEN_IDENTITY_LENGTH = 128; + private static final int MAX_OUTCOME_CODE_LENGTH = 64; + private static final int MAX_RECONCILIATION_REASON_LENGTH = 128; + + private final DSLContext dsl; + + public AccountConnectTokenIssuanceRepository(DSLContext dsl) { + this.dsl = dsl; + } + + /** + * Claims one operation identity without replacing or mutating a prior writer's digest or state. + * PostgreSQL's unique identity constraint arbitrates racing writers; the subsequent read returns + * the winner's durable row. A changed digest is an idempotency conflict and never inserts. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ClaimResult claim(AccountConnectTokenIssuanceIdentity identity, byte[] requestDigest) { + validateIdentity(identity); + byte[] digest = requireDigest(requestDigest, "request digest"); + UUID proposedOperationId = UUID.randomUUID(); + int inserted = + dsl.execute( + "INSERT INTO " + + OPERATION_TABLE + + " (operation_id, account_id, tenant_id, connect_scope_hash, request_id, " + + "request_digest_version, request_digest, status) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, 'PENDING') " + + "ON CONFLICT (account_id, tenant_id, connect_scope_hash, request_id) " + + "DO NOTHING", + proposedOperationId, + identity.accountId(), + identity.tenantId(), + identity.connectScopeHash(), + identity.requestId(), + REQUEST_DIGEST_VERSION, + digest); + if (inserted < 0 || inserted > 1) { + throw new IllegalStateException("Connect-token issuance claim result was ambiguous"); + } + + AccountConnectTokenIssuanceOperation operation = + readOperation(identity) + .orElseThrow( + () -> + new IllegalStateException( + "Connect-token issuance claim has no exact durable readback")); + if (!MessageDigest.isEqual(operation.requestDigest(), digest)) { + throw new IdempotencyConflictException( + "Connect-token request identity was reused with a different digest"); + } + if (inserted == 1 && !proposedOperationId.equals(operation.operationId())) { + throw new IllegalStateException("Connect-token issuance claim returned another operation"); + } + return new ClaimResult( + inserted == 1 ? ClaimDisposition.CLAIMED : ClaimDisposition.REPLAYED, identity, operation); + } + + /** Reads one exact operation identity and requires an exact versioned digest match if present. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional find( + AccountConnectTokenIssuanceIdentity identity, byte[] requestDigest) { + validateIdentity(identity); + byte[] digest = requireDigest(requestDigest, "request digest"); + Optional operation = readOperation(identity); + if (operation.isPresent() && !MessageDigest.isEqual(operation.get().requestDigest(), digest)) { + throw new IdempotencyConflictException( + "Connect-token request identity was reused with a different digest"); + } + return operation; + } + + /** + * Adds previously absent token/authority evidence to the first writer's still-PENDING row. + * Existing evidence is write-once; retries may confirm the same bytes but cannot replace them. + * This lets an ambiguous operation retain what Account already proved without making it terminal + * or permitting a later caller to remint. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AccountConnectTokenIssuanceOperation recordPendingEvidence( + ClaimResult claim, + byte[] requestDigest, + String tokenIdentity, + byte[] tokenHash, + byte[] contextEvidenceDigest, + byte[] authorityTupleDigest, + byte[] issuanceFenceDigest, + byte[] postconditionDigest) { + AccountConnectTokenIssuanceIdentity identity = requireClaimIdentity(claim); + byte[] digest = requireDigest(requestDigest, "request digest"); + byte[] checkedTokenHash = optionalDigest(tokenHash, "token hash"); + byte[] checkedContextDigest = optionalDigest(contextEvidenceDigest, "context digest"); + byte[] checkedAuthorityDigest = optionalDigest(authorityTupleDigest, "authority tuple digest"); + byte[] checkedFenceDigest = optionalDigest(issuanceFenceDigest, "issuance-fence digest"); + byte[] checkedPostconditionDigest = optionalDigest(postconditionDigest, "postcondition digest"); + if (tokenIdentity == null + && checkedContextDigest == null + && checkedAuthorityDigest == null + && checkedFenceDigest == null + && checkedPostconditionDigest == null) { + throw new IllegalArgumentException( + "At least one pending connect-token evidence field is required"); + } + if ((tokenIdentity == null) != (checkedTokenHash == null) + || (tokenIdentity != null + && (tokenIdentity.isBlank() + || tokenIdentity.length() > MAX_TOKEN_IDENTITY_LENGTH + || tokenIdentity.indexOf('\0') >= 0))) { + throw new IllegalArgumentException("Pending connect-token identity/hash evidence is invalid"); + } + + AccountConnectTokenIssuanceOperation operation = requireClaimedOperation(claim, digest); + if (operation.lifecycle() != Lifecycle.PENDING) { + throw new IllegalStateException("Only a pending connect-token operation can add evidence"); + } + requireEvidenceCompatible( + operation, + tokenIdentity, + checkedTokenHash, + checkedContextDigest, + checkedAuthorityDigest, + checkedFenceDigest, + checkedPostconditionDigest); + + Record changed = + dsl.fetchOne( + "UPDATE " + + OPERATION_TABLE + + " SET token_identity = COALESCE(token_identity, ?), " + + "token_hash = COALESCE(token_hash, ?), " + + "context_evidence_digest = COALESCE(context_evidence_digest, ?), " + + "authority_tuple_digest = COALESCE(authority_tuple_digest, ?), " + + "issuance_fence_digest = COALESCE(issuance_fence_digest, ?), " + + "postcondition_digest = COALESCE(postcondition_digest, ?) " + + "WHERE operation_id = ? AND account_id = ? AND tenant_id = ? " + + "AND connect_scope_hash = ? AND request_id = ? " + + "AND request_digest_version = ? AND request_digest = ? AND status = 'PENDING' " + + "AND (?::VARCHAR IS NULL OR token_identity IS NULL OR token_identity = ?) " + + "AND (?::BYTEA IS NULL OR token_hash IS NULL OR token_hash = ?) " + + "AND (?::BYTEA IS NULL OR context_evidence_digest IS NULL " + + "OR context_evidence_digest = ?) " + + "AND (?::BYTEA IS NULL OR authority_tuple_digest IS NULL " + + "OR authority_tuple_digest = ?) " + + "AND (?::BYTEA IS NULL OR issuance_fence_digest IS NULL " + + "OR issuance_fence_digest = ?) " + + "AND (?::BYTEA IS NULL OR postcondition_digest IS NULL OR postcondition_digest = ?) " + + "RETURNING operation_id", + tokenIdentity, + checkedTokenHash, + checkedContextDigest, + checkedAuthorityDigest, + checkedFenceDigest, + checkedPostconditionDigest, + operation.operationId(), + identity.accountId(), + identity.tenantId(), + identity.connectScopeHash(), + identity.requestId(), + REQUEST_DIGEST_VERSION, + digest, + tokenIdentity, + tokenIdentity, + checkedTokenHash, + checkedTokenHash, + checkedContextDigest, + checkedContextDigest, + checkedAuthorityDigest, + checkedAuthorityDigest, + checkedFenceDigest, + checkedFenceDigest, + checkedPostconditionDigest, + checkedPostconditionDigest); + if (changed == null) { + throw new EvidenceMismatchException( + "Pending connect-token operation already contains different evidence"); + } + return readOperation(identity) + .filter(updated -> updated.operationId().equals(operation.operationId())) + .orElseThrow( + () -> + new IllegalStateException( + "Pending connect-token evidence has no exact operation readback")); + } + + /** Records one compare-and-increment reconciliation attempt under the supplied caller cap. */ + @Transactional(propagation = Propagation.MANDATORY) + public AccountConnectTokenIssuanceOperation recordReconciliationAttempt( + AccountConnectTokenIssuanceIdentity identity, + byte[] requestDigest, + int expectedAttemptCount, + int maxAttempts, + Instant attemptedAt, + String reason, + Instant nextAttemptAt) { + validateIdentity(identity); + byte[] digest = requireDigest(requestDigest, "request digest"); + if (expectedAttemptCount < 0 + || maxAttempts < 1 + || expectedAttemptCount >= maxAttempts + || attemptedAt == null + || nextAttemptAt == null + || nextAttemptAt.isBefore(attemptedAt) + || reason == null + || reason.isBlank() + || reason.trim().length() > MAX_RECONCILIATION_REASON_LENGTH) { + throw new IllegalArgumentException( + "Connect-token reconciliation attempt is outside its bounds"); + } + Instant persistedAttemptAt = attemptedAt.truncatedTo(ChronoUnit.MICROS); + Instant persistedNextAttemptAt = nextAttemptAt.truncatedTo(ChronoUnit.MICROS); + if (persistedNextAttemptAt.isBefore(persistedAttemptAt)) { + throw new IllegalArgumentException( + "Connect-token reconciliation times are not ordered at database precision"); + } + + Record changed = + dsl.fetchOne( + "UPDATE " + + OPERATION_TABLE + + " SET reconciliation_attempt_count = reconciliation_attempt_count + 1, " + + "last_reconciliation_attempt_at = CAST(? AS TIMESTAMPTZ), " + + "last_reconciliation_attempt_reason = ?, " + + "next_reconciliation_attempt_at = CAST(? AS TIMESTAMPTZ) " + + "WHERE account_id = ? AND tenant_id = ? AND connect_scope_hash = ? " + + "AND request_id = ? AND request_digest_version = ? AND request_digest = ? " + + "AND status IN ('PENDING', 'ABORTED') " + + "AND reconciliation_attempt_count = ? " + + "AND reconciliation_attempt_count < ? RETURNING operation_id", + persistedAttemptAt.atOffset(ZoneOffset.UTC).toString(), + reason.trim(), + persistedNextAttemptAt.atOffset(ZoneOffset.UTC).toString(), + identity.accountId(), + identity.tenantId(), + identity.connectScopeHash(), + identity.requestId(), + REQUEST_DIGEST_VERSION, + digest, + expectedAttemptCount, + maxAttempts); + if (changed == null) { + throw new IllegalStateException( + "Connect-token reconciliation operation changed or reached its caller attempt cap"); + } + AccountConnectTokenIssuanceOperation operation = + readOperation(identity) + .orElseThrow( + () -> + new IllegalStateException( + "Connect-token reconciliation attempt has no operation readback")); + if (!changed.get("operation_id", UUID.class).equals(operation.operationId()) + || operation.reconciliationAttemptCount() != expectedAttemptCount + 1 + || !persistedAttemptAt.equals(operation.lastReconciliationAttemptAt()) + || !reason.trim().equals(operation.lastReconciliationAttemptReason()) + || !persistedNextAttemptAt.equals(operation.nextReconciliationAttemptAt())) { + throw new IllegalStateException( + "Connect-token reconciliation attempt readback does not match the requested evidence"); + } + return operation; + } + + /** + * Stores one terminal deterministic result with its authenticated ciphertext in the caller's + * transaction. The operation must still be PENDING and the supplied AEAD binding must name that + * exact operation and caller identity. No method in this repository creates or recovers a JWT. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AccountConnectTokenResponseEnvelope completeWithEnvelope( + ClaimResult claim, + byte[] requestDigest, + Lifecycle terminalLifecycle, + String outcomeCode, + String tokenIdentity, + byte[] tokenHash, + AccountEnvelopeBinding binding, + AccountEncryptedEnvelope envelope) { + Objects.requireNonNull(claim, "claim"); + AccountConnectTokenIssuanceIdentity identity = requireClaimIdentity(claim); + byte[] digest = requireDigest(requestDigest, "request digest"); + validateTerminalResult(terminalLifecycle, outcomeCode, tokenIdentity, tokenHash); + Objects.requireNonNull(binding, "binding"); + validateConnectTokenEnvelope(envelope); + + AccountConnectTokenIssuanceOperation operation = requireClaimedOperation(claim, digest); + validateBinding(operation, identity, digest, binding); + requireEvidenceCompatible( + operation, + tokenIdentity, + copyNullable(tokenHash), + binding.contextEvidenceDigest(), + binding.authorityTupleDigest(), + binding.issuanceFenceDigest(), + binding.postconditionDigest()); + if (terminalLifecycle == Lifecycle.FAILED + && (operation.tokenIdentity() != null || operation.tokenHash() != null)) { + throw new EvidenceMismatchException( + "An operation with token identity evidence cannot become a deterministic failure"); + } + if (operation.lifecycle() != Lifecycle.PENDING) { + throw new IllegalStateException( + "Connect-token issuance operation is not pending and cannot be replaced"); + } + + Record changed = + dsl.fetchOne( + "UPDATE " + + OPERATION_TABLE + + " SET status = ?, outcome_code = ?, token_identity = ?, token_hash = ?, " + + "context_evidence_digest = ?, authority_tuple_digest = ?, " + + "issuance_fence_digest = ?, postcondition_digest = ? " + + "WHERE operation_id = ? AND account_id = ? AND tenant_id = ? " + + "AND connect_scope_hash = ? AND request_id = ? " + + "AND request_digest_version = ? AND request_digest = ? AND status = 'PENDING' " + + "RETURNING operation_id", + terminalLifecycle.name(), + outcomeCode, + tokenIdentity, + copyNullable(tokenHash), + binding.contextEvidenceDigest(), + binding.authorityTupleDigest(), + binding.issuanceFenceDigest(), + binding.postconditionDigest(), + operation.operationId(), + identity.accountId(), + identity.tenantId(), + identity.connectScopeHash(), + identity.requestId(), + REQUEST_DIGEST_VERSION, + digest); + if (changed == null + || !operation.operationId().equals(changed.get("operation_id", UUID.class))) { + throw new IllegalStateException("Connect-token issuance operation changed before completion"); + } + + return insertEnvelopeAndReadBack(operation, identity, digest, binding, envelope); + } + + /** + * Completes an ABORTED operation only after the caller has reconciled the ambiguous external + * result and revalidated the applicable authority. The expected reconciliation-attempt count is a + * compare-and-set fence: only the exact still-aborted receipt observed by that reconciliation may + * become terminal. This method never claims or replaces the first writer's request identity. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AccountConnectTokenResponseEnvelope resolveAbortedWithEnvelope( + AccountConnectTokenIssuanceIdentity identity, + byte[] requestDigest, + int expectedReconciliationAttemptCount, + Lifecycle terminalLifecycle, + String outcomeCode, + String tokenIdentity, + byte[] tokenHash, + AccountEnvelopeBinding binding, + AccountEncryptedEnvelope envelope) { + validateIdentity(identity); + byte[] digest = requireDigest(requestDigest, "request digest"); + if (expectedReconciliationAttemptCount < 1) { + throw new IllegalArgumentException( + "Aborted connect-token resolution requires a recorded reconciliation attempt"); + } + byte[] checkedTokenHash = copyNullable(tokenHash); + validateTerminalResult(terminalLifecycle, outcomeCode, tokenIdentity, checkedTokenHash); + Objects.requireNonNull(binding, "binding"); + validateConnectTokenEnvelope(envelope); + + AccountConnectTokenIssuanceOperation operation = + readOperation(identity) + .orElseThrow( + () -> + new IllegalStateException( + "Connect-token issuance operation is missing during reconciliation")); + requireDigestMatch(operation, digest); + if (operation.lifecycle() != Lifecycle.ABORTED + || operation.reconciliationAttemptCount() != expectedReconciliationAttemptCount) { + throw new IllegalStateException( + "Aborted connect-token operation changed before reconciliation resolution"); + } + validateBinding(operation, identity, digest, binding); + requireEvidenceCompatible( + operation, + tokenIdentity, + checkedTokenHash, + binding.contextEvidenceDigest(), + binding.authorityTupleDigest(), + binding.issuanceFenceDigest(), + binding.postconditionDigest()); + if (terminalLifecycle == Lifecycle.FAILED + && (operation.tokenIdentity() != null || operation.tokenHash() != null)) { + throw new EvidenceMismatchException( + "An operation with token identity evidence cannot become a deterministic failure"); + } + + Record changed = + dsl.fetchOne( + "UPDATE " + + OPERATION_TABLE + + " SET status = ?, outcome_code = ?, token_identity = ?, token_hash = ?, " + + "context_evidence_digest = ?, authority_tuple_digest = ?, " + + "issuance_fence_digest = ?, postcondition_digest = ? " + + "WHERE operation_id = ? AND account_id = ? AND tenant_id = ? " + + "AND connect_scope_hash = ? AND request_id = ? " + + "AND request_digest_version = ? AND request_digest = ? " + + "AND status = 'ABORTED' AND reconciliation_attempt_count = ? " + + "RETURNING operation_id", + terminalLifecycle.name(), + outcomeCode, + tokenIdentity, + checkedTokenHash, + binding.contextEvidenceDigest(), + binding.authorityTupleDigest(), + binding.issuanceFenceDigest(), + binding.postconditionDigest(), + operation.operationId(), + identity.accountId(), + identity.tenantId(), + identity.connectScopeHash(), + identity.requestId(), + REQUEST_DIGEST_VERSION, + digest, + expectedReconciliationAttemptCount); + if (changed == null + || !operation.operationId().equals(changed.get("operation_id", UUID.class))) { + throw new IllegalStateException( + "Aborted connect-token operation changed before reconciliation resolution"); + } + + AccountConnectTokenIssuanceOperation resolved = + readOperation(identity) + .orElseThrow( + () -> + new IllegalStateException( + "Resolved connect-token operation has no durable readback")); + if (!resolved.operationId().equals(operation.operationId()) + || !MessageDigest.isEqual(resolved.requestDigest(), digest) + || resolved.lifecycle() != terminalLifecycle + || !Objects.equals(resolved.outcomeCode(), outcomeCode) + || !Objects.equals(resolved.tokenIdentity(), tokenIdentity) + || !sameNullableDigest(resolved.tokenHash(), checkedTokenHash) + || !sameNullableDigest(resolved.contextEvidenceDigest(), binding.contextEvidenceDigest()) + || !sameNullableDigest(resolved.authorityTupleDigest(), binding.authorityTupleDigest()) + || !sameNullableDigest(resolved.issuanceFenceDigest(), binding.issuanceFenceDigest()) + || !sameNullableDigest(resolved.postconditionDigest(), binding.postconditionDigest()) + || resolved.reconciliationAttemptCount() != expectedReconciliationAttemptCount) { + throw new IllegalStateException( + "Resolved connect-token operation readback differs from reconciled evidence"); + } + return insertEnvelopeAndReadBack(resolved, identity, digest, binding, envelope); + } + + private AccountConnectTokenResponseEnvelope insertEnvelopeAndReadBack( + AccountConnectTokenIssuanceOperation operation, + AccountConnectTokenIssuanceIdentity identity, + byte[] digest, + AccountEnvelopeBinding binding, + AccountEncryptedEnvelope envelope) { + int inserted = + dsl.execute( + "INSERT INTO " + + ENVELOPE_TABLE + + " (operation_id, operation_kind, account_id, tenant_id, connect_scope_hash, " + + "request_id, request_digest_version, request_digest, format_version, key_id, " + + "purpose, nonce, ciphertext, context_evidence_digest, " + + "authority_tuple_digest, issuance_fence_digest, postcondition_digest) " + + "VALUES (?, 'CONNECT_TOKEN_ISSUANCE', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + operation.operationId(), + identity.accountId(), + identity.tenantId(), + identity.connectScopeHash(), + identity.requestId(), + REQUEST_DIGEST_VERSION, + digest, + envelope.formatVersion(), + envelope.keyId(), + envelope.purpose().name(), + envelope.nonce(), + envelope.ciphertext(), + binding.contextEvidenceDigest(), + binding.authorityTupleDigest(), + binding.issuanceFenceDigest(), + binding.postconditionDigest()); + if (inserted != 1) { + throw new IllegalStateException( + "Connect-token response envelope was not stored exactly once"); + } + + AccountConnectTokenResponseEnvelope stored = + readResponseEnvelope(identity, digest, binding) + .orElseThrow( + () -> + new IllegalStateException( + "Connect-token response envelope has no exact durable readback")); + if (!stored.operationId().equals(operation.operationId()) + || !stored.binding().equals(binding) + || !stored.envelope().equals(envelope)) { + throw new IllegalStateException( + "Connect-token response envelope readback differs from the requested envelope"); + } + return stored; + } + + /** + * Reads the exact terminal operation and its only response envelope. A pending or unresolved + * aborted operation returns empty only when it has no response envelope; an absent envelope for a + * terminal result or an envelope attached to nonterminal state is ambiguous and fails closed. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readResponseEnvelope( + AccountConnectTokenIssuanceIdentity identity, + byte[] requestDigest, + AccountEnvelopeBinding binding) { + validateIdentity(identity); + byte[] digest = requireDigest(requestDigest, "request digest"); + Objects.requireNonNull(binding, "binding"); + AccountConnectTokenIssuanceOperation operation = + readOperation(identity) + .orElseThrow( + () -> + new IllegalStateException( + "Connect-token issuance operation is missing during envelope readback")); + requireDigestMatch(operation, digest); + validateBinding(operation, identity, digest, binding); + + Record row = + dsl.fetchOne( + "SELECT operation_id, operation_kind, account_id, tenant_id, connect_scope_hash, " + + "request_id, request_digest_version, request_digest, format_version, key_id, " + + "purpose, nonce, ciphertext, context_evidence_digest, " + + "authority_tuple_digest, issuance_fence_digest, postcondition_digest " + + "FROM " + + ENVELOPE_TABLE + + " WHERE operation_id = ?", + operation.operationId()); + boolean terminal = + operation.lifecycle() == Lifecycle.COMMITTED || operation.lifecycle() == Lifecycle.FAILED; + if (!terminal) { + if (row != null) { + throw new IllegalStateException( + "Nonterminal connect-token operation unexpectedly owns a response envelope"); + } + return Optional.empty(); + } + if (row == null) { + throw new IllegalStateException( + "Terminal connect-token issuance result has no response envelope"); + } + + requireEnvelopeIdentity(row, operation, identity, digest, binding); + AccountEnvelopePurpose purpose; + try { + purpose = AccountEnvelopePurpose.valueOf(requiredText(row, "purpose")); + } catch (RuntimeException exception) { + throw new IllegalStateException("Stored connect-token response purpose is invalid"); + } + if (purpose != AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE) { + throw new IllegalStateException("Stored response envelope has the wrong purpose"); + } + AccountEncryptedEnvelope encrypted = + new AccountEncryptedEnvelope( + requiredInt(row, "format_version"), + requiredText(row, "key_id"), + purpose, + requiredBytes(row, "nonce"), + requiredBytes(row, "ciphertext")); + return Optional.of( + new AccountConnectTokenResponseEnvelope(operation.operationId(), binding, encrypted)); + } + + private Optional readOperation( + AccountConnectTokenIssuanceIdentity identity) { + Record row = + dsl.fetchOne( + "SELECT operation_id, account_id, tenant_id, connect_scope_hash, request_id, " + + "request_digest_version, request_digest, status, outcome_code, token_identity, " + + "token_hash, context_evidence_digest, authority_tuple_digest, " + + "issuance_fence_digest, postcondition_digest, reconciliation_attempt_count, " + + "last_reconciliation_attempt_at, last_reconciliation_attempt_reason, " + + "next_reconciliation_attempt_at, created_at, updated_at FROM " + + OPERATION_TABLE + + " WHERE account_id = ? AND tenant_id = ? AND connect_scope_hash = ? " + + "AND request_id = ?", + identity.accountId(), + identity.tenantId(), + identity.connectScopeHash(), + identity.requestId()); + return row == null ? Optional.empty() : Optional.of(toOperation(row, identity)); + } + + private static AccountConnectTokenIssuanceOperation toOperation( + Record row, AccountConnectTokenIssuanceIdentity identity) { + long accountId = requiredLong(row, "account_id"); + long tenantId = requiredLong(row, "tenant_id"); + String scopeHash = requiredText(row, "connect_scope_hash"); + String requestId = requiredText(row, "request_id"); + if (accountId != identity.accountId() + || tenantId != identity.tenantId() + || !scopeHash.equals(identity.connectScopeHash()) + || !requestId.equals(identity.requestId())) { + throw new IllegalStateException("Connect-token issuance readback identity does not match"); + } + return new AccountConnectTokenIssuanceOperation( + requiredUuid(row, "operation_id"), + accountId, + tenantId, + scopeHash, + requestId, + requiredInt(row, "request_digest_version"), + requiredBytes(row, "request_digest"), + Lifecycle.fromDatabase(requiredText(row, "status")), + row.get("outcome_code", String.class), + row.get("token_identity", String.class), + row.get("token_hash", byte[].class), + row.get("context_evidence_digest", byte[].class), + row.get("authority_tuple_digest", byte[].class), + row.get("issuance_fence_digest", byte[].class), + row.get("postcondition_digest", byte[].class), + requiredInt(row, "reconciliation_attempt_count"), + toInstant(row.get("last_reconciliation_attempt_at", OffsetDateTime.class)), + row.get("last_reconciliation_attempt_reason", String.class), + toInstant(row.get("next_reconciliation_attempt_at", OffsetDateTime.class)), + toInstant(row.get("created_at", OffsetDateTime.class)), + toInstant(row.get("updated_at", OffsetDateTime.class))); + } + + private static void requireEnvelopeIdentity( + Record row, + AccountConnectTokenIssuanceOperation operation, + AccountConnectTokenIssuanceIdentity identity, + byte[] digest, + AccountEnvelopeBinding binding) { + if (!operation.operationId().equals(requiredUuid(row, "operation_id")) + || !"CONNECT_TOKEN_ISSUANCE".equals(requiredText(row, "operation_kind")) + || requiredLong(row, "account_id") != identity.accountId() + || requiredLong(row, "tenant_id") != identity.tenantId() + || !identity.connectScopeHash().equals(requiredText(row, "connect_scope_hash")) + || !identity.requestId().equals(requiredText(row, "request_id")) + || requiredInt(row, "request_digest_version") != REQUEST_DIGEST_VERSION + || !MessageDigest.isEqual(digest, requiredBytes(row, "request_digest")) + || !MessageDigest.isEqual( + operation.contextEvidenceDigest(), requiredBytes(row, "context_evidence_digest")) + || !MessageDigest.isEqual( + operation.authorityTupleDigest(), requiredBytes(row, "authority_tuple_digest")) + || !MessageDigest.isEqual( + operation.issuanceFenceDigest(), requiredBytes(row, "issuance_fence_digest")) + || !MessageDigest.isEqual( + operation.postconditionDigest(), requiredBytes(row, "postcondition_digest"))) { + throw new IllegalStateException( + "Connect-token response envelope identity or evidence readback does not match"); + } + validateBinding(operation, identity, digest, binding); + } + + private static void validateBinding( + AccountConnectTokenIssuanceOperation operation, + AccountConnectTokenIssuanceIdentity identity, + byte[] digest, + AccountEnvelopeBinding binding) { + if (binding.operationKind() != AccountEnvelopeBinding.OperationKind.CONNECT_TOKEN_ISSUANCE + || !operation.operationId().toString().equals(binding.operationId()) + || !identity.requestId().equals(binding.requestId()) + || !Long.toString(identity.accountId()).equals(binding.accountId()) + || !Long.toString(identity.tenantId()).equals(binding.tenantId()) + || !identity.connectScopeId().equals(binding.connectScopeId()) + || !MessageDigest.isEqual(digest, binding.requestDigest())) { + throw new EvidenceMismatchException( + "Connect-token response binding does not name the exact operation identity and digest"); + } + if (operation.lifecycle() == Lifecycle.COMMITTED || operation.lifecycle() == Lifecycle.FAILED) { + requireOperationEvidence(operation, binding); + } + } + + private static void requireOperationEvidence( + AccountConnectTokenIssuanceOperation operation, AccountEnvelopeBinding binding) { + if (!MessageDigest.isEqual(operation.contextEvidenceDigest(), binding.contextEvidenceDigest()) + || !MessageDigest.isEqual(operation.authorityTupleDigest(), binding.authorityTupleDigest()) + || !MessageDigest.isEqual(operation.issuanceFenceDigest(), binding.issuanceFenceDigest()) + || !MessageDigest.isEqual(operation.postconditionDigest(), binding.postconditionDigest())) { + throw new EvidenceMismatchException( + "Connect-token response binding differs from committed operation evidence"); + } + } + + private static void validateTerminalResult( + Lifecycle lifecycle, String outcomeCode, String tokenIdentity, byte[] tokenHash) { + if (lifecycle == Lifecycle.COMMITTED) { + if (!"SUCCESS".equals(outcomeCode) + || tokenIdentity == null + || tokenIdentity.isBlank() + || tokenIdentity.length() > MAX_TOKEN_IDENTITY_LENGTH + || tokenIdentity.indexOf('\0') >= 0 + || tokenHash == null + || tokenHash.length != DIGEST_LENGTH_BYTES) { + throw new IllegalArgumentException("Committed connect-token result evidence is invalid"); + } + return; + } + if (lifecycle != Lifecycle.FAILED + || outcomeCode == null + || outcomeCode.isBlank() + || outcomeCode.length() > MAX_OUTCOME_CODE_LENGTH + || outcomeCode.indexOf('\0') >= 0 + || "SUCCESS".equals(outcomeCode) + || tokenIdentity != null + || tokenHash != null) { + throw new IllegalArgumentException("Deterministic connect-token failure evidence is invalid"); + } + } + + private AccountConnectTokenIssuanceIdentity requireClaimIdentity(ClaimResult claim) { + Objects.requireNonNull(claim, "claim"); + if (claim.disposition() != ClaimDisposition.CLAIMED) { + throw new IllegalStateException( + "Only the first connect-token operation claimant may record evidence or an outcome"); + } + return claim.identity(); + } + + private AccountConnectTokenIssuanceOperation requireClaimedOperation( + ClaimResult claim, byte[] digest) { + AccountConnectTokenIssuanceIdentity identity = requireClaimIdentity(claim); + AccountConnectTokenIssuanceOperation operation = + readOperation(identity) + .orElseThrow( + () -> + new IllegalStateException( + "Connect-token issuance operation is missing during owner update")); + if (!claim.operation().operationId().equals(operation.operationId())) { + throw new IllegalStateException("Connect-token claim no longer owns the durable operation"); + } + requireDigestMatch(operation, digest); + return operation; + } + + private static void requireEvidenceCompatible( + AccountConnectTokenIssuanceOperation operation, + String tokenIdentity, + byte[] tokenHash, + byte[] contextEvidenceDigest, + byte[] authorityTupleDigest, + byte[] issuanceFenceDigest, + byte[] postconditionDigest) { + if ((operation.tokenIdentity() != null + && tokenIdentity != null + && !operation.tokenIdentity().equals(tokenIdentity)) + || differsWhenProvided(operation.tokenHash(), tokenHash) + || differsWhenProvided(operation.contextEvidenceDigest(), contextEvidenceDigest) + || differsWhenProvided(operation.authorityTupleDigest(), authorityTupleDigest) + || differsWhenProvided(operation.issuanceFenceDigest(), issuanceFenceDigest) + || differsWhenProvided(operation.postconditionDigest(), postconditionDigest)) { + throw new EvidenceMismatchException( + "Connect-token issuance evidence is already bound to different values"); + } + } + + private static boolean differsWhenProvided(byte[] stored, byte[] candidate) { + return stored != null && candidate != null && !MessageDigest.isEqual(stored, candidate); + } + + private static boolean sameNullableDigest(byte[] left, byte[] right) { + return left == null ? right == null : right != null && MessageDigest.isEqual(left, right); + } + + private static void validateConnectTokenEnvelope(AccountEncryptedEnvelope envelope) { + Objects.requireNonNull(envelope, "envelope"); + if (envelope.purpose() != AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE) { + throw new EvidenceMismatchException( + "Connect-token issuance cannot store an envelope for another purpose"); + } + } + + private static void requireDigestMatch( + AccountConnectTokenIssuanceOperation operation, byte[] expectedDigest) { + if (!MessageDigest.isEqual(operation.requestDigest(), expectedDigest)) { + throw new IdempotencyConflictException( + "Connect-token request identity was reused with a different digest"); + } + } + + private static void validateIdentity(AccountConnectTokenIssuanceIdentity identity) { + Objects.requireNonNull(identity, "identity"); + } + + private static byte[] requireDigest(byte[] value, String fieldName) { + Objects.requireNonNull(value, fieldName); + if (value.length != DIGEST_LENGTH_BYTES) { + throw new IllegalArgumentException(fieldName + " must be 32 bytes"); + } + return Arrays.copyOf(value, value.length); + } + + private static byte[] optionalDigest(byte[] value, String fieldName) { + return value == null ? null : requireDigest(value, fieldName); + } + + private static byte[] copyNullable(byte[] value) { + return value == null ? null : value.clone(); + } + + private static Instant toInstant(OffsetDateTime value) { + return value == null ? null : JooqPersistenceSupport.toInstant(value); + } + + private static long requiredLong(Record row, String field) { + Long value = row.get(field, Long.class); + if (value == null) { + throw new IllegalStateException("Stored connect-token issuance field is missing: " + field); + } + return value; + } + + private static int requiredInt(Record row, String field) { + Integer value = row.get(field, Integer.class); + if (value == null) { + throw new IllegalStateException("Stored connect-token issuance field is missing: " + field); + } + return value; + } + + private static UUID requiredUuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + if (value == null) { + throw new IllegalStateException("Stored connect-token issuance field is missing: " + field); + } + return value; + } + + private static String requiredText(Record row, String field) { + String value = row.get(field, String.class); + if (value == null || value.isBlank()) { + throw new IllegalStateException("Stored connect-token issuance field is missing: " + field); + } + return value; + } + + private static byte[] requiredBytes(Record row, String field) { + byte[] value = row.get(field, byte[].class); + if (value == null) { + throw new IllegalStateException("Stored connect-token issuance field is missing: " + field); + } + return value; + } + + public enum ClaimDisposition { + CLAIMED, + REPLAYED + } + + public static final class ClaimResult { + private final ClaimDisposition disposition; + private final AccountConnectTokenIssuanceIdentity identity; + private final AccountConnectTokenIssuanceOperation operation; + + private ClaimResult( + ClaimDisposition disposition, + AccountConnectTokenIssuanceIdentity identity, + AccountConnectTokenIssuanceOperation operation) { + this.disposition = Objects.requireNonNull(disposition, "disposition"); + this.identity = Objects.requireNonNull(identity, "identity"); + this.operation = Objects.requireNonNull(operation, "operation"); + } + + public ClaimDisposition disposition() { + return disposition; + } + + public AccountConnectTokenIssuanceIdentity identity() { + return identity; + } + + public AccountConnectTokenIssuanceOperation operation() { + return operation; + } + } + + public static class IdempotencyConflictException extends RuntimeException { + public IdempotencyConflictException(String message) { + super(message); + } + } + + public static class EvidenceMismatchException extends RuntimeException { + public EvidenceMismatchException(String message) { + super(message); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenResponseEnvelope.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenResponseEnvelope.java new file mode 100644 index 0000000000..7bd6811f12 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenResponseEnvelope.java @@ -0,0 +1,25 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.security.AccountEncryptedEnvelope; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeBinding; +import net.firedevops.firemud.accountservice.security.AccountEnvelopePurpose; + +/** + * Exact persisted ciphertext plus the caller-verified binding needed for authenticated recovery. + */ +public record AccountConnectTokenResponseEnvelope( + UUID operationId, AccountEnvelopeBinding binding, AccountEncryptedEnvelope envelope) { + + public AccountConnectTokenResponseEnvelope { + Objects.requireNonNull(operationId, "operationId"); + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(envelope, "envelope"); + if (binding.operationKind() != AccountEnvelopeBinding.OperationKind.CONNECT_TOKEN_ISSUANCE + || !operationId.toString().equals(binding.operationId()) + || envelope.purpose() != AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE) { + throw new IllegalArgumentException("Connect-token response envelope binding is invalid"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepository.java new file mode 100644 index 0000000000..0c6b377335 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepository.java @@ -0,0 +1,449 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +/** + * Stores the durable Account-owned authority state for one verified Account/tenant pair. + * + *

This repository does not establish that a membership row, authority event, receipt, or other + * retained history is absent. Callers must establish those facts under the same Account fence + * before enrolling or returning a never-joined sequence-zero snapshot. + */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring transaction collaborator.") +public class AccountMembershipPairAuthorityRepository { + private static final String TABLE = "account_membership_pair_authority"; + private static final String COLUMNS = + "account_uuid, tenant_uuid, legacy_tenant_id, tenant_provenance_kind, " + + "tenant_source_operation_id, tenant_provenance_digest, membership_exists, " + + "membership_version, membership_authority_generation, last_event_sequence, " + + "last_event_id, last_event_digest, last_transition_invalidated"; + private static final Pattern SHA256_DIGEST = Pattern.compile("^sha256:[0-9a-f]{64}$"); + + private final DSLContext dsl; + + public AccountMembershipPairAuthorityRepository(DSLContext dsl) { + this.dsl = dsl; + } + + /** + * Enrolls the positive never-joined baseline after the caller independently proves the pair + * association and absence of membership and committed history under its Account fence. + * + *

Repeated enrollment succeeds only when the complete persisted row still exactly equals the + * baseline and verified tenant provenance. A progressed row fails closed and is never reset. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PairAuthority enrollAbsence( + UUID accountUuid, UUID tenantUuid, VerifiedTenantProvenance provenance) { + requireScope(accountUuid, tenantUuid); + Objects.requireNonNull(provenance, "verified tenant provenance is required"); + + PairAuthority baseline = + new PairAuthority( + accountUuid, tenantUuid, provenance, false, 1L, 1L, 0L, null, null, false); + int inserted = + dsl.execute( + "INSERT INTO " + + TABLE + + " (account_uuid, tenant_uuid, legacy_tenant_id, tenant_provenance_kind, " + + "tenant_source_operation_id, tenant_provenance_digest, membership_exists, " + + "membership_version, membership_authority_generation, last_event_sequence, " + + "last_event_id, last_event_digest, last_transition_invalidated) " + + "VALUES (?, ?, ?, ?, ?, ?, FALSE, 1, 1, 0, NULL, NULL, FALSE) " + + "ON CONFLICT DO NOTHING", + accountUuid, + tenantUuid, + provenance.legacyTenantId(), + provenance.kind().name(), + provenance.sourceOperationId(), + provenance.digest()); + if (inserted != 0 && inserted != 1) { + throw new IllegalStateException("Account membership pair baseline insert was not singular"); + } + + Optional readback = readForUpdate(accountUuid, tenantUuid); + if (readback.isEmpty()) { + if (readByLegacyScopeForUpdate(accountUuid, provenance.legacyTenantId()).isPresent()) { + throw new IllegalStateException( + "Verified Account tenant association conflicts with an existing pair authority"); + } + throw new IllegalStateException("Account membership pair baseline readback is absent"); + } + + PairAuthority current = readback.orElseThrow(); + requireSameImmutableIdentity(baseline, current); + if (!baseline.equals(current)) { + throw new IllegalStateException( + "Account membership pair baseline readback differs from the exact absence state"); + } + return current; + } + + /** + * Enrolls a retained existing membership from caller-verified positive current receipt/event + * readback. This path is limited to approved retained associations and never manufactures a + * sequence-zero baseline or changes supplied counters. + * + *

The caller must prove that the supplied version, generation, event checkpoint, and tenant + * provenance describe the same current retained membership under its Account fence. An existing + * row is accepted only when its complete state is exactly equal to that proof. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PairAuthority enrollProvenPositive( + UUID accountUuid, + UUID tenantUuid, + VerifiedTenantProvenance provenance, + ProvenPositiveCheckpoint checkpoint) { + requireScope(accountUuid, tenantUuid); + Objects.requireNonNull(provenance, "verified tenant provenance is required"); + Objects.requireNonNull(checkpoint, "verified positive membership checkpoint is required"); + if (provenance.kind() != TenantProvenanceKind.APPROVED_RETAINED) { + throw new IllegalArgumentException( + "Positive retained membership requires approved retained tenant provenance"); + } + + PairAuthority expected = + new PairAuthority( + accountUuid, + tenantUuid, + provenance, + true, + checkpoint.membershipVersion(), + checkpoint.membershipAuthorityGeneration(), + checkpoint.eventSequence(), + checkpoint.eventId(), + checkpoint.eventDigest(), + checkpoint.lastTransitionInvalidated()); + int inserted = + dsl.execute( + "INSERT INTO " + + TABLE + + " (account_uuid, tenant_uuid, legacy_tenant_id, tenant_provenance_kind, " + + "tenant_source_operation_id, tenant_provenance_digest, membership_exists, " + + "membership_version, membership_authority_generation, last_event_sequence, " + + "last_event_id, last_event_digest, last_transition_invalidated) " + + "VALUES (?, ?, ?, ?, ?, ?, TRUE, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT DO NOTHING", + accountUuid, + tenantUuid, + provenance.legacyTenantId(), + provenance.kind().name(), + provenance.sourceOperationId(), + provenance.digest(), + checkpoint.membershipVersion(), + checkpoint.membershipAuthorityGeneration(), + checkpoint.eventSequence(), + checkpoint.eventId(), + checkpoint.eventDigest(), + checkpoint.lastTransitionInvalidated()); + if (inserted != 0 && inserted != 1) { + throw new IllegalStateException("Positive Account membership pair insert was not singular"); + } + + Optional readback = readForUpdate(accountUuid, tenantUuid); + if (readback.isEmpty()) { + if (readByLegacyScopeForUpdate(accountUuid, provenance.legacyTenantId()).isPresent()) { + throw new IllegalStateException( + "Verified Account tenant association conflicts with an existing pair authority"); + } + throw new IllegalStateException("Positive Account membership pair readback is absent"); + } + PairAuthority current = readback.orElseThrow(); + if (!expected.equals(current)) { + throw new IllegalStateException( + "Retained Account membership pair differs from verified positive current evidence"); + } + return current; + } + + /** + * Locks and reads one exact pair row. An empty result is not proof that membership or committed + * stream history is absent; the caller owns that cross-table proof. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readForUpdate(UUID accountUuid, UUID tenantUuid) { + requireScope(accountUuid, tenantUuid); + Record row = + dsl.fetchOne( + "SELECT " + + COLUMNS + + " FROM " + + TABLE + + " WHERE account_uuid = ? AND tenant_uuid = ? " + + "FOR UPDATE", + accountUuid, + tenantUuid); + return Optional.ofNullable(row).map(this::mapRow); + } + + /** + * Advances one exact pair state to its next committed authority event. + * + *

The supplied expected value is compared with a locked full-row readback, and the update + * repeats the prior version, sequence, generation, membership state, event identity, and + * immutable provenance as a compare-and-advance guard. The surrounding Account transaction must + * commit the corresponding membership mutation and event atomically. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PairAuthority commitTransition(PairAuthority expected, PairTransition transition) { + Objects.requireNonNull(expected, "expected pair authority is required"); + Objects.requireNonNull(transition, "pair authority transition is required"); + long nextVersion = increment(expected.membershipVersion(), "membership version"); + long nextSequence = increment(expected.lastEventSequence(), "membership event sequence"); + long nextGeneration = + transition.callerBoundAuthorityInvalidated() + ? increment(expected.membershipAuthorityGeneration(), "membership authority generation") + : expected.membershipAuthorityGeneration(); + if (transition.eventSequence() != nextSequence) { + throw new IllegalArgumentException("Membership event sequence must advance by exactly one"); + } + if (expected.lastEventSequence() == 0L && !transition.membershipExists()) { + throw new IllegalArgumentException( + "The first committed membership event must create membership"); + } + + PairAuthority current = + readForUpdate(expected.accountUuid(), expected.tenantUuid()) + .orElseThrow( + () -> new IllegalStateException("Account membership pair authority is missing")); + if (!expected.equals(current)) { + throw new IllegalStateException("Stale or contradictory Account membership pair authority"); + } + + int changed = + dsl.execute( + "UPDATE " + + TABLE + + " SET membership_exists = ?, membership_version = ?, " + + "membership_authority_generation = ?, last_event_sequence = ?, " + + "last_event_id = ?, last_event_digest = ?, last_transition_invalidated = ? " + + "WHERE account_uuid = ? AND tenant_uuid = ? AND legacy_tenant_id = ? " + + "AND tenant_provenance_kind = ? AND tenant_source_operation_id = ? " + + "AND tenant_provenance_digest = ? AND membership_exists = ? " + + "AND membership_version = ? AND membership_authority_generation = ? " + + "AND last_event_sequence = ? AND last_event_id IS NOT DISTINCT FROM ? " + + "AND last_event_digest IS NOT DISTINCT FROM ? " + + "AND last_transition_invalidated = ?", + transition.membershipExists(), + nextVersion, + nextGeneration, + nextSequence, + transition.eventId(), + transition.eventDigest(), + transition.callerBoundAuthorityInvalidated(), + expected.accountUuid(), + expected.tenantUuid(), + expected.provenance().legacyTenantId(), + expected.provenance().kind().name(), + expected.provenance().sourceOperationId(), + expected.provenance().digest(), + expected.membershipExists(), + expected.membershipVersion(), + expected.membershipAuthorityGeneration(), + expected.lastEventSequence(), + expected.lastEventId(), + expected.lastEventDigest(), + expected.lastTransitionInvalidated()); + if (changed != 1) { + throw new IllegalStateException( + "Stale Account membership pair authority compare-and-advance"); + } + + PairAuthority advanced = + readForUpdate(expected.accountUuid(), expected.tenantUuid()) + .orElseThrow( + () -> + new IllegalStateException( + "Advanced Account membership pair readback is absent")); + PairAuthority required = + new PairAuthority( + expected.accountUuid(), + expected.tenantUuid(), + expected.provenance(), + transition.membershipExists(), + nextVersion, + nextGeneration, + nextSequence, + transition.eventId(), + transition.eventDigest(), + transition.callerBoundAuthorityInvalidated()); + if (!required.equals(advanced)) { + throw new IllegalStateException("Advanced Account membership pair readback differs"); + } + return advanced; + } + + private Optional readByLegacyScopeForUpdate( + UUID accountUuid, long legacyTenantId) { + Record row = + dsl.fetchOne( + "SELECT " + + COLUMNS + + " FROM " + + TABLE + + " WHERE account_uuid = ? AND legacy_tenant_id = ? " + + "FOR UPDATE", + accountUuid, + legacyTenantId); + return Optional.ofNullable(row).map(this::mapRow); + } + + private PairAuthority mapRow(Record row) { + try { + return new PairAuthority( + row.get("account_uuid", UUID.class), + row.get("tenant_uuid", UUID.class), + new VerifiedTenantProvenance( + row.get("legacy_tenant_id", Long.class), + TenantProvenanceKind.valueOf(row.get("tenant_provenance_kind", String.class)), + row.get("tenant_source_operation_id", UUID.class), + row.get("tenant_provenance_digest", String.class)), + row.get("membership_exists", Boolean.class), + row.get("membership_version", Long.class), + row.get("membership_authority_generation", Long.class), + row.get("last_event_sequence", Long.class), + row.get("last_event_id", String.class), + row.get("last_event_digest", String.class), + row.get("last_transition_invalidated", Boolean.class)); + } catch (RuntimeException corrupt) { + throw new IllegalStateException( + "Persisted Account membership pair authority is contradictory", corrupt); + } + } + + private void requireSameImmutableIdentity(PairAuthority expected, PairAuthority actual) { + if (!expected.accountUuid().equals(actual.accountUuid()) + || !expected.tenantUuid().equals(actual.tenantUuid()) + || !expected.provenance().equals(actual.provenance())) { + throw new IllegalStateException( + "Account membership pair authority conflicts with verified association provenance"); + } + } + + private void requireScope(UUID accountUuid, UUID tenantUuid) { + if (accountUuid == null || tenantUuid == null) { + throw new IllegalArgumentException("Canonical Account and tenant UUIDs are required"); + } + } + + private long increment(long value, String label) { + try { + return Math.addExact(value, 1L); + } catch (ArithmeticException overflow) { + throw new IllegalStateException("Account membership " + label + " is exhausted", overflow); + } + } + + private static void requireDigest(String digest, String label) { + if (digest == null || !SHA256_DIGEST.matcher(digest).matches()) { + throw new IllegalArgumentException(label + " must be a canonical lowercase SHA-256 digest"); + } + } + + public enum TenantProvenanceKind { + APPROVED_RETAINED, + FRESH_GAME_DESIGN + } + + /** Immutable verified tenant-association facts supplied by the caller. */ + public record VerifiedTenantProvenance( + long legacyTenantId, TenantProvenanceKind kind, UUID sourceOperationId, String digest) { + public VerifiedTenantProvenance { + if (legacyTenantId <= 0L || kind == null || sourceOperationId == null) { + throw new IllegalArgumentException("Verified Account tenant provenance is incomplete"); + } + requireDigest(digest, "Tenant provenance digest"); + } + } + + /** Exact durable state for one canonical Account/tenant pair. */ + public record PairAuthority( + UUID accountUuid, + UUID tenantUuid, + VerifiedTenantProvenance provenance, + boolean membershipExists, + long membershipVersion, + long membershipAuthorityGeneration, + long lastEventSequence, + String lastEventId, + String lastEventDigest, + boolean lastTransitionInvalidated) { + public PairAuthority { + if (accountUuid == null + || tenantUuid == null + || provenance == null + || membershipVersion <= 0L + || membershipAuthorityGeneration <= 0L + || lastEventSequence < 0L) { + throw new IllegalArgumentException("Account membership pair authority state is incomplete"); + } + if (lastEventSequence == 0L) { + if (membershipExists + || lastEventId != null + || lastEventDigest != null + || lastTransitionInvalidated) { + throw new IllegalArgumentException( + "Sequence-zero pair authority cannot claim membership or event evidence"); + } + } else if (lastEventId == null + || lastEventId.isBlank() + || lastEventId.length() > 512 + || lastEventDigest == null) { + throw new IllegalArgumentException( + "Positive pair authority sequence requires event evidence"); + } else { + requireDigest(lastEventDigest, "Membership event digest"); + } + } + } + + /** Caller-selected immutable event evidence for one transition. */ + public record PairTransition( + boolean membershipExists, + long eventSequence, + String eventId, + String eventDigest, + boolean callerBoundAuthorityInvalidated) { + public PairTransition { + if (eventSequence <= 0L || eventId == null || eventId.isBlank() || eventId.length() > 512) { + throw new IllegalArgumentException("Membership transition event identity is incomplete"); + } + requireDigest(eventDigest, "Membership transition event digest"); + } + } + + /** + * Exact positive current membership state supplied by verified retained receipt/event readback. + */ + public record ProvenPositiveCheckpoint( + long membershipVersion, + long membershipAuthorityGeneration, + long eventSequence, + String eventId, + String eventDigest, + boolean lastTransitionInvalidated) { + public ProvenPositiveCheckpoint { + if (membershipVersion <= 0L + || membershipAuthorityGeneration <= 0L + || eventSequence <= 0L + || eventId == null + || eventId.isBlank() + || eventId.length() > 512) { + throw new IllegalArgumentException("Verified positive membership checkpoint is incomplete"); + } + requireDigest(eventDigest, "Verified membership checkpoint digest"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptRepository.java index ef4bfaf8ef..07db5c69f1 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptRepository.java @@ -127,7 +127,9 @@ public MembershipTransitionReceipt appendTransition( * Reads and validates the latest provisional receipt. Empty does not prove a canonical * sequence-zero stream; existing rows without a receipt fail closed. */ - @Transactional(readOnly = true) + // A contradictory read is an expected fail-closed JOIN/reconciliation outcome. The caller + // records that outcome in its existing transaction; this read performs no mutation to undo. + @Transactional(readOnly = true, noRollbackFor = IllegalStateException.class) public Optional findLatestReceipt(long accountId, long tenantId) { ReceiptSnapshot snapshot = readLatestReceiptSnapshot(accountId, tenantId); if (snapshot == null) { @@ -171,7 +173,10 @@ public void assertNewMembershipTransitionCanStart(long accountId, long tenantId) } /** Requires positive retained history before reactivating an existing inactive membership. */ - @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + @Transactional( + propagation = Propagation.MANDATORY, + readOnly = true, + noRollbackFor = IllegalStateException.class) public MembershipTransitionReceipt requireInactiveMembershipHistory( AccountTenantMembership membership) { if (membership == null diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantIdentityResolver.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantIdentityResolver.java new file mode 100644 index 0000000000..261a856e26 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantIdentityResolver.java @@ -0,0 +1,62 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository.ApprovedAssociation; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +/** + * Resolves retained numeric tenant keys through an approved, provenance-backed UUID association. + */ +@Repository +public class AccountTenantIdentityResolver { + private final ApprovedLegacyTenantAssociationRepository associations; + private final LegacyTenantSourceEvidence sourceEvidence; + private final String workloadNamespace; + + public AccountTenantIdentityResolver( + ApprovedLegacyTenantAssociationRepository associations, + LegacyTenantSourceEvidence sourceEvidence, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this.associations = associations; + this.sourceEvidence = sourceEvidence; + this.workloadNamespace = workloadNamespace; + } + + /** + * Returns the canonical UUID and complete immutable migration provenance for a retained key. The + * association and current retained-row evidence are read in the caller's transaction. The caller + * must provide the isolation and fence for its complete authority snapshot; this read is not + * itself a membership-authority snapshot. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ApprovedAssociation resolve(long legacyTenantId) { + if (legacyTenantId <= 0) { + throw new IllegalArgumentException("positive retained Account tenant key is required"); + } + if (workloadNamespace == null || workloadNamespace.isBlank()) { + throw new IllegalStateException("Account workload namespace is not configured"); + } + + Optional stored = associations.findByLegacyTenantId(legacyTenantId); + if (stored.isEmpty()) { + throw new IllegalStateException("approved Account tenant association is absent"); + } + ApprovedAssociation association = stored.orElseThrow(); + if (association.legacyTenantId() != legacyTenantId + || association.canonicalTenantId() == null + || !workloadNamespace.equals(association.targetNamespace())) { + throw new IllegalStateException("approved Account tenant association is mismatched"); + } + + String currentEvidenceDigest = sourceEvidence.digest(legacyTenantId); + if (!Objects.equals(association.accountEvidenceDigest(), currentEvidenceDigest)) { + throw new IllegalStateException( + "approved Account source evidence differs from retained rows"); + } + return association; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRoleSnapshotRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRoleSnapshotRepository.java new file mode 100644 index 0000000000..ec4e2c3245 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRoleSnapshotRepository.java @@ -0,0 +1,289 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +/** + * Persists the current, Account-owned role snapshot for one tenant membership. + * + *

The snapshot header is deliberately separate from its normalized role rows. Its presence and + * version therefore distinguish an authoritative empty role set from a retained membership row for + * which role evidence was never recorded. + */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class AccountTenantMembershipRoleSnapshotRepository { + private static final int MAX_ROLE_IDENTIFIER_LENGTH = 128; + private static final String SNAPSHOT_TABLE = "account_tenant_membership_role_snapshots"; + private static final String ROLE_TABLE = "account_tenant_membership_role_snapshot_roles"; + private static final Comparator ROLE_IDENTIFIER_BYTE_COMPARATOR = + AccountTenantMembershipRoleSnapshotRepository::compareRoleIdentifierBytes; + + private final DSLContext dsl; + + public AccountTenantMembershipRoleSnapshotRepository(DSLContext dsl) { + this.dsl = dsl; + } + + /** + * Reads the exact current snapshot while locking its membership/header evidence. + * + *

An absent header is returned as empty: callers must not infer roles from the global account + * role or the membership admission flag. A present header with no role rows is a valid, + * authoritative empty snapshot. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findForUpdate( + long accountId, long tenantId, long membershipId, long expectedMembershipVersion) { + validatePositive(accountId, "account ID"); + validatePositive(tenantId, "tenant ID"); + validatePositive(membershipId, "membership ID"); + validatePositive(expectedMembershipVersion, "membership version"); + + Record membership = + dsl.fetchOne( + "SELECT id, account_id, tenant_id, membership_version " + + "FROM account_tenant_membership " + + "WHERE id = ? AND account_id = ? AND tenant_id = ? FOR UPDATE", + membershipId, + accountId, + tenantId); + if (membership == null) { + throw new IllegalStateException("Account membership identity is missing or mismatched"); + } + requireExactPositive(membership.get("id", Long.class), membershipId, "membership ID"); + requireExactPositive(membership.get("account_id", Long.class), accountId, "account ID"); + requireExactPositive(membership.get("tenant_id", Long.class), tenantId, "tenant ID"); + requireExactPositive( + membership.get("membership_version", Long.class), + expectedMembershipVersion, + "membership version"); + + Record header = + dsl.fetchOne( + "SELECT membership_id, snapshot_version FROM " + + SNAPSHOT_TABLE + + " WHERE membership_id = ? FOR UPDATE", + membershipId); + if (header == null) { + return Optional.empty(); + } + requireExactPositive(header.get("membership_id", Long.class), membershipId, "membership ID"); + requireExactPositive( + header.get("snapshot_version", Long.class), + expectedMembershipVersion, + "role snapshot version"); + + List roles = + dsl + .fetch( + "SELECT role_identifier FROM " + + ROLE_TABLE + + " WHERE membership_id = ? AND snapshot_version = ?" + + " ORDER BY convert_to(role_identifier, 'UTF8')", + membershipId, + expectedMembershipVersion) + .stream() + .map(row -> requiredRole(row.get("role_identifier", String.class))) + .toList(); + return Optional.of( + new RoleSnapshot(accountId, tenantId, membershipId, expectedMembershipVersion, roles)); + } + + /** Replaces one exact current snapshot in the caller's JOIN transaction. */ + @Transactional(propagation = Propagation.MANDATORY) + public RoleSnapshot replace( + AccountTenantMembership membership, + long snapshotVersion, + Collection roleIdentifiers) { + if (membership == null + || membership.getAccount() == null + || membership.getAccount().getId() == null + || membership.getId() == null + || membership.getTenantId() == null) { + throw new IllegalArgumentException("A persisted Account membership is required"); + } + long accountId = membership.getAccount().getId(); + long tenantId = membership.getTenantId(); + long membershipId = membership.getId(); + validatePositive(accountId, "account ID"); + validatePositive(tenantId, "tenant ID"); + validatePositive(membershipId, "membership ID"); + validatePositive(snapshotVersion, "role snapshot version"); + List canonicalRoles = canonicalizeRoleSet(roleIdentifiers); + + Record current = + dsl.fetchOne( + "SELECT id, account_id, tenant_id, membership_version " + + "FROM account_tenant_membership " + + "WHERE id = ? AND account_id = ? AND tenant_id = ? FOR UPDATE", + membershipId, + accountId, + tenantId); + if (current == null) { + throw new IllegalStateException("Account membership identity is missing or mismatched"); + } + requireExactPositive( + current.get("membership_version", Long.class), snapshotVersion, "membership version"); + + dsl.execute("DELETE FROM " + ROLE_TABLE + " WHERE membership_id = ?", membershipId); + int headerRows = + dsl.execute( + "INSERT INTO " + + SNAPSHOT_TABLE + + " (membership_id, snapshot_version) VALUES (?, ?) " + + "ON CONFLICT (membership_id) DO UPDATE SET snapshot_version = EXCLUDED.snapshot_version", + membershipId, + snapshotVersion); + if (headerRows != 1) { + throw new IllegalStateException("Account role snapshot header was not persisted"); + } + for (String role : canonicalRoles) { + int roleRows = + dsl.execute( + "INSERT INTO " + + ROLE_TABLE + + " (membership_id, snapshot_version, role_identifier) VALUES (?, ?, ?)", + membershipId, + snapshotVersion, + role); + if (roleRows != 1) { + throw new IllegalStateException("Account role snapshot row was not persisted"); + } + } + return new RoleSnapshot(accountId, tenantId, membershipId, snapshotVersion, canonicalRoles); + } + + /** Sorts and validates a role set exactly as the canonical unsigned-byte comparator requires. */ + public static List canonicalizeRoleSet(Collection roleIdentifiers) { + if (roleIdentifiers == null) { + throw new IllegalArgumentException("Role snapshot is required"); + } + List canonical = new ArrayList<>(roleIdentifiers.size()); + Set seen = new HashSet<>(); + for (String role : roleIdentifiers) { + validateRoleIdentifier(role); + if (!seen.add(role)) { + throw new IllegalArgumentException("Role snapshot contains a duplicate role"); + } + canonical.add(role); + } + canonical.sort(ROLE_IDENTIFIER_BYTE_COMPARATOR); + return List.copyOf(canonical); + } + + /** Validates a persisted/readback array without repairing its order or duplicate evidence. */ + public static List requireCanonicalRoleSet(Collection roleIdentifiers) { + if (roleIdentifiers == null) { + throw new IllegalArgumentException("Role snapshot is required"); + } + List validated = new ArrayList<>(roleIdentifiers.size()); + String previous = null; + for (String role : roleIdentifiers) { + validateRoleIdentifier(role); + if (previous != null && compareRoleIdentifierBytes(previous, role) >= 0) { + throw new IllegalArgumentException("Role snapshot is not strictly bytewise sorted"); + } + validated.add(role); + previous = role; + } + return List.copyOf(validated); + } + + /** Compares identifier bytes as unsigned values, with the shorter prefix first. */ + public static int compareRoleIdentifierBytes(String left, String right) { + if (left == null || right == null) { + throw new IllegalArgumentException("Role identifier is required"); + } + validateRoleIdentifier(left); + validateRoleIdentifier(right); + byte[] leftBytes = left.getBytes(StandardCharsets.US_ASCII); + byte[] rightBytes = right.getBytes(StandardCharsets.US_ASCII); + int shared = Math.min(leftBytes.length, rightBytes.length); + for (int index = 0; index < shared; index++) { + int comparison = + Integer.compare( + Byte.toUnsignedInt(leftBytes[index]), Byte.toUnsignedInt(rightBytes[index])); + if (comparison != 0) { + return comparison; + } + } + return Integer.compare(leftBytes.length, rightBytes.length); + } + + private static void validateRoleIdentifier(String role) { + if (role == null || role.isEmpty() || role.length() > MAX_ROLE_IDENTIFIER_LENGTH) { + throw new IllegalArgumentException("Role identifier must match the canonical ASCII grammar"); + } + char first = role.charAt(0); + if (!isAsciiLetter(first)) { + throw new IllegalArgumentException("Role identifier must match the canonical ASCII grammar"); + } + for (int index = 1; index < role.length(); index++) { + char character = role.charAt(index); + if (!isAsciiLetter(character) + && !isAsciiDigit(character) + && character != '_' + && character != '-') { + throw new IllegalArgumentException( + "Role identifier must match the canonical ASCII grammar"); + } + } + } + + private static boolean isAsciiLetter(char character) { + return (character >= 'A' && character <= 'Z') || (character >= 'a' && character <= 'z'); + } + + private static boolean isAsciiDigit(char character) { + return character >= '0' && character <= '9'; + } + + private static String requiredRole(String role) { + validateRoleIdentifier(role); + return role; + } + + private static void validatePositive(long value, String name) { + if (value <= 0L) { + throw new IllegalArgumentException(name + " must be positive"); + } + } + + private static void requireExactPositive(Long actual, long expected, String name) { + if (actual == null || actual <= 0L || actual.longValue() != expected) { + throw new IllegalStateException( + "Account role snapshot " + name + " is missing or mismatched"); + } + } + + public record RoleSnapshot( + long accountId, long tenantId, long membershipId, long snapshotVersion, List roles) { + public RoleSnapshot { + if (accountId <= 0L || tenantId <= 0L || membershipId <= 0L || snapshotVersion <= 0L) { + throw new IllegalArgumentException("Role snapshot identity and version must be positive"); + } + roles = requireCanonicalRoleSet(roles); + } + + @Override + public List roles() { + return List.copyOf(roles); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/ApprovedLegacyTenantAssociationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/ApprovedLegacyTenantAssociationRepository.java index 98240cbae1..7fe9d53d71 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/ApprovedLegacyTenantAssociationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/ApprovedLegacyTenantAssociationRepository.java @@ -23,14 +23,17 @@ public class ApprovedLegacyTenantAssociationRepository { private final DSLContext dsl; private final LegacyTenantSourceEvidence sourceEvidence; private final String workloadNamespace; + private final AccountAuthorityGenerationRepository authorityGenerationRepository; public ApprovedLegacyTenantAssociationRepository( DSLContext dsl, LegacyTenantSourceEvidence sourceEvidence, - @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace, + AccountAuthorityGenerationRepository authorityGenerationRepository) { this.dsl = dsl; this.sourceEvidence = sourceEvidence; this.workloadNamespace = workloadNamespace; + this.authorityGenerationRepository = authorityGenerationRepository; } @Transactional(isolation = Isolation.SERIALIZABLE) @@ -48,6 +51,7 @@ public ApprovedAssociation importApproved( throw new IllegalStateException( "approved Account tenant association conflicts with readback"); } + authorityGenerationRepository.initializeTenantIfAbsent(expected.canonicalTenantId()); return existing.orElseThrow(); } @@ -81,6 +85,7 @@ public ApprovedAssociation importApproved( if (!committed.equals(expected)) { throw new IllegalStateException("approved association readback differs"); } + authorityGenerationRepository.initializeTenantIfAbsent(expected.canonicalTenantId()); return committed; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountEncryptedEnvelope.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountEncryptedEnvelope.java new file mode 100644 index 0000000000..51fa050053 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountEncryptedEnvelope.java @@ -0,0 +1,87 @@ +package net.firedevops.firemud.accountservice.security; + +import java.util.Arrays; +import java.util.Objects; +import java.util.regex.Pattern; + +/** Persistable encrypted response data. Plaintext and key material are never included. */ +public record AccountEncryptedEnvelope( + int formatVersion, + String keyId, + AccountEnvelopePurpose purpose, + byte[] nonce, + byte[] ciphertext) { + + public static final int CURRENT_FORMAT_VERSION = 1; + public static final int NONCE_LENGTH_BYTES = 12; + public static final int AUTHENTICATION_TAG_LENGTH_BYTES = 16; + public static final int MAX_PLAINTEXT_LENGTH_BYTES = 64 * 1024; + public static final int MAX_CIPHERTEXT_LENGTH_BYTES = + MAX_PLAINTEXT_LENGTH_BYTES + AUTHENTICATION_TAG_LENGTH_BYTES; + + private static final Pattern KEY_ID_PATTERN = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + + public AccountEncryptedEnvelope { + if (formatVersion != CURRENT_FORMAT_VERSION) { + throw new IllegalArgumentException("Unsupported envelope format version"); + } + Objects.requireNonNull(keyId, "keyId"); + if (!KEY_ID_PATTERN.matcher(keyId).matches()) { + throw new IllegalArgumentException("Invalid envelope key ID"); + } + Objects.requireNonNull(purpose, "purpose"); + Objects.requireNonNull(nonce, "nonce"); + Objects.requireNonNull(ciphertext, "ciphertext"); + if (nonce.length != NONCE_LENGTH_BYTES + || ciphertext.length < AUTHENTICATION_TAG_LENGTH_BYTES + || ciphertext.length > MAX_CIPHERTEXT_LENGTH_BYTES) { + throw new IllegalArgumentException("Invalid envelope length"); + } + nonce = Arrays.copyOf(nonce, nonce.length); + ciphertext = Arrays.copyOf(ciphertext, ciphertext.length); + } + + @Override + public byte[] nonce() { + return nonce.clone(); + } + + @Override + public byte[] ciphertext() { + return ciphertext.clone(); + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof AccountEncryptedEnvelope that)) { + return false; + } + return formatVersion == that.formatVersion + && keyId.equals(that.keyId) + && purpose == that.purpose + && Arrays.equals(nonce, that.nonce) + && Arrays.equals(ciphertext, that.ciphertext); + } + + @Override + public int hashCode() { + int result = Objects.hash(formatVersion, keyId, purpose); + result = 31 * result + Arrays.hashCode(nonce); + result = 31 * result + Arrays.hashCode(ciphertext); + return result; + } + + @Override + public String toString() { + return "AccountEncryptedEnvelope{formatVersion=" + + formatVersion + + ", keyId='" + + keyId + + "', purpose=" + + purpose + + ", encryptedData=}"; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountEnvelopeBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountEnvelopeBinding.java new file mode 100644 index 0000000000..c7043bbe58 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountEnvelopeBinding.java @@ -0,0 +1,157 @@ +package net.firedevops.firemud.accountservice.security; + +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; + +/** + * Exact Account operation evidence authenticated as byte-framed AEAD additional data. Evidence + * digests are Account-computed, versioned fixed-length digests of the exact canonical request, + * context, authority tuple, Account-local issuance CAS fence, and committed postconditions. That + * local fence is not the gameplay-connect token's replayAdmissionFence or a JWT authority claim. + */ +public record AccountEnvelopeBinding( + OperationKind operationKind, + String operationId, + String requestId, + String accountId, + String tenantId, + String connectScopeId, + String sourceConnectOperationId, + byte[] requestDigest, + byte[] contextEvidenceDigest, + byte[] authorityTupleDigest, + byte[] issuanceFenceDigest, + byte[] postconditionDigest) { + + private static final int DIGEST_LENGTH_BYTES = 32; + private static final int MAX_TEXT_LENGTH_BYTES = 4096; + + public enum OperationKind { + CONNECT_TOKEN_ISSUANCE, + BARE_LOGIN_EXCHANGE + } + + public AccountEnvelopeBinding { + Objects.requireNonNull(operationKind, "operationKind"); + operationId = requireText(operationId, "operationId"); + requestId = requireText(requestId, "requestId"); + accountId = requireText(accountId, "accountId"); + tenantId = requireText(tenantId, "tenantId"); + connectScopeId = requireText(connectScopeId, "connectScopeId"); + if (operationKind == OperationKind.BARE_LOGIN_EXCHANGE) { + sourceConnectOperationId = requireText(sourceConnectOperationId, "sourceConnectOperationId"); + } else if (sourceConnectOperationId != null) { + throw new IllegalArgumentException("sourceConnectOperationId is only valid for bare LOGIN"); + } + requestDigest = copyDigest(requestDigest, "requestDigest"); + contextEvidenceDigest = copyDigest(contextEvidenceDigest, "contextEvidenceDigest"); + authorityTupleDigest = copyDigest(authorityTupleDigest, "authorityTupleDigest"); + issuanceFenceDigest = copyDigest(issuanceFenceDigest, "issuanceFenceDigest"); + postconditionDigest = copyDigest(postconditionDigest, "postconditionDigest"); + } + + @Override + public byte[] requestDigest() { + return requestDigest.clone(); + } + + @Override + public byte[] contextEvidenceDigest() { + return contextEvidenceDigest.clone(); + } + + @Override + public byte[] authorityTupleDigest() { + return authorityTupleDigest.clone(); + } + + @Override + public byte[] issuanceFenceDigest() { + return issuanceFenceDigest.clone(); + } + + @Override + public byte[] postconditionDigest() { + return postconditionDigest.clone(); + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof AccountEnvelopeBinding that)) { + return false; + } + return operationKind == that.operationKind + && operationId.equals(that.operationId) + && requestId.equals(that.requestId) + && accountId.equals(that.accountId) + && tenantId.equals(that.tenantId) + && connectScopeId.equals(that.connectScopeId) + && Objects.equals(sourceConnectOperationId, that.sourceConnectOperationId) + && Arrays.equals(requestDigest, that.requestDigest) + && Arrays.equals(contextEvidenceDigest, that.contextEvidenceDigest) + && Arrays.equals(authorityTupleDigest, that.authorityTupleDigest) + && Arrays.equals(issuanceFenceDigest, that.issuanceFenceDigest) + && Arrays.equals(postconditionDigest, that.postconditionDigest); + } + + @Override + public int hashCode() { + int result = + Objects.hash( + operationKind, + operationId, + requestId, + accountId, + tenantId, + connectScopeId, + sourceConnectOperationId); + result = 31 * result + Arrays.hashCode(requestDigest); + result = 31 * result + Arrays.hashCode(contextEvidenceDigest); + result = 31 * result + Arrays.hashCode(authorityTupleDigest); + result = 31 * result + Arrays.hashCode(issuanceFenceDigest); + result = 31 * result + Arrays.hashCode(postconditionDigest); + return result; + } + + @Override + public String toString() { + return "AccountEnvelopeBinding{operationKind=" + operationKind + ", evidence=}"; + } + + private static String requireText(String value, String fieldName) { + Objects.requireNonNull(value, fieldName); + if (value.isBlank() + || hasUnpairedSurrogate(value) + || value.getBytes(StandardCharsets.UTF_8).length > MAX_TEXT_LENGTH_BYTES) { + throw new IllegalArgumentException("Invalid " + fieldName); + } + return value; + } + + private static byte[] copyDigest(byte[] value, String fieldName) { + Objects.requireNonNull(value, fieldName); + if (value.length != DIGEST_LENGTH_BYTES) { + throw new IllegalArgumentException(fieldName + " must be 32 bytes"); + } + return Arrays.copyOf(value, value.length); + } + + private static boolean hasUnpairedSurrogate(String value) { + 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))) { + return true; + } + index++; + } else if (Character.isLowSurrogate(current)) { + return true; + } + } + return false; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountEnvelopeCrypto.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountEnvelopeCrypto.java new file mode 100644 index 0000000000..3921381452 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountEnvelopeCrypto.java @@ -0,0 +1,476 @@ +package net.firedevops.firemud.accountservice.security; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.GeneralSecurityException; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import javax.crypto.AEADBadTagException; +import javax.crypto.Cipher; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +/** + * Account-local AES-256-GCM for bounded credential-bearing response envelopes. The mounted manifest + * is read for every operation so atomic rotation and key removal take effect immediately. Callers + * must provide an Account-only mounted path and must read back the exact durable operation/envelope + * before using {@link #decrypt} for recovery. + * + *

Manifest v1 is strict ASCII (an ASCII subset of UTF-8), terminated by one LF: + * + *

+ * version=1
+ * activeKeyId=k2
+ * key:k1:bare-login=<43-character-unpadded-base64url>
+ * key:k1:connect-token=<43-character-unpadded-base64url>
+ * key:k2:bare-login=<43-character-unpadded-base64url>
+ * key:k2:connect-token=<43-character-unpadded-base64url>
+ * 
+ * + * Every key ID must have one independent 32-byte key for each purpose. The active ID is used for + * new writes; retained older IDs are decrypt-only. No default key or classpath fallback exists. + */ +public final class AccountEnvelopeCrypto { + public static final String KEY_RING_PATH_ENVIRONMENT_VARIABLE = + "FIREMUD_AUTH_RESPONSE_ENVELOPE_KEY_RING_PATH"; + public static final String EXPECTED_MOUNT_PATH = + "/var/run/secrets/firemud/response-envelope-key-ring/manifest.v1"; + + private static final int MAX_MANIFEST_LENGTH_BYTES = 64 * 1024; + private static final int AES_KEY_LENGTH_BYTES = 32; + private static final int GCM_TAG_LENGTH_BITS = 128; + private static final int MAX_AAD_FIELD_LENGTH_BYTES = 4096; + private static final byte[] AAD_DOMAIN = + "firemud-account-response-envelope/v1".getBytes(StandardCharsets.US_ASCII); + private static final SecureRandom SECURE_RANDOM = new SecureRandom(); + + private final Path manifestPath; + + public AccountEnvelopeCrypto(Path mountedManifestPath) { + Objects.requireNonNull(mountedManifestPath, "mountedManifestPath"); + if (!mountedManifestPath.isAbsolute()) { + throw new IllegalArgumentException("The Account key-ring path must be absolute"); + } + this.manifestPath = mountedManifestPath; + } + + /** Creates the runtime implementation from the required Account-only mount environment value. */ + public static AccountEnvelopeCrypto fromEnvironment() { + String configuredPath = System.getenv(KEY_RING_PATH_ENVIRONMENT_VARIABLE); + if (configuredPath == null || configuredPath.isBlank()) { + throw failure(AccountEnvelopeCryptoException.Failure.KEY_RING_UNAVAILABLE); + } + try { + return new AccountEnvelopeCrypto(Path.of(configuredPath)); + } catch (RuntimeException exception) { + throw failure(AccountEnvelopeCryptoException.Failure.KEY_RING_UNAVAILABLE); + } + } + + public AccountEncryptedEnvelope encrypt( + AccountEnvelopePurpose purpose, AccountEnvelopeBinding binding, byte[] plaintext) { + Objects.requireNonNull(purpose, "purpose"); + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(plaintext, "plaintext"); + requirePurposeBinding(purpose, binding); + if (plaintext.length == 0 + || plaintext.length > AccountEncryptedEnvelope.MAX_PLAINTEXT_LENGTH_BYTES) { + throw failure(AccountEnvelopeCryptoException.Failure.INVALID_ENVELOPE); + } + + try (LoadedKeyRing keyRing = readKeyRing()) { + String keyId = keyRing.activeKeyId; + byte[] keyBytes = keyRing.keyBytes(keyId, purpose); + byte[] nonce = new byte[AccountEncryptedEnvelope.NONCE_LENGTH_BYTES]; + SECURE_RANDOM.nextBytes(nonce); + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init( + Cipher.ENCRYPT_MODE, + new SecretKeySpec(keyBytes, "AES"), + new GCMParameterSpec(GCM_TAG_LENGTH_BITS, nonce)); + cipher.updateAAD( + associatedData(AccountEncryptedEnvelope.CURRENT_FORMAT_VERSION, keyId, purpose, binding)); + byte[] ciphertext = cipher.doFinal(plaintext); + return new AccountEncryptedEnvelope( + AccountEncryptedEnvelope.CURRENT_FORMAT_VERSION, keyId, purpose, nonce, ciphertext); + } catch (AccountEnvelopeCryptoException exception) { + throw exception; + } catch (GeneralSecurityException exception) { + throw failure(AccountEnvelopeCryptoException.Failure.CRYPTO_OPERATION_FAILED); + } + } + + public byte[] decrypt( + AccountEncryptedEnvelope envelope, + AccountEnvelopePurpose expectedPurpose, + AccountEnvelopeBinding binding) { + Objects.requireNonNull(envelope, "envelope"); + Objects.requireNonNull(expectedPurpose, "expectedPurpose"); + Objects.requireNonNull(binding, "binding"); + requirePurposeBinding(expectedPurpose, binding); + if (envelope.purpose() != expectedPurpose) { + throw failure(AccountEnvelopeCryptoException.Failure.PURPOSE_MISMATCH); + } + + try (LoadedKeyRing keyRing = readKeyRing()) { + byte[] keyBytes = keyRing.keyBytes(envelope.keyId(), envelope.purpose()); + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init( + Cipher.DECRYPT_MODE, + new SecretKeySpec(keyBytes, "AES"), + new GCMParameterSpec(GCM_TAG_LENGTH_BITS, envelope.nonce())); + cipher.updateAAD( + associatedData(envelope.formatVersion(), envelope.keyId(), envelope.purpose(), binding)); + return cipher.doFinal(envelope.ciphertext()); + } catch (AEADBadTagException exception) { + throw failure(AccountEnvelopeCryptoException.Failure.AUTHENTICATION_FAILED); + } catch (AccountEnvelopeCryptoException exception) { + throw exception; + } catch (GeneralSecurityException exception) { + throw failure(AccountEnvelopeCryptoException.Failure.CRYPTO_OPERATION_FAILED); + } + } + + private LoadedKeyRing readKeyRing() { + byte[] manifest = null; + try { + if (!Files.isRegularFile(manifestPath)) { + throw failure(AccountEnvelopeCryptoException.Failure.KEY_RING_UNAVAILABLE); + } + try (InputStream input = Files.newInputStream(manifestPath)) { + manifest = input.readNBytes(MAX_MANIFEST_LENGTH_BYTES + 1); + } + if (manifest.length == 0 || manifest.length > MAX_MANIFEST_LENGTH_BYTES) { + throw failure(AccountEnvelopeCryptoException.Failure.KEY_RING_MALFORMED); + } + return parseManifest(manifest); + } catch (AccountEnvelopeCryptoException exception) { + throw exception; + } catch (IOException | SecurityException exception) { + throw failure(AccountEnvelopeCryptoException.Failure.KEY_RING_UNAVAILABLE); + } finally { + if (manifest != null) { + Arrays.fill(manifest, (byte) 0); + } + } + } + + private static LoadedKeyRing parseManifest(byte[] manifest) { + Map> keys = new HashMap<>(); + try { + int lineNumber = 0; + int lineStart = 0; + String activeKeyId = null; + ArrayList seenKeyMaterial = new ArrayList<>(); + if (manifest.length == 0 || manifest[manifest.length - 1] != '\n') { + throw failure(AccountEnvelopeCryptoException.Failure.KEY_RING_MALFORMED); + } + for (int index = 0; index < manifest.length; index++) { + byte value = manifest[index]; + if (value == '\r' || (value < 0x21 && value != '\n') || value > 0x7e) { + throw failure(AccountEnvelopeCryptoException.Failure.KEY_RING_MALFORMED); + } + if (value != '\n') { + continue; + } + if (index == lineStart) { + throw failure(AccountEnvelopeCryptoException.Failure.KEY_RING_MALFORMED); + } + lineNumber++; + if (lineNumber == 1) { + if (!lineEquals(manifest, lineStart, index, "version=1")) { + throw failure(AccountEnvelopeCryptoException.Failure.KEY_RING_MALFORMED); + } + } else if (lineNumber == 2) { + String line = asciiString(manifest, lineStart, index); + String prefix = "activeKeyId="; + if (!line.startsWith(prefix)) { + throw failure(AccountEnvelopeCryptoException.Failure.KEY_RING_MALFORMED); + } + activeKeyId = line.substring(prefix.length()); + if (!isValidKeyId(activeKeyId)) { + throw failure(AccountEnvelopeCryptoException.Failure.KEY_RING_MALFORMED); + } + } else { + byte[] keyBytes = parseKeyLine(manifest, lineStart, index); + String idAndPurpose = keyLineIdAndPurpose(manifest, lineStart, index); + int separator = idAndPurpose.indexOf('\u0000'); + String keyId = idAndPurpose.substring(0, separator); + AccountEnvelopePurpose purpose = + AccountEnvelopePurpose.fromManifestName(idAndPurpose.substring(separator + 1)); + for (byte[] existing : seenKeyMaterial) { + if (MessageDigest.isEqual(existing, keyBytes)) { + Arrays.fill(keyBytes, (byte) 0); + throw failure(AccountEnvelopeCryptoException.Failure.KEY_RING_MALFORMED); + } + } + EnumMap byPurpose = + keys.computeIfAbsent(keyId, ignored -> new EnumMap<>(AccountEnvelopePurpose.class)); + if (byPurpose.putIfAbsent(purpose, keyBytes) != null) { + Arrays.fill(keyBytes, (byte) 0); + throw failure(AccountEnvelopeCryptoException.Failure.KEY_RING_MALFORMED); + } + seenKeyMaterial.add(keyBytes); + } + lineStart = index + 1; + } + if (lineNumber < 3 || activeKeyId == null) { + throw failure(AccountEnvelopeCryptoException.Failure.KEY_RING_MALFORMED); + } + for (Map.Entry> entry : keys.entrySet()) { + if (entry.getValue().size() != AccountEnvelopePurpose.values().length) { + throw failure(AccountEnvelopeCryptoException.Failure.KEY_RING_MALFORMED); + } + } + if (!keys.containsKey(activeKeyId)) { + throw failure(AccountEnvelopeCryptoException.Failure.KEY_RING_MALFORMED); + } + return new LoadedKeyRing(activeKeyId, keys); + } catch (AccountEnvelopeCryptoException exception) { + wipeKeys(keys); + throw exception; + } catch (RuntimeException exception) { + wipeKeys(keys); + throw failure(AccountEnvelopeCryptoException.Failure.KEY_RING_MALFORMED); + } + } + + private static byte[] parseKeyLine(byte[] manifest, int start, int end) { + String identity = keyLineIdAndPurpose(manifest, start, end); + int separator = identity.indexOf('\u0000'); + if (separator < 1 + || !isValidKeyId(identity.substring(0, separator)) + || AccountEnvelopePurpose.fromManifestName(identity.substring(separator + 1)) == null) { + throw failure(AccountEnvelopeCryptoException.Failure.KEY_RING_MALFORMED); + } + int equalsIndex = -1; + for (int index = start; index < end; index++) { + if (manifest[index] == '=') { + if (equalsIndex != -1) { + throw failure(AccountEnvelopeCryptoException.Failure.KEY_RING_MALFORMED); + } + equalsIndex = index; + } + } + int encodedLength = end - equalsIndex - 1; + if (equalsIndex < 0 || encodedLength != 43) { + throw failure(AccountEnvelopeCryptoException.Failure.KEY_RING_MALFORMED); + } + byte[] encoded = Arrays.copyOfRange(manifest, equalsIndex + 1, end); + byte[] keyBytes = null; + try { + keyBytes = Base64.getUrlDecoder().decode(encoded); + if (keyBytes.length != AES_KEY_LENGTH_BYTES + || !Arrays.equals(Base64.getUrlEncoder().withoutPadding().encode(keyBytes), encoded)) { + Arrays.fill(keyBytes, (byte) 0); + throw failure(AccountEnvelopeCryptoException.Failure.KEY_RING_MALFORMED); + } + return keyBytes; + } catch (IllegalArgumentException exception) { + if (keyBytes != null) { + Arrays.fill(keyBytes, (byte) 0); + } + throw failure(AccountEnvelopeCryptoException.Failure.KEY_RING_MALFORMED); + } finally { + Arrays.fill(encoded, (byte) 0); + } + } + + private static String keyLineIdAndPurpose(byte[] manifest, int start, int end) { + int equalsIndex = -1; + for (int index = start; index < end; index++) { + if (manifest[index] == '=') { + if (equalsIndex != -1) { + throw failure(AccountEnvelopeCryptoException.Failure.KEY_RING_MALFORMED); + } + equalsIndex = index; + } + } + if (equalsIndex <= start || !lineStartsWith(manifest, start, equalsIndex, "key:")) { + throw failure(AccountEnvelopeCryptoException.Failure.KEY_RING_MALFORMED); + } + int purposeSeparator = -1; + for (int index = start + 4; index < equalsIndex; index++) { + if (manifest[index] == ':') { + purposeSeparator = index; + break; + } + } + if (purposeSeparator <= start + 4 || purposeSeparator == equalsIndex - 1) { + throw failure(AccountEnvelopeCryptoException.Failure.KEY_RING_MALFORMED); + } + String keyId = asciiString(manifest, start + 4, purposeSeparator); + String purpose = asciiString(manifest, purposeSeparator + 1, equalsIndex); + return keyId + '\u0000' + purpose; + } + + private static byte[] associatedData( + int formatVersion, + String keyId, + AccountEnvelopePurpose purpose, + AccountEnvelopeBinding binding) { + try { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + DataOutputStream output = new DataOutputStream(bytes); + writeFrame(output, AAD_DOMAIN); + output.writeInt(formatVersion); + writeFrame(output, utf8(keyId)); + writeFrame(output, utf8(purpose.manifestName())); + writeFrame(output, utf8(binding.operationKind().name())); + writeFrame(output, utf8(binding.operationId())); + writeFrame(output, utf8(binding.requestId())); + writeFrame(output, utf8(binding.accountId())); + writeFrame(output, utf8(binding.tenantId())); + writeFrame(output, utf8(binding.connectScopeId())); + writeNullableFrame(output, nullableUtf8(binding.sourceConnectOperationId())); + writeFrame(output, binding.requestDigest()); + writeFrame(output, binding.contextEvidenceDigest()); + writeFrame(output, binding.authorityTupleDigest()); + writeFrame(output, binding.issuanceFenceDigest()); + writeFrame(output, binding.postconditionDigest()); + output.flush(); + if (bytes.size() > MAX_AAD_FIELD_LENGTH_BYTES * 8) { + throw failure(AccountEnvelopeCryptoException.Failure.INVALID_ENVELOPE); + } + return bytes.toByteArray(); + } catch (IOException exception) { + throw failure(AccountEnvelopeCryptoException.Failure.CRYPTO_OPERATION_FAILED); + } + } + + private static void writeFrame(DataOutputStream output, byte[] value) throws IOException { + if (value.length > MAX_AAD_FIELD_LENGTH_BYTES) { + throw failure(AccountEnvelopeCryptoException.Failure.INVALID_ENVELOPE); + } + output.writeInt(value.length); + output.write(value); + } + + private static void writeNullableFrame(DataOutputStream output, byte[] value) throws IOException { + if (value == null) { + output.writeInt(-1); + } else { + writeFrame(output, value); + } + } + + private static byte[] nullableUtf8(String value) { + return value == null ? null : utf8(value); + } + + private static byte[] utf8(String value) { + byte[] encoded = value.getBytes(StandardCharsets.UTF_8); + if (encoded.length > MAX_AAD_FIELD_LENGTH_BYTES) { + throw failure(AccountEnvelopeCryptoException.Failure.INVALID_ENVELOPE); + } + return encoded; + } + + private static void requirePurposeBinding( + AccountEnvelopePurpose purpose, AccountEnvelopeBinding binding) { + boolean matches = + (purpose == AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE + && binding.operationKind() + == AccountEnvelopeBinding.OperationKind.CONNECT_TOKEN_ISSUANCE) + || (purpose == AccountEnvelopePurpose.BARE_LOGIN_RESPONSE + && binding.operationKind() + == AccountEnvelopeBinding.OperationKind.BARE_LOGIN_EXCHANGE); + if (!matches) { + throw failure(AccountEnvelopeCryptoException.Failure.PURPOSE_MISMATCH); + } + } + + private static void wipeKeys(Map> keys) { + for (EnumMap byPurpose : keys.values()) { + for (byte[] keyBytes : byPurpose.values()) { + Arrays.fill(keyBytes, (byte) 0); + } + } + keys.clear(); + } + + private static boolean isValidKeyId(String keyId) { + if (keyId == null || keyId.isEmpty() || keyId.length() > 64) { + return false; + } + for (int index = 0; index < keyId.length(); index++) { + char value = keyId.charAt(index); + if (!((value >= 'a' && value <= 'z') + || (value >= 'A' && value <= 'Z') + || (value >= '0' && value <= '9') + || value == '_' + || value == '-')) { + return false; + } + } + return true; + } + + private static boolean lineEquals(byte[] source, int start, int end, String expected) { + byte[] expectedBytes = expected.getBytes(StandardCharsets.US_ASCII); + return end - start == expectedBytes.length + && regionMatches(source, start, expectedBytes, 0, expectedBytes.length); + } + + private static boolean lineStartsWith(byte[] source, int start, int end, String expected) { + byte[] expectedBytes = expected.getBytes(StandardCharsets.US_ASCII); + return end - start >= expectedBytes.length + && regionMatches(source, start, expectedBytes, 0, expectedBytes.length); + } + + private static boolean regionMatches( + byte[] source, int sourceOffset, byte[] target, int targetOffset, int length) { + for (int index = 0; index < length; index++) { + if (source[sourceOffset + index] != target[targetOffset + index]) { + return false; + } + } + return true; + } + + private static String asciiString(byte[] source, int start, int end) { + return new String(source, start, end - start, StandardCharsets.US_ASCII); + } + + private static AccountEnvelopeCryptoException failure( + AccountEnvelopeCryptoException.Failure failure) { + return new AccountEnvelopeCryptoException(failure); + } + + private static final class LoadedKeyRing implements AutoCloseable { + private final String activeKeyId; + private final Map> keys; + + private LoadedKeyRing( + String activeKeyId, Map> keys) { + this.activeKeyId = activeKeyId; + this.keys = keys; + } + + private byte[] keyBytes(String keyId, AccountEnvelopePurpose purpose) { + EnumMap byPurpose = keys.get(keyId); + byte[] keyBytes = byPurpose == null ? null : byPurpose.get(purpose); + if (keyBytes == null) { + throw failure(AccountEnvelopeCryptoException.Failure.KEY_UNAVAILABLE); + } + return keyBytes; + } + + @Override + public void close() { + wipeKeys(keys); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountEnvelopeCryptoException.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountEnvelopeCryptoException.java new file mode 100644 index 0000000000..a2b9a1d27d --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountEnvelopeCryptoException.java @@ -0,0 +1,27 @@ +package net.firedevops.firemud.accountservice.security; + +/** Fail-closed result for an unavailable key ring or an invalid envelope operation. */ +public final class AccountEnvelopeCryptoException extends RuntimeException { + private static final long serialVersionUID = 1L; + + public enum Failure { + KEY_RING_UNAVAILABLE, + KEY_RING_MALFORMED, + KEY_UNAVAILABLE, + INVALID_ENVELOPE, + PURPOSE_MISMATCH, + AUTHENTICATION_FAILED, + CRYPTO_OPERATION_FAILED + } + + private final Failure failure; + + AccountEnvelopeCryptoException(Failure failure) { + super("Account response-envelope operation failed: " + failure.name()); + this.failure = failure; + } + + public Failure failure() { + return failure; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountEnvelopePurpose.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountEnvelopePurpose.java new file mode 100644 index 0000000000..d8c11f3bfc --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountEnvelopePurpose.java @@ -0,0 +1,26 @@ +package net.firedevops.firemud.accountservice.security; + +/** The independently keyed response-envelope purposes owned by Account. */ +public enum AccountEnvelopePurpose { + CONNECT_TOKEN_RESPONSE("connect-token"), + BARE_LOGIN_RESPONSE("bare-login"); + + private final String manifestName; + + AccountEnvelopePurpose(String manifestName) { + this.manifestName = manifestName; + } + + String manifestName() { + return manifestName; + } + + static AccountEnvelopePurpose fromManifestName(String value) { + for (AccountEnvelopePurpose purpose : values()) { + if (purpose.manifestName.equals(value)) { + return purpose; + } + } + return null; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationService.java index efe53bbaf6..3a8ca69e0b 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationService.java @@ -18,12 +18,15 @@ import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceiptDigest; import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository.JoinAuditEvidence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.JoinOperation; import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository.JoinMembershipProof; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; @@ -54,8 +57,10 @@ public class AccountJoinReconciliationService { private final AccountJoinOperationRepository joinOperationRepository; private final AccountConnectScopeRepository connectScopeRepository; private final AccountTenantMembershipRepository membershipRepository; + private final AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository; private final AccountMembershipTransitionReceiptRepository transitionReceiptRepository; private final AccountAuditOutboxRepository auditOutboxRepository; + private final AccountMembershipAuthorityEventProducer membershipAuthorityEventProducer; private final TransactionTemplate joinTransactionTemplate; private final int batchSize; private final int maxAttempts; @@ -69,8 +74,10 @@ public AccountJoinReconciliationService( AccountJoinOperationRepository joinOperationRepository, AccountConnectScopeRepository connectScopeRepository, AccountTenantMembershipRepository membershipRepository, + AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository, AccountMembershipTransitionReceiptRepository transitionReceiptRepository, AccountAuditOutboxRepository auditOutboxRepository, + AccountMembershipAuthorityEventProducer membershipAuthorityEventProducer, MeterRegistry meterRegistry, PlatformTransactionManager transactionManager, @Value("${firemud.account.join-reconciliation.batch-size:50}") int batchSize, @@ -91,8 +98,10 @@ public AccountJoinReconciliationService( this.joinOperationRepository = joinOperationRepository; this.connectScopeRepository = connectScopeRepository; this.membershipRepository = membershipRepository; + this.roleSnapshotRepository = roleSnapshotRepository; this.transitionReceiptRepository = transitionReceiptRepository; this.auditOutboxRepository = auditOutboxRepository; + this.membershipAuthorityEventProducer = membershipAuthorityEventProducer; this.batchSize = batchSize; this.maxAttempts = maxAttempts; this.backoffMillis = backoffMillis; @@ -193,6 +202,28 @@ private ReconciliationResult reconcileLocked(JoinOperation candidate, Instant no } } + RoleSnapshot roleSnapshot = null; + if (unresolvedReason == null) { + try { + roleSnapshot = + roleSnapshotRepository + .findForUpdate( + operation.accountId(), + operation.tenantId(), + membership.membershipId(), + membership.membershipVersion()) + .orElse(null); + } catch (RuntimeException ex) { + unresolvedReason = "MEMBERSHIP_ROLE_SNAPSHOT_UNAVAILABLE"; + } + if (unresolvedReason == null && roleSnapshot == null) { + unresolvedReason = "MEMBERSHIP_ROLE_SNAPSHOT_ABSENT"; + } else if (unresolvedReason == null + && !roleSnapshotMatches(operation, membership, roleSnapshot)) { + unresolvedReason = "MEMBERSHIP_ROLE_SNAPSHOT_MISMATCH"; + } + } + if (unresolvedReason == null) { try { transitionReceipt = @@ -238,6 +269,24 @@ private ReconciliationResult reconcileLocked(JoinOperation candidate, Instant no return recordUnresolvedAttempt(operation, now, unresolvedReason); } + String eventRequestId = + "JOINED".equals(outcome) ? operation.requestId() : transitionReceipt.requestId(); + boolean callerBoundAuthorityInvalidated = + "MEMBERSHIP_REACTIVATED".equals(transitionReceipt.transitionType()); + try { + Checkpoint checkpoint = + membershipAuthorityEventProducer.requireCurrentMembershipEvent( + membership, roleSnapshot, eventRequestId, callerBoundAuthorityInvalidated); + if (checkpoint == null || checkpoint.outboxSequence() <= 0L) { + unresolvedReason = "MEMBERSHIP_AUTHORITY_EVENT_UNAVAILABLE"; + } + } catch (RuntimeException ex) { + unresolvedReason = "MEMBERSHIP_AUTHORITY_EVENT_UNAVAILABLE"; + } + if (unresolvedReason != null) { + return recordUnresolvedAttempt(operation, now, unresolvedReason); + } + joinOperationRepository.finish( operation.requestId(), "COMMITTED", @@ -339,6 +388,22 @@ private static boolean membershipMatches( && membership.membershipAuthorityGeneration() > 0; } + private static boolean roleSnapshotMatches( + JoinOperation operation, JoinMembershipProof membership, RoleSnapshot roleSnapshot) { + if (roleSnapshot.accountId() != operation.accountId() + || roleSnapshot.tenantId() != operation.tenantId() + || roleSnapshot.membershipId() != membership.membershipId() + || roleSnapshot.snapshotVersion() != membership.membershipVersion()) { + return false; + } + try { + AccountTenantMembershipRoleSnapshotRepository.requireCanonicalRoleSet(roleSnapshot.roles()); + return roleSnapshot.roles().contains("player"); + } catch (RuntimeException ex) { + return false; + } + } + private static boolean auditEnvelopeMatches( JoinOperation operation, JoinMembershipProof membership, AccountAuditEnvelope envelope) { if (!joinAuditEventId(operation.requestId()).equals(envelope.auditEventId()) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java new file mode 100644 index 0000000000..2370c3c4ea --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java @@ -0,0 +1,1344 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +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.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceipt; +import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceiptDigest; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.EventEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.JoinOperation; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairTransition; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.ProvenPositiveCheckpoint; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository.JoinMembershipProof; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository.ApprovedAssociation; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +/** Produces the Account-owned V33 authority event for an explicit public-production JOIN. */ +@Service +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected repositories are internal Spring collaborators.") +public class AccountMembershipAuthorityEventProducer { + private final AccountJoinOperationRepository joinOperationRepository; + private final AccountMembershipPairAuthorityRepository pairAuthorityRepository; + private final AccountRepository accountRepository; + private final AccountTenantIdentityResolver tenantIdentityResolver; + private final AccountAuthorityGenerationRepository authorityGenerationRepository; + private final AccountAuthorityOutboxRepository authorityOutboxRepository; + private final AccountMembershipTransitionReceiptRepository transitionReceiptRepository; + private final AccountTenantMembershipRepository membershipRepository; + private final AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository; + + public AccountMembershipAuthorityEventProducer( + AccountJoinOperationRepository joinOperationRepository, + AccountMembershipPairAuthorityRepository pairAuthorityRepository, + AccountRepository accountRepository, + AccountTenantIdentityResolver tenantIdentityResolver, + AccountAuthorityGenerationRepository authorityGenerationRepository, + AccountAuthorityOutboxRepository authorityOutboxRepository, + AccountMembershipTransitionReceiptRepository transitionReceiptRepository, + AccountTenantMembershipRepository membershipRepository, + AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository) { + this.joinOperationRepository = joinOperationRepository; + this.pairAuthorityRepository = pairAuthorityRepository; + this.accountRepository = accountRepository; + this.tenantIdentityResolver = tenantIdentityResolver; + this.authorityGenerationRepository = authorityGenerationRepository; + this.authorityOutboxRepository = authorityOutboxRepository; + this.transitionReceiptRepository = transitionReceiptRepository; + this.membershipRepository = membershipRepository; + this.roleSnapshotRepository = roleSnapshotRepository; + } + + /** + * Reads a positive current membership snapshot under the same Account-row fence used by JOIN. + * + *

This deliberately does not produce sequence-zero absence evidence. A missing row, receipt, + * role snapshot, generation tuple, event, or checkpoint is a denied snapshot. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PositiveMembershipSnapshot readCurrentPositiveMembershipSnapshot( + long accountId, long legacyTenantId) { + if (accountId <= 0L || legacyTenantId <= 0L) { + throw new IllegalArgumentException("Account and retained tenant identities must be positive"); + } + + // JOIN locks the Account row before the operation row and any membership evidence. + joinOperationRepository.lockAccount(accountId); + Identity identity = resolveIdentity(accountId, legacyTenantId); + JoinMembershipProof membership = + membershipRepository + .findJoinProofForUpdate(accountId, legacyTenantId) + .orElseThrow( + () -> new IllegalStateException("Current Account membership row is absent")); + if (membership.accountId() != accountId + || membership.tenantId() != legacyTenantId + || membership.membershipId() <= 0L + || membership.membershipVersion() <= 0L + || membership.membershipAuthorityGeneration() <= 0L + || !"ACTIVE".equals(membership.lifecycleState()) + || !membership.gameplayAdmissionAllowed() + || !"EXPLICIT_JOIN".equals(membership.authorityProvenance())) { + throw new IllegalStateException( + "Current Account membership is not a positive active explicit membership"); + } + + RoleSnapshot roles = + roleSnapshotRepository + .findForUpdate( + accountId, + legacyTenantId, + membership.membershipId(), + membership.membershipVersion()) + .orElseThrow( + () -> + new IllegalStateException( + "Current Account membership role snapshot is absent")); + List exactRoles; + try { + exactRoles = + AccountTenantMembershipRoleSnapshotRepository.requireCanonicalRoleSet(roles.roles()); + } catch (RuntimeException exception) { + throw new IllegalStateException("Current Account role snapshot is not canonical", exception); + } + if (roles.accountId() != accountId + || roles.tenantId() != legacyTenantId + || roles.membershipId() != membership.membershipId() + || roles.snapshotVersion() != membership.membershipVersion() + || !exactRoles.contains("player")) { + throw new IllegalStateException( + "Current Account role snapshot differs from its exact active membership"); + } + + MembershipTransitionReceipt transitionReceipt = + transitionReceiptRepository + .findLatestReceipt(accountId, legacyTenantId) + .orElseThrow( + () -> + new IllegalStateException( + "Current Account membership has no positive transition receipt")); + if (!MembershipTransitionReceiptDigest.receiptStreamKey(accountId, legacyTenantId) + .equals(transitionReceipt.receiptStreamKey()) + || transitionReceipt.receiptSequence() <= 0L + || transitionReceipt.receiptId() == null + || transitionReceipt.receiptDigest() == null + || !MembershipTransitionReceiptDigest.EVIDENCE_STATUS.equals( + transitionReceipt.evidenceStatus()) + || (!"MEMBERSHIP_JOINED".equals(transitionReceipt.transitionType()) + && !"MEMBERSHIP_REACTIVATED".equals(transitionReceipt.transitionType())) + || transitionReceipt.requestId() == null + || transitionReceipt.requestId().isBlank() + || transitionReceipt.membershipId() != membership.membershipId()) { + throw new IllegalStateException( + "Current Account membership transition receipt is incomplete or mismatched"); + } + + CompositeSnapshot authoritySnapshot = readSnapshot(identity); + ScopeState membershipAuthority = only(authoritySnapshot.memberships(), "membership"); + requireMatchingFence(authoritySnapshot, membershipAuthority, identity.accountUuid()); + if (membershipAuthority.generation() != membership.membershipAuthorityGeneration()) { + throw new IllegalStateException( + "Current Account membership differs from its V31 authority generation"); + } + + String streamKey = membershipStreamKey(identity); + Checkpoint checkpoint = + authorityOutboxRepository + .readCheckpoint(streamKey) + .orElseThrow( + () -> + new IllegalStateException("Current Account membership has no V33 checkpoint")); + if (checkpoint.outboxSequence() <= 0L) { + throw new IllegalStateException("Current Account membership checkpoint is not positive"); + } + Event event = + authorityOutboxRepository + .findEvent(streamKey, checkpoint.outboxSequence()) + .orElseThrow( + () -> new IllegalStateException("Current Account V33 checkpoint has no event")); + if (!checkpointMatches(checkpoint, event)) { + throw new IllegalStateException( + "Current Account membership checkpoint differs from its event"); + } + MembershipEvent verified = verifyStoredEvent(event, identity, event.requestId()); + if (!transitionReceipt.requestId().equals(verified.requestId())) { + throw new IllegalStateException( + "Current Account membership receipt differs from its latest V33 event"); + } + requireCurrentMembershipEvent( + identity, + membership.membershipId(), + membership.lifecycleState(), + membership.gameplayAdmissionAllowed(), + membership.membershipVersion(), + membership.membershipAuthorityGeneration(), + membership.authorityProvenance(), + roles, + transitionReceipt.requestId(), + "MEMBERSHIP_REACTIVATED".equals(transitionReceipt.transitionType()), + authoritySnapshot); + + return new PositiveMembershipSnapshot( + true, + verified.accountId(), + verified.tenantId(), + verified.membershipLifecycleState(), + verified.gameplayAdmissionAllowed(), + membershipVersionValue(verified, identity), + verified.membershipAuthorityGeneration(), + verified.roles(), + verified.authorityTuple(), + verified.issuanceFence(), + Instant.now(), + List.of(checkpoint), + transitionReceipt, + verified); + } + + /** + * Preserves an existing active row's exact positive counters and event identity in V36. This is + * not a sequence-zero backfill: absent, inactive, or contradictory retained state stays denied. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PositiveMembershipSnapshot enrollProvenRetainedActivePair( + long accountId, long legacyTenantId) { + PositiveMembershipSnapshot positive = + readCurrentPositiveMembershipSnapshot(accountId, legacyTenantId); + Identity identity = resolveIdentity(accountId, legacyTenantId); + MembershipEvent event = positive.authorityEvent(); + pairAuthorityRepository.enrollProvenPositive( + identity.accountUuid(), + identity.tenantUuid(), + verifiedProvenance(identity), + new ProvenPositiveCheckpoint( + Long.parseLong(positive.membershipVersion()), + Long.parseLong(positive.membershipAuthorityGeneration()), + Long.parseLong(event.outboxSequence()), + event.eventId(), + event.eventDigest(), + event.callerBoundAuthorityInvalidated())); + return positive; + } + + /** Requires the V36 pair row to agree with one current positive Account snapshot. */ + @Transactional(propagation = Propagation.MANDATORY) + public PositiveMembershipSnapshot readCurrentPairBoundPositiveMembershipSnapshot( + long accountId, long legacyTenantId) { + PositiveMembershipSnapshot positive = + readCurrentPositiveMembershipSnapshot(accountId, legacyTenantId); + Identity identity = resolveIdentity(accountId, legacyTenantId); + PairAuthority pair = + pairAuthorityRepository + .readForUpdate(identity.accountUuid(), identity.tenantUuid()) + .orElseThrow( + () -> new IllegalStateException("Current membership pair authority is absent")); + MembershipEvent event = positive.authorityEvent(); + if (!verifiedProvenance(identity).equals(pair.provenance()) + || !pair.membershipExists() + || pair.membershipVersion() != Long.parseLong(positive.membershipVersion()) + || pair.membershipAuthorityGeneration() + != Long.parseLong(positive.membershipAuthorityGeneration()) + || pair.lastEventSequence() != Long.parseLong(event.outboxSequence()) + || !event.eventId().equals(pair.lastEventId()) + || !event.eventDigest().equals(pair.lastEventDigest()) + || pair.lastTransitionInvalidated() != event.callerBoundAuthorityInvalidated()) { + throw new IllegalStateException( + "Current Account membership differs from its durable pair authority"); + } + return positive; + } + + /** + * Reads an explicit sequence-zero checkpoint only from a durable verified pair baseline, after + * the no-membership and no-committed-history proof under one Account-row fence. It never admits + * gameplay and is not exposed through the still-denied runtime membership RPC. + */ + @Transactional(propagation = Propagation.MANDATORY) + public NeverJoinedMembershipSnapshot readNeverJoinedMembershipSnapshot( + long accountId, long legacyTenantId) { + joinOperationRepository.lockAccount(accountId); + Identity identity = resolveIdentity(accountId, legacyTenantId); + if (membershipRepository.findJoinProofForUpdate(accountId, legacyTenantId).isPresent()) { + throw new IllegalStateException("Never-joined Account membership row is not absent"); + } + transitionReceiptRepository.assertNewMembershipTransitionCanStart(accountId, legacyTenantId); + String streamKey = membershipStreamKey(identity); + if (authorityOutboxRepository.readCheckpoint(streamKey).isPresent()) { + throw new IllegalStateException( + "Never-joined Account membership has committed event history"); + } + PairAuthority pair = + pairAuthorityRepository + .readForUpdate(identity.accountUuid(), identity.tenantUuid()) + .orElseThrow(() -> new IllegalStateException("Never-joined pair baseline is absent")); + CompositeSnapshot authority = readSnapshot(identity); + ScopeState member = only(authority.memberships(), "membership"); + requireMatchingFence(authority, member, identity.accountUuid()); + requireNoUnmodeledCutoff(identity); + if (!verifiedProvenance(identity).equals(pair.provenance()) + || pair.membershipExists() + || pair.lastEventSequence() != 0L + || pair.membershipVersion() != 1L + || pair.membershipAuthorityGeneration() != member.generation()) { + throw new IllegalStateException( + "Never-joined Account membership differs from its positive pair baseline"); + } + AuthorityTuple tuple = + new AuthorityTuple( + decimal(authority.issuer().generation()), + decimal(authority.account().generation()), + Map.of( + identity.tenantUuid().toString(), + decimal(only(authority.tenants(), "tenant").generation())), + Map.of(identity.tenantUuid().toString(), decimal(member.generation())), + List.of(), + Optional.empty(), + Optional.empty()); + return new NeverJoinedMembershipSnapshot( + identity.accountUuid().toString(), + identity.tenantUuid().toString(), + decimal(pair.membershipVersion()), + decimal(pair.membershipAuthorityGeneration()), + tuple, + decimal(authority.issuanceFence().value()), + Instant.now(), + streamKey); + } + + /** + * Establishes a committed never-joined baseline before a separate JOIN transaction may consume + * it. A retained active row is enrolled only from its exact current positive event/receipt proof; + * inactive or contradictory retained rows remain denied rather than being assigned sequence zero. + */ + @Transactional(propagation = Propagation.MANDATORY) + public void preparePairAuthorityForJoin(long accountId, long legacyTenantId) { + joinOperationRepository.lockAccount(accountId); + Identity identity = resolveIdentity(accountId, legacyTenantId); + if (membershipRepository.findJoinProofForUpdate(accountId, legacyTenantId).isPresent()) { + // Retained rows are not eligible for an absence baseline. Their existing JOIN/readback + // behavior stays intact until a separate exact positive-history enrollment is proven. + return; + } + + transitionReceiptRepository.assertNewMembershipTransitionCanStart(accountId, legacyTenantId); + if (authorityOutboxRepository.readCheckpoint(membershipStreamKey(identity)).isPresent()) { + throw new IllegalStateException( + "Absent Account membership has retained authority-event history"); + } + Optional existing = + pairAuthorityRepository.readForUpdate(identity.accountUuid(), identity.tenantUuid()); + if (existing.isEmpty()) { + ScopeState generation = + authorityGenerationRepository.initialize( + AuthorityScope.membership(identity.accountUuid(), identity.tenantUuid())); + if (generation.generation() != 1L) { + throw new IllegalStateException( + "Never-joined Account membership generation did not initialize at one"); + } + } + PairAuthority pair = + pairAuthorityRepository.enrollAbsence( + identity.accountUuid(), identity.tenantUuid(), verifiedProvenance(identity)); + CompositeSnapshot snapshot = readSnapshot(identity); + ScopeState member = only(snapshot.memberships(), "membership"); + requireMatchingFence(snapshot, member, identity.accountUuid()); + if (pair.membershipExists() + || pair.lastEventSequence() != 0L + || pair.membershipVersion() != 1L + || pair.membershipAuthorityGeneration() != member.generation() + || pair.membershipAuthorityGeneration() != 1L) { + throw new IllegalStateException( + "Absent Account membership differs from its durable pair authority baseline"); + } + } + + /** + * Ensures that one exact, Account-fenced runtime snapshot has durable pair authority to read. + * + *

A never-joined pair reuses JOIN's committed absence enrollment, then proves the resulting + * sequence-zero snapshot. An existing membership is enrolled only through its exact current + * active receipt/event proof and is read back against the pair row. Inactive, unproved, or + * contradictory history remains denied; this method does not mutate membership or event history. + */ + @Transactional(propagation = Propagation.MANDATORY) + public void preparePairAuthorityForRuntimeSnapshot(long accountId, long legacyTenantId) { + if (accountId <= 0L || legacyTenantId <= 0L) { + throw new IllegalArgumentException("Account and retained tenant identities must be positive"); + } + + // Keep the same lock order as JOIN before resolving identity or inspecting retained history. + joinOperationRepository.lockAccount(accountId); + resolveIdentity(accountId, legacyTenantId); + if (membershipRepository.findJoinProofForUpdate(accountId, legacyTenantId).isEmpty()) { + preparePairAuthorityForJoin(accountId, legacyTenantId); + readNeverJoinedMembershipSnapshot(accountId, legacyTenantId); + return; + } + + enrollProvenRetainedActivePair(accountId, legacyTenantId); + readCurrentPairBoundPositiveMembershipSnapshot(accountId, legacyTenantId); + } + + /** Requires the previously committed never-joined baseline under the JOIN account fence. */ + @Transactional(propagation = Propagation.MANDATORY) + public NewMembershipBaseline requireNewMembershipBaseline(long accountId, long legacyTenantId) { + Identity identity = resolveIdentity(accountId, legacyTenantId); + if (membershipRepository.findByAccountIdAndTenantId(accountId, legacyTenantId).isPresent()) { + throw new IllegalStateException("New Account membership already exists"); + } + transitionReceiptRepository.assertNewMembershipTransitionCanStart(accountId, legacyTenantId); + String streamKey = membershipStreamKey(identity); + if (authorityOutboxRepository.readCheckpoint(streamKey).isPresent()) { + throw new IllegalStateException( + "New Account membership has retained V33 authority-event history"); + } + PairAuthority pair = + pairAuthorityRepository + .readForUpdate(identity.accountUuid(), identity.tenantUuid()) + .orElseThrow( + () -> new IllegalStateException("Never-joined pair authority is not enrolled")); + CompositeSnapshot snapshot = readSnapshot(identity); + ScopeState member = only(snapshot.memberships(), "membership"); + requireMatchingFence(snapshot, member, identity.accountUuid()); + if (!verifiedProvenance(identity).equals(pair.provenance()) + || pair.membershipExists() + || pair.lastEventSequence() != 0L + || pair.membershipVersion() != 1L + || pair.membershipAuthorityGeneration() != member.generation() + || member.generation() != 1L) { + throw new IllegalStateException( + "New Account membership differs from its committed absence baseline"); + } + return new NewMembershipBaseline( + pair.membershipVersion(), pair.membershipAuthorityGeneration()); + } + + /** Locks the current generation tuple and requires it to match the retained inactive row. */ + @Transactional(propagation = Propagation.MANDATORY) + public void requireExistingMembershipAuthorityMatches( + long accountId, + long legacyTenantId, + AccountTenantMembership membership, + RoleSnapshot roleSnapshot) { + Identity identity = resolveIdentity(accountId, legacyTenantId); + requireMembershipIdentity(accountId, legacyTenantId, membership); + if (!"INACTIVE".equals(membership.getLifecycleState()) + || membership.isGameplayAdmissionAllowed() + || !"EXPLICIT_JOIN".equals(membership.getAuthorityProvenance())) { + throw new IllegalStateException("Only retained explicit inactive membership may reactivate"); + } + CompositeSnapshot snapshot = readSnapshot(identity); + ScopeState membershipState = only(snapshot.memberships(), "membership"); + requireMatchingFence(snapshot, membershipState, identity.accountUuid()); + if (membership.getMembershipAuthorityGeneration() <= 0L + || membership.getMembershipAuthorityGeneration() != membershipState.generation()) { + throw new IllegalStateException( + "Embedded and canonical Account membership generations differ"); + } + requireCurrentMembershipEvent( + identity, + membership.getId(), + membership.getLifecycleState(), + membership.isGameplayAdmissionAllowed(), + membership.getMembershipVersion(), + membership.getMembershipAuthorityGeneration(), + membership.getAuthorityProvenance(), + roleSnapshot, + null, + true, + snapshot); + } + + /** + * Requires the latest checkpoint event to prove the exact current retained membership state. This + * read may fail closed during JOIN/reconciliation without undoing a caller's retry receipt. + */ + @Transactional( + propagation = Propagation.MANDATORY, + readOnly = true, + noRollbackFor = IllegalStateException.class) + public Checkpoint requireCurrentMembershipEvent( + long accountId, + long legacyTenantId, + AccountTenantMembership membership, + RoleSnapshot roleSnapshot, + String expectedRequestId, + boolean callerBoundAuthorityInvalidated) { + Identity identity = resolveIdentity(accountId, legacyTenantId); + requireMembershipIdentity(accountId, legacyTenantId, membership); + CompositeSnapshot snapshot = readSnapshot(identity); + ScopeState member = only(snapshot.memberships(), "membership"); + requireMatchingFence(snapshot, member, identity.accountUuid()); + if (member.generation() != membership.getMembershipAuthorityGeneration()) { + throw new IllegalStateException( + "Embedded and canonical Account membership generations differ"); + } + return requireCurrentMembershipEvent( + identity, + membership.getId(), + membership.getLifecycleState(), + membership.isGameplayAdmissionAllowed(), + membership.getMembershipVersion(), + membership.getMembershipAuthorityGeneration(), + membership.getAuthorityProvenance(), + roleSnapshot, + expectedRequestId, + callerBoundAuthorityInvalidated, + snapshot); + } + + /** Reconciliation proof variant for locked membership and role readback records. */ + @Transactional( + propagation = Propagation.MANDATORY, + readOnly = true, + noRollbackFor = IllegalStateException.class) + public Checkpoint requireCurrentMembershipEvent( + JoinMembershipProof membership, + RoleSnapshot roleSnapshot, + String expectedRequestId, + boolean callerBoundAuthorityInvalidated) { + if (membership == null) { + throw new IllegalArgumentException("Locked Account membership evidence is required"); + } + Identity identity = resolveIdentity(membership.accountId(), membership.tenantId()); + CompositeSnapshot snapshot = readSnapshot(identity); + ScopeState member = only(snapshot.memberships(), "membership"); + requireMatchingFence(snapshot, member, identity.accountUuid()); + if (member.generation() != membership.membershipAuthorityGeneration()) { + throw new IllegalStateException( + "Embedded and canonical Account membership generations differ"); + } + return requireCurrentMembershipEvent( + identity, + membership.membershipId(), + membership.lifecycleState(), + membership.gameplayAdmissionAllowed(), + membership.membershipVersion(), + membership.membershipAuthorityGeneration(), + membership.authorityProvenance(), + roleSnapshot, + expectedRequestId, + callerBoundAuthorityInvalidated, + snapshot); + } + + /** Advances and emits the complete committed tuple for a newly created public membership. */ + @Transactional(propagation = Propagation.MANDATORY) + public Checkpoint publishNewMembershipChange( + long accountId, long legacyTenantId, String requestId, AccountTenantMembership membership) { + Identity identity = resolveIdentity(accountId, legacyTenantId); + requireMembershipIdentity(accountId, legacyTenantId, membership); + if (membership.getMembershipVersion() != 2L + || membership.getMembershipAuthorityGeneration() != 1L) { + throw new IllegalStateException( + "New Account membership must advance baseline version one to two without invalidation"); + } + PairAuthority absenceBaseline = + pairAuthorityRepository + .readForUpdate(identity.accountUuid(), identity.tenantUuid()) + .orElseThrow(() -> new IllegalStateException("New membership has no absence baseline")); + if (!verifiedProvenance(identity).equals(absenceBaseline.provenance()) + || absenceBaseline.membershipExists() + || absenceBaseline.membershipVersion() != 1L + || absenceBaseline.membershipAuthorityGeneration() != 1L + || absenceBaseline.lastEventSequence() != 0L) { + throw new IllegalStateException("New membership differs from its exact absence baseline"); + } + CompositeSnapshot snapshot = readSnapshot(identity); + ScopeState membershipState = only(snapshot.memberships(), "membership"); + requireMatchingFence(snapshot, membershipState, identity.accountUuid()); + if (membershipState.generation() != 1L) { + throw new IllegalStateException( + "New Account membership canonical generation is not its first generation"); + } + String streamKey = membershipStreamKey(identity); + if (authorityOutboxRepository.readCheckpoint(streamKey).isPresent()) { + throw new IllegalStateException( + "New Account membership acquired V33 authority-event history before publication"); + } + Checkpoint checkpoint = + appendAndReadBack(identity, requestId, membership, snapshot, false, true); + PairAuthority committed = + pairAuthorityRepository.commitTransition( + absenceBaseline, + new PairTransition( + true, + checkpoint.outboxSequence(), + checkpoint.sourceEventId(), + checkpoint.sourceEventDigest(), + false)); + if (checkpoint.outboxSequence() != 1L + || committed.membershipVersion() != membership.getMembershipVersion() + || committed.membershipAuthorityGeneration() + != membership.getMembershipAuthorityGeneration()) { + throw new IllegalStateException("First JOIN pair authority readback differs from its event"); + } + return checkpoint; + } + + /** Compare-and-advances an inactive member's existing canonical generation before publication. */ + @Transactional(propagation = Propagation.MANDATORY) + public Checkpoint publishReactivatedMembershipChange( + long accountId, long legacyTenantId, String requestId, AccountTenantMembership membership) { + Identity identity = resolveIdentity(accountId, legacyTenantId); + requireMembershipIdentity(accountId, legacyTenantId, membership); + if (!"ACTIVE".equals(membership.getLifecycleState()) + || !membership.isGameplayAdmissionAllowed() + || !"EXPLICIT_JOIN".equals(membership.getAuthorityProvenance())) { + throw new IllegalStateException("Reactivated Account membership is not active and explicit"); + } + long expectedPriorGeneration = decrementPositive(membership.getMembershipAuthorityGeneration()); + PairAuthority priorPair = + pairAuthorityRepository + .readForUpdate(identity.accountUuid(), identity.tenantUuid()) + .orElseThrow( + () -> new IllegalStateException("Reactivated membership has no pair authority")); + if (!verifiedProvenance(identity).equals(priorPair.provenance()) + || !priorPair.membershipExists() + || priorPair.membershipVersion() != membership.getMembershipVersion() - 1L + || priorPair.membershipAuthorityGeneration() != expectedPriorGeneration + || priorPair.lastEventSequence() <= 0L) { + throw new IllegalStateException( + "Reactivated membership differs from its prior pair authority"); + } + CompositeSnapshot beforeAdvance = readSnapshot(identity); + ScopeState currentMembership = only(beforeAdvance.memberships(), "membership"); + requireMatchingFence(beforeAdvance, currentMembership, identity.accountUuid()); + if (currentMembership.generation() != expectedPriorGeneration) { + throw new IllegalStateException( + "Embedded and canonical Account membership generations differ at reactivation"); + } + ScopeState advanced = + authorityGenerationRepository.advance(currentMembership, beforeAdvance.issuanceFence()); + if (advanced.generation() != membership.getMembershipAuthorityGeneration()) { + throw new IllegalStateException( + "Account membership authority generation did not advance with reactivation"); + } + CompositeSnapshot committedCandidate = readSnapshot(identity); + ScopeState committedMembership = only(committedCandidate.memberships(), "membership"); + requireMatchingFence(committedCandidate, committedMembership, identity.accountUuid()); + if (committedMembership.generation() != membership.getMembershipAuthorityGeneration()) { + throw new IllegalStateException( + "Committed Account membership tuple differs from the reactivation candidate"); + } + Checkpoint checkpoint = + appendAndReadBack(identity, requestId, membership, committedCandidate, true, false); + PairAuthority committed = + pairAuthorityRepository.commitTransition( + priorPair, + new PairTransition( + true, + checkpoint.outboxSequence(), + checkpoint.sourceEventId(), + checkpoint.sourceEventDigest(), + true)); + if (committed.membershipVersion() != membership.getMembershipVersion() + || committed.membershipAuthorityGeneration() + != membership.getMembershipAuthorityGeneration()) { + throw new IllegalStateException( + "Reactivated membership pair authority readback differs from its event"); + } + return checkpoint; + } + + /** + * Verifies a JOINED operation against its exact immutable event, even after later stream events. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Checkpoint requireCommittedJoinEvent(JoinOperation operation) { + if (operation == null + || !"COMMITTED".equals(operation.status()) + || !"JOINED".equals(operation.outcome()) + || operation.membershipId() == null + || operation.membershipId() <= 0L + || operation.membershipVersion() == null + || operation.membershipVersion() <= 0L + || operation.membershipAuthorityGeneration() == null + || operation.membershipAuthorityGeneration() <= 0L) { + throw new IllegalStateException( + "Committed JOIN operation lacks exact event readback identity"); + } + Identity identity = resolveIdentity(operation.accountId(), operation.tenantId()); + String streamKey = membershipStreamKey(identity); + Event event = + authorityOutboxRepository + .findEvent(streamKey, operation.requestId()) + .orElseThrow( + () -> + new IllegalStateException( + "Committed JOIN has no matching V33 authority event")); + MembershipEvent verified = verifyStoredEvent(event, identity, operation.requestId()); + if (!Map.of(identity.tenantUuid().toString(), Long.toString(operation.membershipVersion())) + .equals(verified.membershipVersion()) + || !Long.toString(operation.membershipAuthorityGeneration()) + .equals(verified.membershipAuthorityGeneration()) + || !verified.gameplayAdmissionAllowed() + || !"ACTIVE".equals(verified.membershipLifecycleState()) + || !verified.roles().contains("player")) { + throw new IllegalStateException( + "Committed JOIN operation differs from its canonical V33 authority event"); + } + Checkpoint head = + authorityOutboxRepository + .readCheckpoint(streamKey) + .orElseThrow( + () -> + new IllegalStateException("Committed JOIN authority stream has no checkpoint")); + if (head.outboxSequence() < event.outboxSequence()) { + throw new IllegalStateException("Committed JOIN authority checkpoint regressed"); + } + return head; + } + + private Checkpoint appendAndReadBack( + Identity identity, + String requestId, + AccountTenantMembership membership, + CompositeSnapshot snapshot, + boolean callerBoundAuthorityInvalidated, + boolean newMembership) { + requirePositive(requestId, "JOIN request ID"); + requireActiveMembership(membership); + ScopeState issuer = snapshot.issuer(); + ScopeState account = snapshot.account(); + ScopeState tenant = only(snapshot.tenants(), "tenant"); + ScopeState member = only(snapshot.memberships(), "membership"); + requireMatchingFence(snapshot, member, identity.accountUuid()); + if (membership.getMembershipAuthorityGeneration() != member.generation()) { + throw new IllegalStateException( + "Embedded and committed Account membership generations differ"); + } + if (newMembership && member.generation() != 1L) { + throw new IllegalStateException( + "A new Account membership cannot reuse a retained generation"); + } + if (!newMembership && !callerBoundAuthorityInvalidated) { + throw new IllegalStateException("Membership reactivation must invalidate caller authority"); + } + requireNoUnmodeledCutoff(identity); + RoleSnapshot roles = requireRoleSnapshot(identity, membership); + String streamKey = membershipStreamKey(identity); + String expectedEventId = eventIdForRequest(requestId); + MembershipEvent[] candidate = new MembershipEvent[1]; + Event appended = + authorityOutboxRepository.append( + streamKey, + requestId, + sequence -> { + MembershipEvent event = + MembershipAuthorityEventV1Codec.seal( + preimage( + identity, + requestId, + expectedEventId, + streamKey, + sequence, + issuer, + account, + tenant, + member, + snapshot.issuanceFence().value(), + membership, + roles.roles(), + callerBoundAuthorityInvalidated)); + candidate[0] = event; + return new EventEvidence( + event.eventId(), event.eventDigest(), event.canonicalJsonUtf8()); + }); + MembershipEvent expected = candidate[0]; + if (expected == null + || !appended.outboxStreamKey().equals(streamKey) + || !appended.requestId().equals(requestId) + || appended.outboxSequence() != Long.parseLong(expected.outboxSequence()) + || !appended.eventId().equals(expected.eventId()) + || !appended.eventDigest().equals(expected.eventDigest()) + || !Arrays.equals(appended.payload(), expected.canonicalJsonUtf8())) { + throw new IllegalStateException("Account authority event append differs from its candidate"); + } + Event exactReadback = + authorityOutboxRepository + .findEvent(streamKey, requestId) + .orElseThrow( + () -> new IllegalStateException("Account authority event readback is absent")); + if (!appended.equals(exactReadback)) { + throw new IllegalStateException("Account authority event readback differs from its append"); + } + MembershipEvent verified = verifyStoredEvent(exactReadback, identity, requestId); + if (!verified.membershipVersion().equals(expected.membershipVersion()) + || !verified.eventDigest().equals(expected.eventDigest()) + || !verified.canonicalJson().equals(expected.canonicalJson())) { + throw new IllegalStateException("Account authority event codec readback differs"); + } + Checkpoint checkpoint = + authorityOutboxRepository + .readCheckpoint(streamKey) + .orElseThrow( + () -> new IllegalStateException("Account authority event checkpoint is absent")); + if (checkpoint.outboxSequence() != appended.outboxSequence() + || !checkpoint.sourceEventId().equals(appended.eventId()) + || !checkpoint.sourceEventDigest().equals(appended.eventDigest())) { + throw new IllegalStateException("Account authority event checkpoint differs from its append"); + } + return checkpoint; + } + + private Checkpoint requireCurrentMembershipEvent( + Identity identity, + long membershipId, + String lifecycleState, + boolean gameplayAdmissionAllowed, + long membershipVersion, + long membershipAuthorityGeneration, + String authorityProvenance, + RoleSnapshot roleSnapshot, + String expectedRequestId, + boolean callerBoundAuthorityInvalidated, + CompositeSnapshot snapshot) { + if (membershipId <= 0L + || membershipVersion <= 0L + || membershipAuthorityGeneration <= 0L + || (!"ACTIVE".equals(lifecycleState) && !"INACTIVE".equals(lifecycleState)) + || ("INACTIVE".equals(lifecycleState) && gameplayAdmissionAllowed) + || !"EXPLICIT_JOIN".equals(authorityProvenance) + || roleSnapshot == null + || roleSnapshot.accountId() != identity.accountId() + || roleSnapshot.tenantId() != identity.legacyTenantId() + || roleSnapshot.membershipId() != membershipId + || roleSnapshot.snapshotVersion() != membershipVersion) { + throw new IllegalStateException("Current Account membership and role evidence is incomplete"); + } + List exactRoles; + try { + exactRoles = + AccountTenantMembershipRoleSnapshotRepository.requireCanonicalRoleSet( + roleSnapshot.roles()); + } catch (RuntimeException exception) { + throw new IllegalStateException("Current Account role snapshot is not canonical", exception); + } + + String streamKey = membershipStreamKey(identity); + Checkpoint checkpoint = + authorityOutboxRepository + .readCheckpoint(streamKey) + .orElseThrow( + () -> + new IllegalStateException("Current Account membership has no V33 checkpoint")); + Event event = + authorityOutboxRepository + .findEvent(streamKey, checkpoint.outboxSequence()) + .orElseThrow( + () -> new IllegalStateException("Current Account V33 checkpoint has no event")); + if (!checkpointMatches(checkpoint, event) + || (expectedRequestId != null && !expectedRequestId.equals(event.requestId()))) { + throw new IllegalStateException("Current Account membership checkpoint identity differs"); + } + MembershipEvent verified = verifyStoredEvent(event, identity, event.requestId()); + ScopeState issuer = snapshot.issuer(); + ScopeState account = snapshot.account(); + ScopeState tenant = only(snapshot.tenants(), "tenant"); + ScopeState member = only(snapshot.memberships(), "membership"); + requireMatchingFence(snapshot, member, identity.accountUuid()); + var tuple = verified.authorityTuple(); + if (!Long.toString(issuer.generation()).equals(tuple.issuerAuthGeneration()) + || !Long.toString(account.generation()).equals(tuple.accountAuthorityGeneration()) + || !Map.of(identity.tenantUuid().toString(), Long.toString(tenant.generation())) + .equals(tuple.tenantAuthorityGeneration()) + || !Map.of(identity.tenantUuid().toString(), Long.toString(member.generation())) + .equals(tuple.membershipAuthorityGeneration()) + || !tuple.privateRealmGrantVersions().isEmpty() + || tuple.accountSecurityCutoff().isPresent() + || tuple.tenantBillingCutoff().isPresent() + || !Long.toString(snapshot.issuanceFence().value()).equals(verified.issuanceFence()) + || member.generation() != membershipAuthorityGeneration + || !lifecycleState.equals(verified.membershipLifecycleState()) + || !Map.of(identity.tenantUuid().toString(), Long.toString(membershipVersion)) + .equals(verified.membershipVersion()) + || !Long.toString(membershipAuthorityGeneration) + .equals(verified.membershipAuthorityGeneration()) + || !exactRoles.equals(verified.roles()) + || gameplayAdmissionAllowed != verified.gameplayAdmissionAllowed() + || callerBoundAuthorityInvalidated != verified.callerBoundAuthorityInvalidated()) { + throw new IllegalStateException( + "Current Account membership differs from its canonical V33 event and V31 tuple"); + } + return checkpoint; + } + + private static boolean checkpointMatches(Checkpoint checkpoint, Event event) { + return checkpoint.outboxStreamKey().equals(event.outboxStreamKey()) + && checkpoint.outboxSequence() == event.outboxSequence() + && checkpoint.sourceEventId().equals(event.eventId()) + && checkpoint.sourceEventDigest().equals(event.eventDigest()); + } + + private Map preimage( + Identity identity, + String requestId, + String eventId, + String streamKey, + long sequence, + ScopeState issuer, + ScopeState account, + ScopeState tenant, + ScopeState membershipState, + long issuanceFence, + AccountTenantMembership membership, + List roles, + boolean callerBoundAuthorityInvalidated) { + Map authorityTuple = new LinkedHashMap<>(); + authorityTuple.put("issuerAuthGeneration", decimal(issuer.generation())); + authorityTuple.put("accountAuthorityGeneration", decimal(account.generation())); + authorityTuple.put( + "tenantAuthorityGeneration", + Map.of(identity.tenantUuid().toString(), decimal(tenant.generation()))); + authorityTuple.put( + "membershipAuthorityGeneration", + Map.of(identity.tenantUuid().toString(), decimal(membershipState.generation()))); + authorityTuple.put("privateRealmGrantVersions", List.of()); + + Map event = new LinkedHashMap<>(); + event.put("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION); + event.put("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE); + event.put("eventId", eventId); + event.put("requestId", requestId); + event.put("outboxStreamKey", streamKey); + event.put("outboxSequence", decimal(sequence)); + event.put( + "sourceScope", + streamKey.substring(MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX.length())); + event.put("accountId", identity.accountUuid().toString()); + event.put("tenantId", identity.tenantUuid().toString()); + event.put("membershipExists", true); + event.put("membershipLifecycleState", membership.getLifecycleState()); + event.put( + "membershipVersion", + Map.of(identity.tenantUuid().toString(), decimal(membership.getMembershipVersion()))); + event.put( + "membershipAuthorityGeneration", decimal(membership.getMembershipAuthorityGeneration())); + event.put("authorityTuple", authorityTuple); + event.put("issuanceFence", decimal(issuanceFence)); + event.put("roles", roles); + event.put("gameplayAdmissionAllowed", membership.isGameplayAdmissionAllowed()); + event.put("callerBoundAuthorityInvalidated", callerBoundAuthorityInvalidated); + return event; + } + + private MembershipEvent verifyStoredEvent(Event event, Identity identity, String requestId) { + if (!event.outboxStreamKey().equals(membershipStreamKey(identity)) + || !event.requestId().equals(requestId)) { + throw new IllegalStateException( + "Account authority event does not match its exact JOIN scope"); + } + final MembershipEvent verified; + try { + verified = + MembershipAuthorityEventV1Codec.verify( + new String(event.payload(), StandardCharsets.UTF_8)); + } catch (RuntimeException exception) { + throw new IllegalStateException("Stored Account authority event is invalid", exception); + } + if (!Arrays.equals(event.payload(), verified.canonicalJsonUtf8()) + || !verified.eventId().equals(event.eventId()) + || !verified.requestId().equals(requestId) + || !verified.outboxStreamKey().equals(event.outboxStreamKey()) + || !verified.accountId().equals(identity.accountUuid().toString()) + || !verified.tenantId().equals(identity.tenantUuid().toString()) + || !verified.eventDigest().equals(event.eventDigest()) + || !Long.toString(event.outboxSequence()).equals(verified.outboxSequence())) { + throw new IllegalStateException("Stored Account authority event identity or digest differs"); + } + return verified; + } + + /** + * Extracts Account's local numeric membership value only after validating the complete canonical + * one-tenant event carrier. The event itself and all equality checks retain the map unchanged. + */ + private String membershipVersionValue(MembershipEvent event, Identity identity) { + String tenantId = identity.tenantUuid().toString(); + Map versions = event.membershipVersion(); + String version = versions.get(tenantId); + if (versions.size() != 1 + || !versions.containsKey(tenantId) + || version == null + || !version.matches("[1-9][0-9]*")) { + throw new IllegalStateException( + "Stored Account membership event has no exact canonical one-tenant version map"); + } + return version; + } + + private void requireNoUnmodeledCutoff(Identity identity) { + Optional accountCutoff = + authorityOutboxRepository.readCheckpoint(accountStreamKey(identity.accountUuid())); + Optional tenantCutoff = + authorityOutboxRepository.readCheckpoint(tenantStreamKey(identity.tenantUuid())); + if (accountCutoff.isPresent() || tenantCutoff.isPresent()) { + throw new IllegalStateException( + "Account JOIN cannot form optional security or billing cutoff evidence from retained events"); + } + } + + private RoleSnapshot requireRoleSnapshot(Identity identity, AccountTenantMembership membership) { + if (membership.getId() == null || membership.getMembershipVersion() <= 0L) { + throw new IllegalStateException("Account JOIN membership role identity is incomplete"); + } + RoleSnapshot snapshot = + roleSnapshotRepository + .findForUpdate( + identity.accountId(), + identity.legacyTenantId(), + membership.getId(), + membership.getMembershipVersion()) + .orElseThrow(() -> new IllegalStateException("Account JOIN role snapshot is absent")); + if (snapshot.accountId() != identity.accountId() + || snapshot.tenantId() != identity.legacyTenantId() + || snapshot.membershipId() != membership.getId() + || snapshot.snapshotVersion() != membership.getMembershipVersion() + || !snapshot.roles().contains("player")) { + throw new IllegalStateException("Account JOIN role snapshot differs from its membership"); + } + return snapshot; + } + + private CompositeSnapshot readSnapshot(Identity identity) { + return authorityGenerationRepository.readCompositeSnapshot( + AccountServiceImpl.ACCOUNT_JWT_ISSUER, + identity.accountUuid(), + List.of(identity.tenantUuid()), + List.of(identity.tenantUuid())); + } + + private void requireMatchingFence( + CompositeSnapshot snapshot, ScopeState membershipState, UUID accountUuid) { + if (!accountUuid.equals(snapshot.issuanceFence().accountId()) + || !snapshot.issuanceFence().equals(snapshot.account().issuanceFence()) + || !snapshot.issuanceFence().equals(membershipState.issuanceFence())) { + throw new IllegalStateException( + "Account JOIN authority tuple has an incomplete issuance fence"); + } + } + + private ScopeState only(List scopes, String label) { + if (scopes == null || scopes.size() != 1) { + throw new IllegalStateException("Account JOIN authority snapshot has no exact " + label); + } + return scopes.getFirst(); + } + + private Identity resolveIdentity(long accountId, long legacyTenantId) { + if (accountId <= 0L || legacyTenantId <= 0L) { + throw new IllegalArgumentException("Account and retained tenant identities must be positive"); + } + Account account = + accountRepository + .findById(accountId) + .orElseThrow(() -> new IllegalStateException("JOIN Account row is absent")); + if (account.getId() == null + || account.getId() != accountId + || account.getAccountUuid() == null + || account.getAccountUuidProvenance() == null + || account.getAccountUuidSourceNumericId() == null + || account.getAccountUuidSourceNumericId() != accountId) { + throw new IllegalStateException( + "JOIN Account UUID does not exactly identify its persisted row"); + } + ApprovedAssociation association = tenantIdentityResolver.resolve(legacyTenantId); + if (association.legacyTenantId() != legacyTenantId || association.canonicalTenantId() == null) { + throw new IllegalStateException( + "JOIN retained tenant has no exact approved UUID association"); + } + return new Identity( + accountId, + legacyTenantId, + account.getAccountUuid(), + association.canonicalTenantId(), + association); + } + + private VerifiedTenantProvenance verifiedProvenance(Identity identity) { + ApprovedAssociation association = identity.association(); + return new VerifiedTenantProvenance( + identity.legacyTenantId(), + TenantProvenanceKind.APPROVED_RETAINED, + association.operationId(), + association.manifestDigest()); + } + + private void requireMembershipIdentity( + long accountId, long legacyTenantId, AccountTenantMembership membership) { + if (membership == null + || membership.getId() == null + || membership.getId() <= 0L + || membership.getAccount() == null + || membership.getAccount().getId() == null + || membership.getAccount().getId() != accountId + || membership.getTenantId() != legacyTenantId) { + throw new IllegalStateException("JOIN membership does not match its exact Account scope"); + } + } + + private void requireActiveMembership(AccountTenantMembership membership) { + if (membership.getMembershipVersion() <= 0L + || membership.getMembershipAuthorityGeneration() <= 0L + || !"ACTIVE".equals(membership.getLifecycleState()) + || !membership.isGameplayAdmissionAllowed() + || !"EXPLICIT_JOIN".equals(membership.getAuthorityProvenance())) { + throw new IllegalStateException("JOIN event requires a persisted active explicit membership"); + } + } + + private String membershipStreamKey(Identity identity) { + return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + identity.accountUuid() + + "/" + + identity.tenantUuid(); + } + + private String accountStreamKey(UUID accountUuid) { + return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "account/" + accountUuid; + } + + private String tenantStreamKey(UUID tenantUuid) { + return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "tenant/" + tenantUuid; + } + + private String eventIdForRequest(String requestId) { + requirePositive(requestId, "JOIN request ID"); + return UUID.nameUUIDFromBytes( + (MembershipAuthorityEventV1Codec.SCHEMA_VERSION + ":" + requestId) + .getBytes(StandardCharsets.UTF_8)) + .toString(); + } + + private String decimal(long value) { + if (value <= 0L) { + throw new IllegalStateException("Account authority counters must be positive"); + } + return Long.toString(value); + } + + private long decrementPositive(long value) { + if (value <= 1L) { + throw new IllegalStateException("Reactivation requires prior positive membership history"); + } + return value - 1L; + } + + private void requirePositive(String value, String field) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(field + " is required"); + } + } + + /** Positive durable authority values committed before the first membership transition. */ + public record NewMembershipBaseline(long membershipVersion, long membershipAuthorityGeneration) { + public NewMembershipBaseline { + if (membershipVersion <= 0L || membershipAuthorityGeneration <= 0L) { + throw new IllegalArgumentException( + "Never-joined Account authority baseline must be positive"); + } + } + } + + /** + * Local V36 absence evidence. Its scalar version is not the canonical durable/wire carrier, and + * it carries no event identity/digest or gameplay admission. + */ + public record NeverJoinedMembershipSnapshot( + String accountId, + String tenantId, + String membershipVersion, + String membershipAuthorityGeneration, + AuthorityTuple authorityTuple, + String issuanceFence, + Instant evaluatedAt, + String outboxStreamKey) { + public NeverJoinedMembershipSnapshot { + accountId = requireCanonicalUuid(accountId, "canonical Account UUID"); + tenantId = requireCanonicalUuid(tenantId, "canonical tenant UUID"); + membershipVersion = requirePositiveCanonicalDecimal(membershipVersion, "membership version"); + membershipAuthorityGeneration = + requirePositiveCanonicalDecimal( + membershipAuthorityGeneration, "membership authority generation"); + Objects.requireNonNull(authorityTuple, "complete authority tuple is required"); + issuanceFence = requirePositiveCanonicalDecimal(issuanceFence, "Account issuance fence"); + Objects.requireNonNull(evaluatedAt, "Account evaluation time is required"); + outboxStreamKey = + Objects.requireNonNull(outboxStreamKey, "membership stream key is required"); + + if (!isPositiveCanonicalDecimal(authorityTuple.issuerAuthGeneration()) + || !isPositiveCanonicalDecimal(authorityTuple.accountAuthorityGeneration()) + || authorityTuple.tenantAuthorityGeneration().size() != 1 + || authorityTuple.membershipAuthorityGeneration().size() != 1 + || !authorityTuple.tenantAuthorityGeneration().containsKey(tenantId) + || !authorityTuple.membershipAuthorityGeneration().containsKey(tenantId) + || !isPositiveCanonicalDecimal(authorityTuple.tenantAuthorityGeneration().get(tenantId)) + || !membershipAuthorityGeneration.equals( + authorityTuple.membershipAuthorityGeneration().get(tenantId)) + || !authorityTuple.privateRealmGrantVersions().isEmpty() + || authorityTuple.accountSecurityCutoff().isPresent() + || authorityTuple.tenantBillingCutoff().isPresent()) { + throw new IllegalArgumentException( + "Never-joined Account authority tuple is incomplete or mismatched"); + } + + String expectedStreamKey = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + accountId + + "/" + + tenantId; + if (!expectedStreamKey.equals(outboxStreamKey)) { + throw new IllegalArgumentException( + "Never-joined Account membership stream key is not canonical"); + } + } + + public long outboxSequence() { + return 0L; + } + + public boolean membershipExists() { + return false; + } + + public String membershipLifecycleState() { + return "MISSING"; + } + + public List roles() { + return List.of(); + } + + public boolean gameplayAdmissionAllowed() { + return false; + } + + private static String requireCanonicalUuid(String value, String field) { + Objects.requireNonNull(value, field + " is required"); + try { + if (!UUID.fromString(value).toString().equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical lowercase UUID"); + } + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException( + field + " must be a canonical lowercase UUID", exception); + } + return value; + } + + private static String requirePositiveCanonicalDecimal(String value, String field) { + Objects.requireNonNull(value, field + " is required"); + if (!isPositiveCanonicalDecimal(value)) { + throw new IllegalArgumentException( + field + " must be a positive canonical unsigned decimal string"); + } + return value; + } + + private static boolean isPositiveCanonicalDecimal(String value) { + return value != null && value.matches("[1-9][0-9]*"); + } + } + + /** Immutable positive membership evidence assembled from one fenced Account transaction. */ + public record PositiveMembershipSnapshot( + boolean membershipExists, + String accountId, + String tenantId, + String membershipLifecycleState, + boolean gameplayAdmissionAllowed, + String membershipVersion, + String membershipAuthorityGeneration, + List roles, + AuthorityTuple authorityTuple, + String issuanceFence, + Instant evaluatedAt, + List outboxCheckpoints, + MembershipTransitionReceipt transitionReceipt, + MembershipEvent authorityEvent) { + public PositiveMembershipSnapshot { + Objects.requireNonNull(accountId, "canonical Account UUID is required"); + Objects.requireNonNull(tenantId, "canonical tenant UUID is required"); + Objects.requireNonNull(membershipLifecycleState, "membership lifecycle is required"); + Objects.requireNonNull(membershipVersion, "membership version is required"); + Objects.requireNonNull( + membershipAuthorityGeneration, "membership authority generation is required"); + roles = List.copyOf(roles); + Objects.requireNonNull(authorityTuple, "complete authority tuple is required"); + Objects.requireNonNull(issuanceFence, "Account issuance fence is required"); + Objects.requireNonNull(evaluatedAt, "Account evaluation time is required"); + outboxCheckpoints = List.copyOf(outboxCheckpoints); + Objects.requireNonNull(transitionReceipt, "membership transition receipt is required"); + Objects.requireNonNull(authorityEvent, "canonical membership authority event is required"); + + if (!membershipExists + || !"ACTIVE".equals(membershipLifecycleState) + || !gameplayAdmissionAllowed + || !accountId.equals(authorityEvent.accountId()) + || !tenantId.equals(authorityEvent.tenantId()) + || !membershipLifecycleState.equals(authorityEvent.membershipLifecycleState()) + || !membershipVersion.matches("[1-9][0-9]*") + || !Map.of(tenantId, membershipVersion).equals(authorityEvent.membershipVersion()) + || !membershipAuthorityGeneration.equals(authorityEvent.membershipAuthorityGeneration()) + || !roles.equals(authorityEvent.roles()) + || !authorityTuple.equals(authorityEvent.authorityTuple()) + || !issuanceFence.equals(authorityEvent.issuanceFence()) + || !membershipAuthorityGeneration.equals( + authorityTuple.membershipAuthorityGeneration().get(tenantId)) + || outboxCheckpoints.size() != 1 + || !outboxCheckpoints.contains( + new Checkpoint( + authorityEvent.outboxStreamKey(), + Long.parseLong(authorityEvent.outboxSequence()), + authorityEvent.eventId(), + authorityEvent.eventDigest())) + || !transitionReceipt.requestId().equals(authorityEvent.requestId())) { + throw new IllegalArgumentException( + "Positive Account membership snapshot evidence is internally inconsistent"); + } + } + } + + private record Identity( + long accountId, + long legacyTenantId, + UUID accountUuid, + UUID tenantUuid, + ApprovedAssociation association) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 03aac99601..bcaabcad73 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -12,6 +12,7 @@ import java.security.SecureRandom; import java.time.Instant; import java.time.LocalDateTime; +import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; @@ -39,6 +40,7 @@ import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; +import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceipt; import net.firedevops.firemud.accountservice.dto.PasswordResetRequest; import net.firedevops.firemud.accountservice.dto.PlayerBootstrapResult; import net.firedevops.firemud.accountservice.dto.ProfileDto; @@ -54,6 +56,7 @@ import net.firedevops.firemud.accountservice.dto.VerifyEmailRequest; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; import net.firedevops.firemud.accountservice.entity.AccountLoginAuthMode; import net.firedevops.firemud.accountservice.entity.AccountLoginAuthModes; @@ -65,6 +68,8 @@ import net.firedevops.firemud.accountservice.mapper.AccountMapper; import net.firedevops.firemud.accountservice.mapper.ProfileMapper; import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; @@ -73,12 +78,15 @@ import net.firedevops.firemud.accountservice.repository.AccountRealmAccessGrantRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; import net.firedevops.firemud.accountservice.repository.EmailVerificationTokenRepository; import net.firedevops.firemud.accountservice.repository.ExternalAccountRepository; import net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository; import net.firedevops.firemud.accountservice.repository.PaymentTransactionRepository; import net.firedevops.firemud.accountservice.repository.ProfileRepository; import net.firedevops.firemud.accountservice.repository.SubscriptionRepository; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; import net.firedevops.firemud.accountservice.service.AccountService; import net.firedevops.firemud.accountservice.service.EmailService; import net.firedevops.firemud.accountservice.service.NotificationService; @@ -101,6 +109,7 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionException; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronization; @@ -119,19 +128,24 @@ public class AccountServiceImpl implements AccountService { "Connect scope is invalid or expired; rerun bootstrap discovery and request a fresh connect scope"; private static final String JOIN_REQUIRED_CHARACTERS_MESSAGE = "Join the selected world before discovering characters"; + public static final String ACCOUNT_JWT_ISSUER = "firemud-account-service"; private static final String GAMEPLAY_DELEGATION_AUDIENCE = "account-service"; private static final int EMAIL_LOGIN_OTP_MAX_ATTEMPTS = 5; private static final SecureRandom EMAIL_LOGIN_OTP_RANDOM = new SecureRandom(); private static final JsonMapper AUDIT_JSON = JsonMapper.builder().build(); private final AccountRepository accountRepository; + private final AccountAuthorityGenerationRepository accountAuthorityGenerationRepository; private final AccountAuditOutboxRepository accountAuditOutboxRepository; private final AccountConnectScopeRepository accountConnectScopeRepository; private final AccountJoinOperationRepository accountJoinOperationRepository; private final AccountMembershipTransitionReceiptRepository membershipTransitionReceiptRepository; + private final AccountMembershipAuthorityEventProducer membershipAuthorityEventProducer; private final AccountEmailLoginChallengeRepository accountEmailLoginChallengeRepository; private final AccountRealmAccessGrantRepository accountRealmAccessGrantRepository; private final AccountTenantMembershipRepository accountTenantMembershipRepository; + private final AccountTenantMembershipRoleSnapshotRepository + accountTenantMembershipRoleSnapshotRepository; private final AccountMapper accountMapper; private final ProfileRepository profileRepository; private final ProfileMapper profileMapper; @@ -156,13 +170,16 @@ public class AccountServiceImpl implements AccountService { justification = "Dependencies are injected and kept internal") public AccountServiceImpl( AccountRepository accountRepository, + AccountAuthorityGenerationRepository accountAuthorityGenerationRepository, AccountAuditOutboxRepository accountAuditOutboxRepository, AccountConnectScopeRepository accountConnectScopeRepository, AccountJoinOperationRepository accountJoinOperationRepository, AccountMembershipTransitionReceiptRepository membershipTransitionReceiptRepository, + AccountMembershipAuthorityEventProducer membershipAuthorityEventProducer, AccountEmailLoginChallengeRepository accountEmailLoginChallengeRepository, AccountRealmAccessGrantRepository accountRealmAccessGrantRepository, AccountTenantMembershipRepository accountTenantMembershipRepository, + AccountTenantMembershipRoleSnapshotRepository accountTenantMembershipRoleSnapshotRepository, AccountMapper accountMapper, ProfileRepository profileRepository, ProfileMapper profileMapper, @@ -182,13 +199,17 @@ public AccountServiceImpl( net.firedevops.firemud.accountservice.service.session.SessionService sessionService, PlatformTransactionManager transactionManager) { this.accountRepository = accountRepository; + this.accountAuthorityGenerationRepository = accountAuthorityGenerationRepository; this.accountAuditOutboxRepository = accountAuditOutboxRepository; this.accountConnectScopeRepository = accountConnectScopeRepository; this.accountJoinOperationRepository = accountJoinOperationRepository; this.membershipTransitionReceiptRepository = membershipTransitionReceiptRepository; + this.membershipAuthorityEventProducer = membershipAuthorityEventProducer; this.accountEmailLoginChallengeRepository = accountEmailLoginChallengeRepository; this.accountRealmAccessGrantRepository = accountRealmAccessGrantRepository; this.accountTenantMembershipRepository = accountTenantMembershipRepository; + this.accountTenantMembershipRoleSnapshotRepository = + accountTenantMembershipRoleSnapshotRepository; this.accountMapper = accountMapper; this.profileRepository = profileRepository; this.profileMapper = profileMapper; @@ -226,6 +247,9 @@ public AccountDto createAccount(CreateAccountRequest request) { } catch (IntegrityConstraintViolationException | DataIntegrityViolationException ex) { throw new AccountAlreadyExistsException(ex); } + requireCanonicalPersistedIdentity(saved); + accountAuthorityGenerationRepository.initialize( + AccountAuthorityGenerationRepository.AuthorityScope.account(saved.getAccountUuid())); accountAuditOutboxRepository.append( UUID.randomUUID(), "platform", @@ -235,6 +259,17 @@ public AccountDto createAccount(CreateAccountRequest request) { return accountMapper.toDto(saved); } + private void requireCanonicalPersistedIdentity(Account account) { + if (account == null + || account.getId() == null + || account.getAccountUuid() == null + || account.getAccountUuidProvenance() != AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT + || !account.getId().equals(account.getAccountUuidSourceNumericId())) { + throw new IllegalStateException( + "Account UUID readback did not match its exact persisted source row"); + } + } + @Override @Transactional @Timed(value = "account.authenticate") @@ -622,6 +657,38 @@ private JoinPublicProductionResult joinPublicProductionForTrustedCaller( requireMatchingJoinIntent(claimed, requestId, callerBinding, retained); } + JoinOperation beforeAttempt = + accountJoinOperationRepository + .find(requestId) + .orElseThrow( + () -> + new AuthenticationException( + "AUTH_UNAVAILABLE", "JOIN request claim is not yet readable")); + if ("PENDING".equals(beforeAttempt.status()) && !isConnectScopeExpired(retained)) { + try { + // A first JOIN consumes a previously committed positive absence baseline; creating it + // inside the JOIN transaction would never make that baseline durable while absent. + joinTransactionTemplate.execute( + transactionStatus -> { + if (isConnectScopeExpired(retained)) { + return null; + } + membershipAuthorityEventProducer.preparePairAuthorityForJoin( + accountId, retained.tenantId()); + if (isConnectScopeExpired(retained)) { + transactionStatus.setRollbackOnly(); + } + return null; + }); + } catch (RuntimeException unavailablePairAuthority) { + recordJoinAttemptFailureAfterRollback(requestId, "AUTH_UNAVAILABLE"); + throw new AuthenticationException( + "AUTH_UNAVAILABLE", + "JOIN membership pair authority is unavailable; retry the same request", + unavailablePairAuthority); + } + } + try { JoinAttemptOutcome outcome = joinTransactionTemplate.execute( @@ -756,21 +823,32 @@ private JoinPublicProductionResult executePendingJoinAttempt( boolean transitioned = false; String membershipTransitionType = null; if (membership == null) { - membershipTransitionReceiptRepository.assertNewMembershipTransitionCanStart( - accountId, scope.tenantId()); + var absenceBaseline = + membershipAuthorityEventProducer.requireNewMembershipBaseline( + accountId, scope.tenantId()); membership = new AccountTenantMembership(); membership.setAccount(requireAccount(accountId)); membership.setTenantId(scope.tenantId()); - membership.setMembershipVersion(1L); - membership.setMembershipAuthorityGeneration(1L); + membership.setMembershipVersion(Math.addExact(absenceBaseline.membershipVersion(), 1L)); + membership.setMembershipAuthorityGeneration(absenceBaseline.membershipAuthorityGeneration()); membership.setLifecycleState("ACTIVE"); membership.setGameplayAdmissionAllowed(true); membership.setAuthorityProvenance("EXPLICIT_JOIN"); accountTenantMembershipRepository.save(membership); + accountTenantMembershipRoleSnapshotRepository.replace( + membership, membership.getMembershipVersion(), List.of("player")); transitioned = true; membershipTransitionType = "MEMBERSHIP_JOINED"; } else if ("INACTIVE".equals(membership.getLifecycleState())) { - membershipTransitionReceiptRepository.requireInactiveMembershipHistory(membership); + RoleSnapshot roleSnapshot; + try { + roleSnapshot = requireRoleSnapshotForJoin(accountId, scope.tenantId(), membership); + membershipTransitionReceiptRepository.requireInactiveMembershipHistory(membership); + } catch (IllegalStateException contradictoryRetainedEvidence) { + return failedJoin(requestId, scope, "MEMBERSHIP_RECONCILIATION_REQUIRED"); + } + membershipAuthorityEventProducer.requireExistingMembershipAuthorityMatches( + accountId, scope.tenantId(), membership, roleSnapshot); accountJoinOperationRepository.recordCallerBoundAuthorityInvalidation(requestId); membership.setLifecycleState("ACTIVE"); membership.setGameplayAdmissionAllowed(true); @@ -779,20 +857,66 @@ private JoinPublicProductionResult executePendingJoinAttempt( membership.getMembershipAuthorityGeneration() + 1L); membership.setAuthorityProvenance("EXPLICIT_JOIN"); accountTenantMembershipRepository.save(membership); + List restoredRoles = new ArrayList<>(roleSnapshot.roles()); + if (!restoredRoles.contains("player")) { + restoredRoles.add("player"); + } + accountTenantMembershipRoleSnapshotRepository.replace( + membership, membership.getMembershipVersion(), restoredRoles); transitioned = true; membershipTransitionType = "MEMBERSHIP_REACTIVATED"; } else if ("ACTIVE".equals(membership.getLifecycleState()) && membership.isGameplayAdmissionAllowed()) { - membershipTransitionReceiptRepository - .findLatestReceipt(accountId, scope.tenantId()) - .orElseThrow( - () -> - new IllegalStateException( - "Active Account membership lacks a provisional transition receipt")); + RoleSnapshot roleSnapshot; + try { + roleSnapshot = requireRoleSnapshotForJoin(accountId, scope.tenantId(), membership); + } catch (IllegalStateException contradictoryRoleEvidence) { + return failedJoin(requestId, scope, "MEMBERSHIP_RECONCILIATION_REQUIRED"); + } + if (!roleSnapshot.roles().contains("player")) { + return failedJoin(requestId, scope, "MEMBERSHIP_RECONCILIATION_REQUIRED"); + } + MembershipTransitionReceipt receipt; + try { + receipt = + membershipTransitionReceiptRepository + .findLatestReceipt(accountId, scope.tenantId()) + .orElseThrow( + () -> + new IllegalStateException( + "Active Account membership lacks a provisional transition receipt")); + } catch (IllegalStateException contradictoryReceiptEvidence) { + return failedJoin(requestId, scope, "MEMBERSHIP_RECONCILIATION_REQUIRED"); + } + Checkpoint checkpoint = + membershipAuthorityEventProducer.requireCurrentMembershipEvent( + accountId, + scope.tenantId(), + membership, + roleSnapshot, + receipt.requestId(), + "MEMBERSHIP_REACTIVATED".equals(receipt.transitionType())); + if (checkpoint == null || checkpoint.outboxSequence() <= 0L) { + throw new IllegalStateException( + "Active Account membership authority checkpoint readback is incomplete"); + } } else { return failedJoin(requestId, scope, "MEMBERSHIP_RECONCILIATION_REQUIRED"); } if (transitioned) { + var authorityCheckpoint = + switch (membershipTransitionType) { + case "MEMBERSHIP_JOINED" -> + membershipAuthorityEventProducer.publishNewMembershipChange( + accountId, scope.tenantId(), requestId, membership); + case "MEMBERSHIP_REACTIVATED" -> + membershipAuthorityEventProducer.publishReactivatedMembershipChange( + accountId, scope.tenantId(), requestId, membership); + default -> throw new IllegalStateException("Unsupported Account membership transition"); + }; + if (authorityCheckpoint == null || authorityCheckpoint.outboxSequence() <= 0L) { + throw new IllegalStateException("Account JOIN authority checkpoint readback is incomplete"); + } membershipTransitionReceiptRepository.appendTransition( membership, membershipTransitionType, requestId); String payload = @@ -828,6 +952,31 @@ private JoinPublicProductionResult executePendingJoinAttempt( false); } + private RoleSnapshot requireRoleSnapshotForJoin( + long accountId, long tenantId, AccountTenantMembership membership) { + if (membership.getId() == null + || membership.getMembershipVersion() <= 0L + || membership.getAccount() == null + || membership.getAccount().getId() == null) { + throw new IllegalStateException("Account membership role snapshot identity is incomplete"); + } + RoleSnapshot snapshot = + accountTenantMembershipRoleSnapshotRepository + .findForUpdate( + accountId, tenantId, membership.getId(), membership.getMembershipVersion()) + .orElseThrow( + () -> + new IllegalStateException( + "Account membership role snapshot is missing or unverified")); + if (snapshot.accountId() != accountId + || snapshot.tenantId() != tenantId + || snapshot.membershipId() != membership.getId() + || snapshot.snapshotVersion() != membership.getMembershipVersion()) { + throw new IllegalStateException("Account membership role snapshot identity is mismatched"); + } + return snapshot; + } + private JoinPublicProductionResult failedJoin( String requestId, VerifiedJoinScope scope, String outcomeCode) { accountJoinOperationRepository.finish(requestId, "FAILED", outcomeCode, null, null, null); @@ -889,8 +1038,16 @@ private JoinPublicProductionResult replayTerminalJoin( private JoinPublicProductionResult replayTerminalJoinSafely( JoinOperation operation, String callerBinding, VerifiedJoinScope scope) { + // Expired caller scope cannot authorize outcome replay or a fresh policy check. Leave the + // durable operation untouched; reconciliation remains responsible for readback-only recovery. + if (isConnectScopeExpired(scope)) { + return joinRetryFailure(scope, "CONNECT_SCOPE_INVALID"); + } try { + requireCommittedOutcomeEventReadback(operation); return replayTerminalJoin(operation, callerBinding, scope); + } catch (AuthenticationException readbackFailure) { + return joinRetryFailure(scope, readbackFailure.getCode()); } catch (RuntimeException policyCheckFailure) { return joinRetryFailure(scope, "AUTH_UNAVAILABLE"); } @@ -970,6 +1127,87 @@ private void requireMatchingJoinIntent( } } + private void requireCommittedOutcomeEventReadback(JoinOperation operation) { + if ("COMMITTED".equals(operation.status()) + && ("JOINED".equals(operation.outcome()) || "ALREADY_ACTIVE".equals(operation.outcome()))) { + try { + Checkpoint checkpoint; + if (TransactionSynchronizationManager.isActualTransactionActive()) { + checkpoint = requireCommittedOutcomeEventEvidence(operation); + } else { + checkpoint = + joinTransactionTemplate.execute( + transactionStatus -> requireCommittedOutcomeEventEvidence(operation)); + } + if (checkpoint == null || checkpoint.outboxSequence() <= 0L) { + throw new IllegalStateException("Committed JOIN authority checkpoint is incomplete"); + } + } catch (RuntimeException exception) { + boolean unavailable = isCommittedOutcomeEventReadbackUnavailable(exception); + throw new AuthenticationException( + unavailable ? "AUTH_UNAVAILABLE" : "AUTH_SESSION_REVOKED", + unavailable + ? "Committed JOIN authority evidence is unavailable or mismatched" + : "Committed JOIN authority evidence is missing, malformed, or contradictory", + exception); + } + } + } + + private boolean isCommittedOutcomeEventReadbackUnavailable(Throwable exception) { + // Readback validators may retain dependency details as causes; only the top-level category + // determines availability so reachable malformed or contradictory evidence stays revoked. + if (exception instanceof AuthenticationException authenticationException) { + return "AUTH_UNAVAILABLE".equals(authenticationException.getCode()); + } + return exception instanceof org.springframework.dao.DataAccessException + || exception instanceof TransactionException + || exception instanceof org.jooq.exception.DataAccessException + || exception instanceof java.sql.SQLException; + } + + private Checkpoint requireCommittedOutcomeEventEvidence(JoinOperation operation) { + if ("JOINED".equals(operation.outcome())) { + return membershipAuthorityEventProducer.requireCommittedJoinEvent(operation); + } + if (!"ALREADY_ACTIVE".equals(operation.outcome()) + || operation.membershipId() == null + || operation.membershipVersion() == null + || operation.membershipAuthorityGeneration() == null) { + throw new IllegalStateException("Committed JOIN outcome has no exact membership identity"); + } + AccountTenantMembership membership = + accountTenantMembershipRepository + .findByAccountIdAndTenantId(operation.accountId(), operation.tenantId()) + .orElseThrow(() -> new IllegalStateException("Committed active membership is absent")); + if (!operation.membershipId().equals(membership.getId()) + || operation.membershipVersion() != membership.getMembershipVersion() + || operation.membershipAuthorityGeneration() + != membership.getMembershipAuthorityGeneration() + || !"ACTIVE".equals(membership.getLifecycleState()) + || !membership.isGameplayAdmissionAllowed()) { + throw new IllegalStateException( + "Committed ALREADY_ACTIVE operation differs from current membership state"); + } + RoleSnapshot roles = + requireRoleSnapshotForJoin(operation.accountId(), operation.tenantId(), membership); + if (!roles.roles().contains("player")) { + throw new IllegalStateException("Committed active membership lacks the player role"); + } + MembershipTransitionReceipt receipt = + membershipTransitionReceiptRepository + .findLatestReceipt(operation.accountId(), operation.tenantId()) + .orElseThrow( + () -> new IllegalStateException("Committed active membership has no receipt")); + return membershipAuthorityEventProducer.requireCurrentMembershipEvent( + operation.accountId(), + operation.tenantId(), + membership, + roles, + receipt.requestId(), + "MEMBERSHIP_REACTIVATED".equals(receipt.transitionType())); + } + private JoinPublicProductionResult resultFromJoinOperation( JoinOperation operation, boolean replayed) { return new JoinPublicProductionResult( @@ -2065,7 +2303,9 @@ private boolean hasRealmAccessGrant( } private String mintToken(String subject, long expirationMs, Map claims) { - return jwtUtil.generateToken(subject, expirationMs, claims); + Map accountClaims = new HashMap<>(claims); + accountClaims.put("iss", ACCOUNT_JWT_ISSUER); + return jwtUtil.generateToken(subject, expirationMs, accountClaims); } private Map authenticationTokenClaims(String audience, Account account) { diff --git a/services/account-service/src/main/resources/db/migration/V31__account_auth_authority_generations.sql b/services/account-service/src/main/resources/db/migration/V31__account_auth_authority_generations.sql new file mode 100644 index 0000000000..623a7b9d84 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V31__account_auth_authority_generations.sql @@ -0,0 +1,130 @@ +CREATE TABLE account_authority_generations ( + scope_kind VARCHAR(16) NOT NULL, + issuer_id VARCHAR(512), + account_uuid UUID, + tenant_uuid UUID, + generation BIGINT NOT NULL, + source_version BIGINT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_authority_generations_scope_kind_check + CHECK (scope_kind IN ('ISSUER', 'ACCOUNT', 'TENANT', 'MEMBERSHIP')), + CONSTRAINT account_authority_generations_positive_check + CHECK (generation > 0 AND source_version > 0), + CONSTRAINT account_authority_generations_scope_shape_check CHECK ( + (scope_kind = 'ISSUER' AND issuer_id IS NOT NULL AND issuer_id <> '' + AND account_uuid IS NULL AND tenant_uuid IS NULL) + OR (scope_kind = 'ACCOUNT' AND issuer_id IS NULL + AND account_uuid IS NOT NULL AND tenant_uuid IS NULL) + OR (scope_kind = 'TENANT' AND issuer_id IS NULL + AND account_uuid IS NULL AND tenant_uuid IS NOT NULL) + OR (scope_kind = 'MEMBERSHIP' AND issuer_id IS NULL + AND account_uuid IS NOT NULL AND tenant_uuid IS NOT NULL) + ), + CONSTRAINT account_authority_generations_account_fk + FOREIGN KEY (account_uuid) REFERENCES accounts (account_uuid) +); + +CREATE UNIQUE INDEX account_authority_generations_issuer_scope_uq + ON account_authority_generations (issuer_id) + WHERE scope_kind = 'ISSUER'; +CREATE UNIQUE INDEX account_authority_generations_account_scope_uq + ON account_authority_generations (account_uuid) + WHERE scope_kind = 'ACCOUNT'; +CREATE UNIQUE INDEX account_authority_generations_tenant_scope_uq + ON account_authority_generations (tenant_uuid) + WHERE scope_kind = 'TENANT'; +CREATE UNIQUE INDEX account_authority_generations_membership_scope_uq + ON account_authority_generations (account_uuid, tenant_uuid) + WHERE scope_kind = 'MEMBERSHIP'; + +CREATE TABLE account_authority_issuance_fences ( + account_uuid UUID PRIMARY KEY, + issuance_fence BIGINT NOT NULL, + source_version BIGINT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_authority_issuance_fences_positive_check + CHECK (issuance_fence > 0 AND source_version > 0), + CONSTRAINT account_authority_issuance_fences_account_fk + FOREIGN KEY (account_uuid) REFERENCES accounts (account_uuid) +); + +-- [jooq ignore start] +CREATE FUNCTION account_authority_generation_monotonic_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.scope_kind IS DISTINCT FROM OLD.scope_kind + OR NEW.issuer_id IS DISTINCT FROM OLD.issuer_id + OR NEW.account_uuid IS DISTINCT FROM OLD.account_uuid + OR NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid THEN + RAISE EXCEPTION 'Account authority generation scope cannot be reassigned' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_generation_scope_immutable'; + END IF; + IF NEW.generation <> OLD.generation + 1 + OR NEW.source_version <> OLD.source_version + 1 THEN + RAISE EXCEPTION 'Account authority generation and source version must advance by one' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_generation_monotonic'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_authority_generations_monotonic + BEFORE UPDATE ON account_authority_generations + FOR EACH ROW EXECUTE FUNCTION account_authority_generation_monotonic_guard(); + +CREATE FUNCTION account_authority_generation_no_delete() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account authority generation history cannot be deleted' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_generation_no_delete'; + RETURN OLD; +END; +$$; + +CREATE TRIGGER account_authority_generations_no_delete + BEFORE DELETE ON account_authority_generations + FOR EACH ROW EXECUTE FUNCTION account_authority_generation_no_delete(); + +CREATE FUNCTION account_authority_issuance_fence_monotonic_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.account_uuid IS DISTINCT FROM OLD.account_uuid THEN + RAISE EXCEPTION 'Account authority issuance-fence scope cannot be reassigned' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_issuance_fence_scope_immutable'; + END IF; + IF NEW.issuance_fence <> OLD.issuance_fence + 1 + OR NEW.source_version <> OLD.source_version + 1 THEN + RAISE EXCEPTION 'Account authority issuance fence and source version must advance by one' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_issuance_fence_monotonic'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_authority_issuance_fences_monotonic + BEFORE UPDATE ON account_authority_issuance_fences + FOR EACH ROW EXECUTE FUNCTION account_authority_issuance_fence_monotonic_guard(); + +CREATE FUNCTION account_authority_issuance_fence_no_delete() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account authority issuance-fence history cannot be deleted' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_issuance_fence_no_delete'; + RETURN OLD; +END; +$$; + +CREATE TRIGGER account_authority_issuance_fences_no_delete + BEFORE DELETE ON account_authority_issuance_fences + FOR EACH ROW EXECUTE FUNCTION account_authority_issuance_fence_no_delete(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V32__account_membership_role_snapshots.sql b/services/account-service/src/main/resources/db/migration/V32__account_membership_role_snapshots.sql new file mode 100644 index 0000000000..9ded0df97b --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V32__account_membership_role_snapshots.sql @@ -0,0 +1,29 @@ +-- Account-owned tenant-role snapshots are intentionally not backfilled. A snapshot +-- header is the authoritative presence marker, including for an authoritative empty +-- role set; retained membership rows without one remain unverified. +CREATE TABLE account_tenant_membership_role_snapshots ( + membership_id BIGINT PRIMARY KEY + REFERENCES account_tenant_membership(id) ON DELETE RESTRICT, + snapshot_version BIGINT NOT NULL, + CONSTRAINT account_membership_role_snapshot_version_check + CHECK (snapshot_version > 0), + CONSTRAINT account_membership_role_snapshot_identity_unique + UNIQUE (membership_id, snapshot_version) +); + +CREATE TABLE account_tenant_membership_role_snapshot_roles ( + membership_id BIGINT NOT NULL, + snapshot_version BIGINT NOT NULL, + role_identifier VARCHAR(128) NOT NULL, + CONSTRAINT account_membership_role_snapshot_roles_pk + PRIMARY KEY (membership_id, snapshot_version, role_identifier), + CONSTRAINT account_membership_role_snapshot_roles_snapshot_fk + FOREIGN KEY (membership_id, snapshot_version) + REFERENCES account_tenant_membership_role_snapshots(membership_id, snapshot_version) + ON DELETE RESTRICT, + CONSTRAINT account_membership_role_snapshot_role_identifier_check + CHECK (role_identifier ~ '^[A-Za-z][A-Za-z0-9_-]*$') +); + +CREATE INDEX idx_account_membership_role_snapshot_roles_lookup + ON account_tenant_membership_role_snapshot_roles (membership_id, snapshot_version); diff --git a/services/account-service/src/main/resources/db/migration/V33__account_authority_outbox.sql b/services/account-service/src/main/resources/db/migration/V33__account_authority_outbox.sql new file mode 100644 index 0000000000..6d99c8ea00 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V33__account_authority_outbox.sql @@ -0,0 +1,157 @@ +CREATE TABLE account_authority_outbox_streams ( + outbox_stream_key VARCHAR(2048) PRIMARY KEY, + last_sequence BIGINT NOT NULL DEFAULT 0, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_authority_outbox_stream_key_check CHECK ( + outbox_stream_key LIKE 'account:auth-authority:v1:%' + AND length(outbox_stream_key) > char_length('account:auth-authority:v1:') + AND length(btrim(substr(outbox_stream_key, char_length('account:auth-authority:v1:') + 1))) > 0 + ), + CONSTRAINT account_authority_outbox_stream_sequence_check CHECK (last_sequence >= 0) +); + +CREATE TABLE account_authority_outbox_events ( + outbox_stream_key VARCHAR(2048) NOT NULL, + outbox_sequence BIGINT NOT NULL, + request_id VARCHAR(512) NOT NULL, + event_id VARCHAR(512) NOT NULL, + event_digest TEXT NOT NULL, + payload BYTEA NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_authority_outbox_events_pk + PRIMARY KEY (outbox_stream_key, outbox_sequence), + CONSTRAINT account_authority_outbox_events_request_uq + UNIQUE (outbox_stream_key, request_id), + CONSTRAINT account_authority_outbox_events_event_uq + UNIQUE (outbox_stream_key, event_id), + CONSTRAINT account_authority_outbox_events_sequence_check + CHECK (outbox_sequence > 0), + CONSTRAINT account_authority_outbox_events_request_id_check + CHECK (length(btrim(request_id)) > 0), + CONSTRAINT account_authority_outbox_events_event_id_check + CHECK (length(btrim(event_id)) > 0), + CONSTRAINT account_authority_outbox_events_digest_check + CHECK (length(btrim(event_digest)) > 0), + CONSTRAINT account_authority_outbox_events_payload_check + CHECK (octet_length(payload) > 0), + CONSTRAINT account_authority_outbox_events_stream_fk + FOREIGN KEY (outbox_stream_key) + REFERENCES account_authority_outbox_streams (outbox_stream_key) + ON DELETE RESTRICT +); + +-- [jooq ignore start] +CREATE FUNCTION account_authority_outbox_stream_update_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.outbox_stream_key IS DISTINCT FROM OLD.outbox_stream_key THEN + RAISE EXCEPTION 'Account authority outbox stream identity cannot be reassigned' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_outbox_stream_immutable'; + END IF; + IF NEW.last_sequence <> OLD.last_sequence + 1 THEN + RAISE EXCEPTION 'Account authority outbox sequence must advance by one' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_outbox_sequence_contiguous'; + END IF; + NEW.updated_at = CURRENT_TIMESTAMP; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_authority_outbox_stream_delete_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account authority outbox stream history cannot be deleted' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_outbox_stream_no_delete'; + RETURN OLD; +END; +$$; + +CREATE FUNCTION account_authority_outbox_event_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + head_sequence BIGINT; + previous_sequence BIGINT; +BEGIN + SELECT last_sequence INTO head_sequence + FROM account_authority_outbox_streams + WHERE outbox_stream_key = NEW.outbox_stream_key; + SELECT COALESCE(MAX(outbox_sequence), 0) INTO previous_sequence + FROM account_authority_outbox_events + WHERE outbox_stream_key = NEW.outbox_stream_key; + + IF head_sequence IS DISTINCT FROM NEW.outbox_sequence + OR NEW.outbox_sequence <> previous_sequence + 1 THEN + RAISE EXCEPTION 'Account authority outbox event must match the next stream sequence' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_outbox_event_contiguous'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_authority_outbox_event_immutable_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account authority outbox event evidence is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_outbox_event_immutable'; + RETURN OLD; +END; +$$; + +CREATE FUNCTION account_authority_outbox_stream_consistency_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + stream_sequence BIGINT; + event_sequence BIGINT; +BEGIN + SELECT last_sequence INTO stream_sequence + FROM account_authority_outbox_streams + WHERE outbox_stream_key = NEW.outbox_stream_key; + SELECT COALESCE(MAX(outbox_sequence), 0) INTO event_sequence + FROM account_authority_outbox_events + WHERE outbox_stream_key = NEW.outbox_stream_key; + + IF stream_sequence IS NULL OR stream_sequence < 1 OR stream_sequence <> event_sequence THEN + RAISE EXCEPTION 'Account authority outbox stream head must match committed event history' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_outbox_stream_consistent'; + END IF; + RETURN NULL; +END; +$$; + +CREATE TRIGGER account_authority_outbox_stream_update + BEFORE UPDATE ON account_authority_outbox_streams + FOR EACH ROW EXECUTE FUNCTION account_authority_outbox_stream_update_guard(); + +CREATE TRIGGER account_authority_outbox_stream_delete + BEFORE DELETE ON account_authority_outbox_streams + FOR EACH ROW EXECUTE FUNCTION account_authority_outbox_stream_delete_guard(); + +CREATE TRIGGER account_authority_outbox_event_insert + BEFORE INSERT ON account_authority_outbox_events + FOR EACH ROW EXECUTE FUNCTION account_authority_outbox_event_insert_guard(); + +CREATE TRIGGER account_authority_outbox_event_update + BEFORE UPDATE OR DELETE ON account_authority_outbox_events + FOR EACH ROW EXECUTE FUNCTION account_authority_outbox_event_immutable_guard(); + +CREATE CONSTRAINT TRIGGER account_authority_outbox_stream_consistent + AFTER INSERT OR UPDATE ON account_authority_outbox_streams + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_authority_outbox_stream_consistency_guard(); + +CREATE CONSTRAINT TRIGGER account_authority_outbox_event_stream_consistent + AFTER INSERT ON account_authority_outbox_events + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_authority_outbox_stream_consistency_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V34__enroll_retained_account_authority.sql b/services/account-service/src/main/resources/db/migration/V34__enroll_retained_account_authority.sql new file mode 100644 index 0000000000..4a2c86eade --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V34__enroll_retained_account_authority.sql @@ -0,0 +1,70 @@ +-- Retained Account rows receive the exact account-scoped state only when both +-- durable components are absent. The migration transaction keeps the pair +-- atomic with respect to concurrent Account writes. +-- [jooq ignore start] +LOCK TABLE accounts, account_authority_generations, account_authority_issuance_fences + IN SHARE ROW EXCLUSIVE MODE; +-- [jooq ignore stop] + +-- [jooq ignore start] +DO $migration$ +DECLARE + incomplete_account_uuid UUID; +BEGIN + SELECT account.account_uuid + INTO incomplete_account_uuid + FROM accounts AS account + LEFT JOIN account_authority_generations AS generation + ON generation.scope_kind = 'ACCOUNT' + AND generation.account_uuid = account.account_uuid + LEFT JOIN account_authority_issuance_fences AS issuance_fence + ON issuance_fence.account_uuid = account.account_uuid + WHERE (generation.account_uuid IS NULL) <> (issuance_fence.account_uuid IS NULL) + ORDER BY account.account_uuid + LIMIT 1; + + IF incomplete_account_uuid IS NOT NULL THEN + RAISE EXCEPTION + 'Retained Account % has incomplete authority generation and issuance-fence state', + incomplete_account_uuid + USING ERRCODE = '23514', + CONSTRAINT = 'account_authority_retained_pair_incomplete'; + END IF; +END; +$migration$; +-- [jooq ignore stop] + +INSERT INTO account_authority_generations ( + scope_kind, + account_uuid, + generation, + source_version +) +SELECT + 'ACCOUNT', + account.account_uuid, + 1, + 1 +FROM accounts AS account +WHERE NOT EXISTS ( + SELECT 1 + FROM account_authority_generations AS generation + WHERE generation.scope_kind = 'ACCOUNT' + AND generation.account_uuid = account.account_uuid +); + +INSERT INTO account_authority_issuance_fences ( + account_uuid, + issuance_fence, + source_version +) +SELECT + account.account_uuid, + 1, + 1 +FROM accounts AS account +WHERE NOT EXISTS ( + SELECT 1 + FROM account_authority_issuance_fences AS issuance_fence + WHERE issuance_fence.account_uuid = account.account_uuid +); diff --git a/services/account-service/src/main/resources/db/migration/V35__account_connect_token_issuance_storage.sql b/services/account-service/src/main/resources/db/migration/V35__account_connect_token_issuance_storage.sql new file mode 100644 index 0000000000..26130078b2 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V35__account_connect_token_issuance_storage.sql @@ -0,0 +1,283 @@ +-- Durable first-writer-wins receipts own connect-token issuance identity and outcome evidence. +-- The response envelope is a separate bounded, purpose-tagged encrypted record. Neither table +-- stores the raw gameplay-connect JWT. +CREATE TABLE account_connect_token_issuance_operations ( + operation_id UUID PRIMARY KEY, + account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE RESTRICT, + tenant_id BIGINT NOT NULL, + connect_scope_hash VARCHAR(71) NOT NULL, + request_id VARCHAR(128) NOT NULL, + request_digest_version INTEGER NOT NULL, + request_digest BYTEA NOT NULL, + status VARCHAR(16) NOT NULL, + outcome_code VARCHAR(64), + token_identity VARCHAR(128), + token_hash BYTEA, + context_evidence_digest BYTEA, + authority_tuple_digest BYTEA, + issuance_fence_digest BYTEA, + postcondition_digest BYTEA, + reconciliation_attempt_count INTEGER NOT NULL DEFAULT 0, + last_reconciliation_attempt_at TIMESTAMPTZ, + last_reconciliation_attempt_reason VARCHAR(128), + next_reconciliation_attempt_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_connect_token_issuance_identity_uq + UNIQUE (account_id, tenant_id, connect_scope_hash, request_id), + CONSTRAINT account_connect_token_issuance_identity_check + CHECK (account_id > 0 + AND tenant_id > 0 + AND length(btrim(request_id)) BETWEEN 1 AND 128 + AND length(connect_scope_hash) = 71 + AND connect_scope_hash ~ '^sha256:[0-9a-f]{64}$' + AND request_digest_version = 1 + AND octet_length(request_digest) = 32), + CONSTRAINT account_connect_token_issuance_status_check + CHECK (status IN ('PENDING', 'COMMITTED', 'FAILED', 'ABORTED')), + CONSTRAINT account_connect_token_issuance_reconciliation_check + CHECK (reconciliation_attempt_count >= 0 + AND ((reconciliation_attempt_count = 0 + AND last_reconciliation_attempt_at IS NULL + AND last_reconciliation_attempt_reason IS NULL) + OR (reconciliation_attempt_count > 0 + AND last_reconciliation_attempt_at IS NOT NULL + AND last_reconciliation_attempt_reason IS NOT NULL + AND length(btrim(last_reconciliation_attempt_reason)) BETWEEN 1 AND 128))), + CONSTRAINT account_connect_token_issuance_evidence_check + CHECK ((token_hash IS NULL OR octet_length(token_hash) = 32) + AND (context_evidence_digest IS NULL OR octet_length(context_evidence_digest) = 32) + AND (authority_tuple_digest IS NULL OR octet_length(authority_tuple_digest) = 32) + AND (issuance_fence_digest IS NULL OR octet_length(issuance_fence_digest) = 32) + AND (postcondition_digest IS NULL OR octet_length(postcondition_digest) = 32)), + CONSTRAINT account_connect_token_issuance_outcome_check + CHECK ((status IN ('PENDING', 'ABORTED') AND outcome_code IS NULL) + OR (status = 'COMMITTED' + AND outcome_code = 'SUCCESS' + AND token_identity IS NOT NULL + AND length(btrim(token_identity)) BETWEEN 1 AND 128 + AND token_hash IS NOT NULL + AND context_evidence_digest IS NOT NULL + AND authority_tuple_digest IS NOT NULL + AND issuance_fence_digest IS NOT NULL + AND postcondition_digest IS NOT NULL) + OR (status = 'FAILED' + AND outcome_code IS NOT NULL + AND length(btrim(outcome_code)) BETWEEN 1 AND 64 + AND outcome_code <> 'SUCCESS' + AND token_identity IS NULL + AND token_hash IS NULL + AND context_evidence_digest IS NOT NULL + AND authority_tuple_digest IS NOT NULL + AND issuance_fence_digest IS NOT NULL + AND postcondition_digest IS NOT NULL)) +); + +CREATE INDEX idx_account_connect_token_issuance_pending + ON account_connect_token_issuance_operations( + next_reconciliation_attempt_at, + created_at, + operation_id + ) + WHERE status IN ('PENDING', 'ABORTED'); + +CREATE TABLE account_connect_token_response_envelopes ( + operation_id UUID PRIMARY KEY, + operation_kind VARCHAR(32) NOT NULL, + account_id BIGINT NOT NULL, + tenant_id BIGINT NOT NULL, + connect_scope_hash VARCHAR(71) NOT NULL, + request_id VARCHAR(128) NOT NULL, + request_digest_version INTEGER NOT NULL, + request_digest BYTEA NOT NULL, + format_version INTEGER NOT NULL, + key_id VARCHAR(64) NOT NULL, + purpose VARCHAR(32) NOT NULL, + nonce BYTEA NOT NULL, + ciphertext BYTEA NOT NULL, + context_evidence_digest BYTEA NOT NULL, + authority_tuple_digest BYTEA NOT NULL, + issuance_fence_digest BYTEA NOT NULL, + postcondition_digest BYTEA NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_connect_token_response_envelope_operation_fk + FOREIGN KEY (operation_id) + REFERENCES account_connect_token_issuance_operations(operation_id) + ON DELETE RESTRICT, + CONSTRAINT account_connect_token_response_envelope_identity_check + CHECK (operation_kind = 'CONNECT_TOKEN_ISSUANCE' + AND account_id > 0 + AND tenant_id > 0 + AND length(connect_scope_hash) = 71 + AND connect_scope_hash ~ '^sha256:[0-9a-f]{64}$' + AND length(btrim(request_id)) BETWEEN 1 AND 128 + AND request_digest_version = 1 + AND octet_length(request_digest) = 32), + CONSTRAINT account_connect_token_response_envelope_crypto_check + CHECK (format_version = 1 + AND length(btrim(key_id)) BETWEEN 1 AND 64 + AND key_id ~ '^[A-Za-z0-9_-]+$' + AND purpose = 'CONNECT_TOKEN_RESPONSE' + AND octet_length(nonce) = 12 + AND octet_length(ciphertext) BETWEEN 16 AND 65552 + AND octet_length(context_evidence_digest) = 32 + AND octet_length(authority_tuple_digest) = 32 + AND octet_length(issuance_fence_digest) = 32 + AND octet_length(postcondition_digest) = 32) +); + +-- A request's first writer owns its identity and digest. Only its lifecycle/evidence may advance. +-- ABORTED rows may later resolve to a deterministic committed or failed result after reconciliation. +-- No retention cleanup path is defined here; direct deletion of either replay record is rejected. +-- [jooq ignore start] +CREATE FUNCTION account_connect_token_issuance_operation_update_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.operation_id IS DISTINCT FROM OLD.operation_id + OR NEW.account_id IS DISTINCT FROM OLD.account_id + OR NEW.tenant_id IS DISTINCT FROM OLD.tenant_id + OR NEW.connect_scope_hash IS DISTINCT FROM OLD.connect_scope_hash + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.request_digest_version IS DISTINCT FROM OLD.request_digest_version + OR NEW.request_digest IS DISTINCT FROM OLD.request_digest + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'Connect-token issuance identity and request digest are immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_connect_token_issuance_identity_immutable'; + END IF; + IF (OLD.token_identity IS NOT NULL AND NEW.token_identity IS DISTINCT FROM OLD.token_identity) + OR (OLD.token_hash IS NOT NULL AND NEW.token_hash IS DISTINCT FROM OLD.token_hash) + OR (OLD.context_evidence_digest IS NOT NULL + AND NEW.context_evidence_digest IS DISTINCT FROM OLD.context_evidence_digest) + OR (OLD.authority_tuple_digest IS NOT NULL + AND NEW.authority_tuple_digest IS DISTINCT FROM OLD.authority_tuple_digest) + OR (OLD.issuance_fence_digest IS NOT NULL + AND NEW.issuance_fence_digest IS DISTINCT FROM OLD.issuance_fence_digest) + OR (OLD.postcondition_digest IS NOT NULL + AND NEW.postcondition_digest IS DISTINCT FROM OLD.postcondition_digest) THEN + RAISE EXCEPTION 'Connect-token issuance evidence cannot be replaced' + USING ERRCODE = '23514', CONSTRAINT = 'account_connect_token_issuance_evidence_immutable'; + END IF; + IF OLD.status IN ('COMMITTED', 'FAILED') THEN + RAISE EXCEPTION 'Terminal connect-token issuance outcome is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_connect_token_issuance_terminal_immutable'; + END IF; + IF NEW.status IS DISTINCT FROM OLD.status + AND NOT ((OLD.status = 'PENDING' AND NEW.status IN ('COMMITTED', 'FAILED', 'ABORTED')) + OR (OLD.status = 'ABORTED' AND NEW.status IN ('COMMITTED', 'FAILED'))) THEN + RAISE EXCEPTION 'Connect-token issuance lifecycle transition is invalid' + USING ERRCODE = '23514', CONSTRAINT = 'account_connect_token_issuance_lifecycle_transition'; + END IF; + NEW.updated_at = CURRENT_TIMESTAMP; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_connect_token_issuance_operation_update_guard_trigger + BEFORE UPDATE ON account_connect_token_issuance_operations + FOR EACH ROW + EXECUTE FUNCTION account_connect_token_issuance_operation_update_guard(); + +CREATE FUNCTION account_connect_token_response_envelope_update_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Connect-token response envelope is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_connect_token_response_envelope_immutable'; + RETURN OLD; +END; +$$; + +CREATE TRIGGER account_connect_token_response_envelope_update_guard_trigger + BEFORE UPDATE ON account_connect_token_response_envelopes + FOR EACH ROW + EXECUTE FUNCTION account_connect_token_response_envelope_update_guard(); + +CREATE FUNCTION account_connect_token_response_envelope_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + operation account_connect_token_issuance_operations%ROWTYPE; +BEGIN + SELECT * INTO operation + FROM account_connect_token_issuance_operations + WHERE operation_id = NEW.operation_id; + IF NOT FOUND + OR operation.status NOT IN ('COMMITTED', 'FAILED') + OR operation.account_id IS DISTINCT FROM NEW.account_id + OR operation.tenant_id IS DISTINCT FROM NEW.tenant_id + OR operation.connect_scope_hash IS DISTINCT FROM NEW.connect_scope_hash + OR operation.request_id IS DISTINCT FROM NEW.request_id + OR operation.request_digest_version IS DISTINCT FROM NEW.request_digest_version + OR operation.request_digest IS DISTINCT FROM NEW.request_digest + OR operation.context_evidence_digest IS DISTINCT FROM NEW.context_evidence_digest + OR operation.authority_tuple_digest IS DISTINCT FROM NEW.authority_tuple_digest + OR operation.issuance_fence_digest IS DISTINCT FROM NEW.issuance_fence_digest + OR operation.postcondition_digest IS DISTINCT FROM NEW.postcondition_digest THEN + RAISE EXCEPTION 'Connect-token response envelope does not match its terminal operation' + USING ERRCODE = '23514', CONSTRAINT = 'account_connect_token_response_envelope_operation_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_connect_token_response_envelope_insert_guard_trigger + BEFORE INSERT ON account_connect_token_response_envelopes + FOR EACH ROW + EXECUTE FUNCTION account_connect_token_response_envelope_insert_guard(); + +CREATE FUNCTION account_connect_token_issuance_no_delete() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Connect-token issuance replay evidence cannot be deleted' + USING ERRCODE = '23514', CONSTRAINT = 'account_connect_token_issuance_no_delete'; + RETURN OLD; +END; +$$; + +CREATE TRIGGER account_connect_token_issuance_operation_no_delete_trigger + BEFORE DELETE ON account_connect_token_issuance_operations + FOR EACH ROW EXECUTE FUNCTION account_connect_token_issuance_no_delete(); + +CREATE TRIGGER account_connect_token_response_envelope_no_delete_trigger + BEFORE DELETE ON account_connect_token_response_envelopes + FOR EACH ROW EXECUTE FUNCTION account_connect_token_issuance_no_delete(); + +CREATE FUNCTION account_connect_token_terminal_envelope_check() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.status IN ('COMMITTED', 'FAILED') AND NOT EXISTS ( + SELECT 1 + FROM account_connect_token_response_envelopes envelope + WHERE envelope.operation_id = NEW.operation_id + AND envelope.account_id = NEW.account_id + AND envelope.tenant_id = NEW.tenant_id + AND envelope.connect_scope_hash = NEW.connect_scope_hash + AND envelope.request_id = NEW.request_id + AND envelope.request_digest_version = NEW.request_digest_version + AND envelope.request_digest = NEW.request_digest + AND envelope.context_evidence_digest = NEW.context_evidence_digest + AND envelope.authority_tuple_digest = NEW.authority_tuple_digest + AND envelope.issuance_fence_digest = NEW.issuance_fence_digest + AND envelope.postcondition_digest = NEW.postcondition_digest + ) THEN + RAISE EXCEPTION 'Terminal connect-token issuance requires its exact response envelope' + USING ERRCODE = '23514', CONSTRAINT = 'account_connect_token_terminal_envelope_required'; + END IF; + RETURN NULL; +END; +$$; + +CREATE CONSTRAINT TRIGGER account_connect_token_terminal_envelope_check_trigger + AFTER INSERT OR UPDATE ON account_connect_token_issuance_operations + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW + EXECUTE FUNCTION account_connect_token_terminal_envelope_check(); +-- [jooq ignore end] diff --git a/services/account-service/src/main/resources/db/migration/V36__account_membership_pair_authority.sql b/services/account-service/src/main/resources/db/migration/V36__account_membership_pair_authority.sql new file mode 100644 index 0000000000..bf828e02aa --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V36__account_membership_pair_authority.sql @@ -0,0 +1,96 @@ +-- A never-joined pair has durable positive authority before it may report a +-- sequence-zero snapshot. This migration intentionally invents no baseline for +-- retained membership/history; Account enrolls only exact verified pairs. +CREATE TABLE account_membership_pair_authority ( + account_uuid UUID NOT NULL, + tenant_uuid UUID NOT NULL, + legacy_tenant_id BIGINT NOT NULL CHECK (legacy_tenant_id > 0), + tenant_provenance_kind VARCHAR(32) NOT NULL, + tenant_source_operation_id UUID NOT NULL, + tenant_provenance_digest VARCHAR(71) NOT NULL, + membership_exists BOOLEAN NOT NULL, + membership_version BIGINT NOT NULL CHECK (membership_version > 0), + membership_authority_generation BIGINT NOT NULL + CHECK (membership_authority_generation > 0), + last_event_sequence BIGINT NOT NULL CHECK (last_event_sequence >= 0), + last_event_id VARCHAR(512), + last_event_digest VARCHAR(71), + last_transition_invalidated BOOLEAN NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_membership_pair_authority_pk + PRIMARY KEY (account_uuid, tenant_uuid), + CONSTRAINT account_membership_pair_authority_account_fk + FOREIGN KEY (account_uuid) REFERENCES accounts (account_uuid), + CONSTRAINT account_membership_pair_authority_provenance_kind_check + CHECK (tenant_provenance_kind IN ('APPROVED_RETAINED', 'FRESH_GAME_DESIGN')), + CONSTRAINT account_membership_pair_authority_provenance_digest_check + CHECK (tenant_provenance_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT account_membership_pair_authority_event_shape_check CHECK ( + (last_event_sequence = 0 AND NOT membership_exists + AND last_event_id IS NULL AND last_event_digest IS NULL + AND NOT last_transition_invalidated) + OR (last_event_sequence > 0 AND last_event_id IS NOT NULL + AND length(btrim(last_event_id)) > 0 + AND last_event_digest IS NOT NULL + AND last_event_digest ~ '^sha256:[0-9a-f]{64}$') + ) +); + +-- The retained numeric key is an Account-local bridge, never the canonical +-- stream identity. Its pairing must remain one-to-one for each Account UUID. +CREATE UNIQUE INDEX account_membership_pair_authority_legacy_scope_uq + ON account_membership_pair_authority (account_uuid, legacy_tenant_id); + +-- [jooq ignore start] +CREATE FUNCTION account_membership_pair_authority_update_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.account_uuid IS DISTINCT FROM OLD.account_uuid + OR NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid + OR NEW.legacy_tenant_id IS DISTINCT FROM OLD.legacy_tenant_id + OR NEW.tenant_provenance_kind IS DISTINCT FROM OLD.tenant_provenance_kind + OR NEW.tenant_source_operation_id IS DISTINCT FROM OLD.tenant_source_operation_id + OR NEW.tenant_provenance_digest IS DISTINCT FROM OLD.tenant_provenance_digest + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'Account membership pair identity and provenance are immutable' + USING ERRCODE = '23514', + CONSTRAINT = 'account_membership_pair_authority_identity_immutable'; + END IF; + IF NEW.membership_version <> OLD.membership_version + 1 + OR NEW.last_event_sequence <> OLD.last_event_sequence + 1 + OR (NEW.last_transition_invalidated AND NEW.membership_authority_generation <> + OLD.membership_authority_generation + 1) + OR (NOT NEW.last_transition_invalidated AND NEW.membership_authority_generation <> + OLD.membership_authority_generation) THEN + RAISE EXCEPTION 'Account membership pair transition must advance exact authority' + USING ERRCODE = '23514', + CONSTRAINT = 'account_membership_pair_authority_transition_monotonic'; + END IF; + NEW.updated_at = CURRENT_TIMESTAMP; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_membership_pair_authority_no_delete() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account membership pair authority history cannot be deleted' + USING ERRCODE = '23514', + CONSTRAINT = 'account_membership_pair_authority_no_delete'; + RETURN OLD; +END; +$$; + +CREATE TRIGGER account_membership_pair_authority_update + BEFORE UPDATE ON account_membership_pair_authority + FOR EACH ROW EXECUTE FUNCTION account_membership_pair_authority_update_guard(); + +CREATE TRIGGER account_membership_pair_authority_delete + BEFORE DELETE ON account_membership_pair_authority + FOR EACH ROW EXECUTE FUNCTION account_membership_pair_authority_no_delete(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java index decacb239c..8dc940101d 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java @@ -112,6 +112,50 @@ void publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly() throws Number accountId = dsl.resultQuery("SELECT id FROM accounts WHERE email = ?", email).fetchOne(0, Number.class); assertThat(accountId).isNotNull(); + UUID accountUuid = + dsl.resultQuery("SELECT account_uuid FROM accounts WHERE email = ?", email) + .fetchOne(0, UUID.class); + assertThat(accountUuid).isNotNull(); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_authority_generations " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + accountUuid) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + Long generation = + dsl.resultQuery( + "SELECT generation FROM account_authority_generations " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + accountUuid) + .fetchOne(0, Long.class); + Long sourceVersion = + dsl.resultQuery( + "SELECT source_version FROM account_authority_generations " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + accountUuid) + .fetchOne(0, Long.class); + assertThat(generation).isPositive().isEqualTo(1L); + assertThat(sourceVersion).isPositive().isEqualTo(1L); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_authority_issuance_fences " + + "WHERE account_uuid = ?", + accountUuid) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + Long issuanceFence = + dsl.resultQuery( + "SELECT issuance_fence FROM account_authority_issuance_fences WHERE account_uuid = ?", + accountUuid) + .fetchOne(0, Long.class); + Long issuanceFenceSourceVersion = + dsl.resultQuery( + "SELECT source_version FROM account_authority_issuance_fences WHERE account_uuid = ?", + accountUuid) + .fetchOne(0, Long.class); + assertThat(issuanceFence).isPositive().isEqualTo(1L); + assertThat(issuanceFenceSourceVersion).isPositive().isEqualTo(1L); assertThat(dsl.fetchValue("SELECT tenant_id FROM accounts WHERE id = ?", accountId.longValue())) .isNull(); assertThat(dsl.fetchValue("SELECT role FROM accounts WHERE id = ?", accountId.longValue())) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java index 6f052cf92b..030170afb2 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.accountservice; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; @@ -8,11 +9,18 @@ import static org.mockito.Mockito.when; import java.nio.charset.StandardCharsets; +import java.util.Base64; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.UUID; +import 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 java.util.concurrent.atomic.AtomicBoolean; import net.firedevops.firemud.accountservice.client.EntityManagementClient; import net.firedevops.firemud.accountservice.client.GameSessionClient; @@ -24,10 +32,17 @@ import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceipt; import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceiptDigest; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; +import net.firedevops.firemud.accountservice.repository.LegacyTenantSourceEvidence; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; import net.firedevops.firemud.accountservice.service.AccountService; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; import net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer; import net.firedevops.firemud.gamesession.v1.GameplayRealm; import net.firedevops.firemud.test.GatewayTestProperties; @@ -41,8 +56,10 @@ import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; +import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -57,7 +74,8 @@ GatewayTestProperties.SPRING_GRPC_SERVER_SSL_DISABLED, GatewayTestProperties.FIREMUD_GRPC_CERT_CHAIN_PATH, GatewayTestProperties.FIREMUD_GRPC_PRIVATE_KEY_PATH, - GatewayTestProperties.FIREMUD_GRPC_CA_CERT_PATH + GatewayTestProperties.FIREMUD_GRPC_CA_CERT_PATH, + "firemud.grpc.workload-namespace=account_service" }) class AccountJoinPostgresIntegrationTest { private static final UUID REALM_ID = UUID.fromString("4c4b57d8-e3a2-48fe-9977-e7df0fdce901"); @@ -83,10 +101,16 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private DSLContext dsl; @Autowired private AccountService accountService; + @Autowired private AccountMembershipAuthorityEventProducer membershipAuthorityEventProducer; + @Autowired private AccountAuthorityOutboxRepository authorityOutboxRepository; + @Autowired private PlatformTransactionManager transactionManager; @Autowired private AccountMembershipTransitionReceiptRepository membershipTransitionReceiptRepository; + @Autowired private ApprovedLegacyTenantAssociationRepository tenantAssociationRepository; + @Autowired private LegacyTenantSourceEvidence legacyTenantSourceEvidence; + @MockitoBean private EntityManagementClient entityManagementClient; @MockitoBean private GameSessionClient gameSessionClient; @MockitoBean private LoggingAdminClient loggingAdminClient; @@ -127,7 +151,7 @@ public void afterCommit() { fixture.accountId(), fixture.tenantId(), result.membershipId(), - 1L, + 2L, 1L, true)); assertThat(result.membershipId()).isPositive(); @@ -145,11 +169,13 @@ public void afterCommit() { assertThat(row.get("entitlement_version", Long.class)).isEqualTo(1L); assertThat(row.get("allow_public_join", Boolean.class)).isTrue(); assertThat(row.get("membership_id", Long.class)).isEqualTo(result.membershipId()); - assertThat(row.get("outcome_membership_version", Long.class)).isEqualTo(1L); + assertThat(row.get("outcome_membership_version", Long.class)).isEqualTo(2L); assertThat(row.get("outcome_membership_authority_generation", Long.class)) .isEqualTo(1L); }); assertTransitionAndAuditOutboxOnce(fixture, result.membershipId()); + assertRoleSnapshot(fixture, result.membershipId(), 2L, List.of("player")); + assertAuthorityMembershipEvent(fixture, 1L, 2L, false); } @Test @@ -190,6 +216,11 @@ void rolledBackTerminalAttemptStaysPendingAndSameRequestCommitsOnceOnRetry() { assertThat(countMemberships(fixture)).isZero(); assertThat(countJoinOutbox(fixture)).isZero(); assertThat(countMembershipTransitionReceipts(fixture)).isZero(); + assertThat(countRoleSnapshotHeaders(fixture)).isZero(); + assertThat(countRoleSnapshotRows(fixture)).isZero(); + assertThat(countAuthorityMembershipEvents(fixture)).isZero(); + assertThat(countAuthorityMembershipStreams(fixture)).isZero(); + assertThat(countMembershipAuthorityGenerations(fixture)).isEqualTo(1L); JoinPublicProductionResult recovered = join(fixture); @@ -198,6 +229,8 @@ void rolledBackTerminalAttemptStaysPendingAndSameRequestCommitsOnceOnRetry() { assertThat(recovered.replayed()).isFalse(); assertThat(countMemberships(fixture)).isEqualTo(1L); assertTransitionAndAuditOutboxOnce(fixture, recovered.membershipId()); + assertRoleSnapshot(fixture, recovered.membershipId(), 2L, List.of("player")); + assertAuthorityMembershipEvent(fixture, 1L, 2L, false); } @Test @@ -272,6 +305,179 @@ void exactJoinRetryDoesNotAppendAnotherMembershipTransitionReceipt() { assertThat(replayed.replayed()).isTrue(); assertThat(countMembershipTransitionReceipts(fixture)).isEqualTo(1L); assertMembershipTransitionReceipt(fixture, "MEMBERSHIP_JOINED", 1L); + assertThat(countRoleSnapshotHeaders(fixture)).isEqualTo(1L); + assertThat(countRoleSnapshotRows(fixture)).isEqualTo(1L); + assertRoleSnapshot(fixture, joined.membershipId(), 2L, List.of("player")); + assertThat(countAuthorityMembershipEvents(fixture)).isEqualTo(1L); + assertAuthorityMembershipEvent(fixture, 1L, 2L, false); + } + + @Test + void concurrentDistinctJoinRequestsSerializeOneTransitionAndReplayWithoutMutation() + throws Exception { + JoinFixture first = fixture("active"); + JoinFixture second = fixtureForMembership(first); + assertThat(second.accountId()).isEqualTo(first.accountId()); + assertThat(second.tenantId()).isEqualTo(first.tenantId()); + assertThat(second.accountUuid()).isEqualTo(first.accountUuid()); + assertThat(second.tenantUuid()).isEqualTo(first.tenantUuid()); + assertThat(second.requestId()).isNotEqualTo(first.requestId()); + assertThat(countMemberships(first)).isZero(); + assertThat(countMembershipTransitionReceipts(first)).isZero(); + assertThat(countAuthorityMembershipEvents(first)).isZero(); + assertThat(countAuthorityMembershipStreams(first)).isZero(); + assertThat(countMembershipAuthorityGenerations(first)).isZero(); + assertThat(countTenantJoinOutboxEvents(first)).isZero(); + + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future firstAttempt = + executor.submit( + () -> { + await(start); + return join(first); + }); + Future secondAttempt = + executor.submit( + () -> { + await(start); + return join(second); + }); + start.countDown(); + + JoinPublicProductionResult firstResult = firstAttempt.get(30, TimeUnit.SECONDS); + JoinPublicProductionResult secondResult = secondAttempt.get(30, TimeUnit.SECONDS); + + assertThat(List.of(firstResult.outcomeCode(), secondResult.outcomeCode())) + .containsExactlyInAnyOrder("JOINED", "ALREADY_ACTIVE"); + assertThat(firstResult.success()).isTrue(); + assertThat(secondResult.success()).isTrue(); + assertThat(firstResult.replayed()).isFalse(); + assertThat(secondResult.replayed()).isFalse(); + assertThat(firstResult.membershipId()).isPositive(); + assertThat(secondResult.membershipId()).isEqualTo(firstResult.membershipId()); + assertThat(firstResult.membershipVersion()).isEqualTo(2L); + assertThat(secondResult.membershipVersion()).isEqualTo(2L); + assertThat(firstResult.membershipAuthorityGeneration()).isEqualTo(1L); + assertThat(secondResult.membershipAuthorityGeneration()).isEqualTo(1L); + + JoinFixture joinedFixture = "JOINED".equals(firstResult.outcomeCode()) ? first : second; + JoinFixture alreadyActiveFixture = joinedFixture == first ? second : first; + JoinPublicProductionResult joinedResult = joinedFixture == first ? firstResult : secondResult; + JoinPublicProductionResult alreadyActiveResult = + alreadyActiveFixture == first ? firstResult : secondResult; + long membershipId = joinedResult.membershipId(); + assertThat(joinedResult.outcomeCode()).isEqualTo("JOINED"); + assertThat(alreadyActiveResult.outcomeCode()).isEqualTo("ALREADY_ACTIVE"); + assertThat(alreadyActiveResult.success()).isTrue(); + assertThat(alreadyActiveResult.membershipId()).isEqualTo(membershipId); + + assertThat(countMemberships(first)).isEqualTo(1L); + assertThat(countTenantJoinOutboxEvents(first)).isEqualTo(1L); + assertThat(countJoinOutbox(joinedFixture)).isEqualTo(1L); + assertThat(countJoinOutbox(alreadyActiveFixture)).isZero(); + assertThat(countMembershipTransitionReceipts(first)).isEqualTo(1L); + assertThat(countTransitionReceiptsForRequest(alreadyActiveFixture.requestId())).isZero(); + assertMembershipTransitionReceipt(joinedFixture, "MEMBERSHIP_JOINED", 1L); + assertTransitionAndAuditOutboxOnce(joinedFixture, membershipId); + assertRoleSnapshot(joinedFixture, membershipId, 2L, List.of("player")); + assertThat(countAuthorityMembershipEvents(first)).isEqualTo(1L); + assertThat(countAuthorityMembershipStreams(first)).isEqualTo(1L); + assertThat(countMembershipAuthorityGenerations(first)).isEqualTo(1L); + assertAuthorityMembershipEvent(joinedFixture, 1L, 2L, false); + assertCommittedJoinOperation(joinedFixture, "JOINED", membershipId); + assertCommittedJoinOperation(alreadyActiveFixture, "ALREADY_ACTIVE", membershipId); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_join_operations " + + "WHERE account_id = ? AND tenant_id = ?", + first.accountId(), + first.tenantId()) + .fetchOne(0, Long.class)) + .isEqualTo(2L); + + Map joinedOperationBeforeReplay = joinOperationSnapshot(joinedFixture); + Map alreadyActiveOperationBeforeReplay = + joinOperationSnapshot(alreadyActiveFixture); + Map membershipBeforeReplay = membershipSnapshot(joinedFixture); + Map receiptBeforeReplay = membershipTransitionReceiptSnapshot(joinedFixture); + Map auditBeforeReplay = joinAuditEnvelopeSnapshot(joinedFixture); + var eventBeforeReplay = authorityMembershipEventRow(joinedFixture, 1L); + String eventIdBeforeReplay = eventBeforeReplay.get("event_id", String.class); + String eventDigestBeforeReplay = eventBeforeReplay.get("event_digest", String.class); + byte[] eventPayloadBeforeReplay = eventBeforeReplay.get("payload", byte[].class); + + JoinPublicProductionResult joinedReplay = join(joinedFixture); + JoinPublicProductionResult alreadyActiveReplay = join(alreadyActiveFixture); + + assertThat(joinedReplay) + .isEqualTo( + new JoinPublicProductionResult( + true, + "JOINED", + joinedFixture.accountId(), + joinedFixture.tenantId(), + membershipId, + 2L, + 1L, + true)); + assertThat(alreadyActiveReplay) + .isEqualTo( + new JoinPublicProductionResult( + true, + "ALREADY_ACTIVE", + alreadyActiveFixture.accountId(), + alreadyActiveFixture.tenantId(), + membershipId, + 2L, + 1L, + true)); + + assertThat(joinOperationSnapshot(joinedFixture)).isEqualTo(joinedOperationBeforeReplay); + assertThat(joinOperationSnapshot(alreadyActiveFixture)) + .isEqualTo(alreadyActiveOperationBeforeReplay); + assertThat(membershipSnapshot(joinedFixture)).isEqualTo(membershipBeforeReplay); + assertThat(membershipTransitionReceiptSnapshot(joinedFixture)).isEqualTo(receiptBeforeReplay); + assertThat(joinAuditEnvelopeSnapshot(joinedFixture)).isEqualTo(auditBeforeReplay); + var eventAfterReplay = authorityMembershipEventRow(joinedFixture, 1L); + assertThat(eventAfterReplay.get("event_id", String.class)).isEqualTo(eventIdBeforeReplay); + assertThat(eventAfterReplay.get("event_digest", String.class)) + .isEqualTo(eventDigestBeforeReplay); + assertThat(eventAfterReplay.get("payload", byte[].class)) + .containsExactly(eventPayloadBeforeReplay); + assertThat(countMemberships(first)).isEqualTo(1L); + assertThat(countTenantJoinOutboxEvents(first)).isEqualTo(1L); + assertThat(countMembershipTransitionReceipts(first)).isEqualTo(1L); + assertThat(countAuthorityMembershipEvents(first)).isEqualTo(1L); + assertThat(countAuthorityMembershipStreams(first)).isEqualTo(1L); + assertThat(countMembershipAuthorityGenerations(first)).isEqualTo(1L); + assertAuthorityMembershipEvent(joinedFixture, 1L, 2L, false); + } finally { + executor.shutdownNow(); + } + } + + @Test + void missingApprovedTenantAssociationLeavesJoinPendingWithoutAuthorityMutation() { + JoinFixture fixture = fixture("active", TenantAssociationSetup.MISSING); + + AuthenticationException unavailable = + assertThrows(AuthenticationException.class, () -> join(fixture)); + + assertThat(unavailable.getCode()).isEqualTo("AUTH_UNAVAILABLE"); + assertJoinAuthorityFailureRemainsPending(fixture); + } + + @Test + void mismatchedRetainedTenantEvidenceLeavesJoinPendingWithoutAuthorityMutation() { + JoinFixture fixture = fixture("active", TenantAssociationSetup.MISMATCHED_EVIDENCE); + + AuthenticationException unavailable = + assertThrows(AuthenticationException.class, () -> join(fixture)); + + assertThat(unavailable.getCode()).isEqualTo("AUTH_UNAVAILABLE"); + assertJoinAuthorityFailureRemainsPending(fixture); } @Test @@ -288,6 +494,8 @@ void newRequestForRetainedActiveMembershipIsEventFreeAndRequiresPositiveHistory( assertMembershipTransitionReceipt(initialJoin, "MEMBERSHIP_JOINED", 1L); assertThat(countTenantJoinOutboxEvents(initialJoin)).isEqualTo(1L); assertThat(countTenantJoinOutboxEvents(alreadyActive)).isEqualTo(1L); + assertThat(countAuthorityMembershipEvents(initialJoin)).isEqualTo(1L); + assertAuthorityMembershipEvent(initialJoin, 1L, 2L, false); assertThat( dsl.resultQuery( "SELECT COUNT(*) FROM account_join_operations " @@ -297,6 +505,34 @@ void newRequestForRetainedActiveMembershipIsEventFreeAndRequiresPositiveHistory( .isEqualTo(1L); } + @Test + void activeSnapshotWithoutLowercasePlayerFailsClosedInsteadOfAlreadyActive() { + JoinFixture initialJoin = fixture("active"); + JoinPublicProductionResult initial = join(initialJoin); + assertThat(initial.success()).isTrue(); + + dsl.execute( + "DELETE FROM account_tenant_membership_role_snapshot_roles WHERE membership_id = ?", + initial.membershipId()); + dsl.execute( + "INSERT INTO account_tenant_membership_role_snapshot_roles " + + "(membership_id, snapshot_version, role_identifier) VALUES (?, ?, ?)", + initial.membershipId(), + initial.membershipVersion(), + "designer"); + + JoinFixture retry = fixtureForMembership(initialJoin); + JoinPublicProductionResult result = join(retry); + + assertThat(result.success()).isFalse(); + assertThat(result.outcomeCode()).isEqualTo("MEMBERSHIP_RECONCILIATION_REQUIRED"); + assertThat(countMembershipTransitionReceipts(retry)).isEqualTo(1L); + assertThat(countRoleSnapshotHeaders(retry)).isEqualTo(1L); + assertThat(countRoleSnapshotRows(retry)).isEqualTo(1L); + assertRoleSnapshot( + retry, initial.membershipId(), initial.membershipVersion(), List.of("designer")); + } + @Test void membershipTransitionReceiptSequenceIsIndependentForEachAccountTenantStream() { JoinFixture first = fixture("active"); @@ -308,38 +544,123 @@ void membershipTransitionReceiptSequenceIsIndependentForEachAccountTenantStream( assertMembershipTransitionReceipt(first, "MEMBERSHIP_JOINED", 1L); assertMembershipTransitionReceipt(second, "MEMBERSHIP_JOINED", 1L); assertThat(receiptStreamKey(first)).isNotEqualTo(receiptStreamKey(second)); + assertAuthorityMembershipEvent(first, 1L, 2L, false); + assertAuthorityMembershipEvent(second, 1L, 2L, false); } @Test - void reactivationAppendsTheNextPositiveMembershipTransitionReceiptSequence() { + void reactivationWithoutCanonicalInactiveEventFailsClosedWithoutMutation() { JoinFixture initialJoin = fixture("active"); - assertThat(join(initialJoin).success()).isTrue(); + JoinPublicProductionResult initial = join(initialJoin); + assertThat(initial.success()).isTrue(); assertMembershipTransitionReceipt(initialJoin, "MEMBERSHIP_JOINED", 1L); + assertAuthorityMembershipEvent(initialJoin, 1L, 2L, false); + Map originalTransitionReceipt = + membershipTransitionReceiptRowSnapshot(initialJoin, 1L); + var originalAuthorityEvent = authorityMembershipEventRow(initialJoin, 1L); + String originalEventId = originalAuthorityEvent.get("event_id", String.class); + String originalEventDigest = originalAuthorityEvent.get("event_digest", String.class); + byte[] originalEventPayload = originalAuthorityEvent.get("payload", byte[].class); + dsl.execute( + "DELETE FROM account_tenant_membership_role_snapshot_roles " + + "WHERE membership_id IN (SELECT id FROM account_tenant_membership " + + "WHERE account_id = ? AND tenant_id = ?)", + initialJoin.accountId(), + initialJoin.tenantId()); + dsl.execute( + "INSERT INTO account_tenant_membership_role_snapshot_roles " + + "(membership_id, snapshot_version, role_identifier) " + + "SELECT id, membership_version, role_identifier FROM account_tenant_membership " + + "JOIN (VALUES ('designer')) AS roles(role_identifier) ON TRUE " + + "WHERE account_id = ? AND tenant_id = ?", + initialJoin.accountId(), + initialJoin.tenantId()); dsl.execute( "UPDATE account_tenant_membership SET lifecycle_state = 'INACTIVE', " + "gameplay_admission_allowed = FALSE WHERE account_id = ? AND tenant_id = ?", initialJoin.accountId(), initialJoin.tenantId()); + long priorMembershipGeneration = + authorityGeneration( + "MEMBERSHIP", null, initialJoin.accountUuid(), initialJoin.tenantUuid()); + long priorIssuanceFence = + Objects.requireNonNull( + dsl.resultQuery( + "SELECT issuance_fence FROM account_authority_issuance_fences " + + "WHERE account_uuid = ?", + initialJoin.accountUuid()) + .fetchOne(0, Long.class)); JoinFixture reactivation = fixtureForMembership(initialJoin); - JoinPublicProductionResult result = join(reactivation); + AuthenticationException unavailable = + assertThrows(AuthenticationException.class, () -> join(reactivation)); - assertThat(result.success()).isTrue(); - assertThat(result.outcomeCode()).isEqualTo("JOINED"); - assertMembershipTransitionReceipt(reactivation, "MEMBERSHIP_REACTIVATED", 2L); - assertThat(countMembershipTransitionReceipts(reactivation)).isEqualTo(2L); + assertThat(unavailable.getCode()).isEqualTo("AUTH_UNAVAILABLE"); + assertThat(countMembershipTransitionReceipts(reactivation)).isEqualTo(1L); + assertThat(membershipTransitionReceiptRowSnapshot(initialJoin, 1L)) + .isEqualTo(originalTransitionReceipt); assertThat( dsl.resultQuery( - "SELECT membership_version, membership_authority_generation " + "SELECT lifecycle_state, gameplay_admission_allowed, membership_version, " + + "membership_authority_generation, authority_provenance " + "FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", reactivation.accountId(), reactivation.tenantId()) .fetchOne()) .satisfies( row -> { + assertThat(row.get("lifecycle_state", String.class)).isEqualTo("INACTIVE"); + assertThat(row.get("gameplay_admission_allowed", Boolean.class)).isFalse(); assertThat(row.get("membership_version", Long.class)).isEqualTo(2L); - assertThat(row.get("membership_authority_generation", Long.class)).isEqualTo(2L); + assertThat(row.get("membership_authority_generation", Long.class)).isEqualTo(1L); + assertThat(row.get("authority_provenance", String.class)).isEqualTo("EXPLICIT_JOIN"); + }); + assertThat(countRoleSnapshotHeaders(reactivation)).isEqualTo(1L); + assertThat(countRoleSnapshotRows(reactivation)).isEqualTo(1L); + assertRoleSnapshot(reactivation, initial.membershipId(), 2L, List.of("designer")); + assertThat(countAuthorityMembershipEvents(reactivation)).isEqualTo(1L); + assertThat(countAuthorityMembershipStreams(reactivation)).isEqualTo(1L); + assertThat( + dsl.resultQuery( + "SELECT last_sequence FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ?", + authorityStreamKey(reactivation)) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + assertThat( + authorityGeneration( + "MEMBERSHIP", null, reactivation.accountUuid(), reactivation.tenantUuid())) + .isEqualTo(priorMembershipGeneration); + assertThat( + dsl.resultQuery( + "SELECT issuance_fence FROM account_authority_issuance_fences " + + "WHERE account_uuid = ?", + reactivation.accountUuid()) + .fetchOne(0, Long.class)) + .isEqualTo(priorIssuanceFence); + var authorityEventAfter = authorityMembershipEventRow(reactivation, 1L); + assertThat(authorityEventAfter.get("event_id", String.class)).isEqualTo(originalEventId); + assertThat(authorityEventAfter.get("event_digest", String.class)) + .isEqualTo(originalEventDigest); + assertThat(authorityEventAfter.get("payload", byte[].class)) + .containsExactly(originalEventPayload); + assertThat(countTenantJoinOutboxEvents(reactivation)).isEqualTo(1L); + assertThat(countJoinOutbox(reactivation)).isZero(); + assertThat( + dsl.resultQuery( + "SELECT status, outcome, membership_id, outcome_membership_version, " + + "outcome_membership_authority_generation " + + "FROM account_join_operations WHERE request_id = ?", + reactivation.requestId()) + .fetchOne()) + .satisfies( + row -> { + assertThat(row.get("status", String.class)).isEqualTo("PENDING"); + assertThat(row.get("outcome", String.class)).isNull(); + assertThat(row.get("membership_id", Long.class)).isNull(); + assertThat(row.get("outcome_membership_version", Long.class)).isNull(); + assertThat(row.get("outcome_membership_authority_generation", Long.class)).isNull(); }); } @@ -351,6 +672,18 @@ void committedMembershipTransitionReceiptHistorySurvivesAbsenceOfCurrentMembersh dsl.execute("DELETE FROM account_join_operations WHERE request_id = ?", fixture.requestId()); + dsl.execute( + "DELETE FROM account_tenant_membership_role_snapshot_roles " + + "WHERE membership_id IN (SELECT id FROM account_tenant_membership " + + "WHERE account_id = ? AND tenant_id = ?)", + fixture.accountId(), + fixture.tenantId()); + dsl.execute( + "DELETE FROM account_tenant_membership_role_snapshots " + + "WHERE membership_id IN (SELECT id FROM account_tenant_membership " + + "WHERE account_id = ? AND tenant_id = ?)", + fixture.accountId(), + fixture.tenantId()); dsl.execute( "DELETE FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", fixture.accountId(), @@ -473,6 +806,18 @@ void absentMembershipWithRetainedReceiptFailsClosedWithoutResettingSequence() { assertThat(join(initialJoin).success()).isTrue(); dsl.execute( "DELETE FROM account_join_operations WHERE request_id = ?", initialJoin.requestId()); + dsl.execute( + "DELETE FROM account_tenant_membership_role_snapshot_roles " + + "WHERE membership_id IN (SELECT id FROM account_tenant_membership " + + "WHERE account_id = ? AND tenant_id = ?)", + initialJoin.accountId(), + initialJoin.tenantId()); + dsl.execute( + "DELETE FROM account_tenant_membership_role_snapshots " + + "WHERE membership_id IN (SELECT id FROM account_tenant_membership " + + "WHERE account_id = ? AND tenant_id = ?)", + initialJoin.accountId(), + initialJoin.tenantId()); dsl.execute( "DELETE FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", initialJoin.accountId(), @@ -507,6 +852,8 @@ void retainedActiveOrInactiveMembershipWithoutTransitionReceiptFailsClosed() { + "VALUES (?, ?, FALSE, 'INACTIVE', 1, 1, 'EXPLICIT_JOIN')", inactive.accountId(), inactive.tenantId()); + long activeMembershipId = seedPlayerRoleSnapshot(active); + long inactiveMembershipId = seedPlayerRoleSnapshot(inactive); IllegalStateException activeFailure = assertThrows( @@ -528,15 +875,21 @@ void retainedActiveOrInactiveMembershipWithoutTransitionReceiptFailsClosed() { assertThat(countMembershipTransitionReceipts(active)).isZero(); assertThat(countMembershipTransitionReceipts(inactive)).isZero(); - AuthenticationException activeJoinFailure = - assertThrows(AuthenticationException.class, () -> join(active)); - AuthenticationException inactiveJoinFailure = - assertThrows(AuthenticationException.class, () -> join(inactive)); + JoinPublicProductionResult activeJoinFailure = join(active); + JoinPublicProductionResult inactiveJoinFailure = join(inactive); - assertThat(activeJoinFailure.getCode()).isEqualTo("AUTH_UNAVAILABLE"); - assertThat(inactiveJoinFailure.getCode()).isEqualTo("AUTH_UNAVAILABLE"); + assertThat(activeJoinFailure.success()).isFalse(); + assertThat(activeJoinFailure.outcomeCode()).isEqualTo("MEMBERSHIP_RECONCILIATION_REQUIRED"); + assertThat(inactiveJoinFailure.success()).isFalse(); + assertThat(inactiveJoinFailure.outcomeCode()).isEqualTo("MEMBERSHIP_RECONCILIATION_REQUIRED"); assertThat(countMembershipTransitionReceipts(active)).isZero(); assertThat(countMembershipTransitionReceipts(inactive)).isZero(); + assertThat(countRoleSnapshotHeaders(active)).isEqualTo(1L); + assertThat(countRoleSnapshotRows(active)).isEqualTo(1L); + assertRoleSnapshot(active, activeMembershipId, 1L, List.of("player")); + assertThat(countRoleSnapshotHeaders(inactive)).isEqualTo(1L); + assertThat(countRoleSnapshotRows(inactive)).isEqualTo(1L); + assertRoleSnapshot(inactive, inactiveMembershipId, 1L, List.of("player")); assertThat( dsl.resultQuery( "SELECT lifecycle_state FROM account_tenant_membership " @@ -547,43 +900,543 @@ void retainedActiveOrInactiveMembershipWithoutTransitionReceiptFailsClosed() { .isEqualTo("INACTIVE"); } + @Test + void positiveMembershipSnapshotReturnsExactCommittedAuthorityEvidence() { + JoinFixture fixture = fixture("active"); + JoinPublicProductionResult joined = join(fixture); + + var snapshot = readPositiveMembershipSnapshot(fixture); + + assertThat(joined.success()).isTrue(); + assertThat(snapshot).isNotNull(); + assertThat(snapshot.membershipExists()).isTrue(); + assertThat(snapshot.accountId()).isEqualTo(fixture.accountUuid().toString()); + assertThat(snapshot.tenantId()).isEqualTo(fixture.tenantUuid().toString()); + assertThat(snapshot.membershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(snapshot.gameplayAdmissionAllowed()).isTrue(); + assertThat(snapshot.membershipVersion()).isEqualTo(Long.toString(joined.membershipVersion())); + assertThat(snapshot.authorityEvent().membershipVersion()) + .isEqualTo( + Map.of(fixture.tenantUuid().toString(), Long.toString(joined.membershipVersion()))); + assertThat(snapshot.membershipAuthorityGeneration()) + .isEqualTo(Long.toString(joined.membershipAuthorityGeneration())); + assertThat(snapshot.roles()).containsExactly("player"); + assertThat(snapshot.authorityTuple().membershipAuthorityGeneration()) + .containsEntry(fixture.tenantUuid().toString(), snapshot.membershipAuthorityGeneration()); + assertThat(snapshot.evaluatedAt()).isNotNull(); + assertThat(snapshot.authorityEvent().requestId()).isEqualTo(fixture.requestId()); + assertThat(snapshot.transitionReceipt().requestId()).isEqualTo(fixture.requestId()); + assertThat(snapshot.transitionReceipt().membershipId()).isEqualTo(joined.membershipId()); + assertThat(snapshot.outboxCheckpoints()).hasSize(1); + assertThat(snapshot.outboxCheckpoints().getFirst().outboxStreamKey()) + .isEqualTo(authorityStreamKey(fixture)); + assertThat(snapshot.outboxCheckpoints().getFirst().outboxSequence()) + .isEqualTo(Long.parseLong(snapshot.authorityEvent().outboxSequence())); + assertThat(snapshot.outboxCheckpoints().getFirst().sourceEventId()) + .isEqualTo(snapshot.authorityEvent().eventId()); + assertThat(snapshot.outboxCheckpoints().getFirst().sourceEventDigest()) + .isEqualTo(snapshot.authorityEvent().eventDigest()); + } + + @Test + void positiveMembershipSnapshotRejectsScalarAndWrongTenantVersionMaps() { + JoinFixture scalarVersion = fixture("active"); + assertStoredMembershipVersionFailsClosed(scalarVersion, "\"2\""); + + JoinFixture wrongTenantVersion = fixture("active"); + assertStoredMembershipVersionFailsClosed( + wrongTenantVersion, "{\"%s\":\"2\"}".formatted(differentTenantUuid(wrongTenantVersion))); + + JoinFixture extraTenantVersion = fixture("active"); + assertStoredMembershipVersionFailsClosed( + extraTenantVersion, + "{\"" + + extraTenantVersion.tenantUuid() + + "\":\"2\",\"" + + differentTenantUuid(extraTenantVersion) + + "\":\"1\"}"); + } + + @Test + void positiveMembershipSnapshotFailsClosedForAbsentMembershipOrReceipt() { + JoinFixture absent = fixture("active"); + assertThatThrownBy(() -> readPositiveMembershipSnapshot(absent)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Current Account membership row is absent"); + + JoinFixture missingReceipt = fixture("active"); + dsl.execute( + "INSERT INTO account_tenant_membership " + + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " + + "membership_version, membership_authority_generation, authority_provenance) " + + "VALUES (?, ?, TRUE, 'ACTIVE', 1, 1, 'EXPLICIT_JOIN')", + missingReceipt.accountId(), + missingReceipt.tenantId()); + long retainedMembershipId = seedPlayerRoleSnapshot(missingReceipt); + Map retainedMembership = membershipSnapshot(missingReceipt); + + assertThat(retainedMembershipId).isPositive(); + assertThat(countMembershipTransitionReceipts(missingReceipt)).isZero(); + assertThatThrownBy(() -> readPositiveMembershipSnapshot(missingReceipt)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Account membership exists without a provisional transition receipt"); + assertThat(membershipSnapshot(missingReceipt)).isEqualTo(retainedMembership); + assertThat(countMembershipTransitionReceipts(missingReceipt)).isZero(); + assertThat(countAuthorityMembershipEvents(missingReceipt)).isZero(); + } + + @Test + void positiveMembershipSnapshotFailsClosedForMissingRolesAndRetainedInactiveState() { + JoinFixture missingRoles = fixture("active"); + JoinPublicProductionResult joined = join(missingRoles); + dsl.execute( + "DELETE FROM account_tenant_membership_role_snapshot_roles " + + "WHERE membership_id = ? AND snapshot_version = ?", + joined.membershipId(), + joined.membershipVersion()); + + assertThatThrownBy(() -> readPositiveMembershipSnapshot(missingRoles)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("role snapshot differs from its exact active membership"); + + JoinFixture inactive = fixture("active"); + JoinPublicProductionResult inactiveJoin = join(inactive); + dsl.execute( + "UPDATE account_tenant_membership SET lifecycle_state = 'INACTIVE', " + + "gameplay_admission_allowed = FALSE WHERE id = ?", + inactiveJoin.membershipId()); + + assertThatThrownBy(() -> readPositiveMembershipSnapshot(inactive)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not a positive active explicit membership"); + } + + @Test + void positiveMembershipSnapshotFailsClosedForMismatchedAuthorityTuple() { + JoinFixture mismatchedTuple = fixture("active"); + assertThat(join(mismatchedTuple).success()).isTrue(); + dsl.execute( + "UPDATE account_authority_generations SET generation = generation + 1, " + + "source_version = source_version + 1 WHERE scope_kind = 'MEMBERSHIP' " + + "AND account_uuid = ? AND tenant_uuid = ?", + mismatchedTuple.accountUuid(), + mismatchedTuple.tenantUuid()); + + assertThatThrownBy(() -> readPositiveMembershipSnapshot(mismatchedTuple)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("differs from its V31 authority generation"); + } + + @Test + void neverJoinedSnapshotRequiresAndRetainsDurablePairBaselineBeforeFirstJoin() { + JoinFixture fixture = fixture("active"); + long originalIssuanceFence = accountIssuanceFence(fixture); + + prepareRuntimeSnapshotAuthority(fixture); + var absence = readNeverJoinedMembershipSnapshot(fixture); + Map baselineRow = membershipPairAuthorityRow(fixture); + + assertThat(absence.membershipExists()).isFalse(); + assertThat(absence.gameplayAdmissionAllowed()).isFalse(); + assertThat(absence.accountId()).isEqualTo(fixture.accountUuid().toString()); + assertThat(absence.tenantId()).isEqualTo(fixture.tenantUuid().toString()); + assertThat(absence.membershipVersion()).isEqualTo("1"); + assertThat(absence.membershipAuthorityGeneration()).isEqualTo("1"); + assertThat(absence.outboxSequence()).isZero(); + assertThat(absence.outboxStreamKey()).isEqualTo(authorityStreamKey(fixture)); + assertThat(absence.authorityTuple().membershipAuthorityGeneration()) + .containsEntry(fixture.tenantUuid().toString(), "1"); + assertThat(countAuthorityMembershipEvents(fixture)).isZero(); + assertThat(countAuthorityMembershipStreams(fixture)).isZero(); + assertThat(countMemberships(fixture)).isZero(); + assertThat(countMembershipTransitionReceipts(fixture)).isZero(); + assertThat(countRoleSnapshotHeaders(fixture)).isZero(); + assertThat(countRoleSnapshotRows(fixture)).isZero(); + assertThat(countMembershipAuthorityGenerations(fixture)).isEqualTo(1L); + assertThat(countMembershipPairAuthorities(fixture)).isEqualTo(1L); + assertThat(authorityGeneration("MEMBERSHIP", null, fixture.accountUuid(), fixture.tenantUuid())) + .isEqualTo(1L); + assertThat(accountIssuanceFence(fixture)).isEqualTo(originalIssuanceFence); + assertThat(baselineRow) + .containsEntry("account_uuid", fixture.accountUuid()) + .containsEntry("tenant_uuid", fixture.tenantUuid()) + .containsEntry("legacy_tenant_id", fixture.tenantId()) + .containsEntry("tenant_provenance_kind", "APPROVED_RETAINED") + .containsEntry("membership_exists", false) + .containsEntry("membership_version", 1L) + .containsEntry("membership_authority_generation", 1L) + .containsEntry("last_event_sequence", 0L) + .containsEntry("last_event_id", null) + .containsEntry("last_event_digest", null) + .containsEntry("last_transition_invalidated", false); + + prepareRuntimeSnapshotAuthority(fixture); + + assertThat(membershipPairAuthorityRow(fixture)).isEqualTo(baselineRow); + var retriedAbsence = readNeverJoinedMembershipSnapshot(fixture); + assertThat(retriedAbsence.membershipVersion()).isEqualTo("1"); + assertThat(retriedAbsence.membershipAuthorityGeneration()).isEqualTo("1"); + assertThat(retriedAbsence.outboxSequence()).isZero(); + assertThat(countAuthorityMembershipEvents(fixture)).isZero(); + assertThat(countAuthorityMembershipStreams(fixture)).isZero(); + assertThat(countMemberships(fixture)).isZero(); + assertThat(countMembershipTransitionReceipts(fixture)).isZero(); + assertThat(countRoleSnapshotHeaders(fixture)).isZero(); + assertThat(countRoleSnapshotRows(fixture)).isZero(); + assertThat(countMembershipAuthorityGenerations(fixture)).isEqualTo(1L); + assertThat(authorityGeneration("MEMBERSHIP", null, fixture.accountUuid(), fixture.tenantUuid())) + .isEqualTo(1L); + assertThat(accountIssuanceFence(fixture)).isEqualTo(originalIssuanceFence); + + JoinPublicProductionResult joined = join(fixture); + var positive = readPairBoundPositiveMembershipSnapshot(fixture); + Map joinedPairRow = membershipPairAuthorityRow(fixture); + + assertThat(joined.success()).isTrue(); + assertThat(joined.membershipVersion()).isEqualTo(2L); + assertThat(joined.membershipAuthorityGeneration()).isEqualTo(1L); + assertThat(positive.membershipExists()).isTrue(); + assertThat(positive.gameplayAdmissionAllowed()).isTrue(); + assertThat(positive.membershipVersion()).isEqualTo("2"); + assertThat(positive.membershipAuthorityGeneration()).isEqualTo("1"); + assertThat(positive.authorityEvent().outboxSequence()).isEqualTo("1"); + assertThat(positive.authorityEvent().eventId()).isNotBlank(); + assertThat(positive.authorityEvent().eventDigest()).matches("sha256:[0-9a-f]{64}"); + assertThat(positive.outboxCheckpoints()).hasSize(1); + var checkpoint = positive.outboxCheckpoints().getFirst(); + assertThat(checkpoint.outboxStreamKey()).isEqualTo(authorityStreamKey(fixture)); + assertThat(checkpoint.outboxSequence()).isEqualTo(1L); + assertThat(checkpoint.sourceEventId()).isEqualTo(positive.authorityEvent().eventId()); + assertThat(checkpoint.sourceEventDigest()).isEqualTo(positive.authorityEvent().eventDigest()); + assertThat(joinedPairRow) + .containsEntry("membership_exists", true) + .containsEntry("membership_version", 2L) + .containsEntry("membership_authority_generation", 1L) + .containsEntry("last_event_sequence", 1L) + .containsEntry("last_event_id", positive.authorityEvent().eventId()) + .containsEntry("last_event_digest", positive.authorityEvent().eventDigest()) + .containsEntry("last_transition_invalidated", false); + assertThat(countAuthorityMembershipEvents(fixture)).isEqualTo(1L); + + long receiptCount = countMembershipTransitionReceipts(fixture); + long eventCount = countAuthorityMembershipEvents(fixture); + long eventStreamCount = countAuthorityMembershipStreams(fixture); + long membershipGeneration = + authorityGeneration("MEMBERSHIP", null, fixture.accountUuid(), fixture.tenantUuid()); + long issuanceFence = accountIssuanceFence(fixture); + prepareRuntimeSnapshotAuthority(fixture); + assertThat(membershipPairAuthorityRow(fixture)).isEqualTo(joinedPairRow); + assertThat(countMembershipTransitionReceipts(fixture)).isEqualTo(receiptCount); + assertThat(countAuthorityMembershipEvents(fixture)).isEqualTo(eventCount); + assertThat(countAuthorityMembershipStreams(fixture)).isEqualTo(eventStreamCount); + assertThat(authorityGeneration("MEMBERSHIP", null, fixture.accountUuid(), fixture.tenantUuid())) + .isEqualTo(membershipGeneration); + assertThat(accountIssuanceFence(fixture)).isEqualTo(issuanceFence); + var priorEvent = positive.authorityEvent(); + var readbackEvent = readPairBoundPositiveMembershipSnapshot(fixture).authorityEvent(); + assertThat(readbackEvent.eventId()).isEqualTo(priorEvent.eventId()); + assertThat(readbackEvent.eventDigest()).isEqualTo(priorEvent.eventDigest()); + assertThat(readbackEvent.canonicalJson().getBytes(StandardCharsets.UTF_8)) + .containsExactly(priorEvent.canonicalJson().getBytes(StandardCharsets.UTF_8)); + } + + @Test + void concurrentRuntimeSnapshotPreparationAndFirstJoinPreservePairOrdering() throws Exception { + JoinFixture fixture = fixture("active"); + assertThat(countMemberships(fixture)).isZero(); + assertThat(countMembershipAuthorityGenerations(fixture)).isZero(); + assertThat(countMembershipPairAuthorities(fixture)).isZero(); + assertThat(countAuthorityMembershipEvents(fixture)).isZero(); + + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(3); + try { + Future firstPreparation = + executor.submit( + () -> { + await(start); + prepareRuntimeSnapshotAuthority(fixture); + }); + Future secondPreparation = + executor.submit( + () -> { + await(start); + prepareRuntimeSnapshotAuthority(fixture); + }); + Future joinAttempt = + executor.submit( + () -> { + await(start); + return join(fixture); + }); + start.countDown(); + + firstPreparation.get(30, TimeUnit.SECONDS); + secondPreparation.get(30, TimeUnit.SECONDS); + JoinPublicProductionResult joined = joinAttempt.get(30, TimeUnit.SECONDS); + + assertThat(joined.success()).isTrue(); + assertThat(joined.outcomeCode()).isEqualTo("JOINED"); + assertThat(countMemberships(fixture)).isEqualTo(1L); + assertThat(countMembershipAuthorityGenerations(fixture)).isEqualTo(1L); + assertThat(countMembershipPairAuthorities(fixture)).isEqualTo(1L); + assertThat(membershipPairAuthorityRow(fixture)) + .containsEntry("membership_exists", true) + .containsEntry("membership_version", 2L) + .containsEntry("membership_authority_generation", 1L) + .containsEntry("last_event_sequence", 1L); + assertThat(countMembershipTransitionReceipts(fixture)).isEqualTo(1L); + assertThat(countAuthorityMembershipEvents(fixture)).isEqualTo(1L); + assertThat(countAuthorityMembershipStreams(fixture)).isEqualTo(1L); + } finally { + executor.shutdownNow(); + } + } + + @Test + void neverJoinedSnapshotReaderRejectsMissingPairWithoutEnrollingIt() { + JoinFixture missingPair = fixture("active"); + assertThatThrownBy(() -> readNeverJoinedMembershipSnapshot(missingPair)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Never-joined pair baseline is absent"); + assertThat(countMembershipPairAuthorities(missingPair)).isZero(); + assertThat(countMembershipAuthorityGenerations(missingPair)).isZero(); + assertThat(countMemberships(missingPair)).isZero(); + assertThat(countAuthorityMembershipEvents(missingPair)).isZero(); + } + + @Test + void runtimeSnapshotPreparationRejectsUnmappedTenantAndAbsentMembershipHistory() { + JoinFixture unmappedTenant = fixture("active", TenantAssociationSetup.MISSING); + assertThatThrownBy(() -> prepareRuntimeSnapshotAuthority(unmappedTenant)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("approved Account tenant association is absent"); + assertThat(countMemberships(unmappedTenant)).isZero(); + assertThat(countMembershipAuthorityGenerations(unmappedTenant)).isZero(); + assertThat(countMembershipPairAuthorities(unmappedTenant)).isZero(); + assertThat(countAuthorityMembershipEvents(unmappedTenant)).isZero(); + + JoinFixture removedMembership = fixture("active"); + JoinPublicProductionResult joined = join(removedMembership); + Map retainedPair = membershipPairAuthorityRow(removedMembership); + dsl.execute( + "DELETE FROM account_join_operations WHERE request_id = ?", removedMembership.requestId()); + dsl.execute( + "DELETE FROM account_tenant_membership_role_snapshot_roles " + "WHERE membership_id = ?", + joined.membershipId()); + dsl.execute( + "DELETE FROM account_tenant_membership_role_snapshots WHERE membership_id = ?", + joined.membershipId()); + dsl.execute("DELETE FROM account_tenant_membership WHERE id = ?", joined.membershipId()); + + assertThat(joined.success()).isTrue(); + assertThat(countMemberships(removedMembership)).isZero(); + assertThat(countAuthorityMembershipEvents(removedMembership)).isEqualTo(1L); + assertThatThrownBy(() -> prepareRuntimeSnapshotAuthority(removedMembership)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining( + "Retained Account membership history has no supported restoration path"); + assertThat(membershipPairAuthorityRow(removedMembership)).isEqualTo(retainedPair); + assertThat(countMembershipAuthorityGenerations(removedMembership)).isEqualTo(1L); + assertThat(countAuthorityMembershipEvents(removedMembership)).isEqualTo(1L); + } + + @Test + void runtimeSnapshotPreparationRejectsInactiveMembershipWithoutChangingAuthority() { + JoinFixture fixture = fixture("active"); + JoinPublicProductionResult joined = join(fixture); + Map pairRow = membershipPairAuthorityRow(fixture); + long membershipGeneration = + authorityGeneration("MEMBERSHIP", null, fixture.accountUuid(), fixture.tenantUuid()); + dsl.execute( + "UPDATE account_tenant_membership SET lifecycle_state = 'INACTIVE', " + + "gameplay_admission_allowed = FALSE WHERE id = ?", + joined.membershipId()); + + assertThatThrownBy(() -> prepareRuntimeSnapshotAuthority(fixture)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not a positive active explicit membership"); + assertThat(membershipPairAuthorityRow(fixture)).isEqualTo(pairRow); + assertThat(authorityGeneration("MEMBERSHIP", null, fixture.accountUuid(), fixture.tenantUuid())) + .isEqualTo(membershipGeneration); + assertThat(countAuthorityMembershipEvents(fixture)).isEqualTo(1L); + assertThat(countMembershipTransitionReceipts(fixture)).isEqualTo(1L); + } + + @Test + void neverJoinedSnapshotRejectsPairBaselineContradictingV31Authority() { + JoinFixture mismatchedBaseline = fixture("active"); + preparePairAuthorityBaseline(mismatchedBaseline); + dsl.execute( + "UPDATE account_authority_generations SET generation = generation + 1, " + + "source_version = source_version + 1 WHERE scope_kind = 'MEMBERSHIP' " + + "AND account_uuid = ? AND tenant_uuid = ?", + mismatchedBaseline.accountUuid(), + mismatchedBaseline.tenantUuid()); + + assertThatThrownBy(() -> readNeverJoinedMembershipSnapshot(mismatchedBaseline)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("differs from its positive pair baseline"); + } + + private AccountMembershipAuthorityEventProducer.PositiveMembershipSnapshot + readPositiveMembershipSnapshot(JoinFixture fixture) { + return new TransactionTemplate(transactionManager) + .execute( + status -> + membershipAuthorityEventProducer.readCurrentPositiveMembershipSnapshot( + fixture.accountId(), fixture.tenantId())); + } + + private void preparePairAuthorityBaseline(JoinFixture fixture) { + new TransactionTemplate(transactionManager) + .executeWithoutResult( + status -> + membershipAuthorityEventProducer.preparePairAuthorityForJoin( + fixture.accountId(), fixture.tenantId())); + } + + private void prepareRuntimeSnapshotAuthority(JoinFixture fixture) { + new TransactionTemplate(transactionManager) + .executeWithoutResult( + status -> + membershipAuthorityEventProducer.preparePairAuthorityForRuntimeSnapshot( + fixture.accountId(), fixture.tenantId())); + } + + private AccountMembershipAuthorityEventProducer.NeverJoinedMembershipSnapshot + readNeverJoinedMembershipSnapshot(JoinFixture fixture) { + return new TransactionTemplate(transactionManager) + .execute( + status -> + membershipAuthorityEventProducer.readNeverJoinedMembershipSnapshot( + fixture.accountId(), fixture.tenantId())); + } + + private AccountMembershipAuthorityEventProducer.PositiveMembershipSnapshot + readPairBoundPositiveMembershipSnapshot(JoinFixture fixture) { + return new TransactionTemplate(transactionManager) + .execute( + status -> + membershipAuthorityEventProducer.readCurrentPairBoundPositiveMembershipSnapshot( + fixture.accountId(), fixture.tenantId())); + } + + private Map membershipPairAuthorityRow(JoinFixture fixture) { + var row = + dsl.resultQuery( + "SELECT * FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + fixture.accountUuid(), + fixture.tenantUuid()) + .fetchOne(); + assertThat(row).isNotNull(); + return row.intoMap(); + } + + private long countMembershipPairAuthorities(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + fixture.accountUuid(), + fixture.tenantUuid()) + .fetchOne(0, Long.class)); + } + private JoinFixture fixture(String subscriptionStatus) { + return fixture(subscriptionStatus, TenantAssociationSetup.APPROVED); + } + + private JoinFixture fixture(String subscriptionStatus, TenantAssociationSetup associationSetup) { String suffix = UUID.randomUUID().toString(); long accountId = Objects.requireNonNull( dsl.resultQuery( - "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + "INSERT INTO accounts (username, email, password_hash) " + + "VALUES (?, ?, ?) RETURNING id", "join-proof-" + suffix, "join-proof-" + suffix + "@example.com", "test-hash") .fetchOne(0, Long.class)); - return fixture(subscriptionStatus, accountId, null, suffix); + UUID accountUuid = + Objects.requireNonNull( + dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", accountId) + .fetchOne(0, UUID.class)); + seedAccountAuthorityState(accountUuid); + return fixture(subscriptionStatus, accountId, accountUuid, associationSetup, suffix); } private JoinFixture fixture(String subscriptionStatus, long accountId) { - return fixture(subscriptionStatus, accountId, null, UUID.randomUUID().toString()); + return fixture(subscriptionStatus, accountId, TenantAssociationSetup.APPROVED); + } + + private JoinFixture fixture( + String subscriptionStatus, long accountId, TenantAssociationSetup associationSetup) { + String suffix = UUID.randomUUID().toString(); + UUID accountUuid = + Objects.requireNonNull( + dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", accountId) + .fetchOne(0, UUID.class)); + return fixture(subscriptionStatus, accountId, accountUuid, associationSetup, suffix); + } + + private JoinFixture fixture( + String subscriptionStatus, + long accountId, + UUID accountUuid, + TenantAssociationSetup associationSetup, + String suffix) { + long tenantId = positiveRandomLong(); + seedRetainedV26TenantEvidence(tenantId, suffix); + dsl.execute( + "INSERT INTO subscription (account_id, tenant_id, plan_id, status, entitlement_version) " + + "VALUES (?, ?, ?, ?, 1)", + accountId, + tenantId, + "join-proof", + subscriptionStatus); + + UUID tenantUuid = UUID.randomUUID(); + String evidenceDigest = legacyTenantSourceEvidence.digest(tenantId); + if (associationSetup == TenantAssociationSetup.APPROVED) { + tenantAssociationRepository.importApproved( + tenantId, approvedTenantAssociation(tenantId, tenantUuid, evidenceDigest, suffix)); + var storedAssociation = + tenantAssociationRepository.findByLegacyTenantId(tenantId).orElseThrow(); + assertThat(storedAssociation.legacyTenantId()).isEqualTo(tenantId); + assertThat(storedAssociation.canonicalTenantId()).isEqualTo(tenantUuid); + assertThat(storedAssociation.accountEvidenceDigest()).isEqualTo(evidenceDigest); + assertThat(authorityGeneration("TENANT", null, null, tenantUuid)).isEqualTo(1L); + } else if (associationSetup == TenantAssociationSetup.MISMATCHED_EVIDENCE) { + insertApprovedTenantAssociation(tenantId, tenantUuid, "sha256:" + "0".repeat(64), suffix); + seedTenantAuthorityGeneration(tenantUuid); + assertThat(authorityGeneration("TENANT", null, null, tenantUuid)).isEqualTo(1L); + } else { + assertThat(tenantAssociationRepository.findByLegacyTenantId(tenantId)).isEmpty(); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_authority_generations " + + "WHERE scope_kind = 'TENANT' AND tenant_uuid = ?", + tenantUuid) + .fetchOne(0, Long.class)) + .isZero(); + } + return fixture(accountId, accountUuid, tenantId, tenantUuid, suffix); } private JoinFixture fixtureForMembership(JoinFixture existing) { return fixture( - "active", existing.accountId(), existing.tenantId(), UUID.randomUUID().toString()); + existing.accountId(), + existing.accountUuid(), + existing.tenantId(), + existing.tenantUuid(), + UUID.randomUUID().toString()); } private JoinFixture fixture( - String subscriptionStatus, long accountId, Long existingTenantId, String suffix) { + long accountId, UUID accountUuid, long tenantId, UUID tenantUuid, String suffix) { String requestId = "join-proof-" + suffix; - long tenantId = - existingTenantId == null - ? UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE - : existingTenantId; - if (existingTenantId == null) { - dsl.execute( - "INSERT INTO subscription (account_id, tenant_id, plan_id, status, entitlement_version) VALUES (?, ?, ?, ?, 1)", - accountId, - tenantId, - "join-proof", - subscriptionStatus); - } GameplayRealm realm = GameplayRealm.newBuilder() @@ -641,7 +1494,129 @@ private JoinFixture fixture( CATALOG_REVISION, POINTER_VERSION); DirectTextJoinScope scope = accountService.issueDirectTextConnectScope(caller, target); - return new JoinFixture(accountId, tenantId, requestId, caller, scope.connectScopeId()); + return new JoinFixture( + accountId, accountUuid, tenantId, tenantUuid, requestId, caller, scope.connectScopeId()); + } + + private void seedRetainedV26TenantEvidence(long tenantId, String suffix) { + // Keep V26's unverified membership history on a separate retained account, not the joiner. + long donorAccountId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash, tenant_id) " + + "VALUES (?, ?, ?, ?) RETURNING id", + "jpd-" + suffix, + "join-proof-retained-donor-" + suffix + "@example.com", + "test-hash", + tenantId) + .fetchOne(0, Long.class)); + UUID donorAccountUuid = + Objects.requireNonNull( + dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", donorAccountId) + .fetchOne(0, UUID.class)); + seedAccountAuthorityState(donorAccountUuid); + long retainedMembershipId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO account_tenant_membership " + + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " + + "membership_version, membership_authority_generation, authority_provenance) " + + "VALUES (?, ?, FALSE, 'LEGACY_UNVERIFIED', 1, 1, 'LEGACY_UNVERIFIED') " + + "RETURNING id", + donorAccountId, + tenantId) + .fetchOne(0, Long.class)); + dsl.execute( + "INSERT INTO account_legacy_tenant_sources " + + "(account_id, legacy_tenant_id, matching_membership_id, " + + "matching_membership_admission_allowed, profile_tenant_count, " + + "matching_profile_count, disposition) VALUES (?, ?, ?, FALSE, 0, 0, 'UNVERIFIED')", + donorAccountId, + tenantId, + retainedMembershipId); + dsl.execute( + "INSERT INTO account_legacy_membership_sources " + + "(membership_id, account_id, tenant_id, original_gameplay_admission_allowed, " + + "matches_account_legacy_tenant, disposition) " + + "VALUES (?, ?, ?, FALSE, TRUE, 'UNVERIFIED')", + retainedMembershipId, + donorAccountId, + tenantId); + } + + private void seedAccountAuthorityState(UUID accountUuid) { + dsl.execute( + "INSERT INTO account_authority_generations " + + "(scope_kind, account_uuid, generation, source_version) " + + "VALUES ('ACCOUNT', ?, 1, 1)", + accountUuid); + dsl.execute( + "INSERT INTO account_authority_issuance_fences " + + "(account_uuid, issuance_fence, source_version) VALUES (?, 1, 1)", + accountUuid); + } + + private void seedTenantAuthorityGeneration(UUID tenantUuid) { + dsl.execute( + "INSERT INTO account_authority_generations " + + "(scope_kind, tenant_uuid, generation, source_version) " + + "VALUES ('TENANT', ?, 1, 1)", + tenantUuid); + } + + private ResolveLegacyAccountTenantAssociationResponse approvedTenantAssociation( + long legacyTenantId, UUID tenantUuid, String evidenceDigest, String suffix) { + String sourceLegacyGameTenantId = "legacy-game-" + suffix.replace("-", "").substring(0, 24); + return ResolveLegacyAccountTenantAssociationResponse.newBuilder() + .setLegacyAccountTenantId(legacyTenantId) + .setCanonicalTenantId(tenantUuid.toString()) + .setSourceLegacyGameTenantId(sourceLegacyGameTenantId) + .setSourceGameRowId(positiveRandomLong()) + .setAccountEvidenceDigest(evidenceDigest) + .setOperationId(UUID.randomUUID().toString()) + .setManifestDigest("sha256:" + "b".repeat(64)) + .setManifestSignature(Base64.getEncoder().encodeToString(new byte[64])) + .setTargetNamespace("account_service") + .setSignerKeyId("game-design-owner-test") + .setApprovedBy("owner@example.test") + .setApprovalReference("unit-1b-postgres-fixture") + .setSignedAt("2026-09-26T00:00:00Z") + .setOperationEntryCount(1) + .setManifestSchemaVersion(1) + .build(); + } + + private void insertApprovedTenantAssociation( + long legacyTenantId, UUID tenantUuid, String evidenceDigest, String suffix) { + ResolveLegacyAccountTenantAssociationResponse association = + approvedTenantAssociation(legacyTenantId, tenantUuid, evidenceDigest, suffix); + dsl.execute( + "INSERT INTO account_approved_legacy_tenant_associations " + + "(legacy_tenant_id, canonical_tenant_id, source_legacy_game_tenant_id, " + + "source_game_row_id, account_evidence_digest, operation_id, manifest_digest, " + + "manifest_signature, target_namespace, signer_key_id, approved_by, " + + "approval_reference, signed_at, operation_entry_count, manifest_schema_version) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + legacyTenantId, + UUID.fromString(association.getCanonicalTenantId()), + association.getSourceLegacyGameTenantId(), + association.getSourceGameRowId(), + association.getAccountEvidenceDigest(), + UUID.fromString(association.getOperationId()), + association.getManifestDigest(), + association.getManifestSignature(), + association.getTargetNamespace(), + association.getSignerKeyId(), + association.getApprovedBy(), + association.getApprovalReference(), + association.getSignedAt(), + association.getOperationEntryCount(), + association.getManifestSchemaVersion()); + } + + private long positiveRandomLong() { + long candidate = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE; + return candidate == 0L ? 1L : candidate; } private long countMemberships(JoinFixture fixture) { @@ -653,12 +1628,364 @@ private long countMemberships(JoinFixture fixture) { .fetchOne(0, Long.class)); } + private Map joinOperationSnapshot(JoinFixture fixture) { + var row = + dsl.resultQuery( + "SELECT request_id, status, outcome, membership_id, outcome_membership_version, " + + "outcome_membership_authority_generation, request_digest, " + + "request_digest_version, entitlement_version, allow_public_join, " + + "caller_bound_authority_invalidated, last_attempt_failure_code, " + + "entitlement_authority_availability, last_attempt_authority_availability, " + + "created_at, updated_at FROM account_join_operations WHERE request_id = ?", + fixture.requestId()) + .fetchOne(); + assertThat(row).isNotNull(); + return row.intoMap(); + } + + private Map membershipSnapshot(JoinFixture fixture) { + var row = + dsl.resultQuery( + "SELECT id, account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " + + "membership_version, membership_authority_generation, authority_provenance " + + "FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", + fixture.accountId(), + fixture.tenantId()) + .fetchOne(); + assertThat(row).isNotNull(); + return row.intoMap(); + } + + private Map membershipTransitionReceiptSnapshot(JoinFixture fixture) { + var row = + dsl.resultQuery( + "SELECT receipt_stream_key, receipt_sequence, account_id, tenant_id, " + + "evidence_status, transition_type, request_id, membership_id, " + + "membership_lifecycle_state, gameplay_admission_allowed, membership_version, " + + "membership_authority_generation, authority_provenance, receipt_id, " + + "receipt_digest, created_at FROM account_membership_transition_receipts " + + "WHERE account_id = ? AND tenant_id = ?", + fixture.accountId(), + fixture.tenantId()) + .fetchOne(); + assertThat(row).isNotNull(); + return row.intoMap(); + } + + private Map joinAuditEnvelopeSnapshot(JoinFixture fixture) { + UUID eventId = + UUID.nameUUIDFromBytes( + ("account-join-audit/v1:" + fixture.requestId()).getBytes(StandardCharsets.UTF_8)); + var row = + dsl.resultQuery( + "SELECT audit_event_id, scope, tenant_id, producer_service, event_type, " + + "occurred_at, schema_version, payload_digest_version, payload_digest, " + + "payload, created_at FROM account_audit_outbox " + + "WHERE audit_event_id = ? AND tenant_id = ?", + eventId, + fixture.tenantId()) + .fetchOne(); + assertThat(row).isNotNull(); + return row.intoMap(); + } + + private void assertCommittedJoinOperation( + JoinFixture fixture, String outcome, long membershipId) { + var row = + dsl.resultQuery( + "SELECT status, outcome, membership_id, outcome_membership_version, " + + "outcome_membership_authority_generation, request_digest, " + + "request_digest_version, entitlement_version, allow_public_join " + + "FROM account_join_operations WHERE request_id = ?", + fixture.requestId()) + .fetchOne(); + assertThat(row).isNotNull(); + assertThat(row.get("status", String.class)).isEqualTo("COMMITTED"); + assertThat(row.get("outcome", String.class)).isEqualTo(outcome); + assertThat(row.get("membership_id", Long.class)).isEqualTo(membershipId); + assertThat(row.get("outcome_membership_version", Long.class)).isEqualTo(2L); + assertThat(row.get("outcome_membership_authority_generation", Long.class)).isEqualTo(1L); + assertThat(row.get("request_digest", String.class)).matches("sha256:[0-9a-f]{64}"); + assertThat(row.get("request_digest_version", Integer.class)).isEqualTo(1); + assertThat(row.get("entitlement_version", Long.class)).isEqualTo(1L); + assertThat(row.get("allow_public_join", Boolean.class)).isTrue(); + } + + private long countTransitionReceiptsForRequest(String requestId) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_membership_transition_receipts WHERE request_id = ?", + requestId) + .fetchOne(0, Long.class)); + } + private JoinPublicProductionResult join(JoinFixture fixture) { return accountService.joinPublicProductionFromGameSession( fixture.caller(), new JoinPublicProductionRequest(fixture.connectScopeId(), fixture.requestId())); } + private void assertAuthorityMembershipEvent( + JoinFixture fixture, + long expectedSequence, + long expectedMembershipVersion, + boolean expectedCallerBoundAuthorityInvalidated) { + String streamKey = authorityStreamKey(fixture); + long eventCount = countAuthorityMembershipEvents(fixture); + assertThat(eventCount).isGreaterThanOrEqualTo(expectedSequence); + assertThat( + dsl.resultQuery( + "SELECT last_sequence FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ?", + streamKey) + .fetchOne(0, Long.class)) + .isEqualTo(eventCount); + + var row = authorityMembershipEventRow(fixture, expectedSequence); + assertThat(row).isNotNull(); + long sequence = row.get("outbox_sequence", Long.class); + String requestId = row.get("request_id", String.class); + String eventId = row.get("event_id", String.class); + String storedDigest = row.get("event_digest", String.class); + byte[] storedPayload = row.get("payload", byte[].class); + String payloadJson = new String(storedPayload, StandardCharsets.UTF_8); + MembershipAuthorityEventV1Codec.MembershipEvent event = + MembershipAuthorityEventV1Codec.verify(payloadJson); + + assertThat(sequence).isEqualTo(expectedSequence); + assertThat(requestId).isEqualTo(fixture.requestId()); + assertThat(event.eventId()).isEqualTo(eventId); + assertThat(event.requestId()).isEqualTo(requestId); + assertThat(event.schemaVersion()).isEqualTo(MembershipAuthorityEventV1Codec.SCHEMA_VERSION); + assertThat(event.eventType()).isEqualTo(MembershipAuthorityEventV1Codec.EVENT_TYPE); + assertThat(event.outboxStreamKey()).isEqualTo(streamKey); + assertThat(event.outboxSequence()).isEqualTo(Long.toString(expectedSequence)); + assertThat(event.sourceScope()) + .isEqualTo("membership/" + fixture.accountUuid() + "/" + fixture.tenantUuid()); + assertThat(event.accountId()).isEqualTo(fixture.accountUuid().toString()); + assertThat(event.tenantId()).isEqualTo(fixture.tenantUuid().toString()); + assertThat(event.membershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(event.membershipVersion()) + .isEqualTo( + Map.of(fixture.tenantUuid().toString(), Long.toString(expectedMembershipVersion))); + assertThat(event.roles()).containsExactlyElementsOf(committedRoles(fixture)); + assertThat(event.gameplayAdmissionAllowed()).isTrue(); + assertThat(event.callerBoundAuthorityInvalidated()) + .isEqualTo(expectedCallerBoundAuthorityInvalidated); + assertThat(storedDigest).isEqualTo(event.eventDigest()); + assertThat(storedDigest).matches("sha256:[0-9a-f]{64}"); + assertThat(event.canonicalJson()).isEqualTo(payloadJson); + assertThat(storedPayload).containsExactly(event.canonicalJsonUtf8()); + + long issuerGeneration = + authorityGeneration("ISSUER", AccountServiceImpl.ACCOUNT_JWT_ISSUER, null, null); + long accountGeneration = authorityGeneration("ACCOUNT", null, fixture.accountUuid(), null); + long tenantGeneration = authorityGeneration("TENANT", null, null, fixture.tenantUuid()); + long membershipGeneration = + authorityGeneration("MEMBERSHIP", null, fixture.accountUuid(), fixture.tenantUuid()); + long issuanceFence = + Objects.requireNonNull( + dsl.resultQuery( + "SELECT issuance_fence FROM account_authority_issuance_fences " + + "WHERE account_uuid = ?", + fixture.accountUuid()) + .fetchOne(0, Long.class)); + var membership = + dsl.resultQuery( + "SELECT membership_version, membership_authority_generation " + + "FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ? " + + "AND lifecycle_state = 'ACTIVE' AND gameplay_admission_allowed = TRUE", + fixture.accountId(), + fixture.tenantId()) + .fetchOne(); + assertThat(membership).isNotNull(); + long committedMembershipVersion = membership.get("membership_version", Long.class); + long committedMembershipGeneration = + membership.get("membership_authority_generation", Long.class); + assertThat(committedMembershipVersion).isEqualTo(expectedMembershipVersion); + assertThat(membershipGeneration).isEqualTo(committedMembershipGeneration); + assertThat(event.membershipAuthorityGeneration()) + .isEqualTo(Long.toString(committedMembershipGeneration)); + assertThat(event.issuanceFence()).isEqualTo(Long.toString(issuanceFence)); + assertThat(event.authorityTuple()) + .isEqualTo( + new MembershipAuthorityEventV1Codec.AuthorityTuple( + Long.toString(issuerGeneration), + Long.toString(accountGeneration), + Map.of(fixture.tenantUuid().toString(), Long.toString(tenantGeneration)), + Map.of(fixture.tenantUuid().toString(), Long.toString(membershipGeneration)), + List.of(), + Optional.empty(), + Optional.empty())); + } + + private org.jooq.Record authorityMembershipEventRow(JoinFixture fixture, long sequence) { + return dsl.resultQuery( + "SELECT outbox_sequence, request_id, event_id, event_digest, payload " + + "FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ? AND outbox_sequence = ?", + authorityStreamKey(fixture), + sequence) + .fetchOne(); + } + + private void assertStoredMembershipVersionFailsClosed( + JoinFixture fixture, String malformedMembershipVersionJson) { + JoinPublicProductionResult joined = join(fixture); + assertThat(joined.success()).isTrue(); + var row = authorityMembershipEventRow(fixture, 1L); + String payload = new String(row.get("payload", byte[].class), StandardCharsets.UTF_8); + String exactMembershipVersionJson = + "\"membershipVersion\":{\"" + + fixture.tenantUuid() + + "\":\"" + + joined.membershipVersion() + + "\"}"; + assertThat(payload).contains(exactMembershipVersionJson); + String malformedPayload = + payload.replace( + exactMembershipVersionJson, "\"membershipVersion\":" + malformedMembershipVersionJson); + assertThat(malformedPayload).isNotEqualTo(payload); + // V33 events are immutable; append a malformed newer event through the opaque storage boundary. + String malformedRequestId = "malformed-version-" + UUID.randomUUID(); + var malformedEvent = + new TransactionTemplate(transactionManager) + .execute( + status -> + authorityOutboxRepository.append( + authorityStreamKey(fixture), + malformedRequestId, + malformedRequestId + "-event", + row.get("event_digest", String.class), + malformedPayload.getBytes(StandardCharsets.UTF_8))); + assertThat(malformedEvent).isNotNull(); + assertThat(malformedEvent.outboxSequence()).isEqualTo(2L); + + assertThatThrownBy(() -> readPositiveMembershipSnapshot(fixture)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Stored Account authority event is invalid"); + } + + private UUID differentTenantUuid(JoinFixture fixture) { + UUID candidate = UUID.fromString("00000000-0000-0000-0000-000000000001"); + return candidate.equals(fixture.tenantUuid()) + ? UUID.fromString("00000000-0000-0000-0000-000000000002") + : candidate; + } + + private long authorityGeneration( + String scopeKind, String issuerId, UUID accountUuid, UUID tenantUuid) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT generation FROM account_authority_generations " + + "WHERE scope_kind = ? AND issuer_id IS NOT DISTINCT FROM ? " + + "AND account_uuid IS NOT DISTINCT FROM ? " + + "AND tenant_uuid IS NOT DISTINCT FROM ?", + scopeKind, + issuerId, + accountUuid, + tenantUuid) + .fetchOne(0, Long.class)); + } + + private long accountIssuanceFence(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT issuance_fence FROM account_authority_issuance_fences " + + "WHERE account_uuid = ?", + fixture.accountUuid()) + .fetchOne(0, Long.class)); + } + + private List committedRoles(JoinFixture fixture) { + return dsl.resultQuery( + "SELECT roles.role_identifier FROM account_tenant_membership_role_snapshot_roles roles " + + "JOIN account_tenant_membership membership " + + "ON membership.id = roles.membership_id " + + "WHERE membership.account_id = ? AND membership.tenant_id = ? " + + "AND roles.snapshot_version = membership.membership_version " + + "ORDER BY convert_to(roles.role_identifier, 'UTF8')", + fixture.accountId(), + fixture.tenantId()) + .fetch("role_identifier", String.class); + } + + private static void await(CountDownLatch start) { + try { + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException( + "concurrent Account membership test did not receive its start signal"); + } + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("concurrent JOIN test was interrupted", ex); + } + } + + private void assertJoinAuthorityFailureRemainsPending(JoinFixture fixture) { + assertThat(countMemberships(fixture)).isZero(); + assertThat(countRoleSnapshotHeaders(fixture)).isZero(); + assertThat(countRoleSnapshotRows(fixture)).isZero(); + assertThat(countMembershipTransitionReceipts(fixture)).isZero(); + assertThat(countJoinOutbox(fixture)).isZero(); + assertThat(countTenantJoinOutboxEvents(fixture)).isZero(); + assertThat(countAuthorityMembershipEvents(fixture)).isZero(); + assertThat(countAuthorityMembershipStreams(fixture)).isZero(); + assertThat(countMembershipAuthorityGenerations(fixture)).isZero(); + assertThat( + dsl.resultQuery( + "SELECT status, outcome, membership_id, outcome_membership_version, " + + "outcome_membership_authority_generation " + + "FROM account_join_operations WHERE request_id = ?", + fixture.requestId()) + .fetchOne()) + .satisfies( + row -> { + assertThat(row.get("status", String.class)).isEqualTo("PENDING"); + assertThat(row.get("outcome", String.class)).isNull(); + assertThat(row.get("membership_id", Long.class)).isNull(); + assertThat(row.get("outcome_membership_version", Long.class)).isNull(); + assertThat(row.get("outcome_membership_authority_generation", Long.class)).isNull(); + }); + } + + private String authorityStreamKey(JoinFixture fixture) { + return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + fixture.accountUuid() + + "/" + + fixture.tenantUuid(); + } + + private long countAuthorityMembershipEvents(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + authorityStreamKey(fixture)) + .fetchOne(0, Long.class)); + } + + private long countAuthorityMembershipStreams(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ?", + authorityStreamKey(fixture)) + .fetchOne(0, Long.class)); + } + + private long countMembershipAuthorityGenerations(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_authority_generations " + + "WHERE scope_kind = 'MEMBERSHIP' AND account_uuid = ? " + + "AND tenant_uuid = ?", + fixture.accountUuid(), + fixture.tenantUuid()) + .fetchOne(0, Long.class)); + } + private long countJoinOutbox(JoinFixture fixture) { UUID eventId = UUID.nameUUIDFromBytes( @@ -690,6 +2017,83 @@ private long countMembershipTransitionReceipts(JoinFixture fixture) { .fetchOne(0, Long.class)); } + private long countRoleSnapshotHeaders(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_tenant_membership_role_snapshots s " + + "JOIN account_tenant_membership m ON m.id = s.membership_id " + + "WHERE m.account_id = ? AND m.tenant_id = ?", + fixture.accountId(), + fixture.tenantId()) + .fetchOne(0, Long.class)); + } + + private long countRoleSnapshotRows(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_tenant_membership_role_snapshot_roles r " + + "JOIN account_tenant_membership m ON m.id = r.membership_id " + + "WHERE m.account_id = ? AND m.tenant_id = ?", + fixture.accountId(), + fixture.tenantId()) + .fetchOne(0, Long.class)); + } + + private long seedPlayerRoleSnapshot(JoinFixture fixture) { + var membership = + dsl.resultQuery( + "SELECT id, membership_version FROM account_tenant_membership " + + "WHERE account_id = ? AND tenant_id = ?", + fixture.accountId(), + fixture.tenantId()) + .fetchOne(); + assertThat(membership).isNotNull(); + long membershipId = membership.get("id", Long.class); + long membershipVersion = membership.get("membership_version", Long.class); + assertThat( + dsl.execute( + "INSERT INTO account_tenant_membership_role_snapshots " + + "(membership_id, snapshot_version) VALUES (?, ?)", + membershipId, + membershipVersion)) + .isEqualTo(1); + assertThat( + dsl.execute( + "INSERT INTO account_tenant_membership_role_snapshot_roles " + + "(membership_id, snapshot_version, role_identifier) VALUES (?, ?, 'player')", + membershipId, + membershipVersion)) + .isEqualTo(1); + return membershipId; + } + + private void assertRoleSnapshot( + JoinFixture fixture, long membershipId, long expectedVersion, List expectedRoles) { + var header = + dsl.resultQuery( + "SELECT membership_id, snapshot_version " + + "FROM account_tenant_membership_role_snapshots " + + "WHERE membership_id = ?", + membershipId) + .fetchOne(); + assertThat(header).isNotNull(); + assertThat(header.get("membership_id", Long.class)).isEqualTo(membershipId); + assertThat(header.get("snapshot_version", Long.class)).isEqualTo(expectedVersion); + assertThat( + dsl.resultQuery( + "SELECT r.role_identifier " + + "FROM account_tenant_membership_role_snapshot_roles r " + + "JOIN account_tenant_membership m ON m.id = r.membership_id " + + "WHERE m.account_id = ? AND m.tenant_id = ? " + + "AND r.snapshot_version = ? " + + "ORDER BY convert_to(r.role_identifier, 'UTF8')", + fixture.accountId(), + fixture.tenantId(), + expectedVersion) + .fetch("role_identifier", String.class)) + .containsExactlyElementsOf(expectedRoles); + } + private String receiptStreamKey(JoinFixture fixture) { return MembershipTransitionReceiptDigest.receiptStreamKey( fixture.accountId(), fixture.tenantId()); @@ -760,11 +2164,29 @@ private void assertMembershipTransitionReceipt( membershipId)); } + private Map membershipTransitionReceiptRowSnapshot( + JoinFixture fixture, long sequence) { + var row = + dsl.resultQuery( + "SELECT receipt_stream_key, receipt_sequence, evidence_status, transition_type, " + + "request_id, membership_id, membership_lifecycle_state, " + + "gameplay_admission_allowed, membership_version, " + + "membership_authority_generation, authority_provenance, receipt_id, " + + "receipt_digest FROM account_membership_transition_receipts " + + "WHERE account_id = ? AND tenant_id = ? AND receipt_sequence = ?", + fixture.accountId(), + fixture.tenantId(), + sequence) + .fetchOne(); + assertThat(row).isNotNull(); + return row.intoMap(); + } + private void assertTransitionAndAuditOutboxOnce(JoinFixture fixture, long membershipId) { assertThat(countMemberships(fixture)).isEqualTo(1L); assertThat( dsl.resultQuery( - "SELECT COUNT(*) FROM account_tenant_membership WHERE id = ? AND account_id = ? AND tenant_id = ? AND lifecycle_state = 'ACTIVE' AND authority_provenance = 'EXPLICIT_JOIN' AND membership_version = 1 AND membership_authority_generation = 1", + "SELECT COUNT(*) FROM account_tenant_membership WHERE id = ? AND account_id = ? AND tenant_id = ? AND lifecycle_state = 'ACTIVE' AND authority_provenance = 'EXPLICIT_JOIN' AND membership_version = 2 AND membership_authority_generation = 1", membershipId, fixture.accountId(), fixture.tenantId()) @@ -784,9 +2206,17 @@ private void assertTransitionAndAuditOutboxOnce(JoinFixture fixture, long member .isEqualTo(1L); } + private enum TenantAssociationSetup { + APPROVED, + MISSING, + MISMATCHED_EVIDENCE + } + private record JoinFixture( long accountId, + UUID accountUuid, long tenantId, + UUID tenantUuid, String requestId, DirectTextCallerContext caller, String connectScopeId) {} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java index b90b031dbe..b53ffa53b2 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java @@ -8,6 +8,7 @@ import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.UUID; import java.util.concurrent.CountDownLatch; @@ -28,8 +29,12 @@ import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.JoinOperation; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; +import net.firedevops.firemud.accountservice.repository.LegacyTenantSourceEvidence; import net.firedevops.firemud.accountservice.service.AccountJoinReconciliationService; import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; import net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer; import net.firedevops.firemud.gamesession.v1.GameplayRealm; import net.firedevops.firemud.test.GatewayTestProperties; @@ -59,6 +64,7 @@ GatewayTestProperties.FIREMUD_GRPC_CERT_CHAIN_PATH, GatewayTestProperties.FIREMUD_GRPC_PRIVATE_KEY_PATH, GatewayTestProperties.FIREMUD_GRPC_CA_CERT_PATH, + "firemud.grpc.workload-namespace=account_service", "firemud.account.join-reconciliation.interval-ms=3600000", "firemud.account.join-reconciliation.batch-size=20", "firemud.account.join-reconciliation.max-attempts=2", @@ -89,6 +95,8 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private DSLContext dsl; @Autowired private AccountService accountService; @Autowired private AccountJoinReconciliationService reconciliationService; + @Autowired private ApprovedLegacyTenantAssociationRepository tenantAssociationRepository; + @Autowired private LegacyTenantSourceEvidence legacyTenantSourceEvidence; @Autowired private AccountJoinOperationRepository joinOperationRepository; @Autowired private AccountConnectScopeRepository connectScopeRepository; @Autowired private PlatformTransactionManager transactionManager; @@ -145,6 +153,7 @@ void exactPersistedEvidenceRecoversExpiredScopeAndSameRequestRetryWithoutDuplica assertThat(original.success()).isTrue(); assertThat(original.outcomeCode()).isEqualTo("JOINED"); long membershipId = original.membershipId(); + AuthorityEventSnapshot originalAuthorityEvent = assertAuthorityMembershipEvent(fixture); // This is a synthetic ambiguous row assembled from a genuine committed JOIN. The current // atomic terminal transaction cannot naturally commit membership/audit while leaving the @@ -158,12 +167,13 @@ void exactPersistedEvidenceRecoversExpiredScopeAndSameRequestRetryWithoutDuplica assertOperation(fixture, "COMMITTED", "JOINED", 2, null); assertThat( dsl.resultQuery( - "SELECT COUNT(*) FROM account_join_operations WHERE request_id = ? AND status = 'COMMITTED' AND outcome = 'JOINED' AND membership_id = ? AND outcome_membership_version = 1 AND outcome_membership_authority_generation = 1", + "SELECT COUNT(*) FROM account_join_operations WHERE request_id = ? AND status = 'COMMITTED' AND outcome = 'JOINED' AND membership_id = ? AND outcome_membership_version = 2 AND outcome_membership_authority_generation = 1", fixture.requestId(), membershipId) .fetchOne(0, Long.class)) .isEqualTo(1L); assertMembershipAndAuditOnce(fixture, membershipId); + assertThat(assertAuthorityMembershipEvent(fixture)).isEqualTo(originalAuthorityEvent); JoinPublicProductionResult retry = join(fixture); assertThat(retry.success()).isTrue(); @@ -171,6 +181,49 @@ void exactPersistedEvidenceRecoversExpiredScopeAndSameRequestRetryWithoutDuplica assertThat(retry.replayed()).isTrue(); assertThat(retry.membershipId()).isEqualTo(membershipId); assertMembershipAndAuditOnce(fixture, membershipId); + assertThat(assertAuthorityMembershipEvent(fixture)).isEqualTo(originalAuthorityEvent); + } + + @Test + void newerMembershipGenerationWithoutCanonicalEventRemainsPending() { + JoinFixture fixture = fixture("active"); + JoinPublicProductionResult committed = join(fixture); + assertThat(committed.success()).isTrue(); + AuthorityEventSnapshot originalAuthorityEvent = assertAuthorityMembershipEvent(fixture); + makeOperationPendingWithRetainedEvidence(fixture); + Map originalReceipt = membershipTransitionReceiptSnapshot(fixture); + Map originalAudit = joinAuditEnvelopeSnapshot(fixture); + + // Advance the canonical V31 membership generation and issuance fence monotonically while + // retaining the active membership, JOIN receipt, audit, and immutable V33 event unchanged. + // No event records this newer authority checkpoint, so the retained JOIN event is stale. + advanceMembershipGenerationAndFenceWithoutEvent(fixture); + Instant scopeExpiry = expireScopeBeforeReconciliationButAfterEvaluation(fixture); + reconciliationService.reconcileDueOperations(scopeExpiry.plusSeconds(1)); + + assertPendingAfterUnprovedAuthorityEvent(fixture); + assertMembershipAndAuditOnce(fixture, committed.membershipId()); + assertThat(membershipTransitionReceiptSnapshot(fixture)).isEqualTo(originalReceipt); + assertThat(joinAuditEnvelopeSnapshot(fixture)).isEqualTo(originalAudit); + assertThat(countAuthorityMembershipEvents(fixture)).isEqualTo(1L); + assertThat(assertAuthorityMembershipEvent(fixture)).isEqualTo(originalAuthorityEvent); + assertThat( + dsl.resultQuery( + "SELECT lifecycle_state, gameplay_admission_allowed, membership_version, " + + "membership_authority_generation FROM account_tenant_membership " + + "WHERE account_id = ? AND tenant_id = ?", + fixture.accountId(), + fixture.tenantId()) + .fetchOne()) + .satisfies( + row -> { + assertThat(row.get("lifecycle_state", String.class)).isEqualTo("ACTIVE"); + assertThat(row.get("gameplay_admission_allowed", Boolean.class)).isTrue(); + assertThat(row.get("membership_version", Long.class)).isEqualTo(2L); + assertThat(row.get("membership_authority_generation", Long.class)).isEqualTo(1L); + }); + assertThat(membershipAuthorityGeneration(fixture)).isEqualTo(2L); + assertThat(issuanceFence(fixture)).isEqualTo(2L); } @Test @@ -218,10 +271,7 @@ void absentScopeAndExpiredScopeWithoutMembershipProofRemainPendingWithDiagnostic assertThat(countJoinOutbox(absentScope)).isEqualTo(1L); JoinFixture expiredWithoutMembership = committedEvidencePendingFixture(); - dsl.execute( - "DELETE FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", - expiredWithoutMembership.accountId(), - expiredWithoutMembership.tenantId()); + deleteMembershipEvidence(expiredWithoutMembership); Instant scopeExpiry = expireScopeBeforeReconciliationButAfterEvaluation(expiredWithoutMembership); assertUnresolvedAtThreshold( @@ -233,10 +283,7 @@ void absentScopeAndExpiredScopeWithoutMembershipProofRemainPendingWithDiagnostic @Test void absentMembershipOrAuditEnvelopeCannotTerminalizePendingOperation() { JoinFixture absentMembership = committedEvidencePendingFixture(); - dsl.execute( - "DELETE FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", - absentMembership.accountId(), - absentMembership.tenantId()); + deleteMembershipEvidence(absentMembership); assertUnresolved(absentMembership, "MEMBERSHIP_EVIDENCE_ABSENT"); assertThat(countJoinOutbox(absentMembership)).isEqualTo(1L); @@ -249,6 +296,16 @@ void absentMembershipOrAuditEnvelopeCannotTerminalizePendingOperation() { assertThat(countJoinOutbox(absentAudit)).isZero(); } + @Test + void absentRoleSnapshotLeavesPendingAndPreservesMembershipAndAuditEvidence() { + JoinFixture fixture = committedEvidencePendingFixture(); + deleteRoleSnapshot(fixture); + + assertUnresolved(fixture, "MEMBERSHIP_ROLE_SNAPSHOT_ABSENT"); + assertThat(countMemberships(fixture)).isEqualTo(1L); + assertThat(countJoinOutbox(fixture)).isEqualTo(1L); + } + @Test void concurrentCallerRetryAndReconcilerKeepSingleMembershipTransitionAndAudit() throws Exception { JoinFixture fixture = committedEvidencePendingFixture(); @@ -493,6 +550,123 @@ private void assertOperation( } } + private void assertPendingAfterUnprovedAuthorityEvent(JoinFixture fixture) { + var row = + dsl.resultQuery( + "SELECT status, outcome, membership_id, outcome_membership_version, " + + "outcome_membership_authority_generation, reconciliation_attempt_count, " + + "last_reconciliation_attempt_reason, " + + "(next_reconciliation_attempt_at > last_reconciliation_attempt_at) " + + "AS backoff_scheduled FROM account_join_operations WHERE request_id = ?", + fixture.requestId()) + .fetchOne(); + assertThat(row).isNotNull(); + assertThat(row.get("status", String.class)).isEqualTo("PENDING"); + assertThat(row.get("outcome", String.class)).isNull(); + assertThat(row.get("membership_id", Long.class)).isNull(); + assertThat(row.get("outcome_membership_version", Long.class)).isNull(); + assertThat(row.get("outcome_membership_authority_generation", Long.class)).isNull(); + assertThat(row.get("reconciliation_attempt_count", Integer.class)).isEqualTo(1); + assertThat(row.get("last_reconciliation_attempt_reason", String.class)) + .isEqualTo("MEMBERSHIP_AUTHORITY_EVENT_UNAVAILABLE"); + assertThat(row.get("backoff_scheduled", Boolean.class)).isTrue(); + } + + private void advanceMembershipGenerationAndFenceWithoutEvent(JoinFixture fixture) { + dsl.transaction( + configuration -> { + org.jooq.DSLContext transactionDsl = org.jooq.impl.DSL.using(configuration); + var membershipState = + transactionDsl.fetchOne( + "SELECT generation, source_version FROM account_authority_generations " + + "WHERE scope_kind = 'MEMBERSHIP' AND account_uuid = ? " + + "AND tenant_uuid = ? FOR UPDATE", + fixture.accountUuid(), + fixture.tenantUuid()); + assertThat(membershipState).isNotNull(); + long membershipGeneration = membershipState.get("generation", Long.class); + long membershipSourceVersion = membershipState.get("source_version", Long.class); + int generationUpdates = + transactionDsl.execute( + "UPDATE account_authority_generations " + + "SET generation = generation + 1, source_version = source_version + 1 " + + "WHERE scope_kind = 'MEMBERSHIP' AND account_uuid = ? " + + "AND tenant_uuid = ? AND generation = ? AND source_version = ?", + fixture.accountUuid(), + fixture.tenantUuid(), + membershipGeneration, + membershipSourceVersion); + assertThat(generationUpdates).isEqualTo(1); + var fenceState = + transactionDsl.fetchOne( + "SELECT issuance_fence, source_version FROM account_authority_issuance_fences " + + "WHERE account_uuid = ? FOR UPDATE", + fixture.accountUuid()); + assertThat(fenceState).isNotNull(); + long issuanceFence = fenceState.get("issuance_fence", Long.class); + long fenceSourceVersion = fenceState.get("source_version", Long.class); + int fenceUpdates = + transactionDsl.execute( + "UPDATE account_authority_issuance_fences " + + "SET issuance_fence = issuance_fence + 1, " + + "source_version = source_version + 1 " + + "WHERE account_uuid = ? AND issuance_fence = ? AND source_version = ?", + fixture.accountUuid(), + issuanceFence, + fenceSourceVersion); + assertThat(fenceUpdates).isEqualTo(1); + }); + } + + private Map membershipTransitionReceiptSnapshot(JoinFixture fixture) { + var row = + dsl.resultQuery( + "SELECT receipt_stream_key, receipt_sequence, account_id, tenant_id, " + + "evidence_status, transition_type, request_id, membership_id, " + + "membership_lifecycle_state, gameplay_admission_allowed, membership_version, " + + "membership_authority_generation, authority_provenance, receipt_id, " + + "receipt_digest FROM account_membership_transition_receipts " + + "WHERE account_id = ? AND tenant_id = ? ORDER BY receipt_sequence DESC LIMIT 1", + fixture.accountId(), + fixture.tenantId()) + .fetchOne(); + assertThat(row).isNotNull(); + return row.intoMap(); + } + + private Map joinAuditEnvelopeSnapshot(JoinFixture fixture) { + var row = + dsl.resultQuery( + "SELECT audit_event_id, scope, tenant_id, producer_service, event_type, " + + "occurred_at, schema_version, payload_digest_version, payload_digest, " + + "payload FROM account_audit_outbox " + + "WHERE audit_event_id = ? AND tenant_id = ?", + joinAuditEventId(fixture.requestId()), + fixture.tenantId()) + .fetchOne(); + assertThat(row).isNotNull(); + return row.intoMap(); + } + + private long membershipAuthorityGeneration(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT generation FROM account_authority_generations " + + "WHERE scope_kind = 'MEMBERSHIP' AND account_uuid = ? AND tenant_uuid = ?", + fixture.accountUuid(), + fixture.tenantUuid()) + .fetchOne(0, Long.class)); + } + + private long issuanceFence(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT issuance_fence FROM account_authority_issuance_fences " + + "WHERE account_uuid = ?", + fixture.accountUuid()) + .fetchOne(0, Long.class)); + } + private long originalMembershipId(JoinFixture fixture) { return Objects.requireNonNull( dsl.resultQuery( @@ -502,11 +676,48 @@ private long originalMembershipId(JoinFixture fixture) { .fetchOne(0, Long.class)); } + private void deleteMembershipEvidence(JoinFixture fixture) { + long membershipId = deleteRoleSnapshot(fixture); + int deletedMemberships = + dsl.execute( + "DELETE FROM account_tenant_membership WHERE id = ? AND account_id = ? AND tenant_id = ?", + membershipId, + fixture.accountId(), + fixture.tenantId()); + assertThat(deletedMemberships).isEqualTo(1); + } + + private long deleteRoleSnapshot(JoinFixture fixture) { + var membership = + dsl.resultQuery( + "SELECT id, membership_version FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", + fixture.accountId(), + fixture.tenantId()) + .fetchOne(); + assertThat(membership).isNotNull(); + long membershipId = Objects.requireNonNull(membership.get("id", Long.class)); + long snapshotVersion = Objects.requireNonNull(membership.get("membership_version", Long.class)); + + int deletedRoles = + dsl.execute( + "DELETE FROM account_tenant_membership_role_snapshot_roles WHERE membership_id = ? AND snapshot_version = ?", + membershipId, + snapshotVersion); + assertThat(deletedRoles).isEqualTo(1); + int deletedHeaders = + dsl.execute( + "DELETE FROM account_tenant_membership_role_snapshots WHERE membership_id = ? AND snapshot_version = ?", + membershipId, + snapshotVersion); + assertThat(deletedHeaders).isEqualTo(1); + return membershipId; + } + private void assertMembershipAndAuditOnce(JoinFixture fixture, long membershipId) { assertThat(countMemberships(fixture)).isEqualTo(1L); assertThat( dsl.resultQuery( - "SELECT COUNT(*) FROM account_tenant_membership WHERE id = ? AND account_id = ? AND tenant_id = ? AND lifecycle_state = 'ACTIVE' AND gameplay_admission_allowed = TRUE AND authority_provenance = 'EXPLICIT_JOIN' AND membership_version = 1 AND membership_authority_generation = 1", + "SELECT COUNT(*) FROM account_tenant_membership WHERE id = ? AND account_id = ? AND tenant_id = ? AND lifecycle_state = 'ACTIVE' AND gameplay_admission_allowed = TRUE AND authority_provenance = 'EXPLICIT_JOIN' AND membership_version = 2 AND membership_authority_generation = 1", membershipId, fixture.accountId(), fixture.tenantId()) @@ -523,6 +734,72 @@ private void assertMembershipAndAuditOnce(JoinFixture fixture, long membershipId .isEqualTo(1L); } + private AuthorityEventSnapshot assertAuthorityMembershipEvent(JoinFixture fixture) { + String streamKey = authorityStreamKey(fixture); + assertThat(countAuthorityMembershipEvents(fixture)).isEqualTo(1L); + assertThat( + dsl.resultQuery( + "SELECT last_sequence FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ?", + streamKey) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + var row = + dsl.resultQuery( + "SELECT outbox_sequence, request_id, event_id, event_digest, payload " + + "FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ? AND outbox_sequence = 1", + streamKey) + .fetchOne(); + assertThat(row).isNotNull(); + assertThat(row.get("request_id", String.class)).isEqualTo(fixture.requestId()); + String eventId = row.get("event_id", String.class); + String eventDigest = row.get("event_digest", String.class); + byte[] payload = row.get("payload", byte[].class); + String payloadJson = new String(payload, StandardCharsets.UTF_8); + MembershipAuthorityEventV1Codec.MembershipEvent event = + MembershipAuthorityEventV1Codec.verify(payloadJson); + + assertThat(row.get("outbox_sequence", Long.class)).isEqualTo(1L); + assertThat(event.eventId()).isEqualTo(eventId); + assertThat(event.requestId()).isEqualTo(fixture.requestId()); + assertThat(event.schemaVersion()).isEqualTo(MembershipAuthorityEventV1Codec.SCHEMA_VERSION); + assertThat(event.eventType()).isEqualTo(MembershipAuthorityEventV1Codec.EVENT_TYPE); + assertThat(event.outboxStreamKey()).isEqualTo(streamKey); + assertThat(event.outboxSequence()).isEqualTo("1"); + assertThat(event.sourceScope()) + .isEqualTo("membership/" + fixture.accountUuid() + "/" + fixture.tenantUuid()); + assertThat(event.accountId()).isEqualTo(fixture.accountUuid().toString()); + assertThat(event.tenantId()).isEqualTo(fixture.tenantUuid().toString()); + assertThat(event.membershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(event.membershipVersion()).isEqualTo(Map.of(fixture.tenantUuid().toString(), "2")); + assertThat(event.roles()).containsExactly("player"); + assertThat(event.gameplayAdmissionAllowed()).isTrue(); + assertThat(event.canonicalJson()).isEqualTo(payloadJson); + assertThat(payload).containsExactly(event.canonicalJsonUtf8()); + assertThat(eventDigest).isEqualTo(event.eventDigest()); + assertThat(eventDigest).matches("sha256:[0-9a-f]{64}"); + + return new AuthorityEventSnapshot(eventId, eventDigest, payloadJson); + } + + private String authorityStreamKey(JoinFixture fixture) { + return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + fixture.accountUuid() + + "/" + + fixture.tenantUuid(); + } + + private long countAuthorityMembershipEvents(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + authorityStreamKey(fixture)) + .fetchOne(0, Long.class)); + } + private long countMemberships(JoinFixture fixture) { return Objects.requireNonNull( dsl.resultQuery( @@ -550,7 +827,7 @@ private JoinPublicProductionResult join(JoinFixture fixture) { private JoinFixture fixture(String subscriptionStatus) { String suffix = UUID.randomUUID().toString(); String requestId = "join-rec-" + suffix; - long tenantId = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE; + long tenantId = positiveRandomLong(); long accountId = Objects.requireNonNull( dsl.resultQuery( @@ -559,6 +836,41 @@ private JoinFixture fixture(String subscriptionStatus) { "join-rec-" + suffix + "@example.com", "test-hash") .fetchOne(0, Long.class)); + UUID accountUuid = + Objects.requireNonNull( + dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", accountId) + .fetchOne(0, UUID.class)); + seedAccountAuthorityState(accountUuid); + seedRetainedV26TenantEvidence(tenantId, suffix); + UUID tenantUuid = UUID.randomUUID(); + String evidenceDigest = legacyTenantSourceEvidence.digest(tenantId); + tenantAssociationRepository.importApproved( + tenantId, approvedTenantAssociation(tenantId, tenantUuid, evidenceDigest, suffix)); + var storedAssociation = + tenantAssociationRepository.findByLegacyTenantId(tenantId).orElseThrow(); + assertThat(storedAssociation.legacyTenantId()).isEqualTo(tenantId); + assertThat(storedAssociation.canonicalTenantId()).isEqualTo(tenantUuid); + assertThat(storedAssociation.accountEvidenceDigest()).isEqualTo(evidenceDigest); + assertThat( + dsl.resultQuery( + "SELECT generation FROM account_authority_generations " + + "WHERE scope_kind = 'TENANT' AND tenant_uuid = ?", + tenantUuid) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_legacy_tenant_sources " + "WHERE account_id = ?", + accountId) + .fetchOne(0, Long.class)) + .isZero(); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_legacy_membership_sources " + + "WHERE account_id = ?", + accountId) + .fetchOne(0, Long.class)) + .isZero(); dsl.execute( "INSERT INTO subscription (account_id, tenant_id, plan_id, status, entitlement_version) VALUES (?, ?, ?, ?, 1)", accountId, @@ -620,7 +932,92 @@ private JoinFixture fixture(String subscriptionStatus) { CATALOG_REVISION, POINTER_VERSION); DirectTextJoinScope scope = accountService.issueDirectTextConnectScope(caller, target); - return new JoinFixture(accountId, tenantId, requestId, caller, scope.connectScopeId()); + return new JoinFixture( + accountId, accountUuid, tenantId, tenantUuid, requestId, caller, scope.connectScopeId()); + } + + private void seedRetainedV26TenantEvidence(long tenantId, String suffix) { + long donorAccountId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash, tenant_id) " + + "VALUES (?, ?, ?, ?) RETURNING id", + "jrd-" + suffix, + "join-rec-retained-donor-" + suffix + "@example.com", + "test-hash", + tenantId) + .fetchOne(0, Long.class)); + UUID donorAccountUuid = + Objects.requireNonNull( + dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", donorAccountId) + .fetchOne(0, UUID.class)); + seedAccountAuthorityState(donorAccountUuid); + long retainedMembershipId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO account_tenant_membership " + + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " + + "membership_version, membership_authority_generation, authority_provenance) " + + "VALUES (?, ?, FALSE, 'LEGACY_UNVERIFIED', 1, 1, 'LEGACY_UNVERIFIED') " + + "RETURNING id", + donorAccountId, + tenantId) + .fetchOne(0, Long.class)); + dsl.execute( + "INSERT INTO account_legacy_tenant_sources " + + "(account_id, legacy_tenant_id, matching_membership_id, " + + "matching_membership_admission_allowed, profile_tenant_count, " + + "matching_profile_count, disposition) VALUES (?, ?, ?, FALSE, 0, 0, 'UNVERIFIED')", + donorAccountId, + tenantId, + retainedMembershipId); + dsl.execute( + "INSERT INTO account_legacy_membership_sources " + + "(membership_id, account_id, tenant_id, original_gameplay_admission_allowed, " + + "matches_account_legacy_tenant, disposition) " + + "VALUES (?, ?, ?, FALSE, TRUE, 'UNVERIFIED')", + retainedMembershipId, + donorAccountId, + tenantId); + } + + private void seedAccountAuthorityState(UUID accountUuid) { + dsl.execute( + "INSERT INTO account_authority_generations " + + "(scope_kind, account_uuid, generation, source_version) " + + "VALUES ('ACCOUNT', ?, 1, 1)", + accountUuid); + dsl.execute( + "INSERT INTO account_authority_issuance_fences " + + "(account_uuid, issuance_fence, source_version) VALUES (?, 1, 1)", + accountUuid); + } + + private ResolveLegacyAccountTenantAssociationResponse approvedTenantAssociation( + long legacyTenantId, UUID tenantUuid, String evidenceDigest, String suffix) { + String sourceLegacyGameTenantId = "legacy-game-" + suffix.replace("-", "").substring(0, 24); + return ResolveLegacyAccountTenantAssociationResponse.newBuilder() + .setLegacyAccountTenantId(legacyTenantId) + .setCanonicalTenantId(tenantUuid.toString()) + .setSourceLegacyGameTenantId(sourceLegacyGameTenantId) + .setSourceGameRowId(positiveRandomLong()) + .setAccountEvidenceDigest(evidenceDigest) + .setOperationId(UUID.randomUUID().toString()) + .setManifestDigest("sha256:" + "b".repeat(64)) + .setManifestSignature(java.util.Base64.getEncoder().encodeToString(new byte[64])) + .setTargetNamespace("account_service") + .setSignerKeyId("game-design-owner-test") + .setApprovedBy("owner@example.test") + .setApprovalReference("unit-1b-postgres-fixture") + .setSignedAt("2026-09-26T00:00:00Z") + .setOperationEntryCount(1) + .setManifestSchemaVersion(1) + .build(); + } + + private long positiveRandomLong() { + long candidate = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE; + return candidate == 0L ? 1L : candidate; } private static UUID joinAuditEventId(String requestId) { @@ -641,8 +1038,12 @@ private static void await(CountDownLatch start) { private record JoinFixture( long accountId, + UUID accountUuid, long tenantId, + UUID tenantUuid, String requestId, DirectTextCallerContext caller, String connectScopeId) {} + + private record AuthorityEventSnapshot(String eventId, String eventDigest, String payloadJson) {} } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationIntegrationTest.java new file mode 100644 index 0000000000..de9b832c69 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationIntegrationTest.java @@ -0,0 +1,592 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class AccountAuthorityGenerationIntegrationTest { + private static final String SCHEMA_PREFIX = "authority_generation_proof"; + private static final UUID TENANT_A = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID TENANT_B = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void explicitExactScopeStateUsesCompareAndAdvanceAndFailsClosed() throws Exception { + String schema = uniqueSchema(); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?"; + dataSource.setUrl(postgres.getJdbcUrl() + separator + "currentSchema=" + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + + DSLContext setupDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + UUID accountA = insertAccount(setupDsl, "authority-owner-a"); + UUID accountB = insertAccount(setupDsl, "authority-owner-b"); + DSLContext transactionDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + AccountAuthorityGenerationRepository repository = + new AccountAuthorityGenerationRepository(transactionDsl); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + + AuthorityScope issuerScope = AuthorityScope.issuer(AccountServiceImpl.ACCOUNT_JWT_ISSUER); + AuthorityScope lowerIssuerScope = AuthorityScope.issuer("issuer-a"); + AuthorityScope accountScopeA = AuthorityScope.account(accountA); + AuthorityScope accountScopeB = AuthorityScope.account(accountB); + AuthorityScope tenantScopeA = AuthorityScope.tenant(TENANT_A); + AuthorityScope tenantScopeB = AuthorityScope.tenant(TENANT_B); + AuthorityScope membershipAA = AuthorityScope.membership(accountA, TENANT_A); + AuthorityScope membershipAB = AuthorityScope.membership(accountA, TENANT_B); + AuthorityScope membershipBA = AuthorityScope.membership(accountB, TENANT_A); + + assertThatThrownBy(() -> inTransaction(transaction, () -> repository.read(tenantScopeA))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("missing"); + assertThat( + setupDsl + .resultQuery( + "SELECT count(*) FROM account_authority_generations WHERE scope_kind = 'TENANT'") + .fetchOne(0, Long.class)) + .isZero(); + + proveConcurrentIssuerEnrollment(repository, transaction, issuerScope.issuerId()); + assertThat( + setupDsl + .resultQuery( + "SELECT count(*) FROM account_authority_generations " + + "WHERE scope_kind = 'ISSUER' AND issuer_id = ?", + issuerScope.issuerId()) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + ScopeState enrolledIssuer = inTransaction(transaction, () -> repository.read(issuerScope)); + assertThat(enrolledIssuer.generation()).isEqualTo(1L); + assertThat(enrolledIssuer.sourceVersion()).isEqualTo(1L); + ScopeState advancedIssuer = + inTransaction(transaction, () -> repository.advance(enrolledIssuer, null)); + assertThat(advancedIssuer.generation()).isEqualTo(2L); + assertThat(advancedIssuer.sourceVersion()).isEqualTo(2L); + assertThat( + inTransaction( + transaction, () -> repository.initializeIssuerIfAbsent(issuerScope.issuerId()))) + .isEqualTo(advancedIssuer); + inTransaction(transaction, () -> repository.initialize(lowerIssuerScope)); + inTransaction(transaction, () -> repository.initialize(accountScopeA)); + inTransaction(transaction, () -> repository.initialize(accountScopeB)); + assertThatThrownBy(() -> inTransaction(transaction, () -> repository.initialize(membershipAA))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("missing"); + assertThat( + setupDsl + .resultQuery( + "SELECT issuance_fence FROM account_authority_issuance_fences " + + "WHERE account_uuid = ?", + accountA) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + inTransaction(transaction, () -> repository.initialize(tenantScopeA)); + inTransaction(transaction, () -> repository.initialize(tenantScopeB)); + inTransaction(transaction, () -> repository.initialize(membershipAA)); + inTransaction(transaction, () -> repository.initialize(membershipAB)); + inTransaction(transaction, () -> repository.initialize(membershipBA)); + + CompositeSnapshot snapshot = + inTransaction( + transaction, + () -> + repository.readCompositeSnapshot( + issuerScope.issuerId(), + accountA, + List.of(TENANT_B, TENANT_A), + List.of(TENANT_A))); + assertThat(snapshot.issuer().scope()).isEqualTo(issuerScope); + assertThat(snapshot.account().scope()).isEqualTo(accountScopeA); + assertThat(snapshot.tenants()) + .extracting(state -> state.scope().tenantId()) + .containsExactly(TENANT_A, TENANT_B); + assertThat(snapshot.memberships()) + .extracting(state -> state.scope()) + .containsExactly(membershipAA); + assertThat(snapshot.issuanceFence().value()).isEqualTo(1L); + assertThat( + inTransaction(transaction, () -> repository.read(lowerIssuerScope)).scope().issuerId()) + .isEqualTo("issuer-a"); + assertThat(inTransaction(transaction, () -> repository.read(membershipAB)).scope()) + .isEqualTo(membershipAB); + assertThat(inTransaction(transaction, () -> repository.read(membershipBA)).scope()) + .isEqualTo(membershipBA); + + ScopeState tenantExpected = inTransaction(transaction, () -> repository.read(tenantScopeA)); + ScopeState tenantAdvanced = + inTransaction(transaction, () -> repository.advance(tenantExpected, null)); + assertThat(tenantAdvanced.generation()).isEqualTo(2L); + assertThat(tenantAdvanced.sourceVersion()).isEqualTo(2L); + assertThatThrownBy( + () -> inTransaction(transaction, () -> repository.advance(tenantExpected, null))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Stale"); + + ScopeState membershipExpected = inTransaction(transaction, () -> repository.read(membershipAA)); + IssuanceFence staleFence = membershipExpected.issuanceFence(); + ScopeState membershipAdvanced = + inTransaction(transaction, () -> repository.advance(membershipExpected, staleFence)); + assertThat(membershipAdvanced.generation()).isEqualTo(2L); + assertThat(membershipAdvanced.sourceVersion()).isEqualTo(2L); + assertThat(membershipAdvanced.issuanceFence().value()).isEqualTo(staleFence.value() + 1L); + assertThatThrownBy( + () -> + inTransaction( + transaction, () -> repository.advance(membershipExpected, staleFence))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("fence"); + + proveConcurrentStaleMembershipAdvance( + repository, transaction, membershipAdvanced, membershipAdvanced.issuanceFence()); + + assertThatThrownBy( + () -> + setupDsl.execute( + "INSERT INTO account_authority_generations " + + "(scope_kind, tenant_uuid, generation, source_version) " + + "VALUES ('TENANT', ?, 0, 1)", + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"))) + .isInstanceOf(DataAccessException.class); + + AuthorityScope corruptScope = + AuthorityScope.tenant(UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd")); + inTransaction(transaction, () -> repository.initialize(corruptScope)); + setupDsl.execute( + "ALTER TABLE account_authority_generations " + + "DROP CONSTRAINT account_authority_generations_positive_check"); + setupDsl.execute( + "ALTER TABLE account_authority_generations " + + "DISABLE TRIGGER account_authority_generations_monotonic"); + setupDsl.execute( + "UPDATE account_authority_generations SET generation = 0, source_version = 0 " + + "WHERE scope_kind = 'TENANT' AND tenant_uuid = ?", + corruptScope.tenantId()); + setupDsl.execute( + "ALTER TABLE account_authority_generations " + + "ENABLE TRIGGER account_authority_generations_monotonic"); + assertThatThrownBy(() -> inTransaction(transaction, () -> repository.read(corruptScope))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("malformed"); + } + + @Test + void exhaustedAccountCountersRollbackTheWholeCallerTransaction() { + String schema = uniqueSchema(); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?"; + dataSource.setUrl(postgres.getJdbcUrl() + separator + "currentSchema=" + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + + DSLContext setupDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + DSLContext transactionDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + AccountAuthorityGenerationRepository generationRepository = + new AccountAuthorityGenerationRepository(transactionDsl); + AccountAuthorityOutboxRepository outboxRepository = + new AccountAuthorityOutboxRepository(transactionDsl); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + setupDsl.execute( + "CREATE TABLE authority_overflow_sentinel " + + "(sentinel_id INTEGER PRIMARY KEY, value INTEGER NOT NULL)"); + setupDsl.execute( + "INSERT INTO authority_overflow_sentinel (sentinel_id, value) " + + "VALUES (1, 0), (2, 0), (3, 0), (4, 0)"); + + proveOverflowRollsBack( + setupDsl, + transactionDsl, + generationRepository, + outboxRepository, + transaction, + "generation", + 1, + OverflowCounter.GENERATION); + proveOverflowRollsBack( + setupDsl, + transactionDsl, + generationRepository, + outboxRepository, + transaction, + "source-version", + 2, + OverflowCounter.SOURCE_VERSION); + proveOverflowRollsBack( + setupDsl, + transactionDsl, + generationRepository, + outboxRepository, + transaction, + "issuance-fence", + 3, + OverflowCounter.ISSUANCE_FENCE); + proveOverflowRollsBack( + setupDsl, + transactionDsl, + generationRepository, + outboxRepository, + transaction, + "issuance-fence-source-version", + 4, + OverflowCounter.ISSUANCE_FENCE_SOURCE_VERSION); + } + + private void proveOverflowRollsBack( + DSLContext setupDsl, + DSLContext transactionDsl, + AccountAuthorityGenerationRepository generationRepository, + AccountAuthorityOutboxRepository outboxRepository, + TransactionTemplate transaction, + String caseName, + int sentinelId, + OverflowCounter overflowCounter) { + UUID accountId = insertAccount(setupDsl, "auth-overflow-" + UUID.randomUUID()); + AuthorityScope scope = AuthorityScope.account(accountId); + inTransaction(transaction, () -> generationRepository.initialize(scope)); + seedOverflowCounter(setupDsl, accountId, overflowCounter); + + ScopeState original = inTransaction(transaction, () -> generationRepository.read(scope)); + assertOverflowCounterWasSeeded(original, overflowCounter); + String stream = "account:auth-authority:v1:account/" + accountId; + String requestId = "overflow-sentinel-" + caseName; + String eventId = "overflow-sentinel-event-" + caseName; + + assertThatThrownBy( + () -> + inTransaction( + transaction, + () -> { + transactionDsl.execute( + "UPDATE authority_overflow_sentinel SET value = value + 1 " + + "WHERE sentinel_id = ?", + sentinelId); + outboxRepository.append( + stream, + requestId, + eventId, + "overflow-sentinel-digest-" + caseName, + new byte[] {1, 2, 3}); + return generationRepository.advance(original, original.issuanceFence()); + })) + .isInstanceOf(DataAccessException.class); + + ScopeState after = inTransaction(transaction, () -> generationRepository.read(scope)); + assertThat(after).isEqualTo(original); + var generationRow = + setupDsl + .resultQuery( + "SELECT generation, source_version FROM account_authority_generations " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + accountId) + .fetchOne(); + assertThat(generationRow.get("generation", Long.class)).isEqualTo(original.generation()); + assertThat(generationRow.get("source_version", Long.class)).isEqualTo(original.sourceVersion()); + var fenceRow = + setupDsl + .resultQuery( + "SELECT issuance_fence, source_version FROM account_authority_issuance_fences " + + "WHERE account_uuid = ?", + accountId) + .fetchOne(); + assertThat(fenceRow.get("issuance_fence", Long.class)) + .isEqualTo(original.issuanceFence().value()); + assertThat(fenceRow.get("source_version", Long.class)) + .isEqualTo(original.issuanceFence().sourceVersion()); + assertThat( + setupDsl + .resultQuery( + "SELECT value FROM authority_overflow_sentinel WHERE sentinel_id = ?", + sentinelId) + .fetchOne(0, Integer.class)) + .isZero(); + assertThat(inTransaction(transaction, () -> outboxRepository.readCheckpoint(stream))).isEmpty(); + assertThat( + setupDsl + .resultQuery( + "SELECT count(*) FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ?", + stream) + .fetchOne(0, Long.class)) + .isZero(); + assertThat( + setupDsl + .resultQuery( + "SELECT count(*) FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + stream) + .fetchOne(0, Long.class)) + .isZero(); + } + + private void assertOverflowCounterWasSeeded(ScopeState state, OverflowCounter overflowCounter) { + switch (overflowCounter) { + case GENERATION -> { + assertThat(state.generation()).isEqualTo(Long.MAX_VALUE); + assertThat(state.sourceVersion()).isEqualTo(1L); + assertThat(state.issuanceFence().value()).isEqualTo(1L); + assertThat(state.issuanceFence().sourceVersion()).isEqualTo(1L); + } + case SOURCE_VERSION -> { + assertThat(state.generation()).isEqualTo(1L); + assertThat(state.sourceVersion()).isEqualTo(Long.MAX_VALUE); + assertThat(state.issuanceFence().value()).isEqualTo(1L); + assertThat(state.issuanceFence().sourceVersion()).isEqualTo(1L); + } + case ISSUANCE_FENCE -> { + assertThat(state.generation()).isEqualTo(1L); + assertThat(state.sourceVersion()).isEqualTo(1L); + assertThat(state.issuanceFence().value()).isEqualTo(Long.MAX_VALUE); + assertThat(state.issuanceFence().sourceVersion()).isEqualTo(1L); + } + case ISSUANCE_FENCE_SOURCE_VERSION -> { + assertThat(state.generation()).isEqualTo(1L); + assertThat(state.sourceVersion()).isEqualTo(1L); + assertThat(state.issuanceFence().value()).isEqualTo(1L); + assertThat(state.issuanceFence().sourceVersion()).isEqualTo(Long.MAX_VALUE); + } + } + } + + private void seedOverflowCounter( + DSLContext setupDsl, UUID accountId, OverflowCounter overflowCounter) { + // Seed a valid positive maximum directly; only the monotonic update guard is bypassed here. + switch (overflowCounter) { + case GENERATION -> { + setupDsl.execute( + "ALTER TABLE account_authority_generations " + + "DISABLE TRIGGER account_authority_generations_monotonic"); + try { + setupDsl.execute( + "UPDATE account_authority_generations SET generation = ? " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + Long.MAX_VALUE, + accountId); + } finally { + setupDsl.execute( + "ALTER TABLE account_authority_generations " + + "ENABLE TRIGGER account_authority_generations_monotonic"); + } + } + case SOURCE_VERSION -> { + setupDsl.execute( + "ALTER TABLE account_authority_generations " + + "DISABLE TRIGGER account_authority_generations_monotonic"); + try { + setupDsl.execute( + "UPDATE account_authority_generations SET source_version = ? " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + Long.MAX_VALUE, + accountId); + } finally { + setupDsl.execute( + "ALTER TABLE account_authority_generations " + + "ENABLE TRIGGER account_authority_generations_monotonic"); + } + } + case ISSUANCE_FENCE -> { + setupDsl.execute( + "ALTER TABLE account_authority_issuance_fences " + + "DISABLE TRIGGER account_authority_issuance_fences_monotonic"); + try { + setupDsl.execute( + "UPDATE account_authority_issuance_fences SET issuance_fence = ? " + + "WHERE account_uuid = ?", + Long.MAX_VALUE, + accountId); + } finally { + setupDsl.execute( + "ALTER TABLE account_authority_issuance_fences " + + "ENABLE TRIGGER account_authority_issuance_fences_monotonic"); + } + } + case ISSUANCE_FENCE_SOURCE_VERSION -> { + setupDsl.execute( + "ALTER TABLE account_authority_issuance_fences " + + "DISABLE TRIGGER account_authority_issuance_fences_monotonic"); + try { + setupDsl.execute( + "UPDATE account_authority_issuance_fences SET source_version = ? " + + "WHERE account_uuid = ?", + Long.MAX_VALUE, + accountId); + } finally { + setupDsl.execute( + "ALTER TABLE account_authority_issuance_fences " + + "ENABLE TRIGGER account_authority_issuance_fences_monotonic"); + } + } + } + } + + private String uniqueSchema() { + return SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); + } + + private void proveConcurrentStaleMembershipAdvance( + AccountAuthorityGenerationRepository repository, + TransactionTemplate transaction, + ScopeState expectedState, + IssuanceFence expectedFence) + throws Exception { + ExecutorService executor = Executors.newFixedThreadPool(2); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + try { + var first = + executor.submit( + () -> + concurrentAdvance( + repository, transaction, expectedState, expectedFence, ready, start)); + var second = + executor.submit( + () -> + concurrentAdvance( + repository, transaction, expectedState, expectedFence, ready, start)); + ready.await(); + start.countDown(); + List outcomes = List.of(first.get(), second.get()); + assertThat(outcomes).containsExactlyInAnyOrder(true, false); + ScopeState actual = inTransaction(transaction, () -> repository.read(expectedState.scope())); + assertThat(actual.generation()).isEqualTo(expectedState.generation() + 1L); + assertThat(actual.issuanceFence().value()).isEqualTo(expectedFence.value() + 1L); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + private void proveConcurrentIssuerEnrollment( + AccountAuthorityGenerationRepository repository, + TransactionTemplate transaction, + String issuerId) + throws Exception { + ExecutorService executor = Executors.newFixedThreadPool(2); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + try { + var first = + executor.submit( + () -> concurrentIssuerEnrollment(repository, transaction, issuerId, ready, start)); + var second = + executor.submit( + () -> concurrentIssuerEnrollment(repository, transaction, issuerId, ready, start)); + ready.await(); + start.countDown(); + List outcomes = List.of(first.get(), second.get()); + ScopeState initial = new ScopeState(AuthorityScope.issuer(issuerId), 1L, 1L, null); + assertThat(outcomes).containsExactly(initial, initial); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + private ScopeState concurrentIssuerEnrollment( + AccountAuthorityGenerationRepository repository, + TransactionTemplate transaction, + String issuerId, + CountDownLatch ready, + CountDownLatch start) { + ready.countDown(); + await(start); + return inTransaction(transaction, () -> repository.initializeIssuerIfAbsent(issuerId)); + } + + private boolean concurrentAdvance( + AccountAuthorityGenerationRepository repository, + TransactionTemplate transaction, + ScopeState expectedState, + IssuanceFence expectedFence, + CountDownLatch ready, + CountDownLatch start) { + ready.countDown(); + await(start); + try { + inTransaction(transaction, () -> repository.advance(expectedState, expectedFence)); + return true; + } catch (IllegalStateException stale) { + return false; + } + } + + private UUID insertAccount(DSLContext dsl, String username) { + return dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash) " + + "VALUES (?, ?, ?) RETURNING account_uuid", + username, + username + "@example.test", + "hash") + .fetchOne(0, UUID.class); + } + + private T inTransaction(TransactionTemplate transaction, Supplier operation) { + return transaction.execute(status -> operation.get()); + } + + private void await(CountDownLatch latch) { + try { + latch.await(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Authority-generation concurrency proof was interrupted", interrupted); + } + } + + private enum OverflowCounter { + GENERATION, + SOURCE_VERSION, + ISSUANCE_FENCE, + ISSUANCE_FENCE_SOURCE_VERSION + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepositoryIntegrationTest.java new file mode 100644 index 0000000000..469965abec --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepositoryIntegrationTest.java @@ -0,0 +1,330 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import java.util.Map; +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.function.Supplier; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.IdempotencyConflictException; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class AccountAuthorityOutboxRepositoryIntegrationTest { + private static final String SCHEMA_PREFIX = "authority_outbox_proof"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void appendsContiguousPerStreamAndReplaysOnlyExactRequestEvidence() { + TestContext context = newTestContext(); + AccountAuthorityOutboxRepository repository = context.repository(); + TransactionTemplate transaction = context.transaction(); + String stream = membershipStream(UUID.randomUUID(), UUID.randomUUID()); + String unrelated = "account:auth-authority:v1:tenant/" + UUID.randomUUID(); + + assertThat(inTransaction(transaction, () -> repository.readCheckpoint(stream))).isEmpty(); + + Event first = + inTransaction( + transaction, + () -> + repository.append( + stream, "request-1", "event-1", "canonical-digest-1", new byte[] {1, 2})); + Event exactReplay = + inTransaction( + transaction, + () -> + repository.append( + stream, "request-1", "event-1", "canonical-digest-1", new byte[] {1, 2})); + assertThat(exactReplay).isEqualTo(first); + + assertThatThrownBy( + () -> + inTransaction( + transaction, + () -> + repository.append( + stream, "request-1", "event-1", "different-digest", new byte[] {1, 2}))) + .isInstanceOf(IdempotencyConflictException.class); + + Event second = + inTransaction( + transaction, + () -> + repository.append( + stream, "request-2", "event-2", "canonical-digest-2", new byte[] {3, 4})); + Event otherStreamFirst = + inTransaction( + transaction, + () -> + repository.append( + unrelated, "request-1", "event-1", "canonical-digest-1", new byte[] {1, 2})); + Optional checkpoint = + inTransaction(transaction, () -> repository.readCheckpoint(stream)); + + assertThat(first.outboxSequence()).isEqualTo(1L); + assertThat(second.outboxSequence()).isEqualTo(2L); + assertThat(otherStreamFirst.outboxSequence()).isEqualTo(1L); + assertThat(checkpoint).contains(new Checkpoint(stream, 2L, "event-2", "canonical-digest-2")); + assertThat(inTransaction(transaction, () -> repository.findEvent(stream, 1L))).contains(first); + assertThat(inTransaction(transaction, () -> repository.findEvent(stream, 2L))).contains(second); + } + + @Test + void callerRollbackRemovesAppendAndConcurrentExactRetriesShareOneSequence() throws Exception { + TestContext context = newTestContext(); + AccountAuthorityOutboxRepository repository = context.repository(); + TransactionTemplate transaction = context.transaction(); + String rollbackStream = "account:auth-authority:v1:account/" + UUID.randomUUID(); + + transaction.execute( + status -> { + repository.append( + rollbackStream, "rollback-request", "rollback-event", "digest", new byte[] {9}); + status.setRollbackOnly(); + return null; + }); + assertThat(inTransaction(transaction, () -> repository.readCheckpoint(rollbackStream))) + .isEmpty(); + + String concurrentStream = "account:auth-authority:v1:issuer/" + UUID.randomUUID(); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + var first = + executor.submit( + () -> concurrentAppend(repository, transaction, concurrentStream, ready, start)); + var second = + executor.submit( + () -> concurrentAppend(repository, transaction, concurrentStream, ready, start)); + ready.await(); + start.countDown(); + List events = List.of(first.get(), second.get()); + + assertThat(events).allMatch(event -> event.outboxSequence() == 1L); + assertThat(events).extracting(Event::eventId).containsOnly("event-1"); + assertThat(inTransaction(transaction, () -> repository.readCheckpoint(concurrentStream))) + .contains(new Checkpoint(concurrentStream, 1L, "event-1", "digest-1")); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void evidenceFactoryFailureRollsBackStreamCreationAndDoesNotAdvanceHead() { + TestContext context = newTestContext(); + AccountAuthorityOutboxRepository repository = context.repository(); + TransactionTemplate transaction = context.transaction(); + String stream = membershipStream(UUID.randomUUID(), UUID.randomUUID()); + + assertThatThrownBy( + () -> + inTransaction( + transaction, + () -> + repository.append( + stream, + "factory-failure-request", + sequence -> { + assertThat(sequence).isEqualTo(1L); + throw new IllegalStateException("producer failed"); + }))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("producer failed"); + + assertThat(inTransaction(transaction, () -> repository.readCheckpoint(stream))).isEmpty(); + } + + @Test + void exhaustedSequenceRejectsAppendWithoutChangingEventCheckpointOrCallerSentinel() { + TestContext context = newTestContext(); + AccountAuthorityOutboxRepository repository = context.repository(); + TransactionTemplate transaction = context.transaction(); + DSLContext dsl = context.dsl(); + String stream = "account:auth-authority:v1:account/" + UUID.randomUUID(); + byte[] originalPayload = new byte[] {7, 8, 9}; + Event originalEvent = + new Event( + stream, + "exhaustion-seed-request", + Long.MAX_VALUE, + "exhaustion-seed-event", + "exhaustion-seed-digest", + originalPayload); + + dsl.execute( + "CREATE TABLE authority_overflow_sentinel " + + "(sentinel_id INTEGER PRIMARY KEY, value INTEGER NOT NULL)"); + dsl.execute("INSERT INTO authority_overflow_sentinel (sentinel_id, value) VALUES (1, 0)"); + // Seed a consistent exhausted stream; bypass only its contiguous-insert guard for this setup. + dsl.execute( + "ALTER TABLE account_authority_outbox_events " + + "DISABLE TRIGGER account_authority_outbox_event_insert"); + try { + inTransaction( + transaction, + () -> { + dsl.execute( + "INSERT INTO account_authority_outbox_streams " + + "(outbox_stream_key, last_sequence) VALUES (?, ?)", + stream, + Long.MAX_VALUE); + dsl.execute( + "INSERT INTO account_authority_outbox_events " + + "(outbox_stream_key, outbox_sequence, request_id, event_id, " + + "event_digest, payload) VALUES (?, ?, ?, ?, ?, ?)", + stream, + Long.MAX_VALUE, + originalEvent.requestId(), + originalEvent.eventId(), + originalEvent.eventDigest(), + originalPayload); + return null; + }); + } finally { + dsl.execute( + "ALTER TABLE account_authority_outbox_events " + + "ENABLE TRIGGER account_authority_outbox_event_insert"); + } + + assertThat(inTransaction(transaction, () -> repository.readCheckpoint(stream))) + .contains( + new Checkpoint( + stream, Long.MAX_VALUE, "exhaustion-seed-event", "exhaustion-seed-digest")); + assertThat(inTransaction(transaction, () -> repository.findEvent(stream, Long.MAX_VALUE))) + .contains(originalEvent); + + assertThatThrownBy( + () -> + inTransaction( + transaction, + () -> { + dsl.execute( + "UPDATE authority_overflow_sentinel SET value = value + 1 " + + "WHERE sentinel_id = 1"); + return repository.append( + stream, + "exhaustion-attempt-request", + "exhaustion-attempt-event", + "exhaustion-attempt-digest", + new byte[] {1, 2, 3}); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account authority outbox sequence is exhausted"); + + assertThat(inTransaction(transaction, () -> repository.readCheckpoint(stream))) + .contains( + new Checkpoint( + stream, Long.MAX_VALUE, "exhaustion-seed-event", "exhaustion-seed-digest")); + assertThat(inTransaction(transaction, () -> repository.findEvent(stream, Long.MAX_VALUE))) + .contains(originalEvent); + assertThat( + dsl.resultQuery( + "SELECT count(*) FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ?", + stream) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + assertThat( + dsl.resultQuery( + "SELECT count(*) FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + stream) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + assertThat( + dsl.resultQuery( + "SELECT last_sequence FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ?", + stream) + .fetchOne(0, Long.class)) + .isEqualTo(Long.MAX_VALUE); + assertThat( + dsl.resultQuery("SELECT value FROM authority_overflow_sentinel WHERE sentinel_id = 1") + .fetchOne(0, Integer.class)) + .isZero(); + } + + private Event concurrentAppend( + AccountAuthorityOutboxRepository repository, + TransactionTemplate transaction, + String stream, + CountDownLatch ready, + CountDownLatch start) { + ready.countDown(); + await(start); + return inTransaction( + transaction, + () -> repository.append(stream, "same-request", "event-1", "digest-1", new byte[] {1})); + } + + private TestContext newTestContext() { + String schema = SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?"; + dataSource.setUrl(postgres.getJdbcUrl() + separator + "currentSchema=" + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new TestContext( + new AccountAuthorityOutboxRepository(dsl), + new TransactionTemplate(new DataSourceTransactionManager(dataSource)), + dsl); + } + + private String membershipStream(UUID accountId, UUID tenantId) { + return "account:auth-authority:v1:membership/" + accountId + "/" + tenantId; + } + + private T inTransaction(TransactionTemplate transaction, Supplier operation) { + return transaction.execute(status -> operation.get()); + } + + private void await(CountDownLatch latch) { + try { + latch.await(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Authority outbox concurrency proof was interrupted", interrupted); + } + } + + private record TestContext( + AccountAuthorityOutboxRepository repository, + TransactionTemplate transaction, + DSLContext dsl) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceRepositoryIntegrationTest.java new file mode 100644 index 0000000000..e00fb4591f --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceRepositoryIntegrationTest.java @@ -0,0 +1,810 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.Callable; +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 java.util.function.Supplier; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceIdentity; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceOperation.Lifecycle; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepository; +import net.firedevops.firemud.accountservice.security.AccountEncryptedEnvelope; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeBinding; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeCrypto; +import net.firedevops.firemud.accountservice.security.AccountEnvelopePurpose; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class AccountConnectTokenIssuanceRepositoryIntegrationTest { + private static final String SCHEMA = "account_connect_token_issuance_proof"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void claimIsFirstWriterWinsAndChangedDigestDoesNotMutateTheOperation() { + TestContext context = newTestContext(); + AccountConnectTokenIssuanceIdentity identity = newIdentity(insertAccount(context.dsl())); + byte[] digest = digest(1); + + var claimed = + inTransaction(context.transaction(), () -> context.repository().claim(identity, digest)); + var exactRetry = + inTransaction(context.transaction(), () -> context.repository().claim(identity, digest)); + + assertThat(claimed.disposition()) + .isEqualTo(AccountConnectTokenIssuanceRepository.ClaimDisposition.CLAIMED); + assertThat(exactRetry.disposition()) + .isEqualTo(AccountConnectTokenIssuanceRepository.ClaimDisposition.REPLAYED); + assertThat(exactRetry.operation().operationId()).isEqualTo(claimed.operation().operationId()); + assertThat(exactRetry.operation().lifecycle()).isEqualTo(Lifecycle.PENDING); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .repository() + .completeWithEnvelope( + exactRetry, + digest, + Lifecycle.FAILED, + "JOIN_REQUIRED", + null, + null, + binding(exactRetry.operation().operationId(), identity, digest), + encryptedEnvelope(AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE)))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Only the first"); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), () -> context.repository().claim(identity, digest(2)))) + .isInstanceOf(AccountConnectTokenIssuanceRepository.IdempotencyConflictException.class); + assertThat( + inTransaction( + context.transaction(), + () -> context.repository().find(identity, digest).orElseThrow())) + .isEqualTo(claimed.operation()); + } + + @Test + void concurrentExactIssuanceClaimsHaveOneTerminalFirstWriter() throws Exception { + TestContext context = newTestContext(); + AccountConnectTokenIssuanceIdentity identity = newIdentity(insertAccount(context.dsl())); + byte[] requestDigest = digest(2); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Callable issue = + () -> { + ready.countDown(); + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Issuance claim race did not start together"); + } + return inTransaction( + context.transaction(), + () -> { + var claim = context.repository().claim(identity, requestDigest); + if (claim.disposition() + == AccountConnectTokenIssuanceRepository.ClaimDisposition.CLAIMED) { + AccountEnvelopeBinding binding = + binding(claim.operation().operationId(), identity, requestDigest); + context + .repository() + .completeWithEnvelope( + claim, + requestDigest, + Lifecycle.FAILED, + "JOIN_REQUIRED", + null, + null, + binding, + encryptedEnvelope(AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE)); + } + return claim; + }); + }; + Future first = executor.submit(issue); + Future second = executor.submit(issue); + assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + var results = List.of(first.get(20, TimeUnit.SECONDS), second.get(20, TimeUnit.SECONDS)); + assertThat(results) + .extracting(AccountConnectTokenIssuanceRepository.ClaimResult::disposition) + .containsExactlyInAnyOrder( + AccountConnectTokenIssuanceRepository.ClaimDisposition.CLAIMED, + AccountConnectTokenIssuanceRepository.ClaimDisposition.REPLAYED); + assertThat(results.get(0).operation().operationId()) + .isEqualTo(results.get(1).operation().operationId()); + assertThat( + inTransaction( + context.transaction(), + () -> context.repository().find(identity, requestDigest).orElseThrow()) + .lifecycle()) + .isEqualTo(Lifecycle.FAILED); + AccountEnvelopeBinding binding = + binding(results.get(0).operation().operationId(), identity, requestDigest); + assertThat( + inTransaction( + context.transaction(), + () -> + context.repository().readResponseEnvelope(identity, requestDigest, binding))) + .isPresent(); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void lostIssuanceResponseRecoversExactEncryptedResultFromDurableReadback( + @TempDir Path temporaryDirectory) throws Exception { + TestContext context = newTestContext(); + AccountConnectTokenIssuanceIdentity identity = newIdentity(insertAccount(context.dsl())); + byte[] requestDigest = digest(3); + byte[] originalResult = "original-connect-token-result".getBytes(StandardCharsets.UTF_8); + byte[] connectKey = new byte[32]; + byte[] bareLoginKey = new byte[32]; + java.util.Arrays.fill(connectKey, (byte) 1); + java.util.Arrays.fill(bareLoginKey, (byte) 2); + Path manifest = temporaryDirectory.resolve("manifest.v1"); + Files.writeString( + manifest, + "version=1\nactiveKeyId=k1\n" + + "key:k1:bare-login=" + + Base64.getUrlEncoder().withoutPadding().encodeToString(bareLoginKey) + + "\nkey:k1:connect-token=" + + Base64.getUrlEncoder().withoutPadding().encodeToString(connectKey) + + "\n", + StandardCharsets.US_ASCII); + AccountEnvelopeCrypto writer = new AccountEnvelopeCrypto(manifest); + + AccountEnvelopeBinding binding = + inTransaction( + context.transaction(), + () -> { + var claim = context.repository().claim(identity, requestDigest); + AccountEnvelopeBinding issuedBinding = + binding(claim.operation().operationId(), identity, requestDigest); + context + .repository() + .completeWithEnvelope( + claim, + requestDigest, + Lifecycle.COMMITTED, + "SUCCESS", + "connect-jti-recovery", + digest(84), + issuedBinding, + writer.encrypt( + AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, + issuedBinding, + originalResult)); + return issuedBinding; + }); + + var retry = + inTransaction( + context.transaction(), () -> context.repository().claim(identity, requestDigest)); + assertThat(retry.disposition()) + .isEqualTo(AccountConnectTokenIssuanceRepository.ClaimDisposition.REPLAYED); + assertThat(retry.operation().lifecycle()).isEqualTo(Lifecycle.COMMITTED); + var stored = + inTransaction( + context.transaction(), + () -> + context + .repository() + .readResponseEnvelope(identity, requestDigest, binding) + .orElseThrow()); + AccountEnvelopeCrypto recoveryReader = new AccountEnvelopeCrypto(manifest); + assertThat( + recoveryReader.decrypt( + stored.envelope(), AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, stored.binding())) + .containsExactly(originalResult); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), () -> context.repository().find(identity, digest(4)))) + .isInstanceOf(AccountConnectTokenIssuanceRepository.IdempotencyConflictException.class); + } + + @Test + void pendingAmbiguousOperationRetainsWriteOnceEvidenceWithoutAnEnvelope() { + TestContext context = newTestContext(); + AccountConnectTokenIssuanceIdentity identity = newIdentity(insertAccount(context.dsl())); + byte[] digest = digest(6); + var claim = + inTransaction(context.transaction(), () -> context.repository().claim(identity, digest)); + Instant attemptedAt = Instant.parse("2026-09-27T00:00:00Z"); + Instant nextAttemptAt = Instant.parse("2026-09-27T00:00:30Z"); + var scheduled = + inTransaction( + context.transaction(), + () -> + context + .repository() + .recordReconciliationAttempt( + identity, + digest, + 0, + 2, + attemptedAt, + "authority read unavailable", + nextAttemptAt)); + assertThat(scheduled.reconciliationAttemptCount()).isEqualTo(1); + assertThat(scheduled.lastReconciliationAttemptAt()).isEqualTo(attemptedAt); + assertThat(scheduled.nextReconciliationAttemptAt()).isEqualTo(nextAttemptAt); + + var pending = + inTransaction( + context.transaction(), + () -> + context + .repository() + .recordPendingEvidence( + claim, + digest, + "gameplay-connect-jti-uncertain", + digest(82), + digest(35), + digest(36), + digest(37), + null)); + + assertThat(pending.lifecycle()).isEqualTo(Lifecycle.PENDING); + assertThat(pending.tokenIdentity()).isEqualTo("gameplay-connect-jti-uncertain"); + assertThat(pending.tokenHash()).containsExactly(digest(82)); + assertThat(pending.postconditionDigest()).isNull(); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .repository() + .recordPendingEvidence( + claim, + digest, + "different-token-identity", + digest(82), + null, + null, + null, + null))) + .isInstanceOf(AccountConnectTokenIssuanceRepository.EvidenceMismatchException.class); + assertThat( + inTransaction( + context.transaction(), + () -> context.repository().find(identity, digest).orElseThrow())) + .isEqualTo(pending); + assertThat( + inTransaction( + context.transaction(), + () -> + context + .repository() + .readResponseEnvelope( + identity, + digest, + binding(claim.operation().operationId(), identity, digest)))) + .isEmpty(); + } + + @Test + void reconciledAbortedOperationResolvesOnceWithItsOriginalIdentityAndEvidence() { + TestContext context = newTestContext(); + AccountConnectTokenIssuanceIdentity identity = newIdentity(insertAccount(context.dsl())); + byte[] digest = digest(9); + String tokenIdentity = "gameplay-connect-jti-reconciled"; + byte[] tokenHash = digest(83); + var claim = + inTransaction(context.transaction(), () -> context.repository().claim(identity, digest)); + AccountEnvelopeBinding binding = binding(claim.operation().operationId(), identity, digest); + + inTransaction( + context.transaction(), + () -> + context + .repository() + .recordPendingEvidence( + claim, + digest, + tokenIdentity, + tokenHash, + binding.contextEvidenceDigest(), + binding.authorityTupleDigest(), + binding.issuanceFenceDigest(), + binding.postconditionDigest())); + int aborted = + inTransaction( + context.transaction(), + () -> + context + .dsl() + .execute( + "UPDATE account_connect_token_issuance_operations " + + "SET status = 'ABORTED' WHERE operation_id = ?", + claim.operation().operationId())); + assertThat(aborted).isEqualTo(1); + + Instant attemptedAt = Instant.parse("2026-09-27T00:01:00Z"); + Instant nextAttemptAt = Instant.parse("2026-09-27T00:01:30Z"); + var reconciled = + inTransaction( + context.transaction(), + () -> + context + .repository() + .recordReconciliationAttempt( + identity, + digest, + 0, + 2, + attemptedAt, + "token registry result verified", + nextAttemptAt)); + assertThat(reconciled.lifecycle()).isEqualTo(Lifecycle.ABORTED); + assertThat(reconciled.reconciliationAttemptCount()).isEqualTo(1); + + AccountEncryptedEnvelope envelope = + encryptedEnvelope(AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .repository() + .resolveAbortedWithEnvelope( + identity, + digest(10), + 1, + Lifecycle.COMMITTED, + "SUCCESS", + tokenIdentity, + tokenHash, + binding, + envelope))) + .isInstanceOf(AccountConnectTokenIssuanceRepository.IdempotencyConflictException.class); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .repository() + .resolveAbortedWithEnvelope( + identity, + digest, + 0, + Lifecycle.COMMITTED, + "SUCCESS", + tokenIdentity, + tokenHash, + binding, + envelope))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("requires a recorded reconciliation attempt"); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .repository() + .resolveAbortedWithEnvelope( + identity, + digest, + 2, + Lifecycle.COMMITTED, + "SUCCESS", + tokenIdentity, + tokenHash, + binding, + envelope))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("changed before reconciliation resolution"); + + var stored = + inTransaction( + context.transaction(), + () -> + context + .repository() + .resolveAbortedWithEnvelope( + identity, + digest, + 1, + Lifecycle.COMMITTED, + "SUCCESS", + tokenIdentity, + tokenHash, + binding, + envelope)); + assertThat(stored.operationId()).isEqualTo(claim.operation().operationId()); + assertThat(stored.binding()).isEqualTo(binding); + assertThat(stored.envelope()).isEqualTo(envelope); + + var resolved = + inTransaction( + context.transaction(), () -> context.repository().find(identity, digest).orElseThrow()); + assertThat(resolved.operationId()).isEqualTo(claim.operation().operationId()); + assertThat(resolved.requestDigest()).containsExactly(digest); + assertThat(resolved.lifecycle()).isEqualTo(Lifecycle.COMMITTED); + assertThat(resolved.tokenIdentity()).isEqualTo(tokenIdentity); + assertThat(resolved.tokenHash()).containsExactly(tokenHash); + assertThat(resolved.contextEvidenceDigest()).containsExactly(binding.contextEvidenceDigest()); + assertThat(resolved.authorityTupleDigest()).containsExactly(binding.authorityTupleDigest()); + assertThat(resolved.issuanceFenceDigest()).containsExactly(binding.issuanceFenceDigest()); + assertThat(resolved.postconditionDigest()).containsExactly(binding.postconditionDigest()); + assertThat(resolved.reconciliationAttemptCount()).isEqualTo(1); + assertThat( + inTransaction( + context.transaction(), + () -> context.repository().readResponseEnvelope(identity, digest, binding))) + .contains(stored); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .repository() + .resolveAbortedWithEnvelope( + identity, + digest, + 1, + Lifecycle.COMMITTED, + "SUCCESS", + tokenIdentity, + tokenHash, + binding, + encryptedEnvelope(AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE)))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("changed before reconciliation resolution"); + assertThat( + inTransaction( + context.transaction(), + () -> context.repository().find(identity, digest).orElseThrow())) + .isEqualTo(resolved); + } + + @Test + void terminalResultAndEncryptedEnvelopeReadBackExactlyForTheBoundOperation() { + TestContext context = newTestContext(); + AccountConnectTokenIssuanceIdentity identity = newIdentity(insertAccount(context.dsl())); + byte[] digest = digest(11); + var claim = + inTransaction(context.transaction(), () -> context.repository().claim(identity, digest)); + AccountEnvelopeBinding binding = binding(claim.operation().operationId(), identity, digest); + AccountEncryptedEnvelope envelope = + encryptedEnvelope(AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE); + + var stored = + inTransaction( + context.transaction(), + () -> + context + .repository() + .completeWithEnvelope( + claim, + digest, + Lifecycle.COMMITTED, + "SUCCESS", + "gameplay-connect-jti-1", + digest(80), + binding, + envelope)); + var exactReadback = + inTransaction( + context.transaction(), + () -> + context.repository().readResponseEnvelope(identity, digest, binding).orElseThrow()); + + assertThat(stored.operationId()).isEqualTo(claim.operation().operationId()); + assertThat(exactReadback.operationId()).isEqualTo(stored.operationId()); + assertThat(exactReadback.binding()).isEqualTo(binding); + assertThat(exactReadback.envelope()).isEqualTo(envelope); + var committed = + inTransaction( + context.transaction(), () -> context.repository().find(identity, digest).orElseThrow()); + assertThat(committed.lifecycle()).isEqualTo(Lifecycle.COMMITTED); + assertThat(committed.tokenIdentity()).isEqualTo("gameplay-connect-jti-1"); + assertThat(committed.tokenHash()).containsExactly(digest(80)); + assertThat(committed.contextEvidenceDigest()).containsExactly(binding.contextEvidenceDigest()); + + AccountEnvelopeBinding wrongOperationBinding = binding(UUID.randomUUID(), identity, digest); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .repository() + .readResponseEnvelope(identity, digest, wrongOperationBinding))) + .isInstanceOf(AccountConnectTokenIssuanceRepository.EvidenceMismatchException.class); + } + + @Test + void directDeletionOfIssuanceOperationOrResponseEnvelopeIsRejected() { + TestContext context = newTestContext(); + AccountConnectTokenIssuanceIdentity identity = newIdentity(insertAccount(context.dsl())); + byte[] digest = digest(41); + var claim = + inTransaction(context.transaction(), () -> context.repository().claim(identity, digest)); + AccountEnvelopeBinding binding = binding(claim.operation().operationId(), identity, digest); + inTransaction( + context.transaction(), + () -> + context + .repository() + .completeWithEnvelope( + claim, + digest, + Lifecycle.COMMITTED, + "SUCCESS", + "gameplay-connect-jti-retained", + digest(84), + binding, + encryptedEnvelope(AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE))); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .dsl() + .execute( + "DELETE FROM account_connect_token_issuance_operations " + + "WHERE operation_id = ?", + claim.operation().operationId()))) + .hasMessageContaining("Connect-token issuance replay evidence cannot be deleted"); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .dsl() + .execute( + "DELETE FROM account_connect_token_response_envelopes " + + "WHERE operation_id = ?", + claim.operation().operationId()))) + .hasMessageContaining("Connect-token issuance replay evidence cannot be deleted"); + + assertThat( + context + .dsl() + .fetchCount( + DSL.table("account_connect_token_issuance_operations"), + DSL.field("operation_id", UUID.class).eq(claim.operation().operationId()))) + .isEqualTo(1); + assertThat( + context + .dsl() + .fetchCount( + DSL.table("account_connect_token_response_envelopes"), + DSL.field("operation_id", UUID.class).eq(claim.operation().operationId()))) + .isEqualTo(1); + } + + @Test + void deterministicFailureIsStoredOnlyAsItsBoundEncryptedEnvelope() { + TestContext context = newTestContext(); + AccountConnectTokenIssuanceIdentity identity = newIdentity(insertAccount(context.dsl())); + byte[] digest = digest(16); + var claim = + inTransaction(context.transaction(), () -> context.repository().claim(identity, digest)); + AccountEnvelopeBinding binding = binding(claim.operation().operationId(), identity, digest); + AccountEncryptedEnvelope envelope = + encryptedEnvelope(AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE); + + var stored = + inTransaction( + context.transaction(), + () -> + context + .repository() + .completeWithEnvelope( + claim, + digest, + Lifecycle.FAILED, + "JOIN_REQUIRED", + null, + null, + binding, + envelope)); + var operation = + inTransaction( + context.transaction(), () -> context.repository().find(identity, digest).orElseThrow()); + + assertThat(operation.lifecycle()).isEqualTo(Lifecycle.FAILED); + assertThat(operation.outcomeCode()).isEqualTo("JOIN_REQUIRED"); + assertThat(operation.tokenIdentity()).isNull(); + assertThat(operation.tokenHash()).isNull(); + assertThat( + inTransaction( + context.transaction(), + () -> context.repository().readResponseEnvelope(identity, digest, binding))) + .contains(stored); + } + + @Test + void rejectsWrongOperationBindingAndBareLoginPurposeBeforeStoringAnEnvelope() { + TestContext context = newTestContext(); + AccountConnectTokenIssuanceIdentity identity = newIdentity(insertAccount(context.dsl())); + byte[] digest = digest(21); + var claim = + inTransaction(context.transaction(), () -> context.repository().claim(identity, digest)); + AccountEnvelopeBinding binding = binding(claim.operation().operationId(), identity, digest); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .repository() + .completeWithEnvelope( + claim, + digest, + Lifecycle.COMMITTED, + "SUCCESS", + "gameplay-connect-jti-2", + digest(81), + binding(UUID.randomUUID(), identity, digest), + encryptedEnvelope(AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE)))) + .isInstanceOf(AccountConnectTokenIssuanceRepository.EvidenceMismatchException.class); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .repository() + .completeWithEnvelope( + claim, + digest, + Lifecycle.COMMITTED, + "SUCCESS", + "gameplay-connect-jti-2", + digest(81), + binding, + encryptedEnvelope(AccountEnvelopePurpose.BARE_LOGIN_RESPONSE)))) + .isInstanceOf(AccountConnectTokenIssuanceRepository.EvidenceMismatchException.class); + + Optional + stillPending = + inTransaction(context.transaction(), () -> context.repository().find(identity, digest)); + assertThat(stillPending).isPresent(); + assertThat(stillPending.orElseThrow().lifecycle()).isEqualTo(Lifecycle.PENDING); + assertThat( + inTransaction( + context.transaction(), + () -> context.repository().readResponseEnvelope(identity, digest, binding))) + .isEmpty(); + } + + private TestContext newTestContext() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?"; + dataSource.setUrl(postgres.getJdbcUrl() + separator + "currentSchema=" + SCHEMA); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .schemas(SCHEMA) + .defaultSchema(SCHEMA) + .placeholders(Map.of("serviceSchema", SCHEMA)) + .locations("classpath:db/migration") + .load() + .migrate(); + + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new TestContext( + dsl, + new AccountConnectTokenIssuanceRepository(dsl), + new TransactionTemplate(new DataSourceTransactionManager(dataSource))); + } + + private long insertAccount(DSLContext dsl) { + String unique = UUID.randomUUID().toString().replace("-", ""); + Long accountId = + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + "connect_" + unique.substring(0, 12), + unique + "@example.test", + "test-hash") + .fetchOne(0, Long.class); + if (accountId == null) { + throw new IllegalStateException("Connect-token repository test account was not inserted"); + } + return accountId; + } + + private AccountConnectTokenIssuanceIdentity newIdentity(long accountId) { + return new AccountConnectTokenIssuanceIdentity( + accountId, + 77L, + "opaque-connect-scope-" + UUID.randomUUID(), + "request-" + UUID.randomUUID()); + } + + private AccountEnvelopeBinding binding( + UUID operationId, AccountConnectTokenIssuanceIdentity identity, byte[] requestDigest) { + return new AccountEnvelopeBinding( + AccountEnvelopeBinding.OperationKind.CONNECT_TOKEN_ISSUANCE, + operationId.toString(), + identity.requestId(), + Long.toString(identity.accountId()), + Long.toString(identity.tenantId()), + identity.connectScopeId(), + null, + requestDigest, + digest(31), + digest(32), + digest(33), + digest(34)); + } + + private AccountEncryptedEnvelope encryptedEnvelope(AccountEnvelopePurpose purpose) { + return new AccountEncryptedEnvelope( + AccountEncryptedEnvelope.CURRENT_FORMAT_VERSION, + "key_1", + purpose, + new byte[AccountEncryptedEnvelope.NONCE_LENGTH_BYTES], + new byte[AccountEncryptedEnvelope.AUTHENTICATION_TAG_LENGTH_BYTES]); + } + + private byte[] digest(int seed) { + byte[] value = new byte[32]; + for (int index = 0; index < value.length; index++) { + value[index] = (byte) (seed + index); + } + return value; + } + + private T inTransaction(TransactionTemplate transaction, Supplier operation) { + return transaction.execute(status -> operation.get()); + } + + private record TestContext( + DSLContext dsl, + AccountConnectTokenIssuanceRepository repository, + TransactionTemplate transaction) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepositoryIntegrationTest.java new file mode 100644 index 0000000000..5e1f247fed --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepositoryIntegrationTest.java @@ -0,0 +1,429 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairTransition; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.ProvenPositiveCheckpoint; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class AccountMembershipPairAuthorityRepositoryIntegrationTest { + private static final String SCHEMA = "account_membership_pair_authority_proof"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void immutableValueTypesRejectContradictoryAuthorityEvidence() { + VerifiedTenantProvenance provenance = provenance(701L, TenantProvenanceKind.FRESH_GAME_DESIGN); + UUID accountUuid = UUID.randomUUID(); + UUID tenantUuid = UUID.randomUUID(); + + PairAuthority baseline = + new PairAuthority( + accountUuid, tenantUuid, provenance, false, 1L, 1L, 0L, null, null, false); + assertThat(baseline) + .isEqualTo( + new PairAuthority( + accountUuid, tenantUuid, provenance, false, 1L, 1L, 0L, null, null, false)); + + assertThatThrownBy( + () -> + new PairAuthority( + accountUuid, tenantUuid, provenance, true, 1L, 1L, 0L, null, null, false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Sequence-zero"); + assertThatThrownBy( + () -> + new PairAuthority( + accountUuid, tenantUuid, provenance, true, 1L, 1L, 1L, null, digest(1), false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("event evidence"); + assertThatThrownBy( + () -> + new VerifiedTenantProvenance( + 701L, + TenantProvenanceKind.FRESH_GAME_DESIGN, + UUID.randomUUID(), + "SHA256:" + "a".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical lowercase SHA-256"); + assertThatThrownBy(() -> new ProvenPositiveCheckpoint(1L, 1L, 0L, "event", digest(1), false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("incomplete"); + } + + @Test + void enrollmentAndTransitionsPreserveExactPositiveAuthorityAndProvenance() { + TestContext context = newTestContext(); + UUID accountUuid = insertAccount(context.setupDsl()); + UUID tenantUuid = UUID.randomUUID(); + VerifiedTenantProvenance fresh = provenance(702L, TenantProvenanceKind.FRESH_GAME_DESIGN); + + PairAuthority baseline = + inTransaction( + context.transaction(), + () -> context.repository().enrollAbsence(accountUuid, tenantUuid, fresh)); + assertThat(baseline.membershipExists()).isFalse(); + assertThat(baseline.membershipVersion()).isEqualTo(1L); + assertThat(baseline.membershipAuthorityGeneration()).isEqualTo(1L); + assertThat(baseline.lastEventSequence()).isZero(); + assertThat(baseline.lastEventId()).isNull(); + assertThat(baseline.lastEventDigest()).isNull(); + + assertThat( + inTransaction( + context.transaction(), + () -> context.repository().enrollAbsence(accountUuid, tenantUuid, fresh))) + .isEqualTo(baseline); + assertThat( + inTransaction( + context.transaction(), + () -> context.repository().readForUpdate(accountUuid, tenantUuid))) + .contains(baseline); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .repository() + .commitTransition( + new PairAuthority( + accountUuid, + tenantUuid, + fresh, + false, + 2L, + 1L, + 0L, + null, + null, + false), + new PairTransition( + true, 1L, "join-event-stale-version", digest(2), false)))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Stale or contradictory"); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .repository() + .commitTransition( + baseline, + new PairTransition( + true, 2L, "join-event-wrong-sequence", digest(2), false)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("advance by exactly one"); + + PairAuthority firstJoin = + inTransaction( + context.transaction(), + () -> + context + .repository() + .commitTransition( + baseline, new PairTransition(true, 1L, "join-event-1", digest(2), false))); + assertThat(firstJoin.membershipVersion()).isEqualTo(2L); + assertThat(firstJoin.membershipAuthorityGeneration()).isEqualTo(1L); + assertThat(firstJoin.lastEventSequence()).isEqualTo(1L); + assertThat(firstJoin.lastTransitionInvalidated()).isFalse(); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> context.repository().enrollAbsence(accountUuid, tenantUuid, fresh))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact absence state"); + assertThat( + inTransaction( + context.transaction(), + () -> context.repository().readForUpdate(accountUuid, tenantUuid))) + .contains(firstJoin); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .repository() + .commitTransition( + baseline, + new PairTransition(true, 1L, "join-event-1", digest(2), false)))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Stale or contradictory"); + + PairAuthority secondTransition = + inTransaction( + context.transaction(), + () -> + context + .repository() + .commitTransition( + firstJoin, + new PairTransition(false, 2L, "leave-event-2", digest(3), true))); + assertThat(secondTransition.membershipVersion()).isEqualTo(3L); + assertThat(secondTransition.membershipAuthorityGeneration()).isEqualTo(2L); + assertThat(secondTransition.lastEventSequence()).isEqualTo(2L); + assertThat(secondTransition.lastTransitionInvalidated()).isTrue(); + + VerifiedTenantProvenance wrongProvenance = + new VerifiedTenantProvenance( + 702L, TenantProvenanceKind.FRESH_GAME_DESIGN, UUID.randomUUID(), digest(4)); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .repository() + .enrollAbsence(accountUuid, tenantUuid, wrongProvenance))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts with verified association provenance"); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .repository() + .enrollAbsence( + accountUuid, + UUID.randomUUID(), + provenance(702L, TenantProvenanceKind.FRESH_GAME_DESIGN)))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts with an existing pair authority"); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .repository() + .commitTransition( + new PairAuthority( + firstJoin.accountUuid(), + firstJoin.tenantUuid(), + firstJoin.provenance(), + firstJoin.membershipExists(), + firstJoin.membershipVersion(), + firstJoin.membershipAuthorityGeneration() + 1L, + firstJoin.lastEventSequence(), + firstJoin.lastEventId(), + firstJoin.lastEventDigest(), + firstJoin.lastTransitionInvalidated()), + new PairTransition(false, 2L, "leave-event-2", digest(3), true)))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Stale or contradictory"); + + assertThatThrownBy( + () -> + context + .setupDsl() + .execute( + "UPDATE account_membership_pair_authority SET tenant_provenance_digest = ? " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + digest(5), + accountUuid, + tenantUuid)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + context + .setupDsl() + .execute( + "DELETE FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + accountUuid, + tenantUuid)) + .isInstanceOf(DataAccessException.class); + assertThat( + inTransaction( + context.transaction(), + () -> context.repository().readForUpdate(accountUuid, tenantUuid))) + .contains(secondTransition); + } + + @Test + void positiveRetainedEnrollmentUsesSuppliedCountersAndRejectsSeqZeroOrChangedEvidence() { + TestContext context = newTestContext(); + UUID accountUuid = insertAccount(context.setupDsl()); + UUID tenantUuid = UUID.randomUUID(); + VerifiedTenantProvenance retained = provenance(703L, TenantProvenanceKind.APPROVED_RETAINED); + ProvenPositiveCheckpoint checkpoint = + new ProvenPositiveCheckpoint(8L, 3L, 11L, "retained-event-11", digest(6), true); + + PairAuthority enrolled = + inTransaction( + context.transaction(), + () -> + context + .repository() + .enrollProvenPositive(accountUuid, tenantUuid, retained, checkpoint)); + assertThat(enrolled.membershipExists()).isTrue(); + assertThat(enrolled.membershipVersion()).isEqualTo(8L); + assertThat(enrolled.membershipAuthorityGeneration()).isEqualTo(3L); + assertThat(enrolled.lastEventSequence()).isEqualTo(11L); + assertThat(enrolled.lastTransitionInvalidated()).isTrue(); + assertThat( + inTransaction( + context.transaction(), + () -> + context + .repository() + .enrollProvenPositive(accountUuid, tenantUuid, retained, checkpoint))) + .isEqualTo(enrolled); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> context.repository().enrollAbsence(accountUuid, tenantUuid, retained))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact absence state"); + assertThat( + inTransaction( + context.transaction(), + () -> context.repository().readForUpdate(accountUuid, tenantUuid))) + .contains(enrolled); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .repository() + .enrollProvenPositive( + accountUuid, + tenantUuid, + retained, + new ProvenPositiveCheckpoint( + 8L, 3L, 11L, "different-event", digest(6), true)))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("differs from verified positive current evidence"); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .repository() + .enrollProvenPositive( + accountUuid, + tenantUuid, + provenance(703L, TenantProvenanceKind.FRESH_GAME_DESIGN), + checkpoint))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("approved retained tenant provenance"); + } + + @Test + void databaseRejectsPositiveSequenceWithoutEventDigest() { + TestContext context = newTestContext(); + UUID accountUuid = insertAccount(context.setupDsl()); + UUID tenantUuid = UUID.randomUUID(); + VerifiedTenantProvenance retained = provenance(704L, TenantProvenanceKind.APPROVED_RETAINED); + + assertThatThrownBy( + () -> + context + .setupDsl() + .execute( + "INSERT INTO account_membership_pair_authority " + + "(account_uuid, tenant_uuid, legacy_tenant_id, " + + "tenant_provenance_kind, tenant_source_operation_id, " + + "tenant_provenance_digest, membership_exists, membership_version, " + + "membership_authority_generation, last_event_sequence, " + + "last_event_id, last_event_digest, last_transition_invalidated) " + + "VALUES (?, ?, ?, ?, ?, ?, TRUE, 2, 1, 1, 'event-1', NULL, FALSE)", + accountUuid, + tenantUuid, + retained.legacyTenantId(), + retained.kind().name(), + retained.sourceOperationId(), + retained.digest())) + .isInstanceOf(DataAccessException.class); + assertThat( + inTransaction( + context.transaction(), + () -> context.repository().readForUpdate(accountUuid, tenantUuid))) + .isEmpty(); + } + + private TestContext newTestContext() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?"; + dataSource.setUrl(postgres.getJdbcUrl() + separator + "currentSchema=" + SCHEMA); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .schemas(SCHEMA) + .defaultSchema(SCHEMA) + .placeholders(Map.of("serviceSchema", SCHEMA)) + .locations("classpath:db/migration") + .load() + .migrate(); + + DSLContext setupDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + DSLContext transactionDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new TestContext( + setupDsl, + new AccountMembershipPairAuthorityRepository(transactionDsl), + new TransactionTemplate(new DataSourceTransactionManager(dataSource))); + } + + private UUID insertAccount(DSLContext dsl) { + String unique = UUID.randomUUID().toString().replace("-", ""); + return dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) " + + "RETURNING account_uuid", + "pair_" + unique.substring(0, 12), + unique + "@example.test", + "test-hash") + .fetchOne(0, UUID.class); + } + + private VerifiedTenantProvenance provenance(long legacyTenantId, TenantProvenanceKind kind) { + return new VerifiedTenantProvenance(legacyTenantId, kind, UUID.randomUUID(), digest(1)); + } + + private String digest(int digit) { + return "sha256:" + Integer.toString(digit).repeat(64); + } + + private T inTransaction( + TransactionTemplate transaction, java.util.function.Supplier operation) { + return transaction.execute(status -> operation.get()); + } + + private record TestContext( + DSLContext setupDsl, + AccountMembershipPairAuthorityRepository repository, + TransactionTemplate transaction) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/LegacyTenantAssociationImportIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/LegacyTenantAssociationImportIntegrationTest.java index 9dc8228ba4..7cb151c2d2 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/LegacyTenantAssociationImportIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/LegacyTenantAssociationImportIntegrationTest.java @@ -7,6 +7,10 @@ import java.util.Map; import java.util.Objects; import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; import net.firedevops.firemud.accountservice.repository.LegacyTenantSourceEvidence; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; @@ -16,7 +20,11 @@ import org.jooq.exception.DataAccessException; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; @@ -25,8 +33,13 @@ class LegacyTenantAssociationImportIntegrationTest { private static final String SCHEMA = "account_tenant_association_proof"; private static final long LEGACY_TENANT_ID = 41L; + private static final long ROLLBACK_LEGACY_TENANT_ID = 43L; private static final UUID CANONICAL_TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID CONFLICTING_TENANT_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID ROLLBACK_TENANT_ID = + UUID.fromString("55555555-5555-4555-8555-555555555555"); @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @@ -48,22 +61,8 @@ void exactRetainedSourceAndApprovedOwnerReadAreRequiredForImmutableImport() { .load() .migrate(); DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); - long accountId = - Objects.requireNonNull( - (Number) - dsl.fetchValue( - "INSERT INTO accounts (username, email, password_hash, tenant_id) " - + "VALUES ('retained-tenant', 'retained@example.test', 'hash', ?) " - + "RETURNING id", - LEGACY_TENANT_ID)) - .longValue(); - dsl.execute( - "INSERT INTO account_tenant_membership " - + "(account_id, tenant_id, gameplay_admission_allowed) VALUES (?, ?, TRUE)", - accountId, - LEGACY_TENANT_ID); - dsl.execute( - "INSERT INTO profiles (account_id, tenant_id) VALUES (?, ?)", accountId, LEGACY_TENANT_ID); + long accountId = insertRetainedRows(dsl, LEGACY_TENANT_ID, "retained-tenant"); + insertRetainedRows(dsl, ROLLBACK_LEGACY_TENANT_ID, "retained-tenant-rollback"); Flyway.configure() .dataSource(dataSource) .schemas(SCHEMA) @@ -73,27 +72,94 @@ void exactRetainedSourceAndApprovedOwnerReadAreRequiredForImmutableImport() { .load() .migrate(); - LegacyTenantSourceEvidence sources = new LegacyTenantSourceEvidence(dsl); + DSLContext transactionDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + LegacyTenantSourceEvidence sources = new LegacyTenantSourceEvidence(transactionDsl); + AccountAuthorityGenerationRepository generations = + new AccountAuthorityGenerationRepository(transactionDsl); ApprovedLegacyTenantAssociationRepository repository = - new ApprovedLegacyTenantAssociationRepository(dsl, sources, SCHEMA); + new ApprovedLegacyTenantAssociationRepository(transactionDsl, sources, SCHEMA, generations); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); String exactDigest = sources.digest(LEGACY_TENANT_ID); ResolveLegacyAccountTenantAssociationResponse approved = ownerRead(exactDigest); - assertThatThrownBy(() -> repository.importApproved(42L, approved)) + assertThatThrownBy( + () -> inTransaction(transaction, () -> repository.importApproved(42L, approved))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("mismatched"); assertThatThrownBy( () -> - repository.importApproved(LEGACY_TENANT_ID, ownerRead("sha256:" + "f".repeat(64)))) + inTransaction( + transaction, + () -> + repository.importApproved( + LEGACY_TENANT_ID, ownerRead("sha256:" + "f".repeat(64))))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("differs"); assertThat(repository.findByLegacyTenantId(LEGACY_TENANT_ID)).isEmpty(); + assertTenantGenerationAbsent(dsl, CANONICAL_TENANT_ID); - var first = repository.importApproved(LEGACY_TENANT_ID, approved); + var first = + inTransaction(transaction, () -> repository.importApproved(LEGACY_TENANT_ID, approved)); assertThat(first.canonicalTenantId()).isEqualTo(CANONICAL_TENANT_ID); assertThat(first.accountEvidenceDigest()).isEqualTo(exactDigest); - assertThat(repository.importApproved(LEGACY_TENANT_ID, approved)).isEqualTo(first); + ScopeState initialGeneration = + inTransaction( + transaction, () -> generations.read(AuthorityScope.tenant(CANONICAL_TENANT_ID))); + assertThat(initialGeneration.generation()).isEqualTo(1L); + assertThat(initialGeneration.sourceVersion()).isEqualTo(1L); + assertThat( + dsl.resultQuery( + "SELECT count(*) FROM account_authority_generations " + + "WHERE scope_kind = 'MEMBERSHIP'") + .fetchOne(0, Long.class)) + .isZero(); + assertThat( + inTransaction(transaction, () -> repository.importApproved(LEGACY_TENANT_ID, approved))) + .isEqualTo(first); assertThat(repository.findByLegacyTenantId(LEGACY_TENANT_ID)).contains(first); + + ScopeState advancedGeneration = + inTransaction(transaction, () -> generations.advance(initialGeneration, null)); + assertThat(advancedGeneration.generation()).isEqualTo(2L); + assertThat(advancedGeneration.sourceVersion()).isEqualTo(2L); + assertThat( + inTransaction(transaction, () -> repository.importApproved(LEGACY_TENANT_ID, approved))) + .isEqualTo(first); + assertThat( + inTransaction( + transaction, () -> generations.read(AuthorityScope.tenant(CANONICAL_TENANT_ID)))) + .isEqualTo(advancedGeneration); + + ResolveLegacyAccountTenantAssociationResponse conflictingOwnerRead = + approved.toBuilder().setCanonicalTenantId(CONFLICTING_TENANT_ID.toString()).build(); + assertThatThrownBy( + () -> + inTransaction( + transaction, + () -> repository.importApproved(LEGACY_TENANT_ID, conflictingOwnerRead))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts"); + assertTenantGenerationAbsent(dsl, CONFLICTING_TENANT_ID); + + assertThatThrownBy( + () -> + inTransaction( + transaction, + () -> + repository.importApproved( + 42L, + ownerRead(42L, CONFLICTING_TENANT_ID, "sha256:" + "a".repeat(64))))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("source is absent"); + assertThat(repository.findByLegacyTenantId(42L)).isEmpty(); + assertTenantGenerationAbsent(dsl, CONFLICTING_TENANT_ID); + + proveImportAndGenerationRollback( + dsl, transaction, repository, sources, ROLLBACK_LEGACY_TENANT_ID); + assertThatThrownBy( () -> dsl.execute( @@ -108,16 +174,28 @@ void exactRetainedSourceAndApprovedOwnerReadAreRequiredForImmutableImport() { "UPDATE account_legacy_tenant_sources SET disposition = 'CONFLICT' " + "WHERE account_id = ?", accountId); - assertThatThrownBy(() -> repository.importApproved(LEGACY_TENANT_ID, approved)) + assertThatThrownBy( + () -> + inTransaction( + transaction, () -> repository.importApproved(LEGACY_TENANT_ID, approved))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("conflicting"); assertThat(repository.findByLegacyTenantId(LEGACY_TENANT_ID)).contains(first); + assertThat( + inTransaction( + transaction, () -> generations.read(AuthorityScope.tenant(CANONICAL_TENANT_ID)))) + .isEqualTo(advancedGeneration); } private ResolveLegacyAccountTenantAssociationResponse ownerRead(String accountEvidenceDigest) { + return ownerRead(LEGACY_TENANT_ID, CANONICAL_TENANT_ID, accountEvidenceDigest); + } + + private ResolveLegacyAccountTenantAssociationResponse ownerRead( + long legacyTenantId, UUID canonicalTenantId, String accountEvidenceDigest) { return ResolveLegacyAccountTenantAssociationResponse.newBuilder() - .setLegacyAccountTenantId(LEGACY_TENANT_ID) - .setCanonicalTenantId(CANONICAL_TENANT_ID.toString()) + .setLegacyAccountTenantId(legacyTenantId) + .setCanonicalTenantId(canonicalTenantId.toString()) .setSourceLegacyGameTenantId("legacy-game-7") .setSourceGameRowId(7L) .setAccountEvidenceDigest(accountEvidenceDigest) @@ -133,4 +211,79 @@ private ResolveLegacyAccountTenantAssociationResponse ownerRead(String accountEv .setManifestSchemaVersion(1) .build(); } + + private long insertRetainedRows(DSLContext dsl, long tenantId, String username) { + long accountId = + Objects.requireNonNull( + (Number) + dsl.fetchValue( + "INSERT INTO accounts (username, email, password_hash, tenant_id) " + + "VALUES (?, ?, 'hash', ?) RETURNING id", + username, + username + "@example.test", + tenantId)) + .longValue(); + dsl.execute( + "INSERT INTO account_tenant_membership " + + "(account_id, tenant_id, gameplay_admission_allowed) VALUES (?, ?, TRUE)", + accountId, + tenantId); + dsl.execute("INSERT INTO profiles (account_id, tenant_id) VALUES (?, ?)", accountId, tenantId); + return accountId; + } + + private void assertTenantGenerationAbsent(DSLContext dsl, UUID tenantId) { + assertThat( + dsl.resultQuery( + "SELECT count(*) FROM account_authority_generations " + + "WHERE scope_kind = 'TENANT' AND tenant_uuid = ?", + tenantId) + .fetchOne(0, Long.class)) + .isZero(); + } + + private void proveImportAndGenerationRollback( + DSLContext dsl, + TransactionTemplate transaction, + ApprovedLegacyTenantAssociationRepository repository, + LegacyTenantSourceEvidence sources, + long legacyTenantId) { + String evidenceDigest = sources.digest(legacyTenantId); + dsl.execute( + "CREATE FUNCTION reject_test_tenant_generation() RETURNS trigger LANGUAGE plpgsql AS $$ " + + "BEGIN IF NEW.scope_kind = 'TENANT' AND NEW.tenant_uuid = '" + + ROLLBACK_TENANT_ID + + "'::uuid THEN RAISE EXCEPTION 'forced tenant generation failure'; END IF; " + + "RETURN NEW; END; $$"); + dsl.execute( + "CREATE TRIGGER reject_test_tenant_generation BEFORE INSERT " + + "ON account_authority_generations FOR EACH ROW " + + "EXECUTE FUNCTION reject_test_tenant_generation()"); + try { + assertThatThrownBy( + () -> + inTransaction( + transaction, + () -> + repository.importApproved( + legacyTenantId, + ownerRead(legacyTenantId, ROLLBACK_TENANT_ID, evidenceDigest) + .toBuilder() + .setSourceLegacyGameTenantId("legacy-game-9") + .setSourceGameRowId(9L) + .setOperationId("99999999-9999-4999-8999-999999999999") + .build()))) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("forced tenant generation failure"); + assertThat(repository.findByLegacyTenantId(legacyTenantId)).isEmpty(); + assertTenantGenerationAbsent(dsl, ROLLBACK_TENANT_ID); + } finally { + dsl.execute("DROP TRIGGER reject_test_tenant_generation ON account_authority_generations"); + dsl.execute("DROP FUNCTION reject_test_tenant_generation()"); + } + } + + private T inTransaction(TransactionTemplate transaction, Supplier operation) { + return transaction.execute(status -> operation.get()); + } } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/RetainedAccountAuthorityEnrollmentIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/RetainedAccountAuthorityEnrollmentIntegrationTest.java new file mode 100644 index 0000000000..291cf9ac4c --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/RetainedAccountAuthorityEnrollmentIntegrationTest.java @@ -0,0 +1,261 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.FlywayException; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class RetainedAccountAuthorityEnrollmentIntegrationTest { + private static final String MIGRATION_LOCATION = "classpath:db/migration"; + private static final String ACCOUNT_SCOPE = "ACCOUNT"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void enrollsRetainedExactAccountUuidPairWithoutInventingTenantOrMembershipScopes() { + TestDatabase database = createDatabaseAtVersion28(); + long retainedNumericId = + insertRetainedAccount(database.dsl(), "retained-account-enrollment", 73L); + migrateToVersion33(database); + + UUID accountUuid = accountUuid(database.dsl(), retainedNumericId); + migrateToLatest(database); + + assertThat( + fetchString( + database.dsl(), + "SELECT account_uuid_provenance FROM accounts WHERE id = ?", + retainedNumericId)) + .isEqualTo("ACCOUNT_V29_MIGRATION"); + assertThat( + fetchLong( + database.dsl(), + "SELECT account_uuid_source_numeric_id FROM accounts WHERE id = ?", + retainedNumericId)) + .isEqualTo(retainedNumericId); + assertThat(accountGenerationCount(database.dsl(), accountUuid)).isEqualTo(1L); + assertThat( + fetchLong( + database.dsl(), + "SELECT generation FROM account_authority_generations " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + accountUuid)) + .isEqualTo(1L); + assertThat( + fetchLong( + database.dsl(), + "SELECT source_version FROM account_authority_generations " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + accountUuid)) + .isEqualTo(1L); + assertThat( + fetchLong( + database.dsl(), + "SELECT issuance_fence FROM account_authority_issuance_fences WHERE account_uuid = ?", + accountUuid)) + .isEqualTo(1L); + assertThat( + fetchLong( + database.dsl(), + "SELECT source_version FROM account_authority_issuance_fences WHERE account_uuid = ?", + accountUuid)) + .isEqualTo(1L); + assertThat(tenantOrMembershipGenerationCount(database.dsl())).isZero(); + assertThat( + fetchLong( + database.dsl(), + "SELECT count(*) FROM account_tenant_membership WHERE account_id = ?", + retainedNumericId)) + .isZero(); + } + + @Test + void preservesBothExistingAdvancedAccountAuthorityRows() { + TestDatabase database = createDatabaseAtVersion28(); + long retainedNumericId = + insertRetainedAccount(database.dsl(), "advanced-retained-account", 91L); + migrateToVersion33(database); + UUID accountUuid = accountUuid(database.dsl(), retainedNumericId); + database + .dsl() + .execute( + "INSERT INTO account_authority_generations " + + "(scope_kind, account_uuid, generation, source_version) " + + "VALUES ('ACCOUNT', ?, 7, 13)", + accountUuid); + database + .dsl() + .execute( + "INSERT INTO account_authority_issuance_fences " + + "(account_uuid, issuance_fence, source_version) VALUES (?, 17, 29)", + accountUuid); + + migrateToLatest(database); + + assertThat( + fetchLong( + database.dsl(), + "SELECT generation FROM account_authority_generations " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + accountUuid)) + .isEqualTo(7L); + assertThat( + fetchLong( + database.dsl(), + "SELECT source_version FROM account_authority_generations " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + accountUuid)) + .isEqualTo(13L); + assertThat( + fetchLong( + database.dsl(), + "SELECT issuance_fence FROM account_authority_issuance_fences WHERE account_uuid = ?", + accountUuid)) + .isEqualTo(17L); + assertThat( + fetchLong( + database.dsl(), + "SELECT source_version FROM account_authority_issuance_fences WHERE account_uuid = ?", + accountUuid)) + .isEqualTo(29L); + } + + @Test + void failsClosedOnEitherHalfPairWithoutPartiallyEnrollingOtherRetainedAccounts() { + TestDatabase database = createDatabaseAtVersion28(); + long generationOnlyNumericId = + insertRetainedAccount(database.dsl(), "generation-only-account", 101L); + long fenceOnlyNumericId = insertRetainedAccount(database.dsl(), "fence-only-account", 102L); + long unenrolledNumericId = + insertRetainedAccount(database.dsl(), "unenrolled-retained-account", 103L); + migrateToVersion33(database); + + UUID generationOnlyUuid = accountUuid(database.dsl(), generationOnlyNumericId); + UUID fenceOnlyUuid = accountUuid(database.dsl(), fenceOnlyNumericId); + UUID unenrolledUuid = accountUuid(database.dsl(), unenrolledNumericId); + database + .dsl() + .execute( + "INSERT INTO account_authority_generations " + + "(scope_kind, account_uuid, generation, source_version) " + + "VALUES ('ACCOUNT', ?, 3, 5)", + generationOnlyUuid); + database + .dsl() + .execute( + "INSERT INTO account_authority_issuance_fences " + + "(account_uuid, issuance_fence, source_version) VALUES (?, 4, 8)", + fenceOnlyUuid); + + assertThatThrownBy(() -> migrateToLatest(database)) + .isInstanceOf(FlywayException.class) + .hasStackTraceContaining("has incomplete authority generation and issuance-fence state"); + + assertThat(accountGenerationCount(database.dsl(), generationOnlyUuid)).isEqualTo(1L); + assertThat(issuanceFenceCount(database.dsl(), generationOnlyUuid)).isZero(); + assertThat(accountGenerationCount(database.dsl(), fenceOnlyUuid)).isZero(); + assertThat(issuanceFenceCount(database.dsl(), fenceOnlyUuid)).isEqualTo(1L); + assertThat(accountGenerationCount(database.dsl(), unenrolledUuid)).isZero(); + assertThat(issuanceFenceCount(database.dsl(), unenrolledUuid)).isZero(); + } + + private TestDatabase createDatabaseAtVersion28() { + String schema = "retained_account_enrollment_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?"; + dataSource.setUrl(postgres.getJdbcUrl() + separator + "currentSchema=" + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + TestDatabase database = + new TestDatabase(schema, dataSource, DSL.using(dataSource, SQLDialect.POSTGRES)); + flyway(database, "28").migrate(); + return database; + } + + private void migrateToVersion33(TestDatabase database) { + flyway(database, "33").migrate(); + } + + private void migrateToLatest(TestDatabase database) { + flyway(database, null).migrate(); + } + + private Flyway flyway(TestDatabase database, String target) { + var configuration = + Flyway.configure() + .dataSource(database.dataSource()) + .schemas(database.schema()) + .defaultSchema(database.schema()) + .placeholders(Map.of("serviceSchema", database.schema())) + .locations(MIGRATION_LOCATION); + if (target != null) { + configuration.target(target); + } + return configuration.load(); + } + + private long insertRetainedAccount(DSLContext dsl, String username, long legacyTenantId) { + return Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash, tenant_id) " + + "VALUES (?, ?, ?, ?) RETURNING id", + username, + username + "@example.test", + "hash", + legacyTenantId) + .fetchOne(0, Long.class)); + } + + private UUID accountUuid(DSLContext dsl, long numericId) { + return Objects.requireNonNull( + dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", numericId) + .fetchOne(0, UUID.class)); + } + + private long accountGenerationCount(DSLContext dsl, UUID accountUuid) { + return fetchLong( + dsl, + "SELECT count(*) FROM account_authority_generations " + + "WHERE scope_kind = ? AND account_uuid = ?", + ACCOUNT_SCOPE, + accountUuid); + } + + private long issuanceFenceCount(DSLContext dsl, UUID accountUuid) { + return fetchLong( + dsl, + "SELECT count(*) FROM account_authority_issuance_fences WHERE account_uuid = ?", + accountUuid); + } + + private long tenantOrMembershipGenerationCount(DSLContext dsl) { + return fetchLong( + dsl, + "SELECT count(*) FROM account_authority_generations " + + "WHERE scope_kind IN ('TENANT', 'MEMBERSHIP')"); + } + + private long fetchLong(DSLContext dsl, String query, Object... bindings) { + return Objects.requireNonNull(dsl.resultQuery(query, bindings).fetchOne(0, Long.class)); + } + + private String fetchString(DSLContext dsl, String query, Object... bindings) { + return dsl.resultQuery(query, bindings).fetchOne(0, String.class); + } + + private record TestDatabase(String schema, DriverManagerDataSource dataSource, DSLContext dsl) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authority/MembershipAuthorityEventVectorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authority/MembershipAuthorityEventVectorTest.java new file mode 100644 index 0000000000..762c43ba76 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authority/MembershipAuthorityEventVectorTest.java @@ -0,0 +1,239 @@ +package net.firedevops.firemud.accountservice.authority; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.io.InputStream; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import org.junit.jupiter.api.Test; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.node.ArrayNode; +import tools.jackson.databind.node.ObjectNode; + +class MembershipAuthorityEventVectorTest { + private static final String VECTOR_RESOURCE = + "/net/firedevops/firemud/common/account/authority/account-auth-authority-event-v1-vectors.json"; + private static final BigInteger MAX_SAFE_INTEGER = new BigInteger("9007199254740991"); + private static final ObjectMapper JSON = new ObjectMapper(); + + @Test + void sealsEverySharedPreimageToItsExpectedDigest() throws IOException { + JsonNode vectors = readVectors(); + + for (JsonNode vector : vectors.path("validEvents")) { + Map preimage = toMap(vector.path("event")); + String expectedDigest = (String) preimage.remove("eventDigest"); + + var sealed = MembershipAuthorityEventV1Codec.seal(preimage); + + assertEquals(expectedDigest, sealed.eventDigest(), vector.path("name").asText()); + assertEquals( + expectedDigest, + MembershipAuthorityEventV1Codec.verify(toMap(JSON.readTree(sealed.canonicalJson()))) + .eventDigest()); + assertEquals(JSON.readTree(sealed.canonicalJson()), vector.path("event")); + } + } + + @Test + void preservesLargeCountersAsCanonicalDecimalStrings() throws IOException { + JsonNode vectors = readVectors(); + List largeCounters = new ArrayList<>(); + + for (JsonNode vector : vectors.path("validEvents")) { + JsonNode event = vector.path("event"); + collectCounterEvidence(toMap(event), "event", largeCounters); + Map preimage = toMap(event); + String expectedDigest = (String) preimage.remove("eventDigest"); + var sealed = MembershipAuthorityEventV1Codec.seal(preimage); + + assertEquals(expectedDigest, sealed.eventDigest()); + } + + assertFalse(largeCounters.isEmpty(), "shared vectors must include a counter above 2^53"); + assertTrue(largeCounters.stream().anyMatch(value -> value.compareTo(MAX_SAFE_INTEGER) > 0)); + } + + @Test + void membershipVersionVectorsUseTheExactOneTenantMap() throws IOException { + JsonNode vectors = readVectors(); + + for (JsonNode vector : vectors.path("validEvents")) { + JsonNode event = vector.path("event"); + String tenantId = event.path("tenantId").asText(); + JsonNode versions = event.path("membershipVersion"); + + assertTrue(versions.isObject(), "membershipVersion must be an object"); + assertEquals(1, versions.size(), "membershipVersion must contain one tenant"); + assertTrue(versions.has(tenantId), "membershipVersion must use event.tenantId"); + assertTrue(versions.path(tenantId).isTextual(), "membership version must be decimal text"); + assertTrue( + versions.path(tenantId).asText().matches("[1-9][0-9]*"), + "membership version must be a positive canonical decimal"); + assertEquals( + Map.of(tenantId, versions.path(tenantId).asText()), + MembershipAuthorityEventV1Codec.verify(toMap(event)).membershipVersion()); + } + } + + @Test + void changedPreimageFieldProducesDifferentDigest() throws IOException { + JsonNode vectors = readVectors(); + JsonNode sourceEvent = vectors.path("validEvents").get(0).path("event"); + Map originalPreimage = toMap(sourceEvent); + String originalDigest = (String) originalPreimage.remove("eventDigest"); + JsonNode mutation = null; + for (JsonNode candidate : vectors.path("changedFieldMutations")) { + if (candidate.path("name").asText().equals("event-id")) { + mutation = candidate; + break; + } + } + assertTrue(mutation != null, "shared vectors must include a valid event-id mutation"); + ObjectNode changedEvent = (ObjectNode) sourceEvent.deepCopy(); + applyMutation(changedEvent, mutation, "replacement", "replace"); + Map changedPreimage = toMap(changedEvent); + changedPreimage.remove("eventDigest"); + + var sealed = MembershipAuthorityEventV1Codec.seal(changedPreimage); + + assertNotEquals(originalDigest, sealed.eventDigest()); + assertEquals( + sealed.eventDigest(), + MembershipAuthorityEventV1Codec.verify(toMap(JSON.readTree(sealed.canonicalJson()))) + .eventDigest()); + } + + @Test + void rejectsSharedInvalidPreimagesIncludingOptionalAndArrayOrderViolations() throws IOException { + JsonNode vectors = readVectors(); + JsonNode sourceEvent = vectors.path("validEvents").get(0).path("event"); + + for (JsonNode mutation : vectors.path("invalidMutations")) { + String path = mutation.path("path").asText(); + if (path.equals("/eventDigest")) { + continue; + } + ObjectNode changedEvent = (ObjectNode) sourceEvent.deepCopy(); + applyMutation(changedEvent, mutation, "value", null); + Map preimage = toMap(changedEvent); + preimage.remove("eventDigest"); + + assertThrows( + IllegalArgumentException.class, + () -> MembershipAuthorityEventV1Codec.seal(preimage), + mutation.path("name").asText()); + } + } + + private static JsonNode readVectors() throws IOException { + try (InputStream stream = + MembershipAuthorityEventVectorTest.class.getResourceAsStream(VECTOR_RESOURCE)) { + assertTrue(stream != null, "shared authority-event vectors must be on the test classpath"); + return JSON.readTree(stream); + } + } + + private static Map toMap(JsonNode node) { + return JSON.convertValue(node, new TypeReference>() {}); + } + + private static void collectCounterEvidence( + Object value, String fieldName, List largeCounters) { + if (value instanceof Map object) { + object.forEach( + (key, child) -> + collectCounterEvidence( + child, + fieldName.equals("membershipVersion") ? fieldName : key.toString(), + largeCounters)); + return; + } + if (value instanceof List array) { + array.forEach(child -> collectCounterEvidence(child, fieldName, largeCounters)); + return; + } + if (isCounterField(fieldName)) { + assertTrue( + value instanceof String, () -> fieldName + " must be a decimal string in shared vectors"); + String text = (String) value; + assertTrue( + text.matches("0|[1-9][0-9]*"), () -> fieldName + " must be canonical decimal text"); + BigInteger numericValue = new BigInteger(text); + if (numericValue.compareTo(MAX_SAFE_INTEGER) > 0) { + largeCounters.add(numericValue); + } + } + } + + private static void applyMutation( + ObjectNode root, JsonNode mutation, String valueField, String defaultOperation) { + String[] segments = mutation.path("path").asText().substring(1).split("/"); + JsonNode parent = root; + for (int i = 0; i < segments.length - 1; i++) { + String segment = unescapePointerSegment(segments[i]); + parent = + parent instanceof ArrayNode array + ? array.get(Integer.parseInt(segment)) + : parent.path(segment); + } + String finalSegment = unescapePointerSegment(segments[segments.length - 1]); + String operation = mutation.path("op").asText(defaultOperation); + if (operation.equals("remove")) { + if (parent instanceof ObjectNode object) { + object.remove(finalSegment); + } else if (parent instanceof ArrayNode array) { + array.remove(Integer.parseInt(finalSegment)); + } else { + throw new AssertionError("mutation parent is not a JSON container"); + } + return; + } + + JsonNode value = mutation.get(valueField).deepCopy(); + if (parent instanceof ObjectNode object) { + if (operation.equals("add") || operation.equals("replace")) { + object.set(finalSegment, value); + return; + } + } else if (parent instanceof ArrayNode array) { + int index = Integer.parseInt(finalSegment); + if (operation.equals("add")) { + array.insert(index, value); + return; + } + if (operation.equals("replace")) { + array.set(index, value); + return; + } + } + throw new AssertionError("unsupported vector mutation operation: " + operation); + } + + private static String unescapePointerSegment(String segment) { + return segment.replace("~1", "/").replace("~0", "~"); + } + + private static boolean isCounterField(String fieldName) { + return fieldName.equals("outboxSequence") + || fieldName.equals("membershipVersion") + || fieldName.equals("membershipAuthorityGeneration") + || fieldName.equals("issuanceFence") + || fieldName.equals("issuerAuthGeneration") + || fieldName.equals("accountAuthorityGeneration") + || fieldName.equals("tenantAuthorityGeneration") + || fieldName.equals("grantVersion") + || fieldName.equals("tenantBillingSequence"); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/maintenance/AccountAuthorityGenerationEnrollmentRunnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/maintenance/AccountAuthorityGenerationEnrollmentRunnerTest.java new file mode 100644 index 0000000000..649accadd2 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/maintenance/AccountAuthorityGenerationEnrollmentRunnerTest.java @@ -0,0 +1,53 @@ +package unit.net.firedevops.firemud.accountservice.maintenance; + +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.when; + +import net.firedevops.firemud.accountservice.maintenance.AccountAuthorityGenerationEnrollmentRunner; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import org.junit.jupiter.api.Test; +import org.springframework.boot.ApplicationArguments; +import org.springframework.transaction.annotation.Transactional; + +class AccountAuthorityGenerationEnrollmentRunnerTest { + private final AccountAuthorityGenerationRepository authorityGenerationRepository = + mock(AccountAuthorityGenerationRepository.class); + private final AccountAuthorityGenerationEnrollmentRunner runner = + new AccountAuthorityGenerationEnrollmentRunner(authorityGenerationRepository); + + @Test + void startupEnrollsExactAccountJwtIssuerAndRequiresExactReadback() { + AuthorityScope expectedScope = AuthorityScope.issuer("firemud-account-service"); + when(authorityGenerationRepository.initializeIssuerIfAbsent(expectedScope.issuerId())) + .thenReturn(new ScopeState(expectedScope, 1L, 1L, null)); + + runner.run(mock(ApplicationArguments.class)); + + verify(authorityGenerationRepository).initializeIssuerIfAbsent("firemud-account-service"); + } + + @Test + void startupEnrollmentRunsInTransaction() throws ReflectiveOperationException { + Transactional annotation = + AccountAuthorityGenerationEnrollmentRunner.class + .getMethod("run", ApplicationArguments.class) + .getAnnotation(Transactional.class); + + assertThat(annotation).isNotNull(); + } + + @Test + void startupFailsWhenIssuerReadbackIsContradictory() { + when(authorityGenerationRepository.initializeIssuerIfAbsent("firemud-account-service")) + .thenReturn(new ScopeState(AuthorityScope.issuer("different-issuer"), 1L, 1L, null)); + + assertThatThrownBy(() -> runner.run(mock(ApplicationArguments.class))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact issuer"); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java new file mode 100644 index 0000000000..6e48159ff5 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java @@ -0,0 +1,139 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeKind; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +class AccountAuthorityGenerationRepositoryTest { + private final DSLContext dsl = mock(DSLContext.class); + private final AccountAuthorityGenerationRepository repository = + new AccountAuthorityGenerationRepository(dsl); + + @Test + void scopeIdentityPreservesExactIssuerAndUuidPairs() { + UUID accountId = UUID.fromString("11111111-1111-4111-8111-111111111111"); + UUID anotherAccountId = UUID.fromString("22222222-2222-4222-8222-222222222222"); + UUID tenantId = UUID.fromString("33333333-3333-4333-8333-333333333333"); + + assertThat(AuthorityScope.issuer("Issuer-A").issuerId()).isEqualTo("Issuer-A"); + assertThat(AuthorityScope.issuer("Issuer-A")).isNotEqualTo(AuthorityScope.issuer("issuer-a")); + assertThat(AuthorityScope.membership(accountId, tenantId)) + .isNotEqualTo(AuthorityScope.membership(anotherAccountId, tenantId)); + assertThat(AuthorityScope.membership(accountId, tenantId).kind()) + .isEqualTo(ScopeKind.MEMBERSHIP); + } + + @Test + void malformedScopesAndNonPositiveStateFailBeforeStorageAccess() { + UUID accountId = UUID.fromString("11111111-1111-4111-8111-111111111111"); + + assertThatThrownBy(() -> AuthorityScope.issuer(" ")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> AuthorityScope.account(null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new ScopeState( + AuthorityScope.account(accountId), + 0L, + 1L, + new IssuanceFence(accountId, 1L, 1L))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new IssuanceFence(accountId, 0L, 1L)) + .isInstanceOf(IllegalArgumentException.class); + + verifyNoInteractions(dsl); + } + + @Test + void storageOperationsRequireTheCallersTransaction() throws ReflectiveOperationException { + assertMandatory( + AccountAuthorityGenerationRepository.class.getMethod("initialize", AuthorityScope.class)); + assertMandatory( + AccountAuthorityGenerationRepository.class.getMethod( + "initializeIssuerIfAbsent", String.class)); + assertMandatory( + AccountAuthorityGenerationRepository.class.getMethod( + "initializeTenantIfAbsent", UUID.class)); + assertMandatory( + AccountAuthorityGenerationRepository.class.getMethod("read", AuthorityScope.class)); + assertMandatory( + AccountAuthorityGenerationRepository.class.getMethod( + "advance", ScopeState.class, IssuanceFence.class)); + assertMandatory( + AccountAuthorityGenerationRepository.class.getMethod( + "readCompositeSnapshot", + String.class, + UUID.class, + java.util.Collection.class, + java.util.Collection.class)); + } + + @Test + void mismatchedFenceAndScopeStateAreDeniedWithoutDatabaseAccess() { + UUID accountId = UUID.fromString("11111111-1111-4111-8111-111111111111"); + UUID otherAccountId = UUID.fromString("22222222-2222-4222-8222-222222222222"); + IssuanceFence fence = new IssuanceFence(accountId, 1L, 1L); + ScopeState state = new ScopeState(AuthorityScope.account(accountId), 1L, 1L, fence); + + assertThatThrownBy(() -> repository.advance(state, new IssuanceFence(otherAccountId, 1L, 1L))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> repository.advance(state, null)) + .isInstanceOf(IllegalArgumentException.class); + + verifyNoInteractions(dsl); + } + + @Test + void issuerEnrollmentRejectsBlankIssuerBeforeStorageAccess() { + assertThatThrownBy(() -> repository.initializeIssuerIfAbsent(" ")) + .isInstanceOf(IllegalArgumentException.class); + + verifyNoInteractions(dsl); + } + + @Test + void tenantEnrollmentRejectsMissingCanonicalTenantIdentityBeforeStorageAccess() { + assertThatThrownBy(() -> repository.initializeTenantIfAbsent(null)) + .isInstanceOf(IllegalArgumentException.class); + + verifyNoInteractions(dsl); + } + + @Test + void snapshotRequiresEveryExplicitScopeWithoutFillingInMissingAuthority() { + UUID accountId = UUID.fromString("11111111-1111-4111-8111-111111111111"); + + assertThatThrownBy( + () -> + repository.readCompositeSnapshot("issuer-A", accountId, null, java.util.List.of())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + repository.readCompositeSnapshot( + "issuer-A", + accountId, + java.util.List.of(), + java.util.Arrays.asList(accountId, null))) + .isInstanceOf(IllegalArgumentException.class); + + verifyNoInteractions(dsl); + } + + private void assertMandatory(java.lang.reflect.Method method) { + Transactional annotation = method.getAnnotation(Transactional.class); + assertThat(annotation).isNotNull(); + assertThat(annotation.propagation()).isEqualTo(Propagation.MANDATORY); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepositoryTest.java new file mode 100644 index 0000000000..d31f2c9c79 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepositoryTest.java @@ -0,0 +1,359 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.startsWith; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicLong; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.EventEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +class AccountAuthorityOutboxRepositoryTest { + private final DSLContext dsl = mock(DSLContext.class); + private final AccountAuthorityOutboxRepository repository = + new AccountAuthorityOutboxRepository(dsl); + + @Test + void canonicalStreamKeysKeepExactMembershipScopeIdentity() { + String membership = + "account:auth-authority:v1:membership/11111111-1111-4111-8111-111111111111/" + + "22222222-2222-4222-8222-222222222222"; + byte[] payload = {1, 2, 3}; + + Event event = new Event(membership, "request-1", 1L, "event-1", "digest-1", payload); + + assertThat(event.outboxStreamKey()).isEqualTo(membership); + assertThat(event.outboxSequence()).isEqualTo(1L); + assertThat(event.payload()).containsExactly((byte) 1, (byte) 2, (byte) 3); + assertThat(new Checkpoint(membership, 1L, "event-1", "digest-1").outboxStreamKey()) + .isEqualTo(membership); + } + + @Test + void malformedKeysAndZeroCheckpointsFailBeforeStorageAccess() { + assertThatThrownBy(() -> repository.findEvent("account:auth-authority:v1:", 1L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> repository.findEvent("account:auth-authority:v1:account/abc", 0L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> new Checkpoint("account:auth-authority:v1:account/abc", 0L, null, null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + repository.append( + "account:auth-authority:v1:account/abc", + "request-1", + "event-1", + "digest-1", + new byte[0])) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + repository.append( + "account:auth-authority:v1:account/abc", + "r".repeat(513), + "event-1", + "digest-1", + new byte[] {1})) + .isInstanceOf(IllegalArgumentException.class); + + verifyNoInteractions(dsl); + } + + @Test + void returnedPayloadIsDefensivelyCopied() { + byte[] original = {4, 5, 6}; + Event event = + new Event( + "account:auth-authority:v1:tenant/tenant-a", + "request-1", + 1L, + "event-1", + "digest-1", + original); + original[0] = 9; + + byte[] readback = event.payload(); + readback[1] = 9; + + assertThat(event.payload()).containsExactly((byte) 4, (byte) 5, (byte) 6); + } + + @Test + void sequenceBoundFactoryReceivesAllocatedSequenceAndStoresCompletePayloadEvidence() { + String streamKey = "account:auth-authority:v1:membership/account-a/tenant-a"; + stubAppend(8L, null); + byte[] wirePayload = "{\"eventDigest\":\"sha256:wire-digest\"}".getBytes(); + AtomicLong producedSequence = new AtomicLong(); + + Event event = + repository.append( + streamKey, + "request-9", + sequence -> { + producedSequence.set(sequence); + return new EventEvidence("event-9", "sha256:wire-digest", wirePayload); + }); + + assertThat(producedSequence).hasValue(9L); + assertThat(event.outboxSequence()).isEqualTo(9L); + assertThat(event.eventId()).isEqualTo("event-9"); + assertThat(event.eventDigest()).isEqualTo("sha256:wire-digest"); + assertThat(event.payload()).containsExactly(wirePayload); + verify(dsl) + .execute(startsWith("INSERT INTO account_authority_outbox_events"), any(Object[].class)); + } + + @Test + void exactRetryFactoryReceivesCommittedSequenceAndReturnsStoredEvidence() { + String streamKey = "account:auth-authority:v1:membership/account-a/tenant-a"; + stubAppend( + 7L, + eventRecord( + 4L, + "event-4", + "sha256:wire-digest-4", + "{\"eventDigest\":\"sha256:wire-digest-4\"}".getBytes(), + "request-4")); + AtomicLong producedSequence = new AtomicLong(); + + Event event = + repository.append( + streamKey, + "request-4", + sequence -> { + producedSequence.set(sequence); + return new EventEvidence( + "event-4", + "sha256:wire-digest-4", + "{\"eventDigest\":\"sha256:wire-digest-4\"}".getBytes()); + }); + + assertThat(producedSequence).hasValue(4L); + assertThat(event.outboxSequence()).isEqualTo(4L); + assertThat(event.eventDigest()).isEqualTo("sha256:wire-digest-4"); + } + + @Test + void exactRetryWithChangedProducedEvidenceConflictsWithoutAdvancingHead() { + stubAppend( + 7L, + eventRecord( + 4L, + "event-4", + "sha256:wire-digest-4", + "{\"eventDigest\":\"sha256:wire-digest-4\"}".getBytes(), + "request-4")); + + assertThatThrownBy( + () -> + repository.append( + "account:auth-authority:v1:membership/account-a/tenant-a", + "request-4", + sequence -> + new EventEvidence( + "event-4", + "sha256:changed", + "{\"eventDigest\":\"sha256:changed\"}".getBytes()))) + .isInstanceOf(AccountAuthorityOutboxRepository.IdempotencyConflictException.class); + + verify(dsl, never()) + .fetchOne(startsWith("UPDATE account_authority_outbox_streams"), any(Object[].class)); + } + + @Test + void factoryFailureCannotAdvanceHeadOrInsertEvent() { + stubAppend(0L, null); + + assertThatThrownBy( + () -> + repository.append( + "account:auth-authority:v1:membership/account-a/tenant-a", + "request-1", + sequence -> { + throw new IllegalStateException("producer failed"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessage("producer failed"); + + verify(dsl, never()) + .fetchOne(startsWith("UPDATE account_authority_outbox_streams"), any(Object[].class)); + verify(dsl, never()) + .execute(startsWith("INSERT INTO account_authority_outbox_events"), any(Object[].class)); + } + + @Test + void eachUnrelatedStreamFactoryReceivesItsOwnNextSequence() { + stubAppend(0L, null); + List producedSequences = new ArrayList<>(); + + Event first = + repository.append( + "account:auth-authority:v1:account/account-a", + "request-1", + sequence -> { + producedSequences.add(sequence); + return new EventEvidence("event-1", "digest-1", new byte[] {1}); + }); + Event otherStream = + repository.append( + "account:auth-authority:v1:tenant/tenant-b", + "request-1", + sequence -> { + producedSequences.add(sequence); + return new EventEvidence("event-1", "digest-1", new byte[] {1}); + }); + + assertThat(producedSequences).containsExactly(1L, 1L); + assertThat(first.outboxSequence()).isEqualTo(1L); + assertThat(otherStream.outboxSequence()).isEqualTo(1L); + assertThat(otherStream.outboxStreamKey()) + .isEqualTo("account:auth-authority:v1:tenant/tenant-b"); + } + + @Test + void producedEvidenceValidatesBoundsAndDefensivelyCopiesPayload() { + byte[] payload = {4, 5, 6}; + EventEvidence evidence = new EventEvidence("event-1", "digest-1", payload); + payload[0] = 9; + + assertThat(evidence.payload()).containsExactly((byte) 4, (byte) 5, (byte) 6); + assertThatThrownBy(() -> new EventEvidence("e".repeat(513), "digest", new byte[] {1})) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new EventEvidence("event", "d".repeat(513), new byte[] {1})) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void positiveCheckpointReadbackReturnsItsExactEventIdentityAndDigest() { + String streamKey = "account:auth-authority:v1:membership/account-a/tenant-a"; + Record stream = mock(Record.class); + Record event = mock(Record.class); + when(stream.get("last_sequence", Long.class)).thenReturn(2L); + when(event.get("outbox_sequence", Long.class)).thenReturn(2L); + when(event.get("event_id", String.class)).thenReturn("event-2"); + when(event.get("event_digest", String.class)).thenReturn("canonical-digest-2"); + when(event.get("payload", byte[].class)).thenReturn(new byte[] {2}); + when(event.get("request_id", String.class)).thenReturn("request-2"); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> + invocation.getArgument(0).contains("account_authority_outbox_streams") + ? stream + : event); + + assertThat(repository.readCheckpoint(streamKey)) + .contains(new Checkpoint(streamKey, 2L, "event-2", "canonical-digest-2")); + } + + @Test + void requestReadbackFindsAnExactHistoricalEventInItsStream() { + String streamKey = "account:auth-authority:v1:membership/account-a/tenant-a"; + Record event = mock(Record.class); + when(event.get("outbox_sequence", Long.class)).thenReturn(2L); + when(event.get("event_id", String.class)).thenReturn("event-2"); + when(event.get("event_digest", String.class)).thenReturn("canonical-digest-2"); + when(event.get("payload", byte[].class)).thenReturn(new byte[] {2}); + when(event.get("request_id", String.class)).thenReturn("request-2"); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(event); + + assertThat(repository.findEvent(streamKey, "request-2")) + .contains( + new Event(streamKey, "request-2", 2L, "event-2", "canonical-digest-2", new byte[] {2})); + verify(dsl) + .fetchOne( + startsWith( + "SELECT outbox_sequence, request_id, event_id, event_digest, payload " + + "FROM account_authority_outbox_events WHERE outbox_stream_key = ? " + + "AND request_id = ?"), + any(Object[].class)); + } + + @Test + void requestReadbackRejectsInvalidRequestIdentityBeforeStorageAccess() { + assertThatThrownBy( + () -> + repository.findEvent( + "account:auth-authority:v1:membership/account-a/tenant-a", "r".repeat(513))) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(dsl); + } + + @Test + void storageOperationsRequireTheCallersTransaction() throws ReflectiveOperationException { + assertMandatory( + AccountAuthorityOutboxRepository.class.getMethod( + "append", String.class, String.class, String.class, String.class, byte[].class)); + assertMandatory( + AccountAuthorityOutboxRepository.class.getMethod( + "append", String.class, String.class, java.util.function.LongFunction.class)); + assertMandatory( + AccountAuthorityOutboxRepository.class.getMethod("findEvent", String.class, long.class)); + assertMandatory( + AccountAuthorityOutboxRepository.class.getMethod("findEvent", String.class, String.class)); + assertMandatory( + AccountAuthorityOutboxRepository.class.getMethod("readCheckpoint", String.class)); + } + + private void assertMandatory(java.lang.reflect.Method method) { + Transactional annotation = method.getAnnotation(Transactional.class); + assertThat(annotation).isNotNull(); + assertThat(annotation.propagation()).isEqualTo(Propagation.MANDATORY); + } + + private void stubAppend(long currentSequence, Record priorRequest) { + Record stream = streamRecord(currentSequence); + Record advanced = streamRecord(currentSequence + 1L); + when(dsl.execute(anyString(), any(Object[].class))).thenReturn(1); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String query = invocation.getArgument(0); + if (query.startsWith("SELECT last_sequence")) { + return stream; + } + if (query.startsWith("SELECT outbox_sequence")) { + return priorRequest; + } + if (query.startsWith("SELECT request_id")) { + return null; + } + if (query.startsWith("UPDATE account_authority_outbox_streams")) { + return advanced; + } + throw new AssertionError("Unexpected outbox query: " + query); + }); + } + + private Record streamRecord(long sequence) { + Record record = mock(Record.class); + when(record.get("last_sequence", Long.class)).thenReturn(sequence); + return record; + } + + private Record eventRecord( + long sequence, String eventId, String digest, byte[] payload, String requestId) { + Record record = mock(Record.class); + when(record.get("outbox_sequence", Long.class)).thenReturn(sequence); + when(record.get("event_id", String.class)).thenReturn(eventId); + when(record.get("event_digest", String.class)).thenReturn(digest); + when(record.get("payload", byte[].class)).thenReturn(payload); + when(record.get("request_id", String.class)).thenReturn(requestId); + return record; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantIdentityResolverTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantIdentityResolverTest.java new file mode 100644 index 0000000000..3741b1f5c1 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantIdentityResolverTest.java @@ -0,0 +1,134 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository.ApprovedAssociation; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +class AccountTenantIdentityResolverTest { + private static final long LEGACY_TENANT_ID = 41L; + private static final String NAMESPACE = "proof"; + private static final String EVIDENCE_DIGEST = "sha256:" + "a".repeat(64); + + private final ApprovedLegacyTenantAssociationRepository associations = + mock(ApprovedLegacyTenantAssociationRepository.class); + private final LegacyTenantSourceEvidence sourceEvidence = mock(LegacyTenantSourceEvidence.class); + private final AccountTenantIdentityResolver resolver = + new AccountTenantIdentityResolver(associations, sourceEvidence, NAMESPACE); + + @Test + void resolverRequiresCallerOwnedSnapshotTransaction() throws NoSuchMethodException { + Transactional boundary = + AccountTenantIdentityResolver.class + .getMethod("resolve", long.class) + .getAnnotation(Transactional.class); + assertThat(boundary.propagation()).isEqualTo(Propagation.MANDATORY); + } + + @Test + void resolvesCanonicalIdentityWithRetainedProvenanceAfterExactEvidenceReadback() { + ApprovedAssociation association = association(); + when(associations.findByLegacyTenantId(LEGACY_TENANT_ID)).thenReturn(Optional.of(association)); + when(sourceEvidence.digest(LEGACY_TENANT_ID)).thenReturn(EVIDENCE_DIGEST); + + ApprovedAssociation resolved = resolver.resolve(LEGACY_TENANT_ID); + + assertThat(resolved).isSameAs(association); + assertThat(resolved.canonicalTenantId()) + .isEqualTo(UUID.fromString("22222222-2222-4222-8222-222222222222")); + assertThat(resolved.sourceLegacyGameTenantId()).isEqualTo("legacy-game-7"); + assertThat(resolved.sourceGameRowId()).isEqualTo(7L); + assertThat(resolved.accountEvidenceDigest()).isEqualTo(EVIDENCE_DIGEST); + assertThat(resolved.operationId()) + .isEqualTo(UUID.fromString("11111111-1111-4111-8111-111111111111")); + assertThat(resolved.manifestDigest()).isEqualTo("sha256:" + "b".repeat(64)); + assertThat(resolved.targetNamespace()).isEqualTo(NAMESPACE); + verify(sourceEvidence).digest(LEGACY_TENANT_ID); + } + + @Test + void missingAssociationFailsClosedBeforeReadingRetainedEvidence() { + when(associations.findByLegacyTenantId(LEGACY_TENANT_ID)).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> resolver.resolve(LEGACY_TENANT_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("association is absent"); + verify(sourceEvidence, never()).digest(LEGACY_TENANT_ID); + } + + @Test + void changedEvidenceFailsClosed() { + when(associations.findByLegacyTenantId(LEGACY_TENANT_ID)) + .thenReturn(Optional.of(association())); + when(sourceEvidence.digest(LEGACY_TENANT_ID)).thenReturn("sha256:" + "c".repeat(64)); + + assertThatThrownBy(() -> resolver.resolve(LEGACY_TENANT_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("evidence differs"); + } + + @Test + void conflictingEvidenceFailsClosed() { + when(associations.findByLegacyTenantId(LEGACY_TENANT_ID)) + .thenReturn(Optional.of(association())); + when(sourceEvidence.digest(LEGACY_TENANT_ID)) + .thenThrow(new IllegalStateException("retained Account source is conflicting")); + + assertThatThrownBy(() -> resolver.resolve(LEGACY_TENANT_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("source is conflicting"); + } + + @Test + void namespaceMismatchFailsClosedBeforeReadingRetainedEvidence() { + when(associations.findByLegacyTenantId(LEGACY_TENANT_ID)) + .thenReturn(Optional.of(association("other-namespace"))); + + assertThatThrownBy(() -> resolver.resolve(LEGACY_TENANT_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("association is mismatched"); + verify(sourceEvidence, never()).digest(LEGACY_TENANT_ID); + } + + @Test + void invalidKeyFailsClosedBeforeRepositoryReads() { + assertThatThrownBy(() -> resolver.resolve(0L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("positive retained Account tenant key"); + assertThatThrownBy(() -> resolver.resolve(-1L)).isInstanceOf(IllegalArgumentException.class); + verify(associations, never()).findByLegacyTenantId(0L); + verify(associations, never()).findByLegacyTenantId(-1L); + } + + private static ApprovedAssociation association() { + return association(NAMESPACE); + } + + private static ApprovedAssociation association(String targetNamespace) { + return new ApprovedAssociation( + LEGACY_TENANT_ID, + UUID.fromString("22222222-2222-4222-8222-222222222222"), + "legacy-game-7", + 7L, + EVIDENCE_DIGEST, + UUID.fromString("11111111-1111-4111-8111-111111111111"), + "sha256:" + "b".repeat(64), + "A".repeat(88), + targetNamespace, + "game-design-owner-2026", + "owner@example.test", + "reviewed-change-123", + "2026-09-26T00:00:00Z", + 1, + 1); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRoleSnapshotRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRoleSnapshotRepositoryTest.java new file mode 100644 index 0000000000..c61cbbabae --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRoleSnapshotRepositoryTest.java @@ -0,0 +1,90 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +class AccountTenantMembershipRoleSnapshotRepositoryTest { + @Test + void canonicalizesRoleIdentifiersByUnsignedAsciiBytesAndPreservesCase() { + assertThat( + AccountTenantMembershipRoleSnapshotRepository.canonicalizeRoleSet( + List.of("player_2", "player-admin", "player", "Player"))) + .containsExactly("Player", "player", "player-admin", "player_2"); + assertThat( + AccountTenantMembershipRoleSnapshotRepository.compareRoleIdentifierBytes( + "player", "player-admin")) + .isLessThan(0); + assertThat( + AccountTenantMembershipRoleSnapshotRepository.compareRoleIdentifierBytes( + "Player", "player")) + .isLessThan(0); + } + + @Test + void rejectsMalformedDuplicateOrNonCanonicalRoleEvidence() { + assertThatThrownBy( + () -> + AccountTenantMembershipRoleSnapshotRepository.canonicalizeRoleSet( + List.of("player", "player"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountTenantMembershipRoleSnapshotRepository.canonicalizeRoleSet( + List.of("_player"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountTenantMembershipRoleSnapshotRepository.canonicalizeRoleSet( + List.of("player admin"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountTenantMembershipRoleSnapshotRepository.canonicalizeRoleSet( + List.of("pläyer"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountTenantMembershipRoleSnapshotRepository.requireCanonicalRoleSet( + List.of("player_2", "player"))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void emptyRoleSetIsAnAuthoritativeSnapshotOnlyWhenVersionedAndPresent() { + AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot snapshot = + new AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot( + 11L, 7L, 701L, 3L, List.of()); + + assertThat(snapshot.roles()).isEmpty(); + assertThat(snapshot.snapshotVersion()).isEqualTo(3L); + assertThatThrownBy( + () -> + new AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot( + 11L, 7L, 701L, 0L, List.of())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void persistenceMethodsRequireTheCallingJoinTransaction() throws ReflectiveOperationException { + assertMandatory( + AccountTenantMembershipRoleSnapshotRepository.class.getMethod( + "findForUpdate", long.class, long.class, long.class, long.class)); + assertMandatory( + AccountTenantMembershipRoleSnapshotRepository.class.getMethod( + "replace", + net.firedevops.firemud.accountservice.entity.AccountTenantMembership.class, + long.class, + java.util.Collection.class)); + } + + private void assertMandatory(java.lang.reflect.Method method) { + Transactional annotation = method.getAnnotation(Transactional.class); + assertThat(annotation).isNotNull(); + assertThat(annotation.propagation()).isEqualTo(Propagation.MANDATORY); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/ApprovedLegacyTenantAssociationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/ApprovedLegacyTenantAssociationRepositoryTest.java index 6f7f3c5e17..299d1ced0b 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/ApprovedLegacyTenantAssociationRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/ApprovedLegacyTenantAssociationRepositoryTest.java @@ -12,8 +12,10 @@ class ApprovedLegacyTenantAssociationRepositoryTest { private final DSLContext dsl = mock(DSLContext.class); private final LegacyTenantSourceEvidence sources = mock(LegacyTenantSourceEvidence.class); + private final AccountAuthorityGenerationRepository authorityGenerations = + mock(AccountAuthorityGenerationRepository.class); private final ApprovedLegacyTenantAssociationRepository repository = - new ApprovedLegacyTenantAssociationRepository(dsl, sources, "proof"); + new ApprovedLegacyTenantAssociationRepository(dsl, sources, "proof", authorityGenerations); @Test void mismatchedOrIncompleteOwnerReadNeverTouchesRetainedRows() { @@ -32,7 +34,7 @@ void mismatchedOrIncompleteOwnerReadNeverTouchesRetainedRows() { assertThatThrownBy( () -> repository.importApproved(41L, response().clearCanonicalTenantId().build())) .isInstanceOf(IllegalArgumentException.class); - verifyNoInteractions(dsl, sources); + verifyNoInteractions(dsl, sources, authorityGenerations); } private ResolveLegacyAccountTenantAssociationResponse.Builder response() { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountEnvelopeCryptoTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountEnvelopeCryptoTest.java new file mode 100644 index 0000000000..78c39533a4 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountEnvelopeCryptoTest.java @@ -0,0 +1,500 @@ +package unit.net.firedevops.firemud.accountservice.security; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import net.firedevops.firemud.accountservice.security.AccountEncryptedEnvelope; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeBinding; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeCrypto; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeCryptoException; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeCryptoException.Failure; +import net.firedevops.firemud.accountservice.security.AccountEnvelopePurpose; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class AccountEnvelopeCryptoTest { + @TempDir private Path temporaryDirectory; + + private Path manifestPath; + + @BeforeEach + void setUp() { + manifestPath = temporaryDirectory.resolve("manifest.v1"); + } + + @Test + void exactEnvelopeBytesDecryptAfterCryptoObjectRecreationForBothPurposes() throws Exception { + KeyPair firstKey = new KeyPair("k1", key(1), key(2)); + writeManifest("k1", firstKey); + AccountEnvelopeCrypto writer = new AccountEnvelopeCrypto(manifestPath); + AccountEnvelopeBinding binding = connectBinding("connect-op-1", "request-1"); + byte[] exactResult = "the exact previously issued result".getBytes(StandardCharsets.UTF_8); + AccountEnvelopeBinding loginBinding = loginBinding("login-op-1", "login-request-1"); + byte[] exactLoginResult = "the exact bare LOGIN result".getBytes(StandardCharsets.UTF_8); + + AccountEncryptedEnvelope envelope = + writer.encrypt(AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, binding, exactResult); + AccountEncryptedEnvelope loginEnvelope = + writer.encrypt(AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, loginBinding, exactLoginResult); + AccountEnvelopeCrypto recoveryReader = new AccountEnvelopeCrypto(manifestPath); + + assertEquals("k1", envelope.keyId()); + assertEquals(AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, envelope.purpose()); + assertArrayEquals( + exactResult, + recoveryReader.decrypt(envelope, AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, binding)); + assertEquals("k1", loginEnvelope.keyId()); + assertEquals(AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, loginEnvelope.purpose()); + assertArrayEquals( + exactLoginResult, + recoveryReader.decrypt( + loginEnvelope, AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, loginBinding)); + assertFailure( + Failure.AUTHENTICATION_FAILED, + () -> + recoveryReader.decrypt( + envelope, + AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, + connectBinding("connect-op-other", "request-1"))); + } + + @Test + void rotationWritesWithNewIdRetainsOldDecryptKeyAndFailsAfterOldKeyRemoval() throws Exception { + KeyPair firstKey = new KeyPair("k1", key(1), key(2)); + KeyPair secondKey = new KeyPair("k2", key(3), key(4)); + writeManifest("k1", firstKey); + AccountEnvelopeCrypto crypto = new AccountEnvelopeCrypto(manifestPath); + AccountEnvelopeBinding firstBinding = connectBinding("connect-op-1", "request-1"); + AccountEnvelopeBinding secondBinding = connectBinding("connect-op-2", "request-2"); + AccountEnvelopeBinding firstLoginBinding = loginBinding("login-op-1", "login-request-1"); + AccountEnvelopeBinding secondLoginBinding = loginBinding("login-op-2", "login-request-2"); + byte[] firstResult = "first issuance result".getBytes(StandardCharsets.UTF_8); + byte[] secondResult = "second issuance result".getBytes(StandardCharsets.UTF_8); + byte[] firstLoginResult = "first bare LOGIN result".getBytes(StandardCharsets.UTF_8); + byte[] secondLoginResult = "second bare LOGIN result".getBytes(StandardCharsets.UTF_8); + AccountEncryptedEnvelope firstEnvelope = + crypto.encrypt(AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, firstBinding, firstResult); + AccountEncryptedEnvelope firstLoginEnvelope = + crypto.encrypt( + AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, firstLoginBinding, firstLoginResult); + + writeManifest("k2", firstKey, secondKey); + AccountEncryptedEnvelope secondEnvelope = + crypto.encrypt(AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, secondBinding, secondResult); + AccountEncryptedEnvelope secondLoginEnvelope = + crypto.encrypt( + AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, secondLoginBinding, secondLoginResult); + + assertEquals("k2", secondEnvelope.keyId()); + assertEquals("k2", secondLoginEnvelope.keyId()); + assertArrayEquals( + firstResult, + crypto.decrypt(firstEnvelope, AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, firstBinding)); + assertArrayEquals( + secondResult, + crypto.decrypt( + secondEnvelope, AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, secondBinding)); + assertArrayEquals( + firstLoginResult, + crypto.decrypt( + firstLoginEnvelope, AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, firstLoginBinding)); + assertArrayEquals( + secondLoginResult, + crypto.decrypt( + secondLoginEnvelope, AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, secondLoginBinding)); + + writeManifest("k2", secondKey); + assertFailure( + Failure.KEY_UNAVAILABLE, + () -> + crypto.decrypt( + firstEnvelope, AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, firstBinding)); + assertFailure( + Failure.KEY_UNAVAILABLE, + () -> + crypto.decrypt( + firstLoginEnvelope, AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, firstLoginBinding)); + assertArrayEquals( + secondResult, + crypto.decrypt( + secondEnvelope, AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, secondBinding)); + assertArrayEquals( + secondLoginResult, + crypto.decrypt( + secondLoginEnvelope, AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, secondLoginBinding)); + } + + @Test + void wrongPurposeAndOperationCannotAuthenticateWithOverlappingKeyIds() throws Exception { + writeManifest("k1", new KeyPair("k1", key(1), key(2))); + AccountEnvelopeCrypto crypto = new AccountEnvelopeCrypto(manifestPath); + AccountEnvelopeBinding connectBinding = connectBinding("connect-op-1", "request-1"); + AccountEncryptedEnvelope connectEnvelope = + crypto.encrypt( + AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, + connectBinding, + "token result".getBytes(StandardCharsets.UTF_8)); + AccountEnvelopeBinding loginBinding = loginBinding("login-op-1", "request-1"); + + assertFailure( + Failure.PURPOSE_MISMATCH, + () -> + crypto.decrypt( + connectEnvelope, AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, loginBinding)); + + AccountEncryptedEnvelope relabeledEnvelope = + new AccountEncryptedEnvelope( + connectEnvelope.formatVersion(), + connectEnvelope.keyId(), + AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, + connectEnvelope.nonce(), + connectEnvelope.ciphertext()); + assertFailure( + Failure.AUTHENTICATION_FAILED, + () -> + crypto.decrypt( + relabeledEnvelope, AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, loginBinding)); + assertFailure( + Failure.AUTHENTICATION_FAILED, + () -> + crypto.decrypt( + connectEnvelope, + AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, + connectBinding("connect-op-1", "request-other"))); + + AccountEncryptedEnvelope loginEnvelope = + crypto.encrypt( + AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, + loginBinding, + "delegation result".getBytes(StandardCharsets.UTF_8)); + assertFailure( + Failure.AUTHENTICATION_FAILED, + () -> + crypto.decrypt( + loginEnvelope, + AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, + loginBinding("login-op-1", "request-1", "connect-op-other"))); + } + + @Test + void nonceCiphertextAndEveryAuthorityBindingChangeFailAuthentication() throws Exception { + writeManifest("k1", new KeyPair("k1", key(1), key(2))); + AccountEnvelopeCrypto crypto = new AccountEnvelopeCrypto(manifestPath); + AccountEnvelopeBinding binding = connectBinding("connect-op-1", "request-1"); + AccountEncryptedEnvelope envelope = + crypto.encrypt( + AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, + binding, + "exact credential response".getBytes(StandardCharsets.UTF_8)); + + byte[] changedNonce = envelope.nonce(); + changedNonce[0] ^= 1; + AccountEncryptedEnvelope nonceTampered = + new AccountEncryptedEnvelope( + envelope.formatVersion(), + envelope.keyId(), + envelope.purpose(), + changedNonce, + envelope.ciphertext()); + assertAuthenticationFailure(crypto, nonceTampered, binding); + + byte[] changedCiphertext = envelope.ciphertext(); + changedCiphertext[0] ^= 1; + AccountEncryptedEnvelope ciphertextTampered = + new AccountEncryptedEnvelope( + envelope.formatVersion(), + envelope.keyId(), + envelope.purpose(), + envelope.nonce(), + changedCiphertext); + assertAuthenticationFailure(crypto, ciphertextTampered, binding); + + assertAuthenticationFailure( + crypto, + envelope, + connectBinding( + "connect-op-1", + "request-1", + "account-other", + "tenant-a", + "connect-scope-a", + digest(1), + digest(2), + digest(3), + digest(4), + digest(5))); + assertAuthenticationFailure( + crypto, + envelope, + connectBinding( + "connect-op-1", + "request-1", + "account-17", + "tenant-a", + "connect-scope-other", + digest(1), + digest(2), + digest(3), + digest(4), + digest(5))); + assertAuthenticationFailure( + crypto, + envelope, + connectBinding( + "connect-op-1", + "request-1", + "account-17", + "tenant-a", + "connect-scope-a", + digest(11), + digest(2), + digest(3), + digest(4), + digest(5))); + assertAuthenticationFailure( + crypto, + envelope, + connectBinding( + "connect-op-1", + "request-1", + "account-17", + "tenant-a", + "connect-scope-a", + digest(1), + digest(12), + digest(3), + digest(4), + digest(5))); + assertAuthenticationFailure( + crypto, + envelope, + connectBinding( + "connect-op-1", + "request-1", + "account-17", + "tenant-a", + "connect-scope-a", + digest(1), + digest(2), + digest(13), + digest(4), + digest(5))); + assertAuthenticationFailure( + crypto, + envelope, + connectBinding( + "connect-op-1", + "request-1", + "account-17", + "tenant-a", + "connect-scope-a", + digest(1), + digest(2), + digest(3), + digest(14), + digest(5))); + assertAuthenticationFailure( + crypto, + envelope, + connectBinding( + "connect-op-1", + "request-1", + "account-17", + "tenant-a", + "connect-scope-a", + digest(1), + digest(2), + digest(3), + digest(4), + digest(15))); + } + + @Test + void missingMalformedAndCrossPurposeReusedKeysFailClosed() throws Exception { + AccountEnvelopeCrypto missingRing = new AccountEnvelopeCrypto(manifestPath); + AccountEnvelopeBinding binding = connectBinding("connect-op-1", "request-1"); + assertFailure( + Failure.KEY_RING_UNAVAILABLE, + () -> + missingRing.encrypt( + AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, + binding, + "credential".getBytes(StandardCharsets.UTF_8))); + + Files.writeString(manifestPath, "version=2\nactiveKeyId=k1\n", StandardCharsets.US_ASCII); + assertFailure( + Failure.KEY_RING_MALFORMED, + () -> + missingRing.encrypt( + AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, + binding, + "credential".getBytes(StandardCharsets.UTF_8))); + + byte[] reusedKey = key(9); + writeManifest("k1", new KeyPair("k1", reusedKey, reusedKey)); + assertFailure( + Failure.KEY_RING_MALFORMED, + () -> + missingRing.encrypt( + AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, + binding, + "credential".getBytes(StandardCharsets.UTF_8))); + } + + @Test + void envelopeAndBindingByteArraysAreDefensivelyCopied() throws Exception { + writeManifest("k1", new KeyPair("k1", key(1), key(2))); + AccountEnvelopeCrypto crypto = new AccountEnvelopeCrypto(manifestPath); + AccountEnvelopeBinding binding = connectBinding("connect-op-1", "request-1"); + byte[] plaintext = "sensitive response".getBytes(StandardCharsets.UTF_8); + AccountEncryptedEnvelope envelope = + crypto.encrypt(AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, binding, plaintext); + byte[] exposedNonce = envelope.nonce(); + byte[] exposedDigest = binding.requestDigest(); + Arrays.fill(exposedNonce, (byte) 0); + Arrays.fill(exposedDigest, (byte) 0); + + AccountEncryptedEnvelope envelopeCopy = + new AccountEncryptedEnvelope( + envelope.formatVersion(), + envelope.keyId(), + envelope.purpose(), + envelope.nonce(), + envelope.ciphertext()); + AccountEnvelopeBinding bindingCopy = connectBinding("connect-op-1", "request-1"); + byte[] changedNonce = envelope.nonce(); + changedNonce[0] ^= 1; + + assertEquals(envelope, envelopeCopy); + assertEquals(envelope.hashCode(), envelopeCopy.hashCode()); + assertEquals(binding, bindingCopy); + assertEquals(binding.hashCode(), bindingCopy.hashCode()); + assertNotEquals( + envelope, + new AccountEncryptedEnvelope( + envelope.formatVersion(), + envelope.keyId(), + envelope.purpose(), + changedNonce, + envelope.ciphertext())); + + assertArrayEquals( + plaintext, + crypto.decrypt(envelope, AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, binding)); + } + + private void writeManifest(String activeKeyId, KeyPair... keyPairs) throws Exception { + List lines = new ArrayList<>(); + lines.add("version=1"); + lines.add("activeKeyId=" + activeKeyId); + for (KeyPair keyPair : keyPairs) { + lines.add("key:" + keyPair.keyId() + ":bare-login=" + encode(keyPair.bareLoginKey())); + lines.add("key:" + keyPair.keyId() + ":connect-token=" + encode(keyPair.connectTokenKey())); + } + Files.writeString(manifestPath, String.join("\n", lines) + "\n", StandardCharsets.US_ASCII); + } + + private static String encode(byte[] key) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(key); + } + + private static byte[] key(int value) { + byte[] key = new byte[32]; + Arrays.fill(key, (byte) value); + return key; + } + + private static AccountEnvelopeBinding connectBinding(String operationId, String requestId) { + return connectBinding( + operationId, + requestId, + "account-17", + "tenant-a", + "connect-scope-a", + digest(1), + digest(2), + digest(3), + digest(4), + digest(5)); + } + + private static AccountEnvelopeBinding connectBinding( + String operationId, + String requestId, + String accountId, + String tenantId, + String connectScopeId, + byte[] requestDigest, + byte[] contextEvidenceDigest, + byte[] authorityTupleDigest, + byte[] issuanceFenceDigest, + byte[] postconditionDigest) { + return new AccountEnvelopeBinding( + AccountEnvelopeBinding.OperationKind.CONNECT_TOKEN_ISSUANCE, + operationId, + requestId, + accountId, + tenantId, + connectScopeId, + null, + requestDigest, + contextEvidenceDigest, + authorityTupleDigest, + issuanceFenceDigest, + postconditionDigest); + } + + private static AccountEnvelopeBinding loginBinding(String operationId, String requestId) { + return loginBinding(operationId, requestId, "connect-op-1"); + } + + private static AccountEnvelopeBinding loginBinding( + String operationId, String requestId, String sourceConnectOperationId) { + return new AccountEnvelopeBinding( + AccountEnvelopeBinding.OperationKind.BARE_LOGIN_EXCHANGE, + operationId, + requestId, + "account-17", + "tenant-a", + "connect-scope-a", + sourceConnectOperationId, + digest(1), + digest(2), + digest(3), + digest(4), + digest(5)); + } + + private static byte[] digest(int value) { + byte[] digest = new byte[32]; + Arrays.fill(digest, (byte) value); + return digest; + } + + private static void assertFailure(Failure expected, Runnable operation) { + AccountEnvelopeCryptoException exception = + assertThrows(AccountEnvelopeCryptoException.class, operation::run); + assertEquals(expected, exception.failure()); + } + + private static void assertAuthenticationFailure( + AccountEnvelopeCrypto crypto, + AccountEncryptedEnvelope envelope, + AccountEnvelopeBinding binding) { + assertFailure( + Failure.AUTHENTICATION_FAILED, + () -> crypto.decrypt(envelope, AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, binding)); + } + + private record KeyPair(String keyId, byte[] connectTokenKey, byte[] bareLoginKey) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationServiceTest.java index 0402e58dbf..c0eaf79001 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationServiceTest.java @@ -2,6 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -26,6 +27,7 @@ import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository.JoinAuditEvidence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository.ConnectScopeEvidence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; @@ -33,6 +35,8 @@ import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository.JoinMembershipProof; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -59,7 +63,7 @@ class AccountJoinReconciliationServiceTest { private static final UUID REALM_ID = UUID.fromString("4c4b57d8-e3a2-48fe-9977-e7df0fdce901"); @Test - void exactReadbackCommitsEvenWhenScopeExpiredAndAuditOccurredAfterExpiry() { + void matchingRoleSnapshotCommitsEvenWhenScopeExpiredAndAuditOccurredAfterExpiry() { Fixture fixture = fixture(5); JoinOperation pending = pendingOperation(5, NOW.minusSeconds(1)); stubDue(fixture, pending); @@ -90,6 +94,11 @@ void exactReadbackCommitsEvenWhenScopeExpiredAndAuditOccurredAfterExpiry() { .recordReconciliationAttempt( anyString(), anyInt(), anyInt(), any(), any(), anyString(), any()); verify(fixture.transitionReceipts).findLatestReceipt(ACCOUNT_ID, TENANT_ID); + verify(fixture.membershipAuthorityEventProducer) + .requireCurrentMembershipEvent( + any(JoinMembershipProof.class), any(RoleSnapshot.class), eq(REQUEST_ID), eq(false)); + verify(fixture.roleSnapshots) + .findForUpdate(ACCOUNT_ID, TENANT_ID, MEMBERSHIP_ID, MEMBERSHIP_VERSION); verify(fixture.auditOutbox).findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID); assertThat(reconciliationCounter(fixture, "committed")).isEqualTo(1); } @@ -118,6 +127,12 @@ void priorMembershipHistoryCommitsEventFreeAlreadyActiveOutcome() { MEMBERSHIP_VERSION, MEMBERSHIP_AUTHORITY_GENERATION); verify(fixture.transitionReceipts).findLatestReceipt(ACCOUNT_ID, TENANT_ID); + verify(fixture.membershipAuthorityEventProducer) + .requireCurrentMembershipEvent( + any(JoinMembershipProof.class), + any(RoleSnapshot.class), + eq("prior-join-request"), + eq(false)); verify(fixture.auditOutbox).findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID); verify(fixture.auditOutbox, never()) .append(any(), anyString(), any(), anyString(), anyString()); @@ -160,6 +175,91 @@ void mismatchedPriorMembershipReceiptStaysPending() { .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); } + @Test + void missingCanonicalEventKeepsJoinedOperationPending() { + Fixture fixture = fixture(3); + JoinOperation pending = pendingOperation(0, NOW.minusSeconds(1)); + stubDue(fixture, pending); + when(fixture.joinOperations.findForUpdate(REQUEST_ID)).thenReturn(Optional.of(pending)); + when(fixture.connectScopes.findEvidenceByTokenHash(pending.scopeTokenHash())) + .thenReturn(Optional.of(scopeEvidence("PUBLIC_PRODUCTION", TENANT_ID, WORLD_SLUG))); + stubActiveMembership(fixture); + when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) + .thenReturn( + Optional.of( + verifiedJoinAuditEvidence( + joinAuditEnvelope(WORLD_SLUG, TENANT_ID, correctPayloadDigest())))); + when(fixture.membershipAuthorityEventProducer.requireCurrentMembershipEvent( + any(JoinMembershipProof.class), any(RoleSnapshot.class), eq(REQUEST_ID), eq(false))) + .thenThrow(new IllegalStateException("canonical event absent")); + when(fixture.joinOperations.recordReconciliationAttempt( + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "MEMBERSHIP_AUTHORITY_EVENT_UNAVAILABLE", + NOW.plusMillis(5_000))) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.joinOperations) + .recordReconciliationAttempt( + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "MEMBERSHIP_AUTHORITY_EVENT_UNAVAILABLE", + NOW.plusMillis(5_000)); + verify(fixture.joinOperations, never()) + .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); + } + + @Test + void missingCanonicalEventKeepsAlreadyActiveOperationPending() { + Fixture fixture = fixture(3); + JoinOperation pending = pendingOperation(0, NOW.minusSeconds(1)); + stubDue(fixture, pending); + when(fixture.joinOperations.findForUpdate(REQUEST_ID)).thenReturn(Optional.of(pending)); + when(fixture.connectScopes.findEvidenceByTokenHash(pending.scopeTokenHash())) + .thenReturn(Optional.of(scopeEvidence("PUBLIC_PRODUCTION", TENANT_ID, WORLD_SLUG))); + stubActiveMembership(fixture); + stubReceiptFor(fixture, "prior-join-request", MEMBERSHIP_ID); + when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) + .thenReturn(Optional.empty()); + when(fixture.membershipAuthorityEventProducer.requireCurrentMembershipEvent( + any(JoinMembershipProof.class), + any(RoleSnapshot.class), + eq("prior-join-request"), + eq(false))) + .thenThrow(new IllegalStateException("canonical event absent")); + when(fixture.joinOperations.recordReconciliationAttempt( + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "MEMBERSHIP_AUTHORITY_EVENT_UNAVAILABLE", + NOW.plusMillis(5_000))) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.joinOperations) + .recordReconciliationAttempt( + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "MEMBERSHIP_AUTHORITY_EVENT_UNAVAILABLE", + NOW.plusMillis(5_000)); + verify(fixture.joinOperations, never()) + .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); + } + @Test void missingTransitionReceiptDoesNotInferJoinedFromMembershipAndAuditAlone() { Fixture fixture = fixture(3); @@ -332,6 +432,135 @@ void missingMembershipAfterScopeExpiryStaysPendingAndReschedulesAtTheAttemptThre assertThat(reconciliationCounter(fixture, "max_attempts_reached")).isZero(); } + @Test + void missingRoleSnapshotStaysPendingAndDoesNotInferRoles() { + Fixture fixture = fixture(3); + JoinOperation pending = pendingOperation(0, NOW.minusSeconds(1)); + stubDue(fixture, pending); + when(fixture.joinOperations.findForUpdate(REQUEST_ID)).thenReturn(Optional.of(pending)); + when(fixture.connectScopes.findEvidenceByTokenHash(pending.scopeTokenHash())) + .thenReturn(Optional.of(scopeEvidence("PUBLIC_PRODUCTION", TENANT_ID, WORLD_SLUG))); + stubActiveMembership(fixture); + when(fixture.roleSnapshots.findForUpdate( + ACCOUNT_ID, TENANT_ID, MEMBERSHIP_ID, MEMBERSHIP_VERSION)) + .thenReturn(Optional.empty()); + when(fixture.joinOperations.recordReconciliationAttempt( + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "MEMBERSHIP_ROLE_SNAPSHOT_ABSENT", + NOW.plusMillis(5_000))) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.joinOperations) + .recordReconciliationAttempt( + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "MEMBERSHIP_ROLE_SNAPSHOT_ABSENT", + NOW.plusMillis(5_000)); + verify(fixture.joinOperations, never()) + .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); + verify(fixture.transitionReceipts, never()).findLatestReceipt(ACCOUNT_ID, TENANT_ID); + verify(fixture.auditOutbox, never()).findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID); + } + + @Test + void mismatchedRoleSnapshotStaysPendingAndDoesNotInferRoles() { + Fixture fixture = fixture(3); + JoinOperation pending = pendingOperation(0, NOW.minusSeconds(1)); + stubDue(fixture, pending); + when(fixture.joinOperations.findForUpdate(REQUEST_ID)).thenReturn(Optional.of(pending)); + when(fixture.connectScopes.findEvidenceByTokenHash(pending.scopeTokenHash())) + .thenReturn(Optional.of(scopeEvidence("PUBLIC_PRODUCTION", TENANT_ID, WORLD_SLUG))); + stubActiveMembership(fixture); + when(fixture.roleSnapshots.findForUpdate( + ACCOUNT_ID, TENANT_ID, MEMBERSHIP_ID, MEMBERSHIP_VERSION)) + .thenReturn( + Optional.of( + new RoleSnapshot( + ACCOUNT_ID, + TENANT_ID, + MEMBERSHIP_ID, + MEMBERSHIP_VERSION + 1, + List.of("PLAYER")))); + when(fixture.joinOperations.recordReconciliationAttempt( + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "MEMBERSHIP_ROLE_SNAPSHOT_MISMATCH", + NOW.plusMillis(5_000))) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.joinOperations) + .recordReconciliationAttempt( + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "MEMBERSHIP_ROLE_SNAPSHOT_MISMATCH", + NOW.plusMillis(5_000)); + verify(fixture.joinOperations, never()) + .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); + verify(fixture.transitionReceipts, never()).findLatestReceipt(ACCOUNT_ID, TENANT_ID); + verify(fixture.auditOutbox, never()).findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID); + } + + @Test + void publicJoinSnapshotWithoutPlayerStaysPending() { + Fixture fixture = fixture(3); + JoinOperation pending = pendingOperation(0, NOW.minusSeconds(1)); + stubDue(fixture, pending); + when(fixture.joinOperations.findForUpdate(REQUEST_ID)).thenReturn(Optional.of(pending)); + when(fixture.connectScopes.findEvidenceByTokenHash(pending.scopeTokenHash())) + .thenReturn(Optional.of(scopeEvidence("PUBLIC_PRODUCTION", TENANT_ID, WORLD_SLUG))); + stubActiveMembership(fixture); + when(fixture.roleSnapshots.findForUpdate( + ACCOUNT_ID, TENANT_ID, MEMBERSHIP_ID, MEMBERSHIP_VERSION)) + .thenReturn( + Optional.of( + new RoleSnapshot( + ACCOUNT_ID, + TENANT_ID, + MEMBERSHIP_ID, + MEMBERSHIP_VERSION, + List.of("designer")))); + when(fixture.joinOperations.recordReconciliationAttempt( + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "MEMBERSHIP_ROLE_SNAPSHOT_MISMATCH", + NOW.plusMillis(5_000))) + .thenReturn(true); + + fixture.service.reconcileDueOperations(NOW); + + verify(fixture.joinOperations) + .recordReconciliationAttempt( + REQUEST_ID, + 0, + 3, + NOW.minusSeconds(1), + NOW, + "MEMBERSHIP_ROLE_SNAPSHOT_MISMATCH", + NOW.plusMillis(5_000)); + verify(fixture.joinOperations, never()) + .finish(eq(REQUEST_ID), anyString(), anyString(), any(), any(), any()); + } + @Test void attemptThresholdIsReportedOnceAndCappedCountStillReschedules() { Fixture fixture = fixture(1); @@ -605,9 +834,21 @@ private static Fixture fixture(int maxAttempts) { AccountJoinOperationRepository joinOperations = mock(AccountJoinOperationRepository.class); AccountConnectScopeRepository connectScopes = mock(AccountConnectScopeRepository.class); AccountTenantMembershipRepository memberships = mock(AccountTenantMembershipRepository.class); + AccountTenantMembershipRoleSnapshotRepository roleSnapshots = + mock(AccountTenantMembershipRoleSnapshotRepository.class); AccountMembershipTransitionReceiptRepository transitionReceipts = mock(AccountMembershipTransitionReceiptRepository.class); AccountAuditOutboxRepository auditOutbox = mock(AccountAuditOutboxRepository.class); + AccountMembershipAuthorityEventProducer membershipAuthorityEventProducer = + mock(AccountMembershipAuthorityEventProducer.class); + when(membershipAuthorityEventProducer.requireCurrentMembershipEvent( + any(JoinMembershipProof.class), any(RoleSnapshot.class), anyString(), anyBoolean())) + .thenReturn( + new Checkpoint( + "account:auth-authority:v1:membership/account-a/tenant-a", + 1L, + "event-1", + "sha256:" + "0".repeat(64))); PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); when(transactionManager.getTransaction(any(TransactionDefinition.class))) .thenAnswer(invocation -> new SimpleTransactionStatus()); @@ -617,8 +858,10 @@ private static Fixture fixture(int maxAttempts) { joinOperations, connectScopes, memberships, + roleSnapshots, transitionReceipts, auditOutbox, + membershipAuthorityEventProducer, meterRegistry, transactionManager, 10, @@ -629,17 +872,27 @@ private static Fixture fixture(int maxAttempts) { joinOperations, connectScopes, memberships, + roleSnapshots, transitionReceipts, auditOutbox, + membershipAuthorityEventProducer, meterRegistry); } private static void stubActiveMembership(Fixture fixture) { when(fixture.memberships.findJoinProofForUpdate(ACCOUNT_ID, TENANT_ID)) .thenReturn(Optional.of(activeJoinMembership())); + when(fixture.roleSnapshots.findForUpdate( + ACCOUNT_ID, TENANT_ID, MEMBERSHIP_ID, MEMBERSHIP_VERSION)) + .thenReturn(Optional.of(activeRoleSnapshot())); stubReceiptFor(fixture, REQUEST_ID, MEMBERSHIP_ID); } + private static RoleSnapshot activeRoleSnapshot() { + return new RoleSnapshot( + ACCOUNT_ID, TENANT_ID, MEMBERSHIP_ID, MEMBERSHIP_VERSION, List.of("player")); + } + private static void stubReceiptFor(Fixture fixture, String requestId, long membershipId) { String receiptStreamKey = MembershipTransitionReceiptDigest.receiptStreamKey(ACCOUNT_ID, TENANT_ID); @@ -888,7 +1141,9 @@ private record Fixture( AccountJoinOperationRepository joinOperations, AccountConnectScopeRepository connectScopes, AccountTenantMembershipRepository memberships, + AccountTenantMembershipRoleSnapshotRepository roleSnapshots, AccountMembershipTransitionReceiptRepository transitionReceipts, AccountAuditOutboxRepository auditOutbox, + AccountMembershipAuthorityEventProducer membershipAuthorityEventProducer, SimpleMeterRegistry meterRegistry) {} } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/NeverJoinedMembershipSnapshotTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/NeverJoinedMembershipSnapshotTest.java new file mode 100644 index 0000000000..6bb6d3c608 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/NeverJoinedMembershipSnapshotTest.java @@ -0,0 +1,200 @@ +package net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AccountSecurityCutoff; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.PrivateRealmGrantVersion; +import org.junit.jupiter.api.Test; + +class NeverJoinedMembershipSnapshotTest { + private static final String ACCOUNT_ID = "4c4b57d8-e3a2-48fe-9977-e7df0fdce901"; + private static final String TENANT_ID = "57c58f36-c5ea-4aa8-8ef7-91a45e407f01"; + private static final String STREAM_KEY = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + ACCOUNT_ID + + "/" + + TENANT_ID; + + @Test + void constructsEventFreeNonAdmittingSnapshotWithCompleteTuple() { + var snapshot = snapshot(ACCOUNT_ID, TENANT_ID, "1", "1", completeTuple(), "9", STREAM_KEY); + + assertThat(snapshot.membershipExists()).isFalse(); + assertThat(snapshot.membershipLifecycleState()).isEqualTo("MISSING"); + assertThat(snapshot.roles()).isEmpty(); + assertThat(snapshot.gameplayAdmissionAllowed()).isFalse(); + assertThat(snapshot.outboxSequence()).isZero(); + assertThat(snapshot.authorityTuple().membershipAuthorityGeneration()) + .containsEntry(TENANT_ID, "1"); + } + + @Test + void rejectsNonCanonicalIdsAndNonPositiveCounters() { + assertThatThrownBy( + () -> + snapshot( + ACCOUNT_ID.toUpperCase(), + TENANT_ID, + "1", + "1", + completeTuple(), + "9", + STREAM_KEY)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> snapshot(ACCOUNT_ID, TENANT_ID, "0", "1", completeTuple(), "9", STREAM_KEY)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> snapshot(ACCOUNT_ID, TENANT_ID, "1", "0", completeTuple(), "9", STREAM_KEY)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> snapshot(ACCOUNT_ID, TENANT_ID, "1", "1", completeTuple(), "0", STREAM_KEY)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsTupleWithWrongTenantOrMembershipGeneration() { + AuthorityTuple wrongTenant = + new AuthorityTuple( + "4", + "6", + Map.of(ACCOUNT_ID, "8"), + Map.of(TENANT_ID, "1"), + List.of(), + Optional.empty(), + Optional.empty()); + AuthorityTuple wrongMembershipGeneration = + new AuthorityTuple( + "4", + "6", + Map.of(TENANT_ID, "8"), + Map.of(TENANT_ID, "2"), + List.of(), + Optional.empty(), + Optional.empty()); + + assertThatThrownBy( + () -> snapshot(ACCOUNT_ID, TENANT_ID, "1", "1", wrongTenant, "9", STREAM_KEY)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + snapshot( + ACCOUNT_ID, TENANT_ID, "1", "1", wrongMembershipGeneration, "9", STREAM_KEY)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsInvalidTupleCountersAndSequenceZeroAuthorityData() { + AuthorityTuple zeroIssuer = + new AuthorityTuple( + "0", + "6", + Map.of(TENANT_ID, "8"), + Map.of(TENANT_ID, "1"), + List.of(), + Optional.empty(), + Optional.empty()); + AuthorityTuple nonCanonicalAccount = + new AuthorityTuple( + "4", + "01", + Map.of(TENANT_ID, "8"), + Map.of(TENANT_ID, "1"), + List.of(), + Optional.empty(), + Optional.empty()); + AuthorityTuple zeroTenant = + new AuthorityTuple( + "4", + "6", + Map.of(TENANT_ID, "0"), + Map.of(TENANT_ID, "1"), + List.of(), + Optional.empty(), + Optional.empty()); + AuthorityTuple extraGrant = + new AuthorityTuple( + "4", + "6", + Map.of(TENANT_ID, "8"), + Map.of(TENANT_ID, "1"), + List.of(new PrivateRealmGrantVersion(TENANT_ID, "world", "realm", "lifecycle", "1")), + Optional.empty(), + Optional.empty()); + AuthorityTuple presentCutoff = + new AuthorityTuple( + "4", + "6", + Map.of(TENANT_ID, "8"), + Map.of(TENANT_ID, "1"), + List.of(), + Optional.of(new AccountSecurityCutoff("6", "account-stream", "1")), + Optional.empty()); + + assertThatThrownBy(() -> snapshot(ACCOUNT_ID, TENANT_ID, "1", "1", zeroIssuer, "9", STREAM_KEY)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> snapshot(ACCOUNT_ID, TENANT_ID, "1", "1", nonCanonicalAccount, "9", STREAM_KEY)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> snapshot(ACCOUNT_ID, TENANT_ID, "1", "1", zeroTenant, "9", STREAM_KEY)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> snapshot(ACCOUNT_ID, TENANT_ID, "1", "1", extraGrant, "9", STREAM_KEY)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> snapshot(ACCOUNT_ID, TENANT_ID, "1", "1", presentCutoff, "9", STREAM_KEY)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsNonCanonicalMembershipStreamKey() { + assertThatThrownBy( + () -> + snapshot( + ACCOUNT_ID, + TENANT_ID, + "1", + "1", + completeTuple(), + "9", + STREAM_KEY + "/unexpected")) + .isInstanceOf(IllegalArgumentException.class); + } + + private static AccountMembershipAuthorityEventProducer.NeverJoinedMembershipSnapshot snapshot( + String accountId, + String tenantId, + String membershipVersion, + String membershipAuthorityGeneration, + AuthorityTuple authorityTuple, + String issuanceFence, + String streamKey) { + return new AccountMembershipAuthorityEventProducer.NeverJoinedMembershipSnapshot( + accountId, + tenantId, + membershipVersion, + membershipAuthorityGeneration, + authorityTuple, + issuanceFence, + Instant.parse("2026-09-27T00:00:00Z"), + streamKey); + } + + private static AuthorityTuple completeTuple() { + return new AuthorityTuple( + "4", + "6", + Map.of(TENANT_ID, "8"), + Map.of(TENANT_ID, "1"), + List.of(), + Optional.empty(), + Optional.empty()); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index a94d0254cc..940af35540 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -15,6 +15,7 @@ import ch.qos.logback.core.read.ListAppender; import de.mkammerer.argon2.Argon2; import de.mkammerer.argon2.Argon2Factory; +import java.util.Collection; import java.util.Map; import java.util.Optional; import java.util.UUID; @@ -36,12 +37,14 @@ import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; +import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceipt; import net.firedevops.firemud.accountservice.dto.PasswordResetRequest; import net.firedevops.firemud.accountservice.dto.PlayerBootstrapResult; import net.firedevops.firemud.accountservice.dto.RealmAccessGrantRequest; import net.firedevops.firemud.accountservice.dto.UpdateAccountLoginAuthModesRequest; import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; import net.firedevops.firemud.accountservice.entity.AccountLoginAuthMode; import net.firedevops.firemud.accountservice.entity.AccountRealmAccessGrant; @@ -53,6 +56,8 @@ import net.firedevops.firemud.accountservice.mapper.AccountMapper; import net.firedevops.firemud.accountservice.mapper.ProfileMapper; import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; @@ -60,11 +65,14 @@ import net.firedevops.firemud.accountservice.repository.AccountRealmAccessGrantRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; import net.firedevops.firemud.accountservice.repository.EmailVerificationTokenRepository; import net.firedevops.firemud.accountservice.repository.ExternalAccountRepository; import net.firedevops.firemud.accountservice.repository.PaymentTransactionRepository; import net.firedevops.firemud.accountservice.repository.ProfileRepository; import net.firedevops.firemud.accountservice.repository.SubscriptionRepository; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; import net.firedevops.firemud.accountservice.service.EmailService; import net.firedevops.firemud.accountservice.service.NotificationService; import net.firedevops.firemud.accountservice.service.exception.AccountAlreadyExistsException; @@ -101,13 +109,20 @@ class AccountServiceImplTest { private static final String PLAYABLE_STATE_NAMESPACE_ID_TENANT_8 = "a741a4b8-a2cb-405e-a330-8fbf3dfb841f"; @Mock private AccountRepository accountRepository; + @Mock private AccountAuthorityGenerationRepository accountAuthorityGenerationRepository; @Mock private AccountAuditOutboxRepository accountAuditOutboxRepository; @Mock private AccountConnectScopeRepository accountConnectScopeRepository; @Mock private AccountJoinOperationRepository accountJoinOperationRepository; @Mock private AccountMembershipTransitionReceiptRepository membershipTransitionReceiptRepository; + @Mock private AccountMembershipAuthorityEventProducer membershipAuthorityEventProducer; @Mock private AccountEmailLoginChallengeRepository accountEmailLoginChallengeRepository; @Mock private AccountRealmAccessGrantRepository accountRealmAccessGrantRepository; @Mock private AccountTenantMembershipRepository accountTenantMembershipRepository; + + @Mock + private AccountTenantMembershipRoleSnapshotRepository + accountTenantMembershipRoleSnapshotRepository; + @Mock private ProfileRepository profileRepository; @Mock private ProfileMapper profileMapper; @Mock private NotificationService notificationService; @@ -209,16 +224,45 @@ void setup() { .thenReturn(Optional.empty()); when(mailProperties.getResetUrl()).thenReturn("http://reset/%s"); when(mailProperties.getVerificationUrl()).thenReturn("http://verify/%s"); + when(membershipAuthorityEventProducer.publishNewMembershipChange( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(AccountTenantMembership.class))) + .thenReturn(joinAuthorityCheckpoint()); + when(membershipAuthorityEventProducer.requireNewMembershipBaseline( + org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong())) + .thenReturn(new AccountMembershipAuthorityEventProducer.NewMembershipBaseline(1L, 1L)); + when(membershipAuthorityEventProducer.publishReactivatedMembershipChange( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(AccountTenantMembership.class))) + .thenReturn(joinAuthorityCheckpoint()); + when(membershipAuthorityEventProducer.requireCommittedJoinEvent( + org.mockito.ArgumentMatchers.any())) + .thenReturn(joinAuthorityCheckpoint()); + when(membershipAuthorityEventProducer.requireCurrentMembershipEvent( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.any(AccountTenantMembership.class), + org.mockito.ArgumentMatchers.any(RoleSnapshot.class), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyBoolean())) + .thenReturn(joinAuthorityCheckpoint()); service = new AccountServiceImpl( accountRepository, + accountAuthorityGenerationRepository, accountAuditOutboxRepository, accountConnectScopeRepository, accountJoinOperationRepository, membershipTransitionReceiptRepository, + membershipAuthorityEventProducer, accountEmailLoginChallengeRepository, accountRealmAccessGrantRepository, accountTenantMembershipRepository, + accountTenantMembershipRoleSnapshotRepository, mapper, profileRepository, profileMapper, @@ -243,11 +287,15 @@ void setup() { void createAccountPersistsOnlyGlobalIdentity() { CreateAccountRequest request = new CreateAccountRequest("demo", " DEMO@example.com ", "password"); + UUID accountUuid = UUID.randomUUID(); when(accountRepository.save(org.mockito.ArgumentMatchers.any(Account.class))) .thenAnswer( invocation -> { Account saved = invocation.getArgument(0); saved.setId(1L); + saved.setAccountUuid(accountUuid); + saved.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + saved.setAccountUuidSourceNumericId(1L); return saved; }); @@ -259,6 +307,8 @@ void createAccountPersistsOnlyGlobalIdentity() { org.mockito.ArgumentCaptor.forClass(Account.class); org.mockito.Mockito.verify(accountRepository).save(accountCaptor.capture()); assertEquals("demo@example.com", accountCaptor.getValue().getEmail()); + org.mockito.Mockito.verify(accountAuthorityGenerationRepository) + .initialize(AccountAuthorityGenerationRepository.AuthorityScope.account(accountUuid)); org.mockito.Mockito.verify(accountAuditOutboxRepository) .append( org.mockito.ArgumentMatchers.any(java.util.UUID.class), @@ -270,6 +320,81 @@ void createAccountPersistsOnlyGlobalIdentity() { verifyNoInteractions(profileRepository, accountTenantMembershipRepository); } + @Test + void createAccountInitializesCanonicalAccountAuthorityBeforeRegistrationAudit() { + CreateAccountRequest request = new CreateAccountRequest("demo", "demo@example.com", "password"); + UUID accountUuid = UUID.randomUUID(); + when(accountRepository.save(org.mockito.ArgumentMatchers.any(Account.class))) + .thenAnswer( + invocation -> { + Account saved = invocation.getArgument(0); + saved.setId(1L); + saved.setAccountUuid(accountUuid); + saved.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + saved.setAccountUuidSourceNumericId(1L); + return saved; + }); + + service.createAccount(request); + + org.mockito.InOrder inOrder = + org.mockito.Mockito.inOrder( + accountRepository, accountAuthorityGenerationRepository, accountAuditOutboxRepository); + inOrder.verify(accountRepository).save(org.mockito.ArgumentMatchers.any(Account.class)); + inOrder + .verify(accountAuthorityGenerationRepository) + .initialize(AccountAuthorityGenerationRepository.AuthorityScope.account(accountUuid)); + inOrder + .verify(accountAuditOutboxRepository) + .append( + org.mockito.ArgumentMatchers.any(UUID.class), + org.mockito.ArgumentMatchers.eq("platform"), + org.mockito.ArgumentMatchers.isNull(), + org.mockito.ArgumentMatchers.eq("ACCOUNT_REGISTERED"), + org.mockito.ArgumentMatchers.eq("{\"accountId\":1}")); + } + + @Test + void createAccountFailsClosedWithoutCanonicalIdentityBeforeAuthorityOrAudit() { + CreateAccountRequest request = new CreateAccountRequest("demo", "demo@example.com", "password"); + when(accountRepository.save(org.mockito.ArgumentMatchers.any(Account.class))) + .thenAnswer( + invocation -> { + Account saved = invocation.getArgument(0); + saved.setId(1L); + return saved; + }); + + assertThrows(IllegalStateException.class, () -> service.createAccount(request)); + + verifyNoInteractions(accountAuthorityGenerationRepository, accountAuditOutboxRepository); + } + + @Test + void createAccountDoesNotAppendRegistrationAuditWhenAuthorityInitializationFails() { + CreateAccountRequest request = new CreateAccountRequest("demo", "demo@example.com", "password"); + UUID accountUuid = UUID.randomUUID(); + when(accountRepository.save(org.mockito.ArgumentMatchers.any(Account.class))) + .thenAnswer( + invocation -> { + Account saved = invocation.getArgument(0); + saved.setId(1L); + saved.setAccountUuid(accountUuid); + saved.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + saved.setAccountUuidSourceNumericId(1L); + return saved; + }); + when(accountAuthorityGenerationRepository.initialize( + AccountAuthorityGenerationRepository.AuthorityScope.account(accountUuid))) + .thenThrow(new IllegalStateException("authority init failed")); + + assertThrows(IllegalStateException.class, () -> service.createAccount(request)); + + verify(accountAuthorityGenerationRepository) + .initialize(AccountAuthorityGenerationRepository.AuthorityScope.account(accountUuid)); + verifyNoInteractions(accountAuditOutboxRepository); + } + @Test void createAccountReturnsExplicitConflictForCanonicalIdentityCollision() { CreateAccountRequest request = @@ -373,7 +498,7 @@ void joinPublicProductionCreatesMembershipAndAuditOnceAndReplaysExactReceipt() { assertTrue(first.success()); assertEquals("JOINED", first.outcomeCode()); assertEquals(701L, first.membershipId()); - assertEquals(1L, first.membershipVersion()); + assertEquals(2L, first.membershipVersion()); assertTrue(retried.success()); assertTrue(retried.replayed()); assertTrue(readbackReplay.success()); @@ -394,6 +519,14 @@ void joinPublicProductionCreatesMembershipAndAuditOnceAndReplaysExactReceipt() { false)); org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.times(1)) .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.ArgumentCaptor> roleSnapshotCaptor = + org.mockito.ArgumentCaptor.forClass(Collection.class); + org.mockito.Mockito.verify(accountTenantMembershipRoleSnapshotRepository) + .replace( + org.mockito.ArgumentMatchers.any(AccountTenantMembership.class), + org.mockito.ArgumentMatchers.eq(2L), + roleSnapshotCaptor.capture()); + assertEquals(java.util.List.of("player"), roleSnapshotCaptor.getValue().stream().toList()); org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.times(1)) .bindPolicyEvidence( org.mockito.ArgumentMatchers.eq(requestId), @@ -406,7 +539,7 @@ void joinPublicProductionCreatesMembershipAndAuditOnceAndReplaysExactReceipt() { org.mockito.ArgumentMatchers.eq("COMMITTED"), org.mockito.ArgumentMatchers.eq("JOINED"), org.mockito.ArgumentMatchers.eq(701L), - org.mockito.ArgumentMatchers.eq(1L), + org.mockito.ArgumentMatchers.eq(2L), org.mockito.ArgumentMatchers.eq(1L)); org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) .recordAttemptFailure( @@ -423,7 +556,18 @@ void joinPublicProductionCreatesMembershipAndAuditOnceAndReplaysExactReceipt() { org.mockito.ArgumentMatchers.eq("ACCOUNT_JOINED_PUBLIC_PRODUCTION"), org.mockito.ArgumentMatchers.contains(requestId)); assertEquals("COMMITTED", retainedOperation.get().status()); - + org.mockito.Mockito.verify(membershipAuthorityEventProducer) + .preparePairAuthorityForJoin(11L, 7L); + org.mockito.Mockito.verify(membershipAuthorityEventProducer) + .requireNewMembershipBaseline(11L, 7L); + org.mockito.Mockito.verify(membershipAuthorityEventProducer) + .publishNewMembershipChange( + org.mockito.ArgumentMatchers.eq(11L), + org.mockito.ArgumentMatchers.eq(7L), + org.mockito.ArgumentMatchers.eq(requestId), + org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verify(membershipAuthorityEventProducer, org.mockito.Mockito.times(2)) + .requireCommittedJoinEvent(org.mockito.ArgumentMatchers.eq(committedOperation)); AuthenticationException changedDigest = assertThrows( AuthenticationException.class, @@ -432,6 +576,84 @@ void joinPublicProductionCreatesMembershipAndAuditOnceAndReplaysExactReceipt() { bootstrap.bootstrapToken(), new JoinPublicProductionRequest("different-scope", requestId))); assertEquals("IDEMPOTENCY_CONFLICT", changedDigest.getCode()); + + when(accountTenantMembershipRoleSnapshotRepository.findForUpdate(11L, 7L, 701L, 2L)) + .thenReturn(Optional.of(new RoleSnapshot(11L, 7L, 701L, 2L, java.util.List.of("player")))); + when(membershipTransitionReceiptRepository.findLatestReceipt(11L, 7L)) + .thenReturn( + Optional.of( + new MembershipTransitionReceipt( + "membership-transition:account-11:tenant-7", + 1L, + UUID.randomUUID(), + "sha256:" + "0".repeat(64), + "ACCOUNT_MEMBERSHIP_TRANSITION_RECEIPT_V1", + "MEMBERSHIP_JOINED", + requestId, + 701L))); + JoinPublicProductionResult alreadyActive = + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest(connectScopeId, "join-attempt-2")); + + assertTrue(alreadyActive.success()); + assertEquals("ALREADY_ACTIVE", alreadyActive.outcomeCode()); + org.mockito.Mockito.verify(membershipAuthorityEventProducer) + .requireCurrentMembershipEvent( + 11L, + 7L, + joinedMembership.get(), + new RoleSnapshot(11L, 7L, 701L, 2L, java.util.List.of("player")), + requestId, + false); + } + + @Test + void committedJoinReplayClassifiesReadbackDependencyFailureAsUnavailable() { + AtomicReference retainedOperation = + new AtomicReference<>(); + CommittedJoinFixture fixture = + prepareCommittedJoinOperation(retainedOperation, "join-readback-db-1"); + when(membershipAuthorityEventProducer.requireCommittedJoinEvent( + org.mockito.ArgumentMatchers.any())) + .thenThrow( + new org.springframework.transaction.CannotCreateTransactionException( + "authority readback transaction unavailable")); + + JoinPublicProductionResult replayed = + service.joinPublicProduction( + fixture.bootstrapToken(), + new JoinPublicProductionRequest(fixture.connectScopeId(), "join-readback-db-1")); + + assertFalse(replayed.success()); + assertEquals("AUTH_UNAVAILABLE", replayed.outcomeCode()); + org.mockito.ArgumentCaptor operationCaptor = + org.mockito.ArgumentCaptor.forClass(AccountJoinOperationRepository.JoinOperation.class); + verify(membershipAuthorityEventProducer).requireCommittedJoinEvent(operationCaptor.capture()); + assertEquals(retainedOperation.get(), operationCaptor.getValue()); + } + + @Test + void committedJoinReplayClassifiesReachableMalformedReadbackAsSessionRevoked() { + AtomicReference retainedOperation = + new AtomicReference<>(); + CommittedJoinFixture fixture = + prepareCommittedJoinOperation(retainedOperation, "join-readback-invalid-1"); + when(membershipAuthorityEventProducer.requireCommittedJoinEvent( + org.mockito.ArgumentMatchers.any())) + .thenThrow(new IllegalStateException("committed authority event is missing")); + + JoinPublicProductionResult replayed = + service.joinPublicProduction( + fixture.bootstrapToken(), + new JoinPublicProductionRequest(fixture.connectScopeId(), "join-readback-invalid-1")); + + assertFalse(replayed.success()); + assertEquals("AUTH_SESSION_REVOKED", replayed.outcomeCode()); + org.mockito.ArgumentCaptor operationCaptor = + org.mockito.ArgumentCaptor.forClass(AccountJoinOperationRepository.JoinOperation.class); + verify(membershipAuthorityEventProducer).requireCommittedJoinEvent(operationCaptor.capture()); + assertEquals(retainedOperation.get(), operationCaptor.getValue()); } @Test @@ -613,6 +835,7 @@ void committedJoinRetryRejectsChangedPolicyWithoutMutatingStoredOutcomeOrMembers service.joinPublicProduction(bootstrap.bootstrapToken(), request); assertTrue(joined.success()); + assertEquals(2L, joined.membershipVersion()); assertFalse(retry.success()); assertFalse(retry.replayed()); assertEquals("IDEMPOTENCY_CONFLICT", retry.outcomeCode()); @@ -622,7 +845,7 @@ void committedJoinRetryRejectsChangedPolicyWithoutMutatingStoredOutcomeOrMembers assertEquals(5L, retainedOperation.get().entitlementVersion()); assertEquals(membership, joinedMembership.get()); assertEquals("ACTIVE", membership.getLifecycleState()); - assertEquals(1L, membership.getMembershipVersion()); + assertEquals(2L, membership.getMembershipVersion()); when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of()); JoinPublicProductionResult unavailableAuthorityRetry = service.joinPublicProduction(bootstrap.bootstrapToken(), request); @@ -631,6 +854,7 @@ void committedJoinRetryRejectsChangedPolicyWithoutMutatingStoredOutcomeOrMembers assertEquals("AUTH_UNAVAILABLE", unavailableAuthorityRetry.outcomeCode()); assertEquals(committedOperation, retainedOperation.get()); assertEquals(membership, joinedMembership.get()); + assertEquals(joined.membershipVersion(), membership.getMembershipVersion()); org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.times(1)) .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); org.mockito.Mockito.verify(accountAuditOutboxRepository, org.mockito.Mockito.times(1)) @@ -1135,6 +1359,127 @@ void unboundFailedJoinReplaysOnlyAfterCurrentScopeAndAuthorityChecks() { .findByTenantIdForUpdate(7L); } + @Test + void pairAuthorityPreparationFailureRetainsRetryablePolicyIndependentJoinIntent() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + org.mockito.Mockito.doThrow(new IllegalStateException("pair authority storage unavailable")) + .doNothing() + .when(membershipAuthorityEventProducer) + .preparePairAuthorityForJoin(11L, 7L); + + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + active.setEntitlementVersion(1L); + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of(active)); + AtomicReference joinedMembership = new AtomicReference<>(); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenAnswer(invocation -> Optional.ofNullable(joinedMembership.get())); + when(accountTenantMembershipRepository.save(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + AccountTenantMembership membership = invocation.getArgument(0); + membership.setId(701L); + joinedMembership.set(membership); + return membership; + }); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + JoinPublicProductionRequest request = + new JoinPublicProductionRequest(connectScopeId, "join-pair-authority-retry-1"); + + AuthenticationException unavailable = + assertThrows( + AuthenticationException.class, + () -> service.joinPublicProduction(bootstrap.bootstrapToken(), request)); + + assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); + assertEquals("PENDING", retainedOperation.get().status()); + assertEquals(null, retainedOperation.get().outcome()); + assertNotNull(retainedOperation.get().intentDigest()); + assertEquals(null, retainedOperation.get().requestDigest()); + assertEquals(null, retainedOperation.get().requestDigestVersion()); + assertEquals(null, retainedOperation.get().allowPublicJoin()); + assertEquals(null, retainedOperation.get().entitlementVersion()); + assertEquals("NOT_EVALUATED", retainedOperation.get().entitlementAuthorityAvailability()); + assertEquals("AUTH_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); + assertEquals("NOT_EVALUATED", retainedOperation.get().lastAttemptAuthorityAvailability()); + assertEquals(null, joinedMembership.get()); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.never()) + .findByTenantIdForUpdate(7L); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verify( + accountTenantMembershipRoleSnapshotRepository, org.mockito.Mockito.never()) + .replace( + org.mockito.ArgumentMatchers.any(AccountTenantMembership.class), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyCollection()); + org.mockito.Mockito.verify(membershipAuthorityEventProducer, org.mockito.Mockito.never()) + .requireNewMembershipBaseline(11L, 7L); + org.mockito.Mockito.verify(membershipAuthorityEventProducer, org.mockito.Mockito.never()) + .publishNewMembershipChange( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verify(membershipTransitionReceiptRepository, org.mockito.Mockito.never()) + .appendTransition( + org.mockito.ArgumentMatchers.any(AccountTenantMembership.class), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); + + JoinPublicProductionResult retried = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + + assertTrue(retried.success()); + assertFalse(retried.replayed()); + assertEquals("JOINED", retried.outcomeCode()); + assertEquals("COMMITTED", retainedOperation.get().status()); + assertEquals("AVAILABLE", retainedOperation.get().entitlementAuthorityAvailability()); + assertEquals(1L, retainedOperation.get().entitlementVersion()); + assertNotNull(retainedOperation.get().requestDigest()); + org.mockito.Mockito.verify(membershipAuthorityEventProducer, org.mockito.Mockito.times(2)) + .preparePairAuthorityForJoin(11L, 7L); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.times(1)) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verify(membershipAuthorityEventProducer) + .publishNewMembershipChange( + org.mockito.ArgumentMatchers.eq(11L), + org.mockito.ArgumentMatchers.eq(7L), + org.mockito.ArgumentMatchers.eq(request.requestId()), + org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verify(membershipTransitionReceiptRepository) + .appendTransition( + org.mockito.ArgumentMatchers.any(AccountTenantMembership.class), + org.mockito.ArgumentMatchers.eq("MEMBERSHIP_JOINED"), + org.mockito.ArgumentMatchers.eq(request.requestId())); + org.mockito.Mockito.verify(accountAuditOutboxRepository) + .append( + org.mockito.ArgumentMatchers.any(UUID.class), + org.mockito.ArgumentMatchers.eq("tenant"), + org.mockito.ArgumentMatchers.eq(7L), + org.mockito.ArgumentMatchers.eq("ACCOUNT_JOINED_PUBLIC_PRODUCTION"), + org.mockito.ArgumentMatchers.contains(request.requestId())); + } + @Test void joinIntentCommitsSeparatelyWhenPolicyTransactionRollsBack() { Account account = new Account(); @@ -1171,7 +1516,7 @@ void joinIntentCommitsSeparatelyWhenPolicyTransactionRollsBack() { assertNotNull(retainedOperation.get().intentDigest()); assertEquals(null, retainedOperation.get().requestDigest()); assertEquals("AUTH_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); - org.mockito.Mockito.verify(transactionManager, org.mockito.Mockito.times(2)) + org.mockito.Mockito.verify(transactionManager, org.mockito.Mockito.times(3)) .commit(org.mockito.ArgumentMatchers.any()); org.mockito.Mockito.verify(transactionManager, org.mockito.Mockito.times(1)) .rollback(org.mockito.ArgumentMatchers.any()); @@ -1303,6 +1648,7 @@ void expiredPersistedPendingJoinRemainsPendingWithoutAuthorityOrMembershipReads( org.mockito.ArgumentMatchers.nullable(Long.class)); verifyNoInteractions( subscriptionRepository, accountTenantMembershipRepository, accountAuditOutboxRepository); + verifyNoInteractions(membershipAuthorityEventProducer); } @ParameterizedTest @@ -1738,6 +2084,51 @@ void quarantinedLegacyMembershipIsNeverRestoredByPublicJoin() { org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); } + private CommittedJoinFixture prepareCommittedJoinOperation( + AtomicReference retainedOperation, + String requestId) { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + AtomicReference joinedMembership = new AtomicReference<>(); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenAnswer(invocation -> Optional.ofNullable(joinedMembership.get())); + when(accountTenantMembershipRepository.save(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + AccountTenantMembership membership = invocation.getArgument(0); + membership.setId(701L); + joinedMembership.set(membership); + return membership; + }); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + AtomicReference retainedScope = new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + JoinPublicProductionResult joined = + service.joinPublicProduction( + bootstrap.bootstrapToken(), new JoinPublicProductionRequest(connectScopeId, requestId)); + assertTrue(joined.success()); + assertEquals("JOINED", joined.outcomeCode()); + assertEquals("COMMITTED", retainedOperation.get().status()); + return new CommittedJoinFixture(bootstrap.bootstrapToken(), connectScopeId); + } + + private record CommittedJoinFixture(String bootstrapToken, String connectScopeId) {} + private void retainJoinEvidence( AtomicReference retainedScope, AtomicReference retainedOperation) { @@ -1751,9 +2142,21 @@ private void retainJoinEvidence( when(accountConnectScopeRepository.find(org.mockito.ArgumentMatchers.anyString())) .thenAnswer(invocation -> Optional.ofNullable(retainedScope.get())); when(accountJoinOperationRepository.find(org.mockito.ArgumentMatchers.anyString())) - .thenAnswer(invocation -> Optional.ofNullable(retainedOperation.get())); + .thenAnswer( + invocation -> { + var current = retainedOperation.get(); + return current != null && current.requestId().equals(invocation.getArgument(0)) + ? Optional.of(current) + : Optional.empty(); + }); when(accountJoinOperationRepository.findForUpdate(org.mockito.ArgumentMatchers.anyString())) - .thenAnswer(invocation -> Optional.ofNullable(retainedOperation.get())); + .thenAnswer( + invocation -> { + var current = retainedOperation.get(); + return current != null && current.requestId().equals(invocation.getArgument(0)) + ? Optional.of(current) + : Optional.empty(); + }); org.mockito.Mockito.doAnswer( invocation -> { String requestId = invocation.getArgument(0); @@ -2260,6 +2663,62 @@ void authenticateForGameplayReturnsTokenWhenPasswordMatches() { verifyNoInteractions(accountTenantMembershipRepository); } + @Test + void allAccountMintPathsUseCanonicalIssuerAndRetainTheirClaims() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setEmail("demo@example.com"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); + + AuthenticationResult controlUi = service.authenticate("demo", "password"); + AuthenticationResult gameplayDelegation = + service.authenticateForGameplay("demo@example.com", "password"); + assertCanonicalIssuerAndClaims(controlUi.authToken(), "control-ui", 11L); + assertEquals(java.util.List.of(), parseClaims(controlUi.authToken()).get("globalRoles")); + assertCanonicalIssuerAndClaims(gameplayDelegation.authToken(), "account-service", 11L); + assertEquals( + java.util.List.of(), parseClaims(gameplayDelegation.authToken()).get("globalRoles")); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + assertCanonicalIssuerAndClaims(bootstrap.bootstrapToken(), "player-bootstrap", 11L); + + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + var connectScopeClaims = parseClaims(connectScopeId); + assertCanonicalIssuerAndClaims(connectScopeId, "bootstrap-connect-scope", 11L); + assertEquals("4c4b57d8-e3a2-48fe-9977-e7df0fdce901", connectScopeClaims.get("realmId")); + assertEquals(7L, connectScopeClaims.get("tenantId", Long.class)); + + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + ConnectTokenResult connectToken = + service.issueConnectToken( + bootstrap.bootstrapToken(), new ConnectTokenRequest(connectScopeId, "issuer-proof")); + assertCanonicalIssuerAndClaims(connectToken.connectToken(), "gameplay-connect", 11L); + assertEquals(7L, parseClaims(connectToken.connectToken()).get("tenantId", Long.class)); + assertEquals(17L, parseClaims(connectToken.connectToken()).get("pointerVersion", Long.class)); + + Account otpAccount = new Account(); + otpAccount.setId(12L); + otpAccount.setEmail("otp@example.com"); + otpAccount.setLoginAuthModes("EMAIL_OTP"); + var challenge = new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); + challenge.setAccountId(12L); + challenge.setCodeHash(hash("123456")); + challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); + when(accountRepository.findByEmail("otp@example.com")).thenReturn(Optional.of(otpAccount)); + when(accountEmailLoginChallengeRepository.findByAccountId(12L)) + .thenReturn(Optional.of(challenge)); + AuthenticationResult otpDelegation = service.verifyEmailLoginOtp("otp@example.com", "123456"); + assertCanonicalIssuerAndClaims(otpDelegation.authToken(), "account-service", 12L); + assertEquals(java.util.List.of(), parseClaims(otpDelegation.authToken()).get("globalRoles")); + } + @Test void issuePlayerBootstrapReturnsShortLivedToken() { Account account = new Account(); @@ -2410,13 +2869,16 @@ void listBootstrapWorldsDoesNotMaskUnexpectedJwtParserRuntimeFailure() { service = new AccountServiceImpl( accountRepository, + accountAuthorityGenerationRepository, accountAuditOutboxRepository, accountConnectScopeRepository, accountJoinOperationRepository, membershipTransitionReceiptRepository, + membershipAuthorityEventProducer, accountEmailLoginChallengeRepository, accountRealmAccessGrantRepository, accountTenantMembershipRepository, + accountTenantMembershipRoleSnapshotRepository, Mappers.getMapper(AccountMapper.class), profileRepository, profileMapper, @@ -6729,6 +7191,27 @@ void updateLoginAuthModesFailsClosedBeforeReadingOrPersistingAccount() { org.mockito.Mockito.verifyNoInteractions(accountRepository); } + private void assertCanonicalIssuerAndClaims( + String token, String expectedAudience, long expectedAccountId) { + var claims = parseClaims(token); + assertEquals("firemud-account-service", claims.getIssuer()); + assertEquals(expectedAudience, claims.getAudience().iterator().next()); + assertEquals(expectedAccountId, claims.get("accountId", Long.class)); + assertNotNull(claims.get("jti")); + } + + private io.jsonwebtoken.Claims parseClaims(String token) { + return new JwtUtil(JWT_SECRET, 3600000L).parseToken(token).getPayload(); + } + + private static Checkpoint joinAuthorityCheckpoint() { + return new Checkpoint( + "account:auth-authority:v1:membership/account-a/tenant-a", + 1L, + "event-1", + "sha256:" + "0".repeat(64)); + } + private static RuntimeException unexpectedEntitlementFailure(String failureType) { return switch (failureType) { case "illegal-state" -> new IllegalStateException("subscription mapping failed"); diff --git a/services/common-platform-core/build.gradle.kts b/services/common-platform-core/build.gradle.kts index 53f7284080..7e67ecc121 100644 --- a/services/common-platform-core/build.gradle.kts +++ b/services/common-platform-core/build.gradle.kts @@ -10,6 +10,7 @@ dependencies { compileOnly(libs.lombok) implementation("com.fasterxml.jackson.core:jackson-databind") + implementation(libs.java.json.canonicalization) implementation(libs.micrometer.core) implementation(libs.opentelemetry.api) implementation(libs.opentelemetry.sdk) diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/MembershipAuthorityEventV1Codec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/MembershipAuthorityEventV1Codec.java new file mode 100644 index 0000000000..88258a365e --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/MembershipAuthorityEventV1Codec.java @@ -0,0 +1,798 @@ +package net.firedevops.firemud.common.account.authority; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.TreeMap; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; + +/** Strict codec for committed Account membership authority events. */ +public final class MembershipAuthorityEventV1Codec { + public static final String SCHEMA_VERSION = "account-auth-authority-event/v1"; + public static final String EVENT_TYPE = "MEMBERSHIP_CHANGED"; + public static final String EVENT_STREAM_PREFIX = "account:auth-authority:v1:"; + + private static final String EVENT_SCOPE_PREFIX = "membership/"; + private static final Set PREIMAGE_FIELDS = + Set.of( + "schemaVersion", + "eventType", + "eventId", + "requestId", + "outboxStreamKey", + "outboxSequence", + "sourceScope", + "accountId", + "tenantId", + "membershipExists", + "membershipLifecycleState", + "membershipVersion", + "membershipAuthorityGeneration", + "authorityTuple", + "issuanceFence", + "roles", + "gameplayAdmissionAllowed", + "callerBoundAuthorityInvalidated"); + private static final Set WIRE_FIELDS; + private static final Set AUTHORITY_TUPLE_REQUIRED_FIELDS = + Set.of( + "issuerAuthGeneration", + "accountAuthorityGeneration", + "tenantAuthorityGeneration", + "membershipAuthorityGeneration", + "privateRealmGrantVersions"); + private static final Set AUTHORITY_TUPLE_OPTIONAL_FIELDS = + Set.of("accountSecurityCutoff", "tenantBillingCutoff"); + private static final Set GRANT_FIELDS = + Set.of("tenantId", "worldSlug", "realmSlug", "playtestLifecycleId", "grantVersion"); + private static final Set ACCOUNT_CUTOFF_FIELDS = + Set.of("accountAuthorityGeneration", "outboxStreamKey", "outboxSequence"); + private static final Set TENANT_CUTOFF_FIELDS = + Set.of( + "tenantAuthorityGeneration", + "tenantBillingSequence", + "outboxStreamKey", + "outboxSequence"); + private static final Set TENANT_ROLES = + Set.of("player", "designer", "tenantAdmin", "moderator"); + 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 Pattern SLUG_PATTERN = Pattern.compile("[a-z0-9]+(?:-[a-z0-9]+)*"); + private static final Pattern POSITIVE_DECIMAL_PATTERN = Pattern.compile("[1-9][0-9]*"); + private static final Pattern DIGEST_PATTERN = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final ObjectMapper JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + + static { + var wireFields = new java.util.HashSet<>(PREIMAGE_FIELDS); + wireFields.add("eventDigest"); + WIRE_FIELDS = Set.copyOf(wireFields); + } + + private MembershipAuthorityEventV1Codec() {} + + /** Validates a preimage and returns immutable evidence sealed with its canonical digest. */ + public static MembershipEvent seal(Map preimage) { + Objects.requireNonNull(preimage, "preimage must not be null"); + JsonNode tree = JSON.valueToTree(preimage); + if (!(tree instanceof ObjectNode object)) { + throw invalid("event", "must be a JSON object"); + } + requireExactFields(object, PREIMAGE_FIELDS, Set.of(), "event preimage"); + validatePreimage(object); + String digest = digest(object); + ObjectNode wire = object.deepCopy(); + wire.put("eventDigest", digest); + return toEvidence(wire, digest, canonicalJson(wire)); + } + + /** Validates and verifies one wire event from JSON, rejecting duplicate properties. */ + public static MembershipEvent verify(String wireJson) { + Objects.requireNonNull(wireJson, "wireJson must not be null"); + final JsonNode tree; + try { + // JCS parsing rejects duplicate JSON object properties before Jackson builds a tree. + Rfc8785CanonicalJson.canonicalizeUtf8(wireJson); + tree = JSON.readTree(wireJson); + } catch (IOException exception) { + throw new IllegalArgumentException("event JSON is malformed", exception); + } + if (!(tree instanceof ObjectNode wire)) { + throw invalid("event", "must be a JSON object"); + } + return verifyWireNode(wire); + } + + /** Validates and verifies one wire event supplied as JSON-compatible map data. */ + public static MembershipEvent verify(Map wireEvent) { + Objects.requireNonNull(wireEvent, "wireEvent must not be null"); + JsonNode tree = JSON.valueToTree(wireEvent); + if (!(tree instanceof ObjectNode wire)) { + throw invalid("event", "must be a JSON object"); + } + return verifyWireNode(wire); + } + + private static MembershipEvent verifyWireNode(ObjectNode wire) { + requireExactFields(wire, WIRE_FIELDS, Set.of(), "event"); + String suppliedDigest = requireText(wire, "eventDigest", "event"); + if (!DIGEST_PATTERN.matcher(suppliedDigest).matches()) { + throw invalid("eventDigest", "must be lowercase sha256: followed by 64 lowercase hex digits"); + } + ObjectNode preimage = wire.deepCopy(); + preimage.remove("eventDigest"); + validatePreimage(preimage); + String expectedDigest = digest(preimage); + if (!MessageDigest.isEqual( + suppliedDigest.getBytes(StandardCharsets.US_ASCII), + expectedDigest.getBytes(StandardCharsets.US_ASCII))) { + throw invalid("eventDigest", "does not match the canonical event preimage"); + } + return toEvidence(wire, suppliedDigest, canonicalJson(wire)); + } + + private static void validatePreimage(ObjectNode event) { + requireExactFields(event, PREIMAGE_FIELDS, Set.of(), "event preimage"); + requireExactText(event, "schemaVersion", SCHEMA_VERSION, "event"); + requireExactText(event, "eventType", EVENT_TYPE, "event"); + requireNonEmptyText(event, "eventId", "event"); + requireNonEmptyText(event, "requestId", "event"); + + String accountId = requireUuid(event, "accountId", "event"); + String tenantId = requireUuid(event, "tenantId", "event"); + String sourceScope = EVENT_SCOPE_PREFIX + accountId + "/" + tenantId; + String streamKey = EVENT_STREAM_PREFIX + sourceScope; + requireExactText(event, "sourceScope", sourceScope, "event"); + requireExactText(event, "outboxStreamKey", streamKey, "event"); + + requirePositiveDecimal(event, "outboxSequence", "event"); + validateMembershipVersion(event.get("membershipVersion"), tenantId); + String membershipGeneration = + requirePositiveDecimal(event, "membershipAuthorityGeneration", "event"); + requirePositiveDecimal(event, "issuanceFence", "event"); + + if (!event.path("membershipExists").isBoolean() + || !event.path("membershipExists").booleanValue()) { + throw invalid("membershipExists", "must be exactly true for a membership-change event"); + } + String lifecycle = requireText(event, "membershipLifecycleState", "event"); + if (!lifecycle.equals("ACTIVE") && !lifecycle.equals("INACTIVE")) { + throw invalid("membershipLifecycleState", "must be ACTIVE or INACTIVE"); + } + boolean admission = requireBoolean(event, "gameplayAdmissionAllowed", "event"); + if (lifecycle.equals("INACTIVE") && admission) { + throw invalid("gameplayAdmissionAllowed", "must be false for INACTIVE membership"); + } + requireBoolean(event, "callerBoundAuthorityInvalidated", "event"); + + validateRoles(event.get("roles")); + validateAuthorityTuple(event.get("authorityTuple"), accountId, tenantId, membershipGeneration); + } + + private static void validateRoles(JsonNode rolesNode) { + if (rolesNode == null || !rolesNode.isArray()) { + throw invalid("roles", "must be a required array"); + } + String previous = null; + for (JsonNode roleNode : rolesNode) { + if (!roleNode.isTextual()) { + throw invalid("roles", "entries must be canonical tenant-role strings"); + } + String role = roleNode.textValue(); + if (!TENANT_ROLES.contains(role)) { + throw invalid("roles", "contains an undeclared tenant role"); + } + if (previous != null && compareCodePoints(previous, role) >= 0) { + throw invalid( + "roles", "must be sorted by Unicode code-point order and contain no duplicates"); + } + previous = role; + } + } + + private static void validateAuthorityTuple( + JsonNode tupleNode, + String eventAccountId, + String eventTenantId, + String eventMembershipGeneration) { + if (!(tupleNode instanceof ObjectNode tuple)) { + throw invalid("authorityTuple", "must be an object"); + } + requireExactFields( + tuple, AUTHORITY_TUPLE_REQUIRED_FIELDS, AUTHORITY_TUPLE_OPTIONAL_FIELDS, "authorityTuple"); + requirePositiveDecimal(tuple, "issuerAuthGeneration", "authorityTuple"); + requirePositiveDecimal(tuple, "accountAuthorityGeneration", "authorityTuple"); + + Map tenantGenerations = + validateGenerationMap( + tuple.get("tenantAuthorityGeneration"), "authorityTuple.tenantAuthorityGeneration"); + if (tenantGenerations.size() != 1 || !tenantGenerations.containsKey(eventTenantId)) { + throw invalid( + "authorityTuple.tenantAuthorityGeneration", + "must contain exactly the event tenantId key"); + } + + Map membershipGenerations = + validateGenerationMap( + tuple.get("membershipAuthorityGeneration"), + "authorityTuple.membershipAuthorityGeneration"); + if (!membershipGenerations.equals(Map.of(eventTenantId, eventMembershipGeneration))) { + throw invalid( + "authorityTuple.membershipAuthorityGeneration", + "must contain exactly the event tenantId and match membershipAuthorityGeneration"); + } + + validatePrivateRealmGrants(tuple.get("privateRealmGrantVersions"), eventTenantId); + if (tuple.has("accountSecurityCutoff")) { + validateAccountSecurityCutoff(tuple.get("accountSecurityCutoff"), eventAccountId); + } + if (tuple.has("tenantBillingCutoff")) { + validateTenantBillingCutoff(tuple.get("tenantBillingCutoff"), eventTenantId); + } + } + + private static Map validateGenerationMap(JsonNode mapNode, String path) { + if (!(mapNode instanceof ObjectNode object)) { + throw invalid(path, "must be an object keyed by canonical tenant UUID"); + } + Map values = new TreeMap<>(); + object + .fields() + .forEachRemaining( + entry -> { + requireUuidKey(entry.getKey(), path); + JsonNode value = entry.getValue(); + if (value == null || !value.isTextual() || !isPositiveDecimal(value.textValue())) { + throw invalid( + path + "." + entry.getKey(), "must be a positive canonical decimal string"); + } + values.put(entry.getKey(), value.textValue()); + }); + return Collections.unmodifiableMap(values); + } + + private static void validateMembershipVersion( + JsonNode membershipVersionNode, String eventTenantId) { + if (!(membershipVersionNode instanceof ObjectNode membershipVersion)) { + throw invalid("event.membershipVersion", "must be a one-tenant version map"); + } + if (membershipVersion.size() != 1 || !membershipVersion.has(eventTenantId)) { + throw invalid("event.membershipVersion", "must contain exactly the event tenantId key"); + } + requirePositiveDecimal(membershipVersion, eventTenantId, "event.membershipVersion"); + } + + private static void validatePrivateRealmGrants(JsonNode grantsNode, String eventTenantId) { + if (grantsNode == null || !grantsNode.isArray()) { + throw invalid("authorityTuple.privateRealmGrantVersions", "must be a required array"); + } + GrantIdentity previous = null; + for (JsonNode grantNode : grantsNode) { + if (!(grantNode instanceof ObjectNode grant)) { + throw invalid("authorityTuple.privateRealmGrantVersions", "entries must be objects"); + } + requireExactFields(grant, GRANT_FIELDS, Set.of(), "privateRealmGrantVersions entry"); + String tenantId = requireUuid(grant, "tenantId", "privateRealmGrantVersions entry"); + if (!tenantId.equals(eventTenantId)) { + throw invalid( + "authorityTuple.privateRealmGrantVersions", + "entries must be scoped to the event tenantId"); + } + String worldSlug = requireSlug(grant, "worldSlug", "privateRealmGrantVersions entry"); + String realmSlug = requireSlug(grant, "realmSlug", "privateRealmGrantVersions entry"); + String lifecycleId = + requireUuid(grant, "playtestLifecycleId", "privateRealmGrantVersions entry"); + requirePositiveDecimal(grant, "grantVersion", "privateRealmGrantVersions entry"); + GrantIdentity identity = new GrantIdentity(tenantId, worldSlug, realmSlug, lifecycleId); + if (previous != null && compareGrantIdentity(previous, identity) >= 0) { + throw invalid( + "authorityTuple.privateRealmGrantVersions", + "entries must be lexicographically sorted by grant identity and contain no duplicates"); + } + previous = identity; + } + } + + private static void validateAccountSecurityCutoff(JsonNode cutoffNode, String eventAccountId) { + if (!(cutoffNode instanceof ObjectNode cutoff)) { + throw invalid("authorityTuple.accountSecurityCutoff", "must be an object when applicable"); + } + requireExactFields(cutoff, ACCOUNT_CUTOFF_FIELDS, Set.of(), "accountSecurityCutoff"); + requirePositiveDecimal(cutoff, "accountAuthorityGeneration", "accountSecurityCutoff"); + requirePositiveDecimal(cutoff, "outboxSequence", "accountSecurityCutoff"); + requireExactText( + cutoff, + "outboxStreamKey", + EVENT_STREAM_PREFIX + "account/" + eventAccountId, + "accountSecurityCutoff"); + } + + private static void validateTenantBillingCutoff(JsonNode cutoffNode, String eventTenantId) { + if (!(cutoffNode instanceof ObjectNode cutoffs) || cutoffs.isEmpty()) { + throw invalid( + "authorityTuple.tenantBillingCutoff", "must be a non-empty tenant map when applicable"); + } + if (cutoffs.size() != 1 || !cutoffs.has(eventTenantId)) { + throw invalid( + "authorityTuple.tenantBillingCutoff", "must contain exactly the event tenantId key"); + } + cutoffs + .fields() + .forEachRemaining( + entry -> { + String tenantId = entry.getKey(); + requireUuidKey(tenantId, "authorityTuple.tenantBillingCutoff"); + if (!(entry.getValue() instanceof ObjectNode cutoff)) { + throw invalid( + "authorityTuple.tenantBillingCutoff." + tenantId, "must be an object"); + } + requireExactFields( + cutoff, TENANT_CUTOFF_FIELDS, Set.of(), "tenantBillingCutoff entry"); + requirePositiveDecimal( + cutoff, "tenantAuthorityGeneration", "tenantBillingCutoff entry"); + requirePositiveDecimal(cutoff, "tenantBillingSequence", "tenantBillingCutoff entry"); + requirePositiveDecimal(cutoff, "outboxSequence", "tenantBillingCutoff entry"); + requireExactText( + cutoff, + "outboxStreamKey", + EVENT_STREAM_PREFIX + "tenant/" + tenantId, + "tenantBillingCutoff entry"); + }); + } + + private static MembershipEvent toEvidence(ObjectNode wire, String digest, String canonicalJson) { + ObjectNode tupleNode = (ObjectNode) wire.get("authorityTuple"); + Map tenantGenerations = + readStringMap(tupleNode.get("tenantAuthorityGeneration")); + Map membershipGenerations = + readStringMap(tupleNode.get("membershipAuthorityGeneration")); + Map membershipVersions = readStringMap(wire.get("membershipVersion")); + + List grants = new ArrayList<>(); + for (JsonNode grant : tupleNode.get("privateRealmGrantVersions")) { + grants.add( + new PrivateRealmGrantVersion( + grant.get("tenantId").textValue(), + grant.get("worldSlug").textValue(), + grant.get("realmSlug").textValue(), + grant.get("playtestLifecycleId").textValue(), + grant.get("grantVersion").textValue())); + } + + Optional accountCutoff = Optional.empty(); + if (tupleNode.has("accountSecurityCutoff")) { + JsonNode cutoff = tupleNode.get("accountSecurityCutoff"); + accountCutoff = + Optional.of( + new AccountSecurityCutoff( + cutoff.get("accountAuthorityGeneration").textValue(), + cutoff.get("outboxStreamKey").textValue(), + cutoff.get("outboxSequence").textValue())); + } + + Optional> tenantCutoffs = Optional.empty(); + if (tupleNode.has("tenantBillingCutoff")) { + Map values = new TreeMap<>(); + tupleNode + .get("tenantBillingCutoff") + .fields() + .forEachRemaining( + entry -> { + JsonNode cutoff = entry.getValue(); + values.put( + entry.getKey(), + new TenantBillingCutoff( + cutoff.get("tenantAuthorityGeneration").textValue(), + cutoff.get("tenantBillingSequence").textValue(), + cutoff.get("outboxStreamKey").textValue(), + cutoff.get("outboxSequence").textValue())); + }); + tenantCutoffs = Optional.of(immutableMap(values)); + } + + AuthorityTuple authorityTuple = + new AuthorityTuple( + tupleNode.get("issuerAuthGeneration").textValue(), + tupleNode.get("accountAuthorityGeneration").textValue(), + tenantGenerations, + membershipGenerations, + grants, + accountCutoff, + tenantCutoffs); + List roles = new ArrayList<>(); + wire.get("roles").forEach(role -> roles.add(role.textValue())); + return new MembershipEvent( + wire.get("schemaVersion").textValue(), + wire.get("eventType").textValue(), + wire.get("eventId").textValue(), + wire.get("requestId").textValue(), + wire.get("outboxStreamKey").textValue(), + wire.get("outboxSequence").textValue(), + wire.get("sourceScope").textValue(), + wire.get("accountId").textValue(), + wire.get("tenantId").textValue(), + wire.get("membershipLifecycleState").textValue(), + membershipVersions, + wire.get("membershipAuthorityGeneration").textValue(), + authorityTuple, + wire.get("issuanceFence").textValue(), + roles, + wire.get("gameplayAdmissionAllowed").booleanValue(), + wire.get("callerBoundAuthorityInvalidated").booleanValue(), + digest, + canonicalJson); + } + + private static Map readStringMap(JsonNode mapNode) { + Map values = new TreeMap<>(); + mapNode + .fields() + .forEachRemaining(entry -> values.put(entry.getKey(), entry.getValue().textValue())); + return immutableMap(values); + } + + private static String digest(ObjectNode preimage) { + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(preimage)); + byte[] hash = MessageDigest.getInstance("SHA-256").digest(canonical); + StringBuilder hex = new StringBuilder(64); + for (byte item : hash) { + hex.append(Character.forDigit((item >>> 4) & 0x0f, 16)); + hex.append(Character.forDigit(item & 0x0f, 16)); + } + return "sha256:" + hex; + } catch (IOException | NoSuchAlgorithmException exception) { + throw new IllegalStateException( + "Unable to compute canonical membership event digest", exception); + } + } + + private static String canonicalJson(ObjectNode node) { + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(node)), + StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new IllegalArgumentException("event cannot be serialized as RFC 8785 JSON", exception); + } + } + + private static void requireExactFields( + ObjectNode object, Set required, Set optional, String path) { + for (String field : required) { + if (!object.has(field)) { + throw invalid(path + "." + field, "is required"); + } + } + object + .fieldNames() + .forEachRemaining( + field -> { + if (!required.contains(field) && !optional.contains(field)) { + throw invalid(path + "." + field, "is not declared by this schema"); + } + }); + } + + private static String requireExactText( + ObjectNode object, String field, String expected, String path) { + String value = requireText(object, field, path); + if (!value.equals(expected)) { + throw invalid(path + "." + field, "must equal " + expected); + } + return value; + } + + private static String requireNonEmptyText(ObjectNode object, String field, String path) { + String value = requireText(object, field, path); + if (value.isBlank() || value.codePointCount(0, value.length()) > 512) { + throw invalid(path + "." + field, "must be nonblank and at most 512 characters"); + } + return value; + } + + private static String requireText(ObjectNode object, String field, String path) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual()) { + throw invalid(path + "." + field, "must be a string"); + } + return value.textValue(); + } + + private static String requireUuid(ObjectNode object, String field, String path) { + String value = requireText(object, field, path); + if (!isUuid(value)) { + throw invalid(path + "." + field, "must be a canonical lowercase UUID string"); + } + return value; + } + + private static void requireUuidKey(String value, String path) { + if (!isUuid(value)) { + throw invalid(path + "." + value, "map key must be a canonical lowercase UUID"); + } + } + + private static boolean isUuid(String value) { + return UUID_PATTERN.matcher(value).matches(); + } + + private static String requireSlug(ObjectNode object, String field, String path) { + String value = requireText(object, field, path); + if (value.getBytes(StandardCharsets.UTF_8).length > 120 + || !SLUG_PATTERN.matcher(value).matches()) { + throw invalid(path + "." + field, "must be a canonical lowercase ASCII slug of 1-120 bytes"); + } + return value; + } + + private static String requirePositiveDecimal(ObjectNode object, String field, String path) { + String value = requireText(object, field, path); + if (!isPositiveDecimal(value)) { + throw invalid(path + "." + field, "must be a positive canonical unsigned decimal string"); + } + return value; + } + + private static boolean isPositiveDecimal(String value) { + return POSITIVE_DECIMAL_PATTERN.matcher(value).matches(); + } + + private static boolean requireBoolean(ObjectNode object, String field, String path) { + JsonNode value = object.get(field); + if (value == null || !value.isBoolean()) { + throw invalid(path + "." + field, "must be a boolean"); + } + return value.booleanValue(); + } + + private static Map immutableMap(Map values) { + return Collections.unmodifiableMap(new TreeMap<>(values)); + } + + private static int compareGrantIdentity(GrantIdentity left, GrantIdentity right) { + int compare = compareCodePoints(left.tenantId(), right.tenantId()); + if (compare == 0) { + compare = compareCodePoints(left.worldSlug(), right.worldSlug()); + } + if (compare == 0) { + compare = compareCodePoints(left.realmSlug(), right.realmSlug()); + } + if (compare == 0) { + compare = compareCodePoints(left.playtestLifecycleId(), right.playtestLifecycleId()); + } + return compare; + } + + private static int compareCodePoints(String left, String right) { + int leftIndex = 0; + int rightIndex = 0; + while (leftIndex < left.length() && rightIndex < right.length()) { + int leftPoint = left.codePointAt(leftIndex); + int rightPoint = right.codePointAt(rightIndex); + if (leftPoint != rightPoint) { + return Integer.compare(leftPoint, rightPoint); + } + leftIndex += Character.charCount(leftPoint); + rightIndex += Character.charCount(rightPoint); + } + return Integer.compare(left.length() - leftIndex, right.length() - rightIndex); + } + + private static IllegalArgumentException invalid(String path, String message) { + return new IllegalArgumentException(path + " " + message); + } + + private record GrantIdentity( + String tenantId, String worldSlug, String realmSlug, String playtestLifecycleId) {} + + /** Immutable verified or producer-sealed event evidence. */ + public static final class MembershipEvent { + private final String schemaVersion; + private final String eventType; + private final String eventId; + private final String requestId; + private final String outboxStreamKey; + private final String outboxSequence; + private final String sourceScope; + private final String accountId; + private final String tenantId; + private final String membershipLifecycleState; + private final Map membershipVersion; + private final String membershipAuthorityGeneration; + private final AuthorityTuple authorityTuple; + private final String issuanceFence; + private final List roles; + private final boolean gameplayAdmissionAllowed; + private final boolean callerBoundAuthorityInvalidated; + private final String eventDigest; + private final String canonicalJson; + + private MembershipEvent( + String schemaVersion, + String eventType, + String eventId, + String requestId, + String outboxStreamKey, + String outboxSequence, + String sourceScope, + String accountId, + String tenantId, + String membershipLifecycleState, + Map membershipVersion, + String membershipAuthorityGeneration, + AuthorityTuple authorityTuple, + String issuanceFence, + List roles, + boolean gameplayAdmissionAllowed, + boolean callerBoundAuthorityInvalidated, + String eventDigest, + String canonicalJson) { + this.schemaVersion = schemaVersion; + this.eventType = eventType; + this.eventId = eventId; + this.requestId = requestId; + this.outboxStreamKey = outboxStreamKey; + this.outboxSequence = outboxSequence; + this.sourceScope = sourceScope; + this.accountId = accountId; + this.tenantId = tenantId; + this.membershipLifecycleState = membershipLifecycleState; + this.membershipVersion = immutableMap(membershipVersion); + this.membershipAuthorityGeneration = membershipAuthorityGeneration; + this.authorityTuple = authorityTuple; + this.issuanceFence = issuanceFence; + this.roles = List.copyOf(roles); + this.gameplayAdmissionAllowed = gameplayAdmissionAllowed; + this.callerBoundAuthorityInvalidated = callerBoundAuthorityInvalidated; + this.eventDigest = eventDigest; + this.canonicalJson = canonicalJson; + } + + public String schemaVersion() { + return schemaVersion; + } + + public String eventType() { + return eventType; + } + + public String eventId() { + return eventId; + } + + public String requestId() { + return requestId; + } + + public String outboxStreamKey() { + return outboxStreamKey; + } + + public String outboxSequence() { + return outboxSequence; + } + + public String sourceScope() { + return sourceScope; + } + + public String accountId() { + return accountId; + } + + public String tenantId() { + return tenantId; + } + + public String membershipLifecycleState() { + return membershipLifecycleState; + } + + public Map membershipVersion() { + return immutableMap(membershipVersion); + } + + public String membershipAuthorityGeneration() { + return membershipAuthorityGeneration; + } + + public AuthorityTuple authorityTuple() { + return authorityTuple; + } + + public String issuanceFence() { + return issuanceFence; + } + + public List roles() { + return roles; + } + + public boolean gameplayAdmissionAllowed() { + return gameplayAdmissionAllowed; + } + + public boolean callerBoundAuthorityInvalidated() { + return callerBoundAuthorityInvalidated; + } + + public String eventDigest() { + return eventDigest; + } + + /** Returns the canonical complete wire event. */ + public String canonicalJson() { + return canonicalJson; + } + + /** Returns a caller-owned copy of the canonical complete wire event bytes. */ + public byte[] canonicalJsonUtf8() { + return canonicalJson.getBytes(StandardCharsets.UTF_8); + } + } + + /** Immutable authority tuple carried by a membership event. */ + public record AuthorityTuple( + String issuerAuthGeneration, + String accountAuthorityGeneration, + Map tenantAuthorityGeneration, + Map membershipAuthorityGeneration, + List privateRealmGrantVersions, + Optional accountSecurityCutoff, + Optional> tenantBillingCutoff) { + public AuthorityTuple { + tenantAuthorityGeneration = immutableMap(tenantAuthorityGeneration); + membershipAuthorityGeneration = immutableMap(membershipAuthorityGeneration); + privateRealmGrantVersions = List.copyOf(privateRealmGrantVersions); + accountSecurityCutoff = Objects.requireNonNull(accountSecurityCutoff); + tenantBillingCutoff = tenantBillingCutoff.map(MembershipAuthorityEventV1Codec::immutableMap); + } + + @Override + public Map tenantAuthorityGeneration() { + return immutableMap(tenantAuthorityGeneration); + } + + @Override + public Map membershipAuthorityGeneration() { + return immutableMap(membershipAuthorityGeneration); + } + } + + /** Immutable lifecycle-bound private-realm grant version. */ + public record PrivateRealmGrantVersion( + String tenantId, + String worldSlug, + String realmSlug, + String playtestLifecycleId, + String grantVersion) {} + + /** Immutable Account security cutoff checkpoint. */ + public record AccountSecurityCutoff( + String accountAuthorityGeneration, String outboxStreamKey, String outboxSequence) {} + + /** Immutable tenant billing cutoff checkpoint. */ + public record TenantBillingCutoff( + String tenantAuthorityGeneration, + String tenantBillingSequence, + String outboxStreamKey, + String outboxSequence) {} +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/json/Rfc8785CanonicalJson.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/json/Rfc8785CanonicalJson.java new file mode 100644 index 0000000000..5f6d40cf9f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/json/Rfc8785CanonicalJson.java @@ -0,0 +1,16 @@ +package net.firedevops.firemud.common.json; + +import java.io.IOException; +import java.util.Objects; +import org.erdtman.jcs.JsonCanonicalizer; + +/** RFC 8785 JSON Canonicalization Scheme support shared across service boundaries. */ +public final class Rfc8785CanonicalJson { + private Rfc8785CanonicalJson() {} + + /** Returns the RFC 8785 canonical UTF-8 bytes for a JSON object or array. */ + public static byte[] canonicalizeUtf8(String json) throws IOException { + Objects.requireNonNull(json, "json must not be null"); + return new JsonCanonicalizer(json).getEncodedUTF8(); + } +} diff --git a/services/common-platform-core/src/main/resources/net/firedevops/firemud/common/account/authority/account-auth-authority-event-v1-vectors.json b/services/common-platform-core/src/main/resources/net/firedevops/firemud/common/account/authority/account-auth-authority-event-v1-vectors.json new file mode 100644 index 0000000000..0d8383ac09 --- /dev/null +++ b/services/common-platform-core/src/main/resources/net/firedevops/firemud/common/account/authority/account-auth-authority-event-v1-vectors.json @@ -0,0 +1,235 @@ +{ + "schemaVersion": "account-auth-authority-event-vectors/v1", + "validEvents": [ + { + "name": "active-membership-with-cutoffs-and-grant", + "event": { + "schemaVersion": "account-auth-authority-event/v1", + "eventType": "MEMBERSHIP_CHANGED", + "eventId": "event-membership-001", + "requestId": "request-membership-001", + "outboxStreamKey": "account:auth-authority:v1:membership/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a/018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f", + "outboxSequence": "7", + "sourceScope": "membership/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a/018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f", + "accountId": "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "tenantId": "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f", + "membershipExists": true, + "membershipLifecycleState": "ACTIVE", + "membershipVersion": { + "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f": "9007199254740993" + }, + "membershipAuthorityGeneration": "12", + "authorityTuple": { + "issuerAuthGeneration": "5", + "accountAuthorityGeneration": "8", + "tenantAuthorityGeneration": { + "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f": "13" + }, + "membershipAuthorityGeneration": { + "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f": "12" + }, + "privateRealmGrantVersions": [ + { + "tenantId": "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f", + "worldSlug": "alpha", + "realmSlug": "builders", + "playtestLifecycleId": "018f8f0a-3c8d-7b35-ad26-7b0c9d8e6f4a", + "grantVersion": "3" + } + ], + "accountSecurityCutoff": { + "accountAuthorityGeneration": "8", + "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "outboxSequence": "4" + }, + "tenantBillingCutoff": { + "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f": { + "tenantAuthorityGeneration": "13", + "tenantBillingSequence": "5", + "outboxStreamKey": "account:auth-authority:v1:tenant/018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f", + "outboxSequence": "9" + } + } + }, + "issuanceFence": "9007199254740995", + "roles": ["designer", "player"], + "gameplayAdmissionAllowed": true, + "callerBoundAuthorityInvalidated": true, + "eventDigest": "sha256:c8f05f154c6a2a2983789936a65082a7906704d06451111c0d35f77438901da6" + } + }, + { + "name": "inactive-membership-with-optional-cutoffs-omitted", + "event": { + "schemaVersion": "account-auth-authority-event/v1", + "eventType": "MEMBERSHIP_CHANGED", + "eventId": "event-membership-002", + "requestId": "request-membership-002", + "outboxStreamKey": "account:auth-authority:v1:membership/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a/018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f", + "outboxSequence": "8", + "sourceScope": "membership/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a/018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f", + "accountId": "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "tenantId": "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f", + "membershipExists": true, + "membershipLifecycleState": "INACTIVE", + "membershipVersion": { + "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f": "43" + }, + "membershipAuthorityGeneration": "13", + "authorityTuple": { + "issuerAuthGeneration": "5", + "accountAuthorityGeneration": "8", + "tenantAuthorityGeneration": { + "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f": "13" + }, + "membershipAuthorityGeneration": { + "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f": "13" + }, + "privateRealmGrantVersions": [] + }, + "issuanceFence": "28", + "roles": [], + "gameplayAdmissionAllowed": false, + "callerBoundAuthorityInvalidated": false, + "eventDigest": "sha256:d91160853c4c86fc4f08ce8e5201087fcf2e91aacd2072e9a24080653b63ba5d" + } + }, + { + "name": "large-counter-values", + "event": { + "schemaVersion": "account-auth-authority-event/v1", + "eventType": "MEMBERSHIP_CHANGED", + "eventId": "event-membership-large", + "requestId": "request-membership-large", + "outboxStreamKey": "account:auth-authority:v1:membership/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a/018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f", + "outboxSequence": "9007199254740993", + "sourceScope": "membership/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a/018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f", + "accountId": "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "tenantId": "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f", + "membershipExists": true, + "membershipLifecycleState": "ACTIVE", + "membershipVersion": { + "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f": "9007199254740993" + }, + "membershipAuthorityGeneration": "9007199254740993", + "authorityTuple": { + "issuerAuthGeneration": "9007199254740993", + "accountAuthorityGeneration": "9007199254740993", + "tenantAuthorityGeneration": { + "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f": "9007199254740993" + }, + "membershipAuthorityGeneration": { + "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f": "9007199254740993" + }, + "privateRealmGrantVersions": [ + { + "tenantId": "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f", + "worldSlug": "alpha", + "realmSlug": "builders", + "playtestLifecycleId": "018f8f0a-3c8d-7b35-ad26-7b0c9d8e6f4a", + "grantVersion": "9007199254740993" + } + ], + "accountSecurityCutoff": { + "accountAuthorityGeneration": "9007199254740993", + "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "outboxSequence": "9007199254740993" + }, + "tenantBillingCutoff": { + "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f": { + "tenantAuthorityGeneration": "9007199254740993", + "tenantBillingSequence": "9007199254740993", + "outboxStreamKey": "account:auth-authority:v1:tenant/018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f", + "outboxSequence": "9007199254740993" + } + } + }, + "issuanceFence": "9007199254740993", + "roles": ["player"], + "gameplayAdmissionAllowed": true, + "callerBoundAuthorityInvalidated": true, + "eventDigest": "sha256:1474381be42037f4ab9f88ac50c82eb3b649bf59993f5228a2a7b06a83252c86" + } + } + ], + "changedFieldMutations": [ + {"name": "schema-version", "path": "/schemaVersion", "replacement": "account-auth-authority-event/v2"}, + {"name": "event-type", "path": "/eventType", "replacement": "MEMBERSHIP_DELETED"}, + {"name": "event-id", "path": "/eventId", "replacement": "event-membership-changed"}, + {"name": "request-id", "path": "/requestId", "replacement": "request-membership-changed"}, + {"name": "stream-key", "path": "/outboxStreamKey", "replacement": "account:auth-authority:v1:membership/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a/018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e50"}, + {"name": "sequence", "path": "/outboxSequence", "replacement": "8"}, + {"name": "source-scope", "path": "/sourceScope", "replacement": "membership/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a/018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e50"}, + {"name": "account-id", "path": "/accountId", "replacement": "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0b"}, + {"name": "tenant-id", "path": "/tenantId", "replacement": "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e50"}, + {"name": "membership-exists", "path": "/membershipExists", "replacement": false}, + {"name": "lifecycle", "path": "/membershipLifecycleState", "replacement": "INACTIVE"}, + {"name": "membership-version", "path": "/membershipVersion/018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f", "replacement": "9007199254740994"}, + {"name": "membership-authority-generation", "path": "/membershipAuthorityGeneration", "replacement": "13"}, + {"name": "issuer-generation", "path": "/authorityTuple/issuerAuthGeneration", "replacement": "6"}, + {"name": "account-generation", "path": "/authorityTuple/accountAuthorityGeneration", "replacement": "9"}, + {"name": "tenant-generation", "path": "/authorityTuple/tenantAuthorityGeneration/018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f", "replacement": "14"}, + {"name": "membership-generation-map", "path": "/authorityTuple/membershipAuthorityGeneration/018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f", "replacement": "13"}, + {"name": "grant-version", "path": "/authorityTuple/privateRealmGrantVersions/0/grantVersion", "replacement": "4"}, + {"name": "grant-scope", "path": "/authorityTuple/privateRealmGrantVersions/0/worldSlug", "replacement": "beta"}, + {"name": "account-cutoff-generation", "path": "/authorityTuple/accountSecurityCutoff/accountAuthorityGeneration", "replacement": "9"}, + {"name": "account-cutoff-sequence", "path": "/authorityTuple/accountSecurityCutoff/outboxSequence", "replacement": "5"}, + {"name": "tenant-cutoff-generation", "path": "/authorityTuple/tenantBillingCutoff/018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f/tenantAuthorityGeneration", "replacement": "14"}, + {"name": "tenant-billing-sequence", "path": "/authorityTuple/tenantBillingCutoff/018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f/tenantBillingSequence", "replacement": "6"}, + {"name": "tenant-cutoff-sequence", "path": "/authorityTuple/tenantBillingCutoff/018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f/outboxSequence", "replacement": "10"}, + {"name": "issuance-fence", "path": "/issuanceFence", "replacement": "9007199254740996"}, + {"name": "roles", "path": "/roles/0", "replacement": "moderator"}, + {"name": "admission", "path": "/gameplayAdmissionAllowed", "replacement": false}, + {"name": "caller-bound-invalidation", "path": "/callerBoundAuthorityInvalidated", "replacement": false} + ], + "invalidMutations": [ + {"name": "unsupported-schema", "op": "replace", "path": "/schemaVersion", "value": "account-auth-authority-event/v2"}, + {"name": "unsupported-event-type", "op": "replace", "path": "/eventType", "value": "MEMBERSHIP_DELETED"}, + {"name": "missing-event-digest", "op": "remove", "path": "/eventDigest"}, + {"name": "undeclared-top-level-field", "op": "add", "path": "/unexpected", "value": true}, + {"name": "missing-required-roles", "op": "remove", "path": "/roles"}, + {"name": "null-optional-account-cutoff", "op": "replace", "path": "/authorityTuple/accountSecurityCutoff", "value": null}, + {"name": "null-optional-tenant-cutoff", "op": "replace", "path": "/authorityTuple/tenantBillingCutoff", "value": null}, + {"name": "empty-present-tenant-cutoff", "op": "replace", "path": "/authorityTuple/tenantBillingCutoff", "value": {}}, + {"name": "json-number-counter", "op": "replace", "path": "/outboxSequence", "value": 7}, + {"name": "membership-version-scalar", "op": "replace", "path": "/membershipVersion", "value": "43"}, + {"name": "membership-version-empty-map", "op": "replace", "path": "/membershipVersion", "value": {}}, + {"name": "membership-version-extra-tenant", "op": "add", "path": "/membershipVersion/018f8f0a-3c8d-7b35-ad26-7b0c9d8e6f4a", "value": "1"}, + {"name": "membership-version-wrong-tenant", "op": "replace", "path": "/membershipVersion", "value": {"018f8f0a-3c8d-7b35-ad26-7b0c9d8e6f4a": "1"}}, + {"name": "membership-version-leading-zero", "op": "replace", "path": "/membershipVersion/018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f", "value": "01"}, + {"name": "membership-version-zero", "op": "replace", "path": "/membershipVersion/018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f", "value": "0"}, + {"name": "membership-version-json-number", "op": "replace", "path": "/membershipVersion/018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f", "value": 7}, + {"name": "zero-sequence", "op": "replace", "path": "/outboxSequence", "value": "0"}, + {"name": "mismatched-membership-generation", "op": "replace", "path": "/authorityTuple/membershipAuthorityGeneration/018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f", "value": "99"}, + {"name": "extra-tenant-generation-scope", "op": "add", "path": "/authorityTuple/tenantAuthorityGeneration/018f8f0a-3c8d-7b35-ad26-7b0c9d8e6f4a", "value": "1"}, + {"name": "extra-tenant-cutoff-scope", "op": "add", "path": "/authorityTuple/tenantBillingCutoff/018f8f0a-3c8d-7b35-ad26-7b0c9d8e6f4a", "value": { + "tenantAuthorityGeneration": "1", + "tenantBillingSequence": "1", + "outboxStreamKey": "account:auth-authority:v1:tenant/018f8f0a-3c8d-7b35-ad26-7b0c9d8e6f4a", + "outboxSequence": "1" + }}, + {"name": "foreign-tenant-grant", "op": "replace", "path": "/authorityTuple/privateRealmGrantVersions/0/tenantId", "value": "018f8f0a-3c8d-7b35-ad26-7b0c9d8e6f4a"}, + {"name": "extra-tuple-field", "op": "add", "path": "/authorityTuple/unknown", "value": "x"}, + {"name": "missing-required-tuple-field", "op": "remove", "path": "/authorityTuple/issuerAuthGeneration"}, + {"name": "extra-account-cutoff-field", "op": "add", "path": "/authorityTuple/accountSecurityCutoff/unknown", "value": "x"}, + {"name": "missing-account-cutoff-sequence", "op": "remove", "path": "/authorityTuple/accountSecurityCutoff/outboxSequence"}, + {"name": "wrong-account-cutoff-stream", "op": "replace", "path": "/authorityTuple/accountSecurityCutoff/outboxStreamKey", "value": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0b"}, + {"name": "missing-tenant-cutoff-sequence", "op": "remove", "path": "/authorityTuple/tenantBillingCutoff/018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f/outboxSequence"}, + {"name": "incomplete-grant-entry", "op": "remove", "path": "/authorityTuple/privateRealmGrantVersions/0/playtestLifecycleId"}, + {"name": "unsorted-roles", "op": "replace", "path": "/roles", "value": ["player", "designer"]}, + {"name": "duplicate-roles", "op": "replace", "path": "/roles", "value": ["designer", "designer"]}, + {"name": "global-role-in-membership", "op": "replace", "path": "/roles", "value": ["support"]}, + {"name": "inactive-admission", "op": "replace", "path": "/membershipLifecycleState", "value": "INACTIVE"}, + {"name": "uppercase-account-uuid", "op": "replace", "path": "/accountId", "value": "018F8F0A-1A6B-7B13-8D04-5F6E7D8C9B0A"}, + {"name": "noncanonical-uuid", "op": "replace", "path": "/tenantId", "value": "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5"}, + {"name": "unsorted-grants", "op": "replace", "path": "/authorityTuple/privateRealmGrantVersions", "value": [ + {"tenantId": "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f", "worldSlug": "zeta", "realmSlug": "builders", "playtestLifecycleId": "018f8f0a-3c8d-7b35-ad26-7b0c9d8e6f4a", "grantVersion": "4"}, + {"tenantId": "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f", "worldSlug": "alpha", "realmSlug": "builders", "playtestLifecycleId": "018f8f0a-3c8d-7b35-ad26-7b0c9d8e6f4a", "grantVersion": "3"} + ]}, + {"name": "duplicate-grant-identity", "op": "replace", "path": "/authorityTuple/privateRealmGrantVersions", "value": [ + {"tenantId": "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f", "worldSlug": "alpha", "realmSlug": "builders", "playtestLifecycleId": "018f8f0a-3c8d-7b35-ad26-7b0c9d8e6f4a", "grantVersion": "3"}, + {"tenantId": "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f", "worldSlug": "alpha", "realmSlug": "builders", "playtestLifecycleId": "018f8f0a-3c8d-7b35-ad26-7b0c9d8e6f4a", "grantVersion": "4"} + ]}, + {"name": "invalid-digest", "op": "replace", "path": "/eventDigest", "value": "sha256:1111111111111111111111111111111111111111111111111111111111111111"} + ] +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/MembershipAuthorityEventV1CodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/MembershipAuthorityEventV1CodecTest.java new file mode 100644 index 0000000000..29ca3b7ae7 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/MembershipAuthorityEventV1CodecTest.java @@ -0,0 +1,202 @@ +package net.firedevops.firemud.common.account.authority; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +class MembershipAuthorityEventV1CodecTest { + private static final String VECTOR_RESOURCE = + "/net/firedevops/firemud/common/account/authority/" + + "account-auth-authority-event-v1-vectors.json"; + private static final ObjectMapper JSON = new ObjectMapper(); + private static JsonNode vectors; + + @BeforeAll + static void loadVectors() throws IOException { + try (var stream = + MembershipAuthorityEventV1CodecTest.class.getResourceAsStream(VECTOR_RESOURCE)) { + if (stream == null) { + throw new IOException("Missing shared event vectors: " + VECTOR_RESOURCE); + } + vectors = JSON.readTree(stream); + } + } + + @Test + void sharedVectorsVerifyAndSealCanonicalEvents() throws Exception { + assertThat(vectors.path("schemaVersion").asText()) + .isEqualTo("account-auth-authority-event-vectors/v1"); + var digestMismatches = new ArrayList(); + for (JsonNode vector : vectors.path("validEvents")) { + ObjectNode wireEvent = (ObjectNode) vector.path("event").deepCopy(); + Map preimage = + JSON.convertValue(wireEvent, new TypeReference>() {}); + preimage.remove("eventDigest"); + MembershipEvent sealed = MembershipAuthorityEventV1Codec.seal(preimage); + if (!sealed.eventDigest().equals(wireEvent.path("eventDigest").asText())) { + digestMismatches.add(vector.path("name").asText() + "=" + sealed.eventDigest()); + } + wireEvent.put("eventDigest", sealed.eventDigest()); + MembershipEvent verified = MembershipAuthorityEventV1Codec.verify(wireEvent.toString()); + assertThat(verified.membershipVersion()) + .isEqualTo( + Map.of( + verified.tenantId(), + wireEvent.path("membershipVersion").path(verified.tenantId()).asText())); + assertThat(verified.canonicalJsonUtf8()) + .isEqualTo(Rfc8785CanonicalJson.canonicalizeUtf8(wireEvent.toString())); + assertThat(sealed.eventDigest()).isEqualTo(verified.eventDigest()); + assertThat(sealed.canonicalJson()).isEqualTo(verified.canonicalJson()); + } + assertThat(digestMismatches).isEmpty(); + } + + @Test + void changedDeclaredFieldsChangeTheDigestAndCannotReuseTheOriginalDigest() throws Exception { + ObjectNode baseline = (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); + String originalDigest = baseline.path("eventDigest").asText(); + String baselinePreimageDigest = preimageDigest(baseline); + + for (JsonNode mutation : vectors.path("changedFieldMutations")) { + ObjectNode changed = baseline.deepCopy(); + set(changed, mutation.path("path").asText(), mutation.get("replacement")); + assertThat(preimageDigest(changed)) + .as(mutation.path("name").asText()) + .isNotEqualTo(baselinePreimageDigest); + assertThat(changed.path("eventDigest").asText()).isEqualTo(originalDigest); + assertThatThrownBy(() -> MembershipAuthorityEventV1Codec.verify(changed.toString())) + .as(mutation.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void malformedAndNoncanonicalVectorsAreRejected() { + ObjectNode baseline = (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); + for (JsonNode mutation : vectors.path("invalidMutations")) { + ObjectNode changed = baseline.deepCopy(); + String operation = mutation.path("op").asText(); + String path = mutation.path("path").asText(); + if (operation.equals("remove")) { + remove(changed, path); + } else if (operation.equals("replace") || operation.equals("add")) { + set(changed, path, mutation.get("value")); + } else { + throw new IllegalArgumentException("Unknown vector operation: " + operation); + } + assertThatThrownBy(() -> MembershipAuthorityEventV1Codec.verify(changed.toString())) + .as(mutation.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void duplicatePropertiesAreRejectedBeforeJacksonTreeValidation() { + String duplicatePropertyJson = + "{\"schemaVersion\":\"wrong\",\"schemaVersion\":\"wrong-again\"}"; + assertThatThrownBy(() -> MembershipAuthorityEventV1Codec.verify(duplicatePropertyJson)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("event JSON is malformed"); + } + + @Test + void eventAndRequestIdsMustBeNonblankAndBounded() { + ObjectNode blankId = (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); + blankId.put("eventId", " \t"); + assertThatThrownBy(() -> MembershipAuthorityEventV1Codec.verify(blankId.toString())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("nonblank"); + + ObjectNode longRequestId = + (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); + longRequestId.put("requestId", "x".repeat(513)); + assertThatThrownBy(() -> MembershipAuthorityEventV1Codec.verify(longRequestId.toString())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("512 characters"); + } + + @Test + void returnedEvidenceIsImmutableAndByteArraysAreCallerOwned() { + JsonNode wireEvent = vectors.path("validEvents").get(0).path("event"); + MembershipEvent event = MembershipAuthorityEventV1Codec.verify(wireEvent.toString()); + byte[] bytes = event.canonicalJsonUtf8(); + bytes[0] = (byte) 'x'; + + assertThat(event.canonicalJsonUtf8()[0]).isNotEqualTo((byte) 'x'); + assertThatThrownBy(() -> event.roles().add("moderator")) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> event.authorityTuple().membershipAuthorityGeneration().put("x", "1")) + .isInstanceOf(UnsupportedOperationException.class); + assertThat(event.membershipVersion()) + .isEqualTo( + Map.of( + event.tenantId(), + wireEvent.path("membershipVersion").path(event.tenantId()).asText())); + assertThatThrownBy(() -> event.membershipVersion().put(event.tenantId(), "2")) + .isInstanceOf(UnsupportedOperationException.class); + assertThat(event.membershipAuthorityGeneration()) + .isEqualTo(event.authorityTuple().membershipAuthorityGeneration().get(event.tenantId())); + } + + private static String preimageDigest(ObjectNode wireEvent) throws Exception { + ObjectNode preimage = wireEvent.deepCopy(); + preimage.remove("eventDigest"); + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(preimage)); + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } + + private static void set(ObjectNode root, String pointer, JsonNode value) { + String[] parts = pointer.substring(1).split("/"); + JsonNode parent = root; + for (int index = 0; index < parts.length - 1; index++) { + parent = child(parent, parts[index]); + } + String leaf = parts[parts.length - 1]; + if (parent instanceof ObjectNode object) { + object.set(leaf, value.deepCopy()); + } else if (parent.isArray()) { + ((com.fasterxml.jackson.databind.node.ArrayNode) parent) + .set(Integer.parseInt(leaf), value.deepCopy()); + } else { + throw new IllegalArgumentException("Mutation parent is not a JSON container: " + pointer); + } + } + + private static void remove(ObjectNode root, String pointer) { + String[] parts = pointer.substring(1).split("/"); + JsonNode parent = root; + for (int index = 0; index < parts.length - 1; index++) { + parent = child(parent, parts[index]); + } + String leaf = parts[parts.length - 1]; + if (parent instanceof ObjectNode object) { + object.remove(leaf); + } else if (parent.isArray()) { + ((com.fasterxml.jackson.databind.node.ArrayNode) parent).remove(Integer.parseInt(leaf)); + } else { + throw new IllegalArgumentException("Mutation parent is not a JSON container: " + pointer); + } + } + + private static JsonNode child(JsonNode parent, String part) { + if (parent.isArray()) { + return parent.get(Integer.parseInt(part)); + } + return parent.path(part); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/json/Rfc8785CanonicalJsonTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/json/Rfc8785CanonicalJsonTest.java new file mode 100644 index 0000000000..ec498185de --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/json/Rfc8785CanonicalJsonTest.java @@ -0,0 +1,79 @@ +package net.firedevops.firemud.common.json; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import org.junit.jupiter.api.Test; + +class Rfc8785CanonicalJsonTest { + @Test + void sortsObjectKeysByUtf16CodeUnitsAndPreservesArrayOrder() throws Exception { + String input = + """ + [ + 56, + { + "d": true, + "10": null, + "1": [] + } + ] + """; + + assertThat(Rfc8785CanonicalJson.canonicalizeUtf8(input)) + .isEqualTo("[56,{\"1\":[],\"10\":null,\"d\":true}]".getBytes(StandardCharsets.UTF_8)); + } + + @Test + void sortsUnicodeObjectKeysByRawUtf16CodeUnits() throws Exception { + String input = + """ + { + "\\u20ac": "Euro Sign", + "\\r": "Carriage Return", + "\\u000a": "Newline", + "1": "One", + "\\u0080": "Control\\u007f", + "\\ud83d\\ude02": "Smiley", + "\\u00f6": "Latin Small Letter O With Diaeresis", + "\\ufb33": "Hebrew Letter Dalet With Dagesh", + "": "Browser Challenge" + } + """; + String expected = + "{\"\\n\":\"Newline\",\"\\r\":\"Carriage Return\",\"1\":\"One\"," + + "\"\":\"Browser Challenge\",\"\u0080\":\"Control\u007f\"," + + "\"\u00f6\":\"Latin Small Letter O With Diaeresis\",\"\u20ac\":\"Euro Sign\"," + + "\"\ud83d\ude02\":\"Smiley\",\"\ufb33\":\"Hebrew Letter Dalet With Dagesh\"}"; + + assertThat(Rfc8785CanonicalJson.canonicalizeUtf8(input)) + .isEqualTo(expected.getBytes(StandardCharsets.UTF_8)); + } + + @Test + void preservesUnicodeCodePointsWithoutNormalization() throws Exception { + String input = "{\"decomposed\":\"e\\u0301\",\"composed\":\"\\u00e9\"}"; + String expected = "{\"composed\":\"\u00e9\",\"decomposed\":\"e\u0301\"}"; + + assertThat(Rfc8785CanonicalJson.canonicalizeUtf8(input)) + .isEqualTo(expected.getBytes(StandardCharsets.UTF_8)); + } + + @Test + void rejectsDuplicateObjectProperties() { + assertThatThrownBy(() -> Rfc8785CanonicalJson.canonicalizeUtf8("{\"a\":1,\"a\":2}")) + .isInstanceOf(java.io.IOException.class) + .hasMessageContaining("Duplicate property: a"); + } + + @Test + void rendersNumbersUsingJcsEcmascriptRules() throws Exception { + String input = + "{\"numbers\":[333333333.33333329,1E30,4.50,2e-3,0.000000000000000000000000001]}"; + String expected = "{\"numbers\":[333333333.3333333,1e+30,4.5,0.002,1e-27]}"; + + assertThat(Rfc8785CanonicalJson.canonicalizeUtf8(input)) + .isEqualTo(expected.getBytes(StandardCharsets.UTF_8)); + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContextSignature.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContextSignature.java new file mode 100644 index 0000000000..e2789a7de4 --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContextSignature.java @@ -0,0 +1,297 @@ +package net.firedevops.firemud.common.security; + +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.Signature; +import java.util.Base64; +import java.util.Map; + +/** + * Signs and verifies the Gateway-to-Game Session connect-context envelope. + * + *

This is a compact JWS envelope, not an Account JWT. The payload is opaque to this class: + * callers supply and receive the exact UTF-8 payload bytes, while receiving services validate the + * payload's semantic fields. + */ +public final class GatewayConnectContextSignature { + public static final String ALGORITHM = "EdDSA"; + public static final String KEY_ALGORITHM = "Ed25519"; + public static final String TYPE = "firemud-gateway-connect-context+jws"; + + /** Maximum payload size accepted by this bounded transport envelope. */ + public static final int MAX_PAYLOAD_BYTES = 16 * 1024; + + /** Maximum compact envelope size in UTF-8 bytes. */ + public static final int MAX_ENVELOPE_BYTES = 32 * 1024; + + /** Maximum key identifier length. */ + public static final int MAX_KID_LENGTH = 128; + + /** Gateway key rotation permits one current and one previous verification key. */ + public static final int MAX_VERIFICATION_KEYS = 2; + + private static final String HEADER_PREFIX = "{\"alg\":\"" + ALGORITHM + "\",\"kid\":\""; + private static final String HEADER_SUFFIX = "\",\"typ\":\"" + TYPE + "\"}"; + + private GatewayConnectContextSignature() {} + + /** + * Signs the exact payload bytes and returns a canonical compact JWS envelope. + * + * @param payload exact payload bytes (normally the UTF-8 serialization produced by the caller) + * @param kid bounded, non-blank Gateway signing-key identifier + * @param signingKey Ed25519 private key from the Gateway signing-key namespace + */ + public static String sign(byte[] payload, String kid, PrivateKey signingKey) { + requirePayload(payload); + requireKid(kid); + requireKey(signingKey, "signing key", PrivateKey.class); + + String protectedHeader = canonicalProtectedHeader(kid); + String protectedSegment = encodeBase64Url(protectedHeader.getBytes(StandardCharsets.US_ASCII)); + String payloadSegment = encodeBase64Url(payload); + byte[] signingInput = + (protectedSegment + "." + payloadSegment).getBytes(StandardCharsets.US_ASCII); + byte[] signature = signInput(signingInput, signingKey); + String envelope = protectedSegment + "." + payloadSegment + "." + encodeBase64Url(signature); + requireEnvelopeSize(envelope); + return envelope; + } + + /** + * Verifies a compact JWS envelope against an explicitly supplied Gateway key set. + * + *

The key set is deliberately bounded to one or two keys so rotation cannot silently become an + * unbounded trust expansion. This method performs envelope/signature checks only; it does not + * interpret issuer, audience, recipient, expiry, target, or any other payload field. + */ + public static VerifiedContext verify( + String envelope, Map verificationKeys) { + requireVerificationKeys(verificationKeys); + requireEnvelope(envelope); + + String[] segments = splitCompactSerialization(envelope); + byte[] protectedHeaderBytes = decodeCanonicalBase64Url(segments[0], "protected header"); + String protectedHeader = decodeAscii(protectedHeaderBytes, "protected header"); + String kid = parseCanonicalProtectedHeader(protectedHeader); + + PublicKey verificationKey = verificationKeys.get(kid); + if (verificationKey == null) { + throw invalid("unknown Gateway verification key"); + } + requireKey(verificationKey, "verification key", PublicKey.class); + + byte[] payload = decodeCanonicalBase64Url(segments[1], "payload"); + requirePayload(payload); + byte[] signature = decodeCanonicalBase64Url(segments[2], "signature"); + if (signature.length != 64) { + throw invalid("invalid Ed25519 signature length"); + } + + byte[] signingInput = (segments[0] + "." + segments[1]).getBytes(StandardCharsets.US_ASCII); + if (!verifyInput(signingInput, signature, verificationKey)) { + throw invalid("invalid Gateway context signature"); + } + return new VerifiedContext(payload, kid); + } + + private static String[] splitCompactSerialization(String envelope) { + int firstDot = envelope.indexOf('.'); + int secondDot = firstDot < 0 ? -1 : envelope.indexOf('.', firstDot + 1); + if (firstDot <= 0 || secondDot <= firstDot + 1 || secondDot == envelope.length() - 1) { + throw invalid("malformed compact JWS envelope"); + } + if (envelope.indexOf('.', secondDot + 1) >= 0) { + throw invalid("malformed compact JWS envelope"); + } + return new String[] { + envelope.substring(0, firstDot), + envelope.substring(firstDot + 1, secondDot), + envelope.substring(secondDot + 1) + }; + } + + private static String parseCanonicalProtectedHeader(String header) { + if (!header.startsWith(HEADER_PREFIX) || !header.endsWith(HEADER_SUFFIX)) { + throw invalid("unsupported or non-canonical protected header"); + } + int kidStart = HEADER_PREFIX.length(); + int kidEnd = header.length() - HEADER_SUFFIX.length(); + if (kidEnd <= kidStart) { + throw invalid("missing Gateway key identifier"); + } + String kid = header.substring(kidStart, kidEnd); + requireKid(kid); + if (!header.equals(canonicalProtectedHeader(kid))) { + throw invalid("unsupported or non-canonical protected header"); + } + return kid; + } + + private static String canonicalProtectedHeader(String kid) { + return HEADER_PREFIX + kid + HEADER_SUFFIX; + } + + private static String encodeBase64Url(byte[] value) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(value); + } + + private static byte[] decodeCanonicalBase64Url(String value, String component) { + if (value.isEmpty() || value.length() > MAX_ENVELOPE_BYTES) { + throw invalid("invalid " + component + " encoding"); + } + for (int index = 0; index < value.length(); index++) { + char character = value.charAt(index); + if (!isBase64UrlCharacter(character)) { + throw invalid("invalid " + component + " encoding"); + } + } + final byte[] decoded; + try { + decoded = Base64.getUrlDecoder().decode(value); + } catch (IllegalArgumentException ex) { + throw invalid("invalid " + component + " encoding"); + } + if (!value.equals(encodeBase64Url(decoded))) { + throw invalid("non-canonical " + component + " encoding"); + } + return decoded; + } + + private static boolean isBase64UrlCharacter(char character) { + return character >= 'A' && character <= 'Z' + || character >= 'a' && character <= 'z' + || character >= '0' && character <= '9' + || character == '-' + || character == '_'; + } + + private static String decodeAscii(byte[] value, String component) { + for (byte character : value) { + if (character < 0x21 || character > 0x7e) { + throw invalid("invalid " + component + " encoding"); + } + } + return new String(value, StandardCharsets.US_ASCII); + } + + private static byte[] signInput(byte[] signingInput, PrivateKey signingKey) { + try { + Signature signature = Signature.getInstance(KEY_ALGORITHM); + signature.initSign(signingKey); + signature.update(signingInput); + return signature.sign(); + } catch (GeneralSecurityException ex) { + throw invalid("Gateway Ed25519 signing failed"); + } + } + + private static boolean verifyInput( + byte[] signingInput, byte[] signatureBytes, PublicKey verificationKey) { + try { + Signature signature = Signature.getInstance(KEY_ALGORITHM); + signature.initVerify(verificationKey); + signature.update(signingInput); + return signature.verify(signatureBytes); + } catch (GeneralSecurityException ex) { + throw invalid("Gateway Ed25519 verification failed"); + } + } + + private static void requirePayload(byte[] payload) { + if (payload == null) { + throw new IllegalArgumentException("Gateway context payload is required"); + } + if (payload.length == 0) { + throw new IllegalArgumentException("Gateway context payload must not be empty"); + } + if (payload.length > MAX_PAYLOAD_BYTES) { + throw new IllegalArgumentException("Gateway context payload exceeds the bounded limit"); + } + } + + private static void requireEnvelope(String envelope) { + if (envelope == null || envelope.isEmpty()) { + throw invalid("Gateway context envelope is required"); + } + if (envelope.length() > MAX_ENVELOPE_BYTES) { + throw invalid("Gateway context envelope exceeds the bounded limit"); + } + for (int index = 0; index < envelope.length(); index++) { + if (envelope.charAt(index) > 0x7e || envelope.charAt(index) < 0x21) { + throw invalid("Gateway context envelope is not ASCII compact JWS"); + } + } + } + + private static void requireEnvelopeSize(String envelope) { + if (envelope.getBytes(StandardCharsets.US_ASCII).length > MAX_ENVELOPE_BYTES) { + throw new IllegalArgumentException("Gateway context envelope exceeds the bounded limit"); + } + } + + private static void requireKid(String kid) { + if (kid == null || kid.isEmpty() || kid.length() > MAX_KID_LENGTH) { + throw new IllegalArgumentException("Gateway key identifier must be non-blank and bounded"); + } + for (int index = 0; index < kid.length(); index++) { + char character = kid.charAt(index); + if (character < 0x21 || character > 0x7e || character == '"' || character == '\\') { + throw new IllegalArgumentException( + "Gateway key identifier contains an unsupported character"); + } + } + } + + private static void requireVerificationKeys(Map verificationKeys) { + if (verificationKeys == null || verificationKeys.isEmpty()) { + throw invalid("Gateway verification keys are unavailable"); + } + if (verificationKeys.size() > MAX_VERIFICATION_KEYS) { + throw invalid("Gateway verification key set exceeds the bounded rotation window"); + } + for (Map.Entry entry : verificationKeys.entrySet()) { + requireKid(entry.getKey()); + requireKey(entry.getValue(), "verification key", PublicKey.class); + } + } + + private static void requireKey(Object key, String description, Class expectedType) { + if (key == null || !expectedType.isInstance(key)) { + throw new IllegalArgumentException(description + " is required"); + } + String algorithm = + key instanceof PrivateKey privateKey + ? privateKey.getAlgorithm() + : ((PublicKey) key).getAlgorithm(); + if (!isEd25519Algorithm(algorithm)) { + throw new IllegalArgumentException(description + " must use Ed25519"); + } + } + + private static boolean isEd25519Algorithm(String algorithm) { + return KEY_ALGORITHM.equalsIgnoreCase(algorithm) || "EdDSA".equalsIgnoreCase(algorithm); + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + /** The only data returned after successful signature verification. */ + public record VerifiedContext(byte[] payload, String kid) { + public VerifiedContext { + if (payload == null) { + throw new IllegalArgumentException("verified payload is required"); + } + payload = payload.clone(); + requireKid(kid); + } + + @Override + public byte[] payload() { + return payload.clone(); + } + } +} diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayConnectContextSignatureTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayConnectContextSignatureTest.java new file mode 100644 index 0000000000..2ff912d0db --- /dev/null +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayConnectContextSignatureTest.java @@ -0,0 +1,228 @@ +package unit.net.firedevops.firemud.common.security; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.nio.charset.StandardCharsets; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.util.Base64; +import java.util.Map; +import net.firedevops.firemud.common.security.GatewayConnectContextSignature; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class GatewayConnectContextSignatureTest { + private static final String CURRENT_KID = "gateway-2026-current"; + private static final String PREVIOUS_KID = "gateway-2026-previous"; + + private KeyPair currentKey; + private KeyPair previousKey; + + @BeforeEach + void setUp() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("Ed25519"); + currentKey = generator.generateKeyPair(); + previousKey = generator.generateKeyPair(); + } + + @Test + void signsAndVerifiesExactPayloadBytes() { + byte[] payload = {0, 1, (byte) 0xff, 2, 3}; + + String envelope = + GatewayConnectContextSignature.sign(payload, CURRENT_KID, currentKey.getPrivate()); + GatewayConnectContextSignature.VerifiedContext verified = + GatewayConnectContextSignature.verify( + envelope, Map.of(CURRENT_KID, currentKey.getPublic())); + + assertArrayEquals(payload, verified.payload()); + assertEquals(CURRENT_KID, verified.kid()); + } + + @Test + void rejectsEmptyAndNullPayloadsBeforeSigning() { + assertThrows( + IllegalArgumentException.class, + () -> + GatewayConnectContextSignature.sign(new byte[0], CURRENT_KID, currentKey.getPrivate())); + assertThrows( + IllegalArgumentException.class, + () -> GatewayConnectContextSignature.sign(null, CURRENT_KID, currentKey.getPrivate())); + } + + @Test + void acceptsCurrentAndPreviousKeysDuringRotation() { + byte[] payload = "rotation-safe context".getBytes(StandardCharsets.UTF_8); + String envelope = + GatewayConnectContextSignature.sign(payload, PREVIOUS_KID, previousKey.getPrivate()); + + GatewayConnectContextSignature.VerifiedContext verified = + GatewayConnectContextSignature.verify( + envelope, + Map.of( + CURRENT_KID, currentKey.getPublic(), + PREVIOUS_KID, previousKey.getPublic())); + + assertArrayEquals(payload, verified.payload()); + assertEquals(PREVIOUS_KID, verified.kid()); + } + + @Test + void rejectsAlteredPayloadAndSignature() { + byte[] payload = "signed context".getBytes(StandardCharsets.UTF_8); + String envelope = + GatewayConnectContextSignature.sign(payload, CURRENT_KID, currentKey.getPrivate()); + String[] segments = envelope.split("\\.", -1); + String alteredPayload = + Base64.getUrlEncoder() + .withoutPadding() + .encodeToString("altered".getBytes(StandardCharsets.UTF_8)); + String alteredSignature = flipLastCharacter(segments[2]); + + assertThrows( + IllegalArgumentException.class, + () -> + GatewayConnectContextSignature.verify( + segments[0] + "." + alteredPayload + "." + segments[2], + Map.of(CURRENT_KID, currentKey.getPublic()))); + assertThrows( + IllegalArgumentException.class, + () -> + GatewayConnectContextSignature.verify( + segments[0] + "." + segments[1] + "." + alteredSignature, + Map.of(CURRENT_KID, currentKey.getPublic()))); + } + + @Test + void rejectsMalformedOrNonCanonicalProtectedHeaders() { + byte[] payload = "context".getBytes(StandardCharsets.UTF_8); + String envelope = + GatewayConnectContextSignature.sign(payload, CURRENT_KID, currentKey.getPrivate()); + String[] segments = envelope.split("\\.", -1); + + assertThrows( + IllegalArgumentException.class, + () -> + verifyWithHeader( + segments[1], + segments[2], + "{\"alg\":\"HS256\",\"kid\":\"" + + CURRENT_KID + + "\",\"typ\":\"" + + GatewayConnectContextSignature.TYPE + + "\"}")); + assertThrows( + IllegalArgumentException.class, + () -> + verifyWithHeader( + segments[1], + segments[2], + "{\"alg\":\"EdDSA\",\"kid\":\"" + CURRENT_KID + "\",\"typ\":\"wrong\"}")); + assertThrows( + IllegalArgumentException.class, + () -> + verifyWithHeader( + segments[1], + segments[2], + "{\"alg\":\"EdDSA\",\"kid\":\"" + + CURRENT_KID + + "\",\"extra\":true,\"typ\":\"" + + GatewayConnectContextSignature.TYPE + + "\"}")); + assertThrows( + IllegalArgumentException.class, + () -> + verifyWithHeader( + segments[1], + segments[2], + "{ \"alg\": \"EdDSA\", \"kid\": \"" + + CURRENT_KID + + "\", \"typ\": \"" + + GatewayConnectContextSignature.TYPE + + "\" }")); + } + + @Test + void rejectsMalformedBase64UnknownKidAndUnavailableOrOversizedKeySets() throws Exception { + byte[] payload = "context".getBytes(StandardCharsets.UTF_8); + String envelope = + GatewayConnectContextSignature.sign(payload, CURRENT_KID, currentKey.getPrivate()); + String[] segments = envelope.split("\\.", -1); + + assertThrows( + IllegalArgumentException.class, + () -> + GatewayConnectContextSignature.verify( + "!" + segments[0].substring(1) + "." + segments[1] + "." + segments[2], + Map.of(CURRENT_KID, currentKey.getPublic()))); + assertThrows( + IllegalArgumentException.class, + () -> + GatewayConnectContextSignature.verify( + envelope, Map.of("unknown", currentKey.getPublic()))); + assertThrows( + IllegalArgumentException.class, + () -> GatewayConnectContextSignature.verify(envelope, Map.of())); + + KeyPair thirdKey = keyPair(); + assertThrows( + IllegalArgumentException.class, + () -> + GatewayConnectContextSignature.verify( + envelope, + Map.of( + CURRENT_KID, + currentKey.getPublic(), + PREVIOUS_KID, + previousKey.getPublic(), + "gateway-2026-third", + thirdKey.getPublic()))); + assertThrows( + IllegalArgumentException.class, + () -> + GatewayConnectContextSignature.sign( + new byte[GatewayConnectContextSignature.MAX_PAYLOAD_BYTES + 1], + CURRENT_KID, + currentKey.getPrivate())); + } + + @Test + void rejectsInvalidKidsAndNonEd25519Keys() throws Exception { + assertThrows( + IllegalArgumentException.class, + () -> GatewayConnectContextSignature.sign(new byte[] {1}, " ", currentKey.getPrivate())); + assertThrows( + IllegalArgumentException.class, + () -> + GatewayConnectContextSignature.sign( + new byte[] {1}, "gateway-\\\"quoted", currentKey.getPrivate())); + + KeyPairGenerator rsaGenerator = KeyPairGenerator.getInstance("RSA"); + KeyPair rsaKey = rsaGenerator.generateKeyPair(); + assertThrows( + IllegalArgumentException.class, + () -> + GatewayConnectContextSignature.sign(new byte[] {1}, CURRENT_KID, rsaKey.getPrivate())); + } + + private void verifyWithHeader(String payloadSegment, String signatureSegment, String header) { + String protectedSegment = + Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(header.getBytes(StandardCharsets.US_ASCII)); + GatewayConnectContextSignature.verify( + protectedSegment + "." + payloadSegment + "." + signatureSegment, + Map.of(CURRENT_KID, currentKey.getPublic())); + } + + private static String flipLastCharacter(String value) { + char last = value.charAt(value.length() - 1); + return value.substring(0, value.length() - 1) + (last == 'A' ? 'B' : 'A'); + } + + private static KeyPair keyPair() throws Exception { + return KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/authority/MembershipAuthorityEventVectorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/authority/MembershipAuthorityEventVectorTest.java new file mode 100644 index 0000000000..00cdea6e6d --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/authority/MembershipAuthorityEventVectorTest.java @@ -0,0 +1,176 @@ +package net.firedevops.firemud.gamesession.authority; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.io.InputStream; +import java.math.BigInteger; +import java.util.Map; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.node.ArrayNode; +import tools.jackson.databind.node.ObjectNode; + +class MembershipAuthorityEventVectorTest { + private static final String VECTOR_RESOURCE = + "/net/firedevops/firemud/common/account/authority/account-auth-authority-event-v1-vectors.json"; + private static final ObjectMapper JSON = new ObjectMapper(); + + @Test + void verifiesEverySharedWireEventAndItsCanonicalDigest() throws IOException { + JsonNode vectors = readVectors(); + + for (JsonNode vector : vectors.path("validEvents")) { + JsonNode wireEvent = vector.path("event"); + var verified = MembershipAuthorityEventV1Codec.verify(JSON.writeValueAsString(wireEvent)); + + assertEquals(wireEvent.path("eventDigest").asText(), verified.eventDigest()); + assertEquals(wireEvent.path("outboxSequence").asText(), verified.outboxSequence()); + String tenantId = wireEvent.path("tenantId").asText(); + assertEquals( + Map.of(tenantId, wireEvent.path("membershipVersion").path(tenantId).asText()), + verified.membershipVersion()); + assertEquals( + wireEvent.path("membershipAuthorityGeneration").asText(), + verified.membershipAuthorityGeneration()); + assertEquals(wireEvent.path("roles").size(), verified.roles().size()); + assertEquals(wireEvent, JSON.readTree(verified.canonicalJson())); + } + } + + @Test + void acceptsLargeCountersOnlyInTheirCanonicalDecimalStringForm() throws IOException { + JsonNode vectors = readVectors(); + boolean sawLargeCounter = false; + boolean sawLargeMembershipVersion = false; + BigInteger maxSafeInteger = new BigInteger("9007199254740991"); + + for (JsonNode vector : vectors.path("validEvents")) { + JsonNode event = vector.path("event"); + JsonNode sequence = event.path("outboxSequence"); + String tenantId = event.path("tenantId").asText(); + JsonNode membershipVersions = event.path("membershipVersion"); + JsonNode membershipVersion = membershipVersions.path(tenantId); + assertTrue(sequence.isTextual(), "outboxSequence must remain a decimal string"); + assertTrue(membershipVersions.isObject(), "membershipVersion must be a tenant map"); + assertEquals(1, membershipVersions.size(), "membershipVersion must have exactly one tenant"); + assertTrue(membershipVersion.isTextual(), "membershipVersion must remain a decimal string"); + if (new BigInteger(sequence.asText()).compareTo(maxSafeInteger) > 0) { + sawLargeCounter = true; + } + if (new BigInteger(membershipVersion.asText()).compareTo(maxSafeInteger) > 0) { + sawLargeMembershipVersion = true; + } + var verified = MembershipAuthorityEventV1Codec.verify(JSON.writeValueAsString(event)); + assertEquals(sequence.asText(), verified.outboxSequence()); + assertEquals(Map.of(tenantId, membershipVersion.asText()), verified.membershipVersion()); + } + + assertTrue(sawLargeCounter, "shared vectors must include a counter above 2^53"); + assertTrue(sawLargeMembershipVersion, "membershipVersion must include a value above 2^53"); + } + + @Test + void rejectsEveryChangedFieldWhileKeepingTheOriginalDigest() throws IOException { + JsonNode vectors = readVectors(); + JsonNode sourceEvent = vectors.path("validEvents").get(0).path("event"); + + for (JsonNode mutation : vectors.path("changedFieldMutations")) { + ObjectNode changedEvent = (ObjectNode) sourceEvent.deepCopy(); + applyMutation(changedEvent, mutation, "replacement", "replace"); + + assertThrows( + IllegalArgumentException.class, + () -> MembershipAuthorityEventV1Codec.verify(JSON.writeValueAsString(changedEvent)), + mutation.path("name").asText()); + } + } + + @Test + void rejectsSharedInvalidMutationsIncludingOptionalAndArrayOrderViolations() throws IOException { + JsonNode vectors = readVectors(); + JsonNode sourceEvent = vectors.path("validEvents").get(0).path("event"); + + for (JsonNode mutation : vectors.path("invalidMutations")) { + ObjectNode changedEvent = (ObjectNode) sourceEvent.deepCopy(); + applyMutation(changedEvent, mutation, "value", null); + + assertThrows( + IllegalArgumentException.class, + () -> MembershipAuthorityEventV1Codec.verify(JSON.writeValueAsString(changedEvent)), + mutation.path("name").asText()); + } + } + + @Test + void rejectsDuplicatePropertiesInRawEventJson() throws IOException { + JsonNode event = readVectors().path("validEvents").get(0).path("event"); + String validJson = JSON.writeValueAsString(event); + String duplicatePropertyJson = + validJson.replaceFirst("^\\{", "{\"eventId\":\"duplicate-event\","); + + assertThrows( + IllegalArgumentException.class, + () -> MembershipAuthorityEventV1Codec.verify(duplicatePropertyJson)); + } + + private static JsonNode readVectors() throws IOException { + try (InputStream stream = + MembershipAuthorityEventVectorTest.class.getResourceAsStream(VECTOR_RESOURCE)) { + assertTrue(stream != null, "shared authority-event vectors must be on the test classpath"); + return JSON.readTree(stream); + } + } + + private static void applyMutation( + ObjectNode root, JsonNode mutation, String valueField, String defaultOperation) { + String[] segments = mutation.path("path").asText().substring(1).split("/"); + JsonNode parent = root; + for (int i = 0; i < segments.length - 1; i++) { + String segment = unescapePointerSegment(segments[i]); + parent = + parent instanceof ArrayNode array + ? array.get(Integer.parseInt(segment)) + : parent.path(segment); + } + String finalSegment = unescapePointerSegment(segments[segments.length - 1]); + String operation = mutation.path("op").asText(defaultOperation); + if (operation.equals("remove")) { + if (parent instanceof ObjectNode object) { + object.remove(finalSegment); + } else if (parent instanceof ArrayNode array) { + array.remove(Integer.parseInt(finalSegment)); + } else { + throw new AssertionError("mutation parent is not a JSON container"); + } + return; + } + + JsonNode value = mutation.get(valueField).deepCopy(); + if (parent instanceof ObjectNode object) { + if (operation.equals("add") || operation.equals("replace")) { + object.set(finalSegment, value); + return; + } + } else if (parent instanceof ArrayNode array) { + int index = Integer.parseInt(finalSegment); + if (operation.equals("add")) { + array.insert(index, value); + return; + } + if (operation.equals("replace")) { + array.set(index, value); + return; + } + } + throw new AssertionError("unsupported vector mutation operation: " + operation); + } + + private static String unescapePointerSegment(String segment) { + return segment.replace("~1", "/").replace("~0", "~"); + } +}