From ce9a9fea79f879025bc9fc4a8fd347d9927b7a4d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 27 Sep 2026 14:44:34 +1300 Subject: [PATCH 01/14] feat(account): stage atomic bare-login exchange storage --- .../account-service/runtime-and-data.md | 2 +- design/project-management/ai-observations.md | 5 + .../player-access-and-session.md | 4 +- .../AccountBareLoginExchangeIdentity.java | 72 ++ .../AccountBareLoginExchangeOperation.java | 208 +++++ .../AccountBareLoginExchangeRepository.java | 827 ++++++++++++++++++ .../AccountBareLoginResponseEnvelope.java | 23 + ...7__account_bare_login_exchange_storage.sql | 328 +++++++ ...oginExchangeRepositoryIntegrationTest.java | 756 ++++++++++++++++ 9 files changed, 2223 insertions(+), 2 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeIdentity.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeOperation.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginResponseEnvelope.java create mode 100644 services/account-service/src/main/resources/db/migration/V37__account_bare_login_exchange_storage.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 4c8e646aa7..9866a13c31 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -150,7 +150,7 @@ The `player-bootstrap` token profile is distinct from both `control-ui` and priv - It establishes account identity for first-party gameplay bootstrap only. Target behavior is that public-game membership is created only by explicit `/auth/bootstrap/join`; character discovery, character creation, and `POST /auth/connect-token` later require that membership and recheck applicable grants, entitlements, and the discovery-selected runtime target. The current Account REST runtime requires existing caller-bound membership for character discovery and connect-token issuance and uses only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; world and realm discovery remain available before membership. The separate Game Session text `PLAY` path is currently blocked earlier by Account runtime membership/grant/entitlement gRPC methods returning `FAILED_PRECONDITION` before reads, producing `AUTH_UNAVAILABLE`; its downstream membership outcomes require successful mocked Account responses. For a publicly visible public-production target whose joining policy permits entry, the Account connect-token issuance branch may return `JOIN_REQUIRED` without creating or restoring membership; the latter existing-membership case is not lifecycle-aware while explicit `JOIN` is a separate local action. Non-public or non-visible targets remain subject to their realm-access and grant checks rather than using public onboarding semantics. - It is stored in memory only by first-party gameplay UIs and is accepted only on gameplay-bootstrap surfaces such as bootstrap discovery and `POST /auth/connect-token`. - For first-party `/ws/game/**`, subsequent gameplay `LOGIN` must complete from the bootstrap/connect context already established for that socket; browser clients must not be required to replay account credentials after bootstrap. -- Account issues the private `game-session-account-delegation` JWT for bare first-party `LOGIN` only through the one-use, idempotent exchange defined in [Authentication and Authorization](../../system-architecture-authentication.md). Its own committed connect issuance and bootstrap subject, independently verified Gateway-signed context, exact Game Session mTLS identity, target binding, current authority, and issuance fence must all agree before issuance. The current Redis-only connect replay/session records and Gateway context verifier configuration do not establish that proof, so no current bare-`LOGIN` exchange or live runtime-read authorization is claimed. +- Account issues the private `game-session-account-delegation` JWT for bare first-party `LOGIN` only through the one-use, idempotent exchange defined in [Authentication and Authorization](../../system-architecture-authentication.md). Its own committed connect issuance and bootstrap subject, independently verified Gateway-signed context, exact Game Session mTLS identity, target binding, current authority, and issuance fence must all agree before issuance. The V37 storage candidate binds an exchange to a committed V35 connect operation and stores an immutable purpose-bound terminal envelope, but neither operation is wired to credential issuance or recovery. The current Redis-only connect replay/session records and Gateway context verifier configuration do not establish the complete proof, so no current bare-`LOGIN` exchange or live runtime-read authorization is claimed. - If the token is lost because the page/app process is restarted, the client must restart bootstrap from `POST /auth/player-bootstrap`; the current architecture does not define a hidden silent-bootstrap refresh mechanism. - It is backed by one `session:auth:token:` record so per-token logout and account-level revocation semantics remain consistent. - `POST /auth/logout` and `POST /auth/logout-all` must accept this profile so first-party gameplay UIs can explicitly revoke bootstrap capability on sign-out rather than waiting for expiry. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 7bf56695ba..c906b0b844 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -127,3 +127,8 @@ Entry format: - 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-27`: Hosted database task success may lack per-case proof artifacts + - Context: Unit 1B Account integration tests skipped locally without Docker. Hosted runs executed the integration task and passed on corrected code, but the uploaded artifact contained JaCoCo output without JUnit XML for the named PostgreSQL case. + - Observation: task-level execution and success are useful composed evidence, but they do not independently identify which newly corrected database methods ran or whether any were skipped. + - Expected pattern: retain and upload the exact integration JUnit XML alongside coverage artifacts when individual database regressions are needed as proof; until then report task-level success separately from per-case execution. 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 643ce1f025..bea60a0025 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -10,6 +10,8 @@ The unmerged #2876 `account-auth-authority-event/v1` correction uses ADR 0030's Draft #2880's Account membership-snapshot child retains the exact one-tenant version map and assembles four canonically ordered two-field issuer/account/tenant/membership checkpoints with separate positive membership event ID/digest evidence. A never-joined pair returns nonadmitting sequence zero only from its durable positive pair baseline, absent membership/receipt/event history, and pristine upstream generation/source-version rows under the Account fence; advanced upstream authority without matching event proof remains denied. A later account-local issuance fence is retained rather than reset to one. This is a local producer boundary, not a wire response or Game Session consumer: the runtime RPC remains denied. The exact local Account check executed 377 unit tests, while all 78 PostgreSQL integration tests were skipped without Docker. Hosted run `36282748942` executed 82 Account integration cases on the earlier draft head: 81 passed and one new negative test failed because its expected message named the later pair-baseline check rather than the earlier correct rejection of an advanced membership generation without a source event. The corrected-code run `36283628361` executed the Account integration task and its job passed, but uploaded only JaCoCo artifacts, so the corrected method's individual result cannot be attested. Both aggregate gates remain red on a shared TLS-watcher test race, Ruff, and EA-3.1 checks outside #2880's unique snapshot patch. Overseer resolved the ADR 0030 wording conflict: the closed v1 event is insufficient without a separately Account-authenticated same-snapshot checkpoint/source carrier bound to its exact event ID/digest; the ADR correction is in #2876, while that runtime carrier and consumer remain open. +V37's deferred database guard rejects an exchange transaction that would commit `PENDING` without its terminal envelope: a pre-commit crash rolls back the claim, while a post-commit exact retry reads the original operation and envelope. This is still storage-only until PostgreSQL executes the new cases and the caller proves that source validation, current authority, credential creation, and envelope completion use that same transaction. Deletion is denied until Account adds a proven receipt/envelope retention and safe-cleanup path; no fixed TTL, timeout, or absent row is interpreted as a terminal result. Lost-response producer/consumer proof remains an activation gate. + Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, explicit public-production JOIN, durable Account audit outbox and Logging receipt handling, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. Account now has a bounded readback-only worker for abandoned JOIN `PENDING` intents, but PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof are not claimed. Expiry and absent evidence do not create terminal outcomes. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and durable post-logout episode fencing remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. 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. @@ -28,7 +30,7 @@ The in-progress #2873 tenant bridge now has a signed Game Design migration-manif 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 gives missing non-public grant a separate `REALM_ACCESS_DENIED` outcome. 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. 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 approved first-party bare-`LOGIN` private-delegation exchange is not live. 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 or key-ring deployment. The separate V37 storage candidate binds one exchange request to a committed V35 source, preserves first-writer request identity and digest, and permits only an atomic write-once pending-evidence to terminal-success transition with an exact purpose-bound envelope; it does not mint, decrypt, or return a delegation JWT. Its seven PostgreSQL cases compile but skipped without Docker; database execution, caller lost-response recovery, current-authority revalidation, exact Game Session caller proof, and the complete producer/consumer path remain open. 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. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeIdentity.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeIdentity.java new file mode 100644 index 0000000000..ff09941d56 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeIdentity.java @@ -0,0 +1,72 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.UUID; + +/** Exact identity for one Account-owned bare first-party LOGIN exchange attempt. */ +public record AccountBareLoginExchangeIdentity( + UUID sourceConnectOperationId, + 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 AccountBareLoginExchangeIdentity { + Objects.requireNonNull(sourceConnectOperationId, "sourceConnectOperationId"); + if (accountId <= 0 || tenantId <= 0) { + throw new IllegalArgumentException("Bare LOGIN 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("Bare LOGIN scope ID exceeds its storage bound"); + } + if (requestId.length() > MAX_REQUEST_ID_LENGTH) { + throw new IllegalArgumentException("Bare LOGIN request ID exceeds its storage bound"); + } + } + + String connectScopeHash() { + return net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash(connectScopeId); + } + + @Override + public String toString() { + return "AccountBareLoginExchangeIdentity{sourceConnectOperationId=" + + sourceConnectOperationId + + ", 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/AccountBareLoginExchangeOperation.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeOperation.java new file mode 100644 index 0000000000..4aec299355 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeOperation.java @@ -0,0 +1,208 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.time.Instant; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; + +/** Readback-only view of one durable bare first-party LOGIN exchange operation. */ +public record AccountBareLoginExchangeOperation( + UUID operationId, + UUID sourceConnectOperationId, + 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, + Instant createdAt, + Instant updatedAt) { + + private static final Pattern SCOPE_HASH_PATTERN = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final int DIGEST_LENGTH_BYTES = 32; + private static final int MAX_TOKEN_IDENTITY_LENGTH = 128; + + public enum Lifecycle { + PENDING, + COMMITTED; + + static Lifecycle fromDatabase(String value) { + try { + return Lifecycle.valueOf(value); + } catch (RuntimeException exception) { + throw new IllegalStateException("Stored bare LOGIN exchange lifecycle is invalid"); + } + } + } + + public AccountBareLoginExchangeOperation { + if (operationId == null + || sourceConnectOperationId == null + || accountId <= 0 + || tenantId <= 0 + || connectScopeHash == null + || !SCOPE_HASH_PATTERN.matcher(connectScopeHash).matches() + || requestId == null + || requestId.isBlank() + || requestId.length() > AccountBareLoginExchangeIdentity.MAX_REQUEST_ID_LENGTH + || requestDigestVersion != 1 + || lifecycle == null + || createdAt == null + || updatedAt == null) { + throw new IllegalArgumentException("Stored bare LOGIN exchange 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); + if ((tokenIdentity == null) != (tokenHash == null)) { + throw new IllegalArgumentException("Bare LOGIN token identity and hash evidence must pair"); + } + if (tokenIdentity != null + && (tokenIdentity.isBlank() + || tokenIdentity.length() > MAX_TOKEN_IDENTITY_LENGTH + || tokenIdentity.indexOf('\0') >= 0)) { + throw new IllegalArgumentException("Stored bare LOGIN token identity is malformed"); + } + if (lifecycle == Lifecycle.PENDING) { + if (outcomeCode != null) { + throw new IllegalArgumentException("Pending bare LOGIN exchange cannot have an outcome"); + } + } else if (!"SUCCESS".equals(outcomeCode) + || tokenIdentity == null + || contextEvidenceDigest == null + || authorityTupleDigest == null + || issuanceFenceDigest == null + || postconditionDigest == null) { + throw new IllegalArgumentException("Committed bare LOGIN exchange evidence is incomplete"); + } + } + + @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 AccountBareLoginExchangeOperation that)) { + return false; + } + return accountId == that.accountId + && tenantId == that.tenantId + && requestDigestVersion == that.requestDigestVersion + && operationId.equals(that.operationId) + && sourceConnectOperationId.equals(that.sourceConnectOperationId) + && 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(createdAt, that.createdAt) + && Objects.equals(updatedAt, that.updatedAt); + } + + @Override + public int hashCode() { + int result = + Objects.hash( + operationId, + sourceConnectOperationId, + accountId, + tenantId, + connectScopeHash, + requestId, + requestDigestVersion, + lifecycle, + outcomeCode, + tokenIdentity, + 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 "AccountBareLoginExchangeOperation{operationId=" + + operationId + + ", sourceConnectOperationId=" + + sourceConnectOperationId + + ", 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 != DIGEST_LENGTH_BYTES) { + 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/AccountBareLoginExchangeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeRepository.java new file mode 100644 index 0000000000..522c0c23bb --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeRepository.java @@ -0,0 +1,827 @@ +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.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginExchangeOperation.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 storage and exact readback for bare first-party LOGIN exchange. Claim, + * pending evidence, terminal success, and its exact envelope must share one Account transaction; + * V37 permits {@code PENDING} only as an in-transaction intermediate and rejects a still-pending + * exchange at transaction commit. + */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class AccountBareLoginExchangeRepository { + private static final String OPERATION_TABLE = "account_bare_login_exchange_operations"; + private static final String SOURCE_OPERATION_TABLE = "account_connect_token_issuance_operations"; + private static final String ENVELOPE_TABLE = "account_bare_login_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 final DSLContext dsl; + + public AccountBareLoginExchangeRepository(DSLContext dsl) { + this.dsl = dsl; + } + + /** + * Claims one source connect-operation identity without replacing a prior writer's request + * identity or digest. A source connect operation must already be a committed V35 issuance; a + * pending or absent source is not Account authentication and cannot start an exchange. The caller + * must keep this claim in the same Account transaction as pending evidence and terminal envelope + * completion; committing the claim alone is rejected. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ClaimResult claim(AccountBareLoginExchangeIdentity identity, byte[] requestDigest) { + validateIdentity(identity); + byte[] digest = requireDigest(requestDigest, "request digest"); + requireCommittedSource(identity); + + Optional existing = readOperationBySource(identity); + if (existing.isEmpty()) { + existing = readOperationByRequest(identity); + } + if (existing.isPresent()) { + AccountBareLoginExchangeOperation operation = existing.orElseThrow(); + assertIdentityMatches(operation, identity); + requireDigestMatch(operation, digest); + return new ClaimResult(ClaimDisposition.REPLAYED, identity, operation); + } + + UUID proposedOperationId = UUID.randomUUID(); + int inserted = + dsl.execute( + "INSERT INTO " + + OPERATION_TABLE + + " (operation_id, source_connect_operation_id, account_id, tenant_id, " + + "connect_scope_hash, request_id, request_digest_version, request_digest, status) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'PENDING') " + + "ON CONFLICT DO NOTHING", + proposedOperationId, + identity.sourceConnectOperationId(), + identity.accountId(), + identity.tenantId(), + identity.connectScopeHash(), + identity.requestId(), + REQUEST_DIGEST_VERSION, + digest); + if (inserted < 0 || inserted > 1) { + throw new IllegalStateException("Bare LOGIN exchange claim result was ambiguous"); + } + + Optional winner = readOperationBySource(identity); + if (winner.isEmpty()) { + winner = readOperationByRequest(identity); + } + AccountBareLoginExchangeOperation operation = + winner.orElseThrow( + () -> + new IllegalStateException( + "Bare LOGIN exchange claim has no exact durable readback")); + assertIdentityMatches(operation, identity); + requireDigestMatch(operation, digest); + if (inserted == 1 && !proposedOperationId.equals(operation.operationId())) { + throw new IllegalStateException("Bare LOGIN exchange claim returned another operation"); + } + return new ClaimResult( + inserted == 1 ? ClaimDisposition.CLAIMED : ClaimDisposition.REPLAYED, identity, operation); + } + + /** Reads one exact source/request identity and rejects a changed request digest. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional find( + AccountBareLoginExchangeIdentity identity, byte[] requestDigest) { + validateIdentity(identity); + byte[] digest = requireDigest(requestDigest, "request digest"); + requireCommittedSource(identity); + Optional operation = readOperationBySource(identity); + if (operation.isEmpty()) { + operation = readOperationByRequest(identity); + } + if (operation.isPresent()) { + assertIdentityMatches(operation.orElseThrow(), identity); + requireDigestMatch(operation.orElseThrow(), digest); + } + return operation; + } + + /** + * Adds write-once source/token/authority evidence to a still-pending exchange. It never marks a + * transient or ambiguous result terminal; the claim, this evidence binding, and the later + * terminal call must share one transaction, which must store the exact purpose-bound envelope + * before commit. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AccountBareLoginExchangeOperation recordPendingEvidence( + ClaimResult claim, + byte[] requestDigest, + String tokenIdentity, + byte[] tokenHash, + byte[] contextEvidenceDigest, + byte[] authorityTupleDigest, + byte[] issuanceFenceDigest, + byte[] postconditionDigest) { + AccountBareLoginExchangeIdentity 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"); + validateTokenEvidence(tokenIdentity, checkedTokenHash); + if (tokenIdentity == null + && checkedContextDigest == null + && checkedAuthorityDigest == null + && checkedFenceDigest == null + && checkedPostconditionDigest == null) { + throw new IllegalArgumentException( + "At least one pending bare LOGIN exchange evidence field is required"); + } + + AccountBareLoginExchangeOperation operation = requireClaimedOperation(claim, digest); + if (operation.lifecycle() != Lifecycle.PENDING) { + throw new IllegalStateException("Only a pending bare LOGIN exchange 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 source_connect_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.sourceConnectOperationId(), + 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 bare LOGIN exchange already contains different evidence"); + } + AccountBareLoginExchangeOperation updated = + readOperationBySource(identity) + .filter(read -> read.operationId().equals(operation.operationId())) + .orElseThrow( + () -> + new IllegalStateException( + "Pending bare LOGIN exchange evidence has no exact operation readback")); + return updated; + } + + /** + * Stores one terminal successful result and its authenticated ciphertext in the caller's + * transaction. The claim and any pending evidence must have occurred in this same transaction; + * this repository never creates or decrypts the delegation JWT. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AccountBareLoginResponseEnvelope completeWithEnvelope( + ClaimResult claim, + byte[] requestDigest, + String tokenIdentity, + byte[] tokenHash, + AccountEnvelopeBinding binding, + AccountEncryptedEnvelope envelope) { + AccountBareLoginExchangeIdentity identity = requireClaimIdentity(claim); + byte[] digest = requireDigest(requestDigest, "request digest"); + validateTerminalResult(tokenIdentity, tokenHash); + Objects.requireNonNull(binding, "binding"); + validateBareLoginEnvelope(envelope); + + AccountBareLoginExchangeOperation operation = requireClaimedOperation(claim, digest); + if (operation.lifecycle() != Lifecycle.PENDING) { + throw new IllegalStateException( + "Bare LOGIN exchange operation is not pending and cannot be replaced"); + } + validateBinding(operation, identity, digest, binding); + requireEvidenceCompatible( + operation, + tokenIdentity, + copyNullable(tokenHash), + binding.contextEvidenceDigest(), + binding.authorityTupleDigest(), + binding.issuanceFenceDigest(), + binding.postconditionDigest()); + + Record changed = + dsl.fetchOne( + "UPDATE " + + OPERATION_TABLE + + " SET status = 'COMMITTED', outcome_code = 'SUCCESS', token_identity = ?, " + + "token_hash = ?, context_evidence_digest = ?, authority_tuple_digest = ?, " + + "issuance_fence_digest = ?, postcondition_digest = ? " + + "WHERE operation_id = ? AND source_connect_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 token_identity IS NOT DISTINCT FROM CAST(? AS VARCHAR) " + + "AND token_hash IS NOT DISTINCT FROM CAST(? AS BYTEA) " + + "AND context_evidence_digest IS NOT DISTINCT FROM CAST(? AS BYTEA) " + + "AND authority_tuple_digest IS NOT DISTINCT FROM CAST(? AS BYTEA) " + + "AND issuance_fence_digest IS NOT DISTINCT FROM CAST(? AS BYTEA) " + + "AND postcondition_digest IS NOT DISTINCT FROM CAST(? AS BYTEA) " + + "RETURNING operation_id", + tokenIdentity, + copyNullable(tokenHash), + binding.contextEvidenceDigest(), + binding.authorityTupleDigest(), + binding.issuanceFenceDigest(), + binding.postconditionDigest(), + operation.operationId(), + identity.sourceConnectOperationId(), + identity.accountId(), + identity.tenantId(), + identity.connectScopeHash(), + identity.requestId(), + REQUEST_DIGEST_VERSION, + digest, + operation.tokenIdentity(), + operation.tokenHash(), + operation.contextEvidenceDigest(), + operation.authorityTupleDigest(), + operation.issuanceFenceDigest(), + operation.postconditionDigest()); + if (changed == null + || !operation.operationId().equals(changed.get("operation_id", UUID.class))) { + throw new EvidenceMismatchException("Bare LOGIN exchange evidence changed before completion"); + } + + AccountBareLoginExchangeOperation committed = + readOperationBySource(identity) + .filter(read -> read.operationId().equals(operation.operationId())) + .orElseThrow( + () -> + new IllegalStateException( + "Committed bare LOGIN exchange has no exact operation readback")); + if (committed.lifecycle() != Lifecycle.COMMITTED + || !"SUCCESS".equals(committed.outcomeCode()) + || !Objects.equals(committed.tokenIdentity(), tokenIdentity) + || !sameDigest(committed.tokenHash(), tokenHash) + || !sameDigest(committed.contextEvidenceDigest(), binding.contextEvidenceDigest()) + || !sameDigest(committed.authorityTupleDigest(), binding.authorityTupleDigest()) + || !sameDigest(committed.issuanceFenceDigest(), binding.issuanceFenceDigest()) + || !sameDigest(committed.postconditionDigest(), binding.postconditionDigest())) { + throw new IllegalStateException( + "Committed bare LOGIN exchange readback differs from requested evidence"); + } + return insertEnvelopeAndReadBack(committed, identity, digest, binding, envelope); + } + + /** + * Reads the exact terminal operation and its only response envelope. A pending operation without + * an envelope remains pending; a terminal operation without its exact envelope fails closed. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readResponseEnvelope( + AccountBareLoginExchangeIdentity identity, + byte[] requestDigest, + AccountEnvelopeBinding binding) { + validateIdentity(identity); + byte[] digest = requireDigest(requestDigest, "request digest"); + Objects.requireNonNull(binding, "binding"); + requireCommittedSource(identity); + AccountBareLoginExchangeOperation operation = + readOperationBySource(identity) + .orElseThrow( + () -> + new IllegalStateException( + "Bare LOGIN exchange operation is missing during envelope readback")); + assertIdentityMatches(operation, identity); + requireDigestMatch(operation, digest); + validateBinding(operation, identity, digest, binding); + + Record row = + dsl.fetchOne( + "SELECT operation_id, operation_kind, source_connect_operation_id, 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()); + if (operation.lifecycle() == Lifecycle.PENDING) { + if (row != null) { + throw new IllegalStateException( + "Pending bare LOGIN exchange unexpectedly owns a response envelope"); + } + return Optional.empty(); + } + if (row == null) { + throw new IllegalStateException( + "Committed bare LOGIN exchange 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 bare LOGIN response purpose is invalid"); + } + if (purpose != AccountEnvelopePurpose.BARE_LOGIN_RESPONSE) { + throw new IllegalStateException("Stored bare LOGIN 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 AccountBareLoginResponseEnvelope(operation.operationId(), binding, encrypted)); + } + + private AccountBareLoginResponseEnvelope insertEnvelopeAndReadBack( + AccountBareLoginExchangeOperation operation, + AccountBareLoginExchangeIdentity identity, + byte[] digest, + AccountEnvelopeBinding binding, + AccountEncryptedEnvelope envelope) { + int inserted = + dsl.execute( + "INSERT INTO " + + ENVELOPE_TABLE + + " (operation_id, operation_kind, source_connect_operation_id, 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 (?, 'BARE_LOGIN_EXCHANGE', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + operation.operationId(), + identity.sourceConnectOperationId(), + 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("Bare LOGIN response envelope was not stored exactly once"); + } + + AccountBareLoginResponseEnvelope stored = + readResponseEnvelope(identity, digest, binding) + .orElseThrow( + () -> + new IllegalStateException( + "Bare LOGIN response envelope has no exact durable readback")); + if (!stored.operationId().equals(operation.operationId()) + || !stored.binding().equals(binding) + || !stored.envelope().equals(envelope)) { + throw new IllegalStateException( + "Bare LOGIN response envelope readback differs from requested envelope"); + } + return stored; + } + + private Optional readOperationBySource( + AccountBareLoginExchangeIdentity identity) { + Record row = + dsl.fetchOne( + "SELECT operation_id, source_connect_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, " + + "created_at, updated_at FROM " + + OPERATION_TABLE + + " WHERE source_connect_operation_id = ?", + identity.sourceConnectOperationId()); + return row == null ? Optional.empty() : Optional.of(toOperation(row)); + } + + private Optional readOperationByRequest( + AccountBareLoginExchangeIdentity identity) { + Record row = + dsl.fetchOne( + "SELECT operation_id, source_connect_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, " + + "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)); + } + + private void requireCommittedSource(AccountBareLoginExchangeIdentity identity) { + Record source = + dsl.fetchOne( + "SELECT operation_id, account_id, tenant_id, connect_scope_hash, status FROM " + + SOURCE_OPERATION_TABLE + + " WHERE operation_id = ?", + identity.sourceConnectOperationId()); + if (source == null) { + throw new IllegalStateException( + "Bare LOGIN exchange source connect operation is missing or untrusted"); + } + String status = requiredText(source, "status"); + if (!"COMMITTED".equals(status)) { + throw new IllegalStateException( + "Bare LOGIN exchange source connect operation is not committed"); + } + if (requiredLong(source, "account_id") != identity.accountId() + || requiredLong(source, "tenant_id") != identity.tenantId() + || !identity.connectScopeHash().equals(requiredText(source, "connect_scope_hash"))) { + throw new IdentityConflictException( + "Bare LOGIN exchange source connect operation identity does not match"); + } + } + + private static AccountBareLoginExchangeOperation toOperation(Record row) { + return new AccountBareLoginExchangeOperation( + requiredUuid(row, "operation_id"), + requiredUuid(row, "source_connect_operation_id"), + requiredLong(row, "account_id"), + requiredLong(row, "tenant_id"), + requiredText(row, "connect_scope_hash"), + requiredText(row, "request_id"), + 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), + toInstant(row.get("created_at", OffsetDateTime.class)), + toInstant(row.get("updated_at", OffsetDateTime.class))); + } + + private static void requireEnvelopeIdentity( + Record row, + AccountBareLoginExchangeOperation operation, + AccountBareLoginExchangeIdentity identity, + byte[] digest, + AccountEnvelopeBinding binding) { + if (!operation.operationId().equals(requiredUuid(row, "operation_id")) + || !"BARE_LOGIN_EXCHANGE".equals(requiredText(row, "operation_kind")) + || !operation + .sourceConnectOperationId() + .equals(requiredUuid(row, "source_connect_operation_id")) + || 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( + "Bare LOGIN response envelope identity or evidence readback does not match"); + } + validateBinding(operation, identity, digest, binding); + } + + private static void validateBinding( + AccountBareLoginExchangeOperation operation, + AccountBareLoginExchangeIdentity identity, + byte[] digest, + AccountEnvelopeBinding binding) { + if (binding.operationKind() != AccountEnvelopeBinding.OperationKind.BARE_LOGIN_EXCHANGE + || !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()) + || !identity + .sourceConnectOperationId() + .toString() + .equals(binding.sourceConnectOperationId()) + || !MessageDigest.isEqual(digest, binding.requestDigest())) { + throw new EvidenceMismatchException( + "Bare LOGIN response binding does not name the exact operation identity and digest"); + } + if (operation.lifecycle() == Lifecycle.COMMITTED) { + requireOperationEvidence(operation, binding); + } else { + requireEvidenceCompatible( + operation, + null, + null, + binding.contextEvidenceDigest(), + binding.authorityTupleDigest(), + binding.issuanceFenceDigest(), + binding.postconditionDigest()); + } + } + + private static void requireOperationEvidence( + AccountBareLoginExchangeOperation operation, AccountEnvelopeBinding binding) { + if (!sameDigest(operation.contextEvidenceDigest(), binding.contextEvidenceDigest()) + || !sameDigest(operation.authorityTupleDigest(), binding.authorityTupleDigest()) + || !sameDigest(operation.issuanceFenceDigest(), binding.issuanceFenceDigest()) + || !sameDigest(operation.postconditionDigest(), binding.postconditionDigest())) { + throw new EvidenceMismatchException( + "Bare LOGIN response binding differs from committed operation evidence"); + } + } + + private static void validateTerminalResult(String tokenIdentity, byte[] tokenHash) { + if (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 bare LOGIN result evidence is invalid"); + } + } + + private static void validateTokenEvidence(String tokenIdentity, byte[] tokenHash) { + if ((tokenIdentity == null) != (tokenHash == null)) { + throw new IllegalArgumentException("Bare LOGIN token identity and hash evidence must pair"); + } + if (tokenIdentity != null + && (tokenIdentity.isBlank() + || tokenIdentity.length() > MAX_TOKEN_IDENTITY_LENGTH + || tokenIdentity.indexOf('\0') >= 0)) { + throw new IllegalArgumentException("Bare LOGIN token identity evidence is invalid"); + } + } + + private AccountBareLoginExchangeIdentity requireClaimIdentity(ClaimResult claim) { + Objects.requireNonNull(claim, "claim"); + if (claim.disposition() != ClaimDisposition.CLAIMED) { + throw new IllegalStateException( + "Only the first bare LOGIN exchange claimant may record evidence or an outcome"); + } + return claim.identity(); + } + + private AccountBareLoginExchangeOperation requireClaimedOperation( + ClaimResult claim, byte[] digest) { + AccountBareLoginExchangeIdentity identity = requireClaimIdentity(claim); + requireCommittedSource(identity); + AccountBareLoginExchangeOperation operation = + readOperationBySource(identity) + .orElseThrow( + () -> + new IllegalStateException( + "Bare LOGIN exchange operation is missing during owner update")); + if (!claim.operation().operationId().equals(operation.operationId())) { + throw new IllegalStateException("Bare LOGIN claim no longer owns the durable operation"); + } + assertIdentityMatches(operation, identity); + requireDigestMatch(operation, digest); + return operation; + } + + private static void assertIdentityMatches( + AccountBareLoginExchangeOperation operation, AccountBareLoginExchangeIdentity identity) { + if (!identity.sourceConnectOperationId().equals(operation.sourceConnectOperationId()) + || identity.accountId() != operation.accountId() + || identity.tenantId() != operation.tenantId() + || !identity.connectScopeHash().equals(operation.connectScopeHash()) + || !identity.requestId().equals(operation.requestId())) { + throw new IdentityConflictException( + "Bare LOGIN exchange identity was reused with different source or binding"); + } + } + + private static void requireEvidenceCompatible( + AccountBareLoginExchangeOperation 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( + "Bare LOGIN exchange 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 sameDigest(byte[] left, byte[] right) { + return left == null ? right == null : right != null && MessageDigest.isEqual(left, right); + } + + private static void validateBareLoginEnvelope(AccountEncryptedEnvelope envelope) { + Objects.requireNonNull(envelope, "envelope"); + if (envelope.purpose() != AccountEnvelopePurpose.BARE_LOGIN_RESPONSE) { + throw new EvidenceMismatchException( + "Bare LOGIN exchange cannot store an envelope for another purpose"); + } + } + + private static void requireDigestMatch( + AccountBareLoginExchangeOperation operation, byte[] expectedDigest) { + if (!MessageDigest.isEqual(operation.requestDigest(), expectedDigest)) { + throw new IdempotencyConflictException( + "Bare LOGIN exchange request identity was reused with a different digest"); + } + } + + private static void validateIdentity(AccountBareLoginExchangeIdentity 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 bare LOGIN exchange 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 bare LOGIN exchange 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 bare LOGIN exchange 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 bare LOGIN exchange 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 bare LOGIN exchange field is missing: " + field); + } + return value; + } + + public enum ClaimDisposition { + CLAIMED, + REPLAYED + } + + public static class IdempotencyConflictException extends IllegalStateException { + public IdempotencyConflictException(String message) { + super(message); + } + } + + public static final class IdentityConflictException extends IdempotencyConflictException { + public IdentityConflictException(String message) { + super(message); + } + } + + public static final class EvidenceMismatchException extends IllegalStateException { + public EvidenceMismatchException(String message) { + super(message); + } + } + + public static final class ClaimResult { + private final ClaimDisposition disposition; + private final AccountBareLoginExchangeIdentity identity; + private final AccountBareLoginExchangeOperation operation; + + private ClaimResult( + ClaimDisposition disposition, + AccountBareLoginExchangeIdentity identity, + AccountBareLoginExchangeOperation 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 AccountBareLoginExchangeIdentity identity() { + return identity; + } + + public AccountBareLoginExchangeOperation operation() { + return operation; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginResponseEnvelope.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginResponseEnvelope.java new file mode 100644 index 0000000000..1b7fa043f9 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginResponseEnvelope.java @@ -0,0 +1,23 @@ +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 binding required for authenticated bare-LOGIN recovery. */ +public record AccountBareLoginResponseEnvelope( + UUID operationId, AccountEnvelopeBinding binding, AccountEncryptedEnvelope envelope) { + + public AccountBareLoginResponseEnvelope { + Objects.requireNonNull(operationId, "operationId"); + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(envelope, "envelope"); + if (binding.operationKind() != AccountEnvelopeBinding.OperationKind.BARE_LOGIN_EXCHANGE + || !operationId.toString().equals(binding.operationId()) + || envelope.purpose() != AccountEnvelopePurpose.BARE_LOGIN_RESPONSE) { + throw new IllegalArgumentException("Bare LOGIN response envelope binding is invalid"); + } + } +} diff --git a/services/account-service/src/main/resources/db/migration/V37__account_bare_login_exchange_storage.sql b/services/account-service/src/main/resources/db/migration/V37__account_bare_login_exchange_storage.sql new file mode 100644 index 0000000000..0ba9c3f90c --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V37__account_bare_login_exchange_storage.sql @@ -0,0 +1,328 @@ +-- Durable first-writer-wins storage for the Account-owned bare first-party LOGIN exchange. +-- The source connect-operation identity is consumed at most once. The response envelope is a +-- separate purpose-tagged encrypted record; neither table stores a raw delegation JWT. +CREATE TABLE account_bare_login_exchange_operations ( + operation_id UUID PRIMARY KEY, + source_connect_operation_id UUID NOT NULL + REFERENCES account_connect_token_issuance_operations(operation_id) ON DELETE RESTRICT, + 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, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_bare_login_exchange_source_uq + UNIQUE (source_connect_operation_id), + CONSTRAINT account_bare_login_exchange_request_uq + UNIQUE (account_id, tenant_id, connect_scope_hash, request_id), + CONSTRAINT account_bare_login_exchange_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_bare_login_exchange_status_check + CHECK (status IN ('PENDING', 'COMMITTED')), + CONSTRAINT account_bare_login_exchange_evidence_check + CHECK (((token_identity IS NULL AND token_hash IS NULL) + OR (token_identity IS NOT NULL + AND length(btrim(token_identity)) BETWEEN 1 AND 128 + AND token_hash IS NOT NULL + AND 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_bare_login_exchange_outcome_check + CHECK ((status = 'PENDING' AND outcome_code IS NULL) + OR (status = 'COMMITTED' + AND outcome_code = 'SUCCESS' + AND token_identity IS NOT NULL + 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)) +); + +CREATE TABLE account_bare_login_response_envelopes ( + operation_id UUID PRIMARY KEY, + operation_kind VARCHAR(32) NOT NULL, + source_connect_operation_id UUID NOT NULL + REFERENCES account_connect_token_issuance_operations(operation_id) ON DELETE RESTRICT, + 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_bare_login_response_envelope_operation_fk + FOREIGN KEY (operation_id) + REFERENCES account_bare_login_exchange_operations(operation_id) + ON DELETE RESTRICT, + CONSTRAINT account_bare_login_response_envelope_identity_check + CHECK (operation_kind = 'BARE_LOGIN_EXCHANGE' + AND source_connect_operation_id IS NOT NULL + 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_bare_login_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 = 'BARE_LOGIN_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 the source operation, exchange request ID, and digest. Only the +-- still-pending row may acquire evidence and reach the one immutable terminal success outcome. +-- This migration rejects deletion and deliberately defines no expiry or cleanup behavior. +-- [jooq ignore start] +CREATE FUNCTION account_bare_login_exchange_source_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + source_operation account_connect_token_issuance_operations%ROWTYPE; +BEGIN + SELECT * INTO source_operation + FROM account_connect_token_issuance_operations + WHERE operation_id = NEW.source_connect_operation_id; + IF NOT FOUND + OR source_operation.status <> 'COMMITTED' + OR source_operation.account_id IS DISTINCT FROM NEW.account_id + OR source_operation.tenant_id IS DISTINCT FROM NEW.tenant_id + OR source_operation.connect_scope_hash IS DISTINCT FROM NEW.connect_scope_hash THEN + RAISE EXCEPTION 'Bare LOGIN exchange source must be committed and match its identity' + USING ERRCODE = '23514', CONSTRAINT = 'account_bare_login_exchange_source_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_bare_login_exchange_source_insert_guard_trigger + BEFORE INSERT ON account_bare_login_exchange_operations + FOR EACH ROW + EXECUTE FUNCTION account_bare_login_exchange_source_insert_guard(); + +CREATE FUNCTION account_bare_login_exchange_operation_update_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.operation_id IS DISTINCT FROM OLD.operation_id + OR NEW.source_connect_operation_id IS DISTINCT FROM OLD.source_connect_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 'Bare LOGIN exchange identity and request digest are immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_bare_login_exchange_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 'Bare LOGIN exchange evidence cannot be replaced' + USING ERRCODE = '23514', CONSTRAINT = 'account_bare_login_exchange_evidence_immutable'; + END IF; + IF OLD.status = 'COMMITTED' THEN + RAISE EXCEPTION 'Terminal bare LOGIN exchange outcome is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_bare_login_exchange_terminal_immutable'; + END IF; + IF NEW.status IS DISTINCT FROM OLD.status + AND NOT (OLD.status = 'PENDING' AND NEW.status = 'COMMITTED') THEN + RAISE EXCEPTION 'Bare LOGIN exchange lifecycle transition is invalid' + USING ERRCODE = '23514', CONSTRAINT = 'account_bare_login_exchange_lifecycle_transition'; + END IF; + NEW.updated_at = CURRENT_TIMESTAMP; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_bare_login_exchange_operation_update_guard_trigger + BEFORE UPDATE ON account_bare_login_exchange_operations + FOR EACH ROW + EXECUTE FUNCTION account_bare_login_exchange_operation_update_guard(); + +CREATE FUNCTION account_bare_login_exchange_operation_delete_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Bare LOGIN exchange operation is immutable and cannot be deleted' + USING ERRCODE = '23514', CONSTRAINT = 'account_bare_login_exchange_operation_no_delete'; + RETURN OLD; +END; +$$; + +CREATE TRIGGER account_bare_login_exchange_operation_delete_guard_trigger + BEFORE DELETE ON account_bare_login_exchange_operations + FOR EACH ROW + EXECUTE FUNCTION account_bare_login_exchange_operation_delete_guard(); + +CREATE FUNCTION account_bare_login_response_envelope_update_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Bare LOGIN response envelope is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_bare_login_response_envelope_immutable'; + RETURN OLD; +END; +$$; + +CREATE TRIGGER account_bare_login_response_envelope_update_guard_trigger + BEFORE UPDATE ON account_bare_login_response_envelopes + FOR EACH ROW + EXECUTE FUNCTION account_bare_login_response_envelope_update_guard(); + +CREATE FUNCTION account_bare_login_response_envelope_delete_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Bare LOGIN response envelope is immutable and cannot be deleted' + USING ERRCODE = '23514', CONSTRAINT = 'account_bare_login_response_envelope_no_delete'; + RETURN OLD; +END; +$$; + +CREATE TRIGGER account_bare_login_response_envelope_delete_guard_trigger + BEFORE DELETE ON account_bare_login_response_envelopes + FOR EACH ROW + EXECUTE FUNCTION account_bare_login_response_envelope_delete_guard(); + +CREATE FUNCTION account_bare_login_pending_commit_check() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + final_status VARCHAR(16); +BEGIN + SELECT status INTO final_status + FROM account_bare_login_exchange_operations + WHERE operation_id = NEW.operation_id; + IF final_status = 'PENDING' THEN + RAISE EXCEPTION 'Bare LOGIN exchange cannot commit while still pending' + USING ERRCODE = '23514', CONSTRAINT = 'account_bare_login_pending_commit_required'; + END IF; + RETURN NULL; +END; +$$; + +CREATE CONSTRAINT TRIGGER account_bare_login_pending_commit_check_trigger + AFTER INSERT OR UPDATE ON account_bare_login_exchange_operations + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW + EXECUTE FUNCTION account_bare_login_pending_commit_check(); + +CREATE FUNCTION account_bare_login_response_envelope_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + operation account_bare_login_exchange_operations%ROWTYPE; +BEGIN + SELECT * INTO operation + FROM account_bare_login_exchange_operations + WHERE operation_id = NEW.operation_id; + IF NOT FOUND + OR operation.status <> 'COMMITTED' + OR operation.source_connect_operation_id IS DISTINCT FROM NEW.source_connect_operation_id + 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 'Bare LOGIN response envelope does not match its terminal operation' + USING ERRCODE = '23514', CONSTRAINT = 'account_bare_login_response_envelope_operation_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_bare_login_response_envelope_insert_guard_trigger + BEFORE INSERT ON account_bare_login_response_envelopes + FOR EACH ROW + EXECUTE FUNCTION account_bare_login_response_envelope_insert_guard(); + +CREATE FUNCTION account_bare_login_terminal_envelope_check() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.status = 'COMMITTED' AND NOT EXISTS ( + SELECT 1 + FROM account_bare_login_response_envelopes envelope + WHERE envelope.operation_id = NEW.operation_id + AND envelope.source_connect_operation_id = NEW.source_connect_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 bare LOGIN exchange requires its exact response envelope' + USING ERRCODE = '23514', CONSTRAINT = 'account_bare_login_terminal_envelope_required'; + END IF; + RETURN NULL; +END; +$$; + +CREATE CONSTRAINT TRIGGER account_bare_login_terminal_envelope_check_trigger + AFTER INSERT OR UPDATE ON account_bare_login_exchange_operations + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW + EXECUTE FUNCTION account_bare_login_terminal_envelope_check(); +-- [jooq ignore end] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java new file mode 100644 index 0000000000..de1852f5d8 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java @@ -0,0 +1,756 @@ +package integration.net.firedevops.firemud.accountservice; + +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 java.util.function.Supplier; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginExchangeIdentity; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginExchangeOperation.Lifecycle; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginExchangeRepository; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginResponseEnvelope; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceIdentity; +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.AccountEnvelopePurpose; +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.TransactionSystemException; +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 AccountBareLoginExchangeRepositoryIntegrationTest { + private static final String SCHEMA = "account_bare_login_exchange_proof"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void claimOnlyTransactionRollsBackPendingExchange() { + TestContext context = newTestContext(); + Source source = committedSource(context); + AccountBareLoginExchangeIdentity identity = source.exchangeIdentity(); + byte[] requestDigest = digest(0); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> context.repository().claim(identity, requestDigest))) + .isInstanceOf(TransactionSystemException.class); + assertThat( + inTransaction( + context.transaction(), () -> context.repository().find(identity, requestDigest))) + .isEmpty(); + } + + @Test + void sourceMustBeCommittedAndFirstWriterOwnsTheExchangeIdentity() { + TestContext context = newTestContext(); + Source source = committedSource(context); + AccountBareLoginExchangeIdentity identity = source.exchangeIdentity(); + byte[] digest = digest(1); + + ExchangeResult firstResult = + inTransaction( + context.transaction(), + () -> { + var claimed = context.repository().claim(identity, digest); + AccountEnvelopeBinding binding = + binding(claimed.operation().operationId(), identity, digest, 2); + context + .repository() + .recordPendingEvidence( + claimed, + digest, + "delegation-jti-source", + digest(80), + binding.contextEvidenceDigest(), + binding.authorityTupleDigest(), + binding.issuanceFenceDigest(), + binding.postconditionDigest()); + AccountBareLoginResponseEnvelope stored = + context + .repository() + .completeWithEnvelope( + claimed, + digest, + "delegation-jti-source", + digest(80), + binding, + encryptedEnvelope(AccountEnvelopePurpose.BARE_LOGIN_RESPONSE)); + return new ExchangeResult(claimed, binding, stored); + }); + var claimed = firstResult.claim(); + var exactRetry = + inTransaction(context.transaction(), () -> context.repository().claim(identity, digest)); + + assertThat(claimed.disposition()) + .isEqualTo(AccountBareLoginExchangeRepository.ClaimDisposition.CLAIMED); + assertThat(exactRetry.disposition()) + .isEqualTo(AccountBareLoginExchangeRepository.ClaimDisposition.REPLAYED); + assertThat(exactRetry.operation().operationId()).isEqualTo(claimed.operation().operationId()); + assertThat(exactRetry.operation().lifecycle()).isEqualTo(Lifecycle.COMMITTED); + assertThat( + inTransaction( + context.transaction(), + () -> + context + .repository() + .readResponseEnvelope(identity, digest, firstResult.binding()))) + .contains(firstResult.envelope()); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), () -> context.repository().claim(identity, digest(2)))) + .isInstanceOf(AccountBareLoginExchangeRepository.IdempotencyConflictException.class); + + AccountBareLoginExchangeIdentity competingIdentity = + new AccountBareLoginExchangeIdentity( + identity.sourceConnectOperationId(), + identity.accountId(), + identity.tenantId(), + identity.connectScopeId(), + "different-exchange-request"); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> context.repository().claim(competingIdentity, digest))) + .isInstanceOf(AccountBareLoginExchangeRepository.IdentityConflictException.class); + + Source pendingSource = pendingSource(context, identity.accountId(), identity.connectScopeId()); + AccountBareLoginExchangeIdentity pendingIdentity = pendingSource.exchangeIdentity(); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> context.repository().claim(pendingIdentity, digest))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not committed"); + } + + @Test + void pendingEvidenceThenTerminalSuccessReadBacksExactPurposeBoundEnvelope() { + TestContext context = newTestContext(); + Source source = committedSource(context); + AccountBareLoginExchangeIdentity identity = source.exchangeIdentity(); + byte[] requestDigest = digest(10); + ExchangeResult result = + inTransaction( + context.transaction(), + () -> { + var claim = context.repository().claim(identity, requestDigest); + AccountEnvelopeBinding binding = + binding(claim.operation().operationId(), identity, requestDigest, 21); + var pending = + context + .repository() + .recordPendingEvidence( + claim, + requestDigest, + "delegation-jti-1", + digest(80), + binding.contextEvidenceDigest(), + binding.authorityTupleDigest(), + binding.issuanceFenceDigest(), + binding.postconditionDigest()); + assertThat(pending.lifecycle()).isEqualTo(Lifecycle.PENDING); + assertThat(pending.tokenIdentity()).isEqualTo("delegation-jti-1"); + AccountBareLoginResponseEnvelope stored = + context + .repository() + .completeWithEnvelope( + claim, + requestDigest, + "delegation-jti-1", + digest(80), + binding, + encryptedEnvelope(AccountEnvelopePurpose.BARE_LOGIN_RESPONSE)); + return new ExchangeResult(claim, binding, stored); + }); + var claim = result.claim(); + AccountEnvelopeBinding binding = result.binding(); + var stored = result.envelope(); + assertThat( + inTransaction( + context.transaction(), + () -> context.repository().readResponseEnvelope(identity, requestDigest, binding))) + .contains(stored); + var exactReadback = + inTransaction( + context.transaction(), + () -> + context + .repository() + .readResponseEnvelope(identity, requestDigest, binding) + .orElseThrow()); + + assertThat(stored.operationId()).isEqualTo(claim.operation().operationId()); + assertThat(exactReadback).isEqualTo(stored); + assertThat(exactReadback.binding()).isEqualTo(binding); + assertThat(exactReadback.envelope()).isEqualTo(stored.envelope()); + var exactRetry = + inTransaction( + context.transaction(), () -> context.repository().claim(identity, requestDigest)); + assertThat(exactRetry.disposition()) + .isEqualTo(AccountBareLoginExchangeRepository.ClaimDisposition.REPLAYED); + assertThat(exactRetry.operation().operationId()).isEqualTo(claim.operation().operationId()); + var committed = + inTransaction( + context.transaction(), + () -> context.repository().find(identity, requestDigest).orElseThrow()); + assertThat(committed.lifecycle()).isEqualTo(Lifecycle.COMMITTED); + assertThat(committed.outcomeCode()).isEqualTo("SUCCESS"); + assertThat(committed.tokenHash()).containsExactly(digest(80)); + assertThat(committed.contextEvidenceDigest()).containsExactly(binding.contextEvidenceDigest()); + assertThat(committed.toString()) + .isEqualTo( + "AccountBareLoginExchangeOperation{operationId=" + + committed.operationId() + + ", sourceConnectOperationId=" + + committed.sourceConnectOperationId() + + ", accountId=" + + committed.accountId() + + ", tenantId=" + + committed.tenantId() + + ", requestId='" + + committed.requestId() + + "', lifecycle=COMMITTED, secretEvidence=}"); + assertThat(committed.toString()).doesNotContain("delegation-jti-1"); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), () -> context.repository().find(identity, digest(11)))) + .isInstanceOf(AccountBareLoginExchangeRepository.IdempotencyConflictException.class); + } + + @Test + void wrongIdentityBindingOrPurposeCannotTerminalizeThePendingExchange() { + TestContext context = newTestContext(); + Source source = committedSource(context); + AccountBareLoginExchangeIdentity identity = source.exchangeIdentity(); + byte[] requestDigest = digest(20); + ExchangeResult result = + inTransaction( + context.transaction(), + () -> { + var claim = context.repository().claim(identity, requestDigest); + AccountEnvelopeBinding binding = + binding(claim.operation().operationId(), identity, requestDigest, 31); + assertThatThrownBy( + () -> + context + .repository() + .completeWithEnvelope( + claim, + requestDigest, + "delegation-jti-2", + digest(81), + binding(UUID.randomUUID(), identity, requestDigest, 31), + encryptedEnvelope(AccountEnvelopePurpose.BARE_LOGIN_RESPONSE))) + .isInstanceOf(AccountBareLoginExchangeRepository.EvidenceMismatchException.class); + assertThatThrownBy( + () -> + context + .repository() + .completeWithEnvelope( + claim, + requestDigest, + "delegation-jti-2", + digest(81), + binding, + encryptedEnvelope(AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE))) + .isInstanceOf(AccountBareLoginExchangeRepository.EvidenceMismatchException.class); + AccountBareLoginResponseEnvelope stored = + context + .repository() + .completeWithEnvelope( + claim, + requestDigest, + "delegation-jti-2", + digest(81), + binding, + encryptedEnvelope(AccountEnvelopePurpose.BARE_LOGIN_RESPONSE)); + return new ExchangeResult(claim, binding, stored); + }); + assertThat(result.envelope().operationId()).isEqualTo(result.claim().operation().operationId()); + assertThat( + inTransaction( + context.transaction(), + () -> + context + .repository() + .readResponseEnvelope(identity, requestDigest, result.binding()))) + .contains(result.envelope()); + } + + @Test + void conflictingPendingEvidenceCannotReplaceWriteOnceTerminalEvidence() { + TestContext context = newTestContext(); + Source source = committedSource(context); + AccountBareLoginExchangeIdentity identity = source.exchangeIdentity(); + byte[] requestDigest = digest(30); + ExchangeResult result = + inTransaction( + context.transaction(), + () -> { + var claim = context.repository().claim(identity, requestDigest); + AccountEnvelopeBinding originalBinding = + binding(claim.operation().operationId(), identity, requestDigest, 41); + var pending = + context + .repository() + .recordPendingEvidence( + claim, + requestDigest, + "delegation-jti-original", + digest(90), + originalBinding.contextEvidenceDigest(), + originalBinding.authorityTupleDigest(), + originalBinding.issuanceFenceDigest(), + originalBinding.postconditionDigest()); + assertThat(pending.lifecycle()).isEqualTo(Lifecycle.PENDING); + assertThat(pending.tokenIdentity()).isEqualTo("delegation-jti-original"); + + AccountEnvelopeBinding conflictingBinding = + binding(claim.operation().operationId(), identity, requestDigest, 42); + assertThatThrownBy( + () -> + context + .repository() + .recordPendingEvidence( + claim, + requestDigest, + "delegation-jti-conflict", + digest(91), + conflictingBinding.contextEvidenceDigest(), + conflictingBinding.authorityTupleDigest(), + conflictingBinding.issuanceFenceDigest(), + conflictingBinding.postconditionDigest())) + .isInstanceOf(AccountBareLoginExchangeRepository.EvidenceMismatchException.class); + assertThatThrownBy( + () -> + context + .repository() + .completeWithEnvelope( + claim, + requestDigest, + "delegation-jti-conflict", + digest(91), + conflictingBinding, + encryptedEnvelope(AccountEnvelopePurpose.BARE_LOGIN_RESPONSE))) + .isInstanceOf(AccountBareLoginExchangeRepository.EvidenceMismatchException.class); + AccountBareLoginResponseEnvelope stored = + context + .repository() + .completeWithEnvelope( + claim, + requestDigest, + "delegation-jti-original", + digest(90), + originalBinding, + encryptedEnvelope(AccountEnvelopePurpose.BARE_LOGIN_RESPONSE)); + return new ExchangeResult(claim, originalBinding, stored); + }); + assertThat(result.envelope().operationId()).isEqualTo(result.claim().operation().operationId()); + assertThat( + inTransaction( + context.transaction(), + () -> + context + .repository() + .readResponseEnvelope(identity, requestDigest, result.binding()))) + .contains(result.envelope()); + } + + @Test + void directSqlExchangeInsertRequiresCommittedMatchingSourceIdentity() { + TestContext context = newTestContext(); + long pendingAccountId = insertAccount(context.dsl()); + Source pendingSource = + pendingSource(context, pendingAccountId, "pending-source-" + UUID.randomUUID()); + AccountBareLoginExchangeIdentity pendingIdentity = pendingSource.exchangeIdentity(); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + insertBareOperationDirect( + context, UUID.randomUUID(), pendingIdentity, digest(70)))) + .isInstanceOf(DataAccessException.class); + + Source committedSource = committedSource(context); + AccountBareLoginExchangeIdentity committedIdentity = committedSource.exchangeIdentity(); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + insertBareOperationDirect( + context, + UUID.randomUUID(), + committedIdentity.sourceConnectOperationId(), + committedIdentity.accountId(), + committedIdentity.tenantId() + 1, + committedIdentity.connectScopeId(), + "wrong-tenant-" + UUID.randomUUID(), + digest(71)))) + .isInstanceOf(DataAccessException.class); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + insertBareOperationDirect( + context, + UUID.randomUUID(), + committedIdentity.sourceConnectOperationId(), + committedIdentity.accountId(), + committedIdentity.tenantId(), + committedIdentity.connectScopeId() + "-wrong", + "wrong-scope-" + UUID.randomUUID(), + digest(72)))) + .isInstanceOf(DataAccessException.class); + + long otherAccountId = insertAccount(context.dsl()); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + insertBareOperationDirect( + context, + UUID.randomUUID(), + committedIdentity.sourceConnectOperationId(), + otherAccountId, + committedIdentity.tenantId(), + committedIdentity.connectScopeId(), + "wrong-account-" + UUID.randomUUID(), + digest(73)))) + .isInstanceOf(DataAccessException.class); + } + + @Test + void directSqlCannotDeletePendingOrTerminalExchangeRows() { + TestContext context = newTestContext(); + Source pendingSource = committedSource(context); + AccountBareLoginExchangeIdentity pendingIdentity = pendingSource.exchangeIdentity(); + byte[] pendingDigest = digest(74); + UUID pendingOperationId = UUID.randomUUID(); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + deletePendingOperationDirect( + context, pendingOperationId, pendingIdentity, pendingDigest))) + .isInstanceOf(DataAccessException.class); + assertThat( + inTransaction( + context.transaction(), + () -> context.repository().find(pendingIdentity, pendingDigest))) + .isEmpty(); + + Source terminalSource = committedSource(context); + AccountBareLoginExchangeIdentity terminalIdentity = terminalSource.exchangeIdentity(); + byte[] terminalDigest = digest(75); + ExchangeResult terminalResult = + inTransaction( + context.transaction(), + () -> { + var terminalClaim = context.repository().claim(terminalIdentity, terminalDigest); + AccountEnvelopeBinding terminalBinding = + binding( + terminalClaim.operation().operationId(), + terminalIdentity, + terminalDigest, + 76); + context + .repository() + .recordPendingEvidence( + terminalClaim, + terminalDigest, + "delegation-jti-delete-guard", + digest(92), + terminalBinding.contextEvidenceDigest(), + terminalBinding.authorityTupleDigest(), + terminalBinding.issuanceFenceDigest(), + terminalBinding.postconditionDigest()); + AccountBareLoginResponseEnvelope stored = + context + .repository() + .completeWithEnvelope( + terminalClaim, + terminalDigest, + "delegation-jti-delete-guard", + digest(92), + terminalBinding, + encryptedEnvelope(AccountEnvelopePurpose.BARE_LOGIN_RESPONSE)); + return new ExchangeResult(terminalClaim, terminalBinding, stored); + }); + AccountBareLoginResponseEnvelope stored = terminalResult.envelope(); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .dsl() + .execute( + "DELETE FROM account_bare_login_response_envelopes " + + "WHERE operation_id = ?", + stored.operationId()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .dsl() + .execute( + "DELETE FROM account_bare_login_exchange_operations " + + "WHERE operation_id = ?", + stored.operationId()))) + .isInstanceOf(DataAccessException.class); + var terminalReadback = + inTransaction( + context.transaction(), + () -> + context + .repository() + .readResponseEnvelope( + terminalIdentity, terminalDigest, terminalResult.binding())); + assertThat(terminalReadback).contains(stored); + } + + 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 AccountBareLoginExchangeRepository(dsl), + new AccountConnectTokenIssuanceRepository(dsl), + new TransactionTemplate(new DataSourceTransactionManager(dataSource))); + } + + private Source committedSource(TestContext context) { + long accountId = insertAccount(context.dsl()); + return createSource(context, accountId, "connect-scope-" + UUID.randomUUID(), true); + } + + private Source pendingSource(TestContext context, long accountId, String connectScopeId) { + return createSource(context, accountId, connectScopeId, false); + } + + private Source createSource( + TestContext context, long accountId, String connectScopeId, boolean commitSource) { + AccountConnectTokenIssuanceIdentity sourceIdentity = + new AccountConnectTokenIssuanceIdentity( + accountId, 77L, connectScopeId, "connect-request-" + UUID.randomUUID()); + byte[] sourceDigest = digest(commitSource ? 60 : 61); + var sourceClaim = + inTransaction( + context.transaction(), + () -> context.sourceRepository().claim(sourceIdentity, sourceDigest)); + if (commitSource) { + AccountEnvelopeBinding sourceBinding = + new AccountEnvelopeBinding( + AccountEnvelopeBinding.OperationKind.CONNECT_TOKEN_ISSUANCE, + sourceClaim.operation().operationId().toString(), + sourceIdentity.requestId(), + Long.toString(sourceIdentity.accountId()), + Long.toString(sourceIdentity.tenantId()), + sourceIdentity.connectScopeId(), + null, + sourceDigest, + digest(62), + digest(63), + digest(64), + digest(65)); + inTransaction( + context.transaction(), + () -> + context + .sourceRepository() + .completeWithEnvelope( + sourceClaim, + sourceDigest, + net.firedevops.firemud.accountservice.repository + .AccountConnectTokenIssuanceOperation.Lifecycle.COMMITTED, + "SUCCESS", + "connect-jti-" + UUID.randomUUID(), + digest(66), + sourceBinding, + encryptedEnvelope(AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE))); + } + return new Source( + sourceClaim.operation().operationId(), + new AccountBareLoginExchangeIdentity( + sourceClaim.operation().operationId(), + sourceClaim.operation().accountId(), + sourceClaim.operation().tenantId(), + connectScopeId, + "exchange-request-" + UUID.randomUUID())); + } + + 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", + "bare_login_" + unique.substring(0, 12), + unique + "@example.test", + "test-hash") + .fetchOne(0, Long.class); + if (accountId == null) { + throw new IllegalStateException("Bare LOGIN repository test account was not inserted"); + } + return accountId; + } + + private int insertBareOperationDirect( + TestContext context, + UUID operationId, + AccountBareLoginExchangeIdentity identity, + byte[] requestDigest) { + return insertBareOperationDirect( + context, + operationId, + identity.sourceConnectOperationId(), + identity.accountId(), + identity.tenantId(), + identity.connectScopeId(), + identity.requestId(), + requestDigest); + } + + private int insertBareOperationDirect( + TestContext context, + UUID operationId, + UUID sourceOperationId, + long accountId, + long tenantId, + String connectScopeId, + String requestId, + byte[] requestDigest) { + return context + .dsl() + .execute( + "INSERT INTO account_bare_login_exchange_operations " + + "(operation_id, source_connect_operation_id, account_id, tenant_id, " + + "connect_scope_hash, request_id, request_digest_version, request_digest, status) " + + "VALUES (?, ?, ?, ?, ?, ?, 1, ?, 'PENDING')", + operationId, + sourceOperationId, + accountId, + tenantId, + AccountJoinDigest.tokenHash(connectScopeId), + requestId, + requestDigest); + } + + private int deletePendingOperationDirect( + TestContext context, + UUID operationId, + AccountBareLoginExchangeIdentity identity, + byte[] requestDigest) { + insertBareOperationDirect(context, operationId, identity, requestDigest); + return context + .dsl() + .execute( + "DELETE FROM account_bare_login_exchange_operations WHERE operation_id = ?", + operationId); + } + + private AccountEnvelopeBinding binding( + UUID operationId, AccountBareLoginExchangeIdentity identity, byte[] requestDigest, int seed) { + return new AccountEnvelopeBinding( + AccountEnvelopeBinding.OperationKind.BARE_LOGIN_EXCHANGE, + operationId.toString(), + identity.requestId(), + Long.toString(identity.accountId()), + Long.toString(identity.tenantId()), + identity.connectScopeId(), + identity.sourceConnectOperationId().toString(), + requestDigest, + digest(seed), + digest(seed + 1), + digest(seed + 2), + digest(seed + 3)); + } + + 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 ExchangeResult( + AccountBareLoginExchangeRepository.ClaimResult claim, + AccountEnvelopeBinding binding, + AccountBareLoginResponseEnvelope envelope) {} + + private record Source(UUID sourceOperationId, AccountBareLoginExchangeIdentity exchangeIdentity) { + private Source { + if (!sourceOperationId.equals(exchangeIdentity.sourceConnectOperationId())) { + throw new IllegalArgumentException("Source operation identity must be bound exactly"); + } + } + } + + private record TestContext( + DSLContext dsl, + AccountBareLoginExchangeRepository repository, + AccountConnectTokenIssuanceRepository sourceRepository, + TransactionTemplate transaction) {} +} From a3f93197137068571399145722ed2f5bf2a24300 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 27 Sep 2026 15:23:39 +1300 Subject: [PATCH 02/14] Fail closed bare first-party login and require Account database proof --- .github/workflows/ci.yml | 17 +- .../game-session-service/protocols.md | 2 + .../system-architecture-authentication.md | 1 + .../player-access-and-session.md | 2 + dev-tools/README.md | 2 +- .../tests/gradle-proof-tooling-contract.sh | 164 +++++++++++ dev-tools/validation/inspect-test-results.sh | 267 +++++++++++++++++- .../command/text/LoginCommandHandler.java | 49 +--- .../command/text/LoginCommandHandlerTest.java | 52 ++-- 9 files changed, 485 insertions(+), 71 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 12ea985a33..5f5fda367f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -941,9 +941,24 @@ jobs: id: checks run: | echo "::group::Run Module Validation" - ./gradlew :${{ matrix.module }}:check -PfullCheck + if [[ "${{ matrix.module }}" == "account-service" ]]; then + ./gradlew :${{ matrix.module }}:check -PfullCheck --no-build-cache + else + ./gradlew :${{ matrix.module }}:check -PfullCheck + fi echo "::endgroup::" + - name: 🔎 Verify Account PostgreSQL proof cases + if: ${{ matrix.module == 'account-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest \ + --require-suite integration.net.firedevops.firemud.accountservice.AccountBareLoginExchangeRepositoryIntegrationTest \ + --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#positiveMembershipSnapshotRejectsScalarAndWrongTenantVersionMaps()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountBareLoginExchangeRepositoryIntegrationTest#claimOnlyTransactionRollsBackPendingExchange()' \ + account-service + - name: 📦 Build Runtime JAR if: ${{ contains(fromJSON(needs.changes.outputs.bootable_modules), matrix.module) }} run: ./gradlew :${{ matrix.module }}:bootJar -PfullCheck diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index c2e970b5d8..492eda06b7 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -14,6 +14,8 @@ For bootstrap-backed direct-text `LOGIN` and first-party `/ws/game/**`, the [Gat Unless explicitly described as current behavior, this document defines the target protocol. The target direct-text flow is public `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY`. Current credential and email-code `LOGIN` authenticate global Account identity without sending a tenant or requiring membership; the bootstrap instance tenant remains local transport context only and is not Account authentication authority. The target flow requires explicit `JOIN`/`Join & Play` for first public-production entry, while an existing durable `membershipLifecycleState=ACTIVE` membership permits direct `PLAY` and a grant-backed non-public path may proceed only when that same `ACTIVE` membership already exists. A grant never creates or substitutes membership. The local Account `JoinPublicProductionMembership` operation and Game Session translation/scope seam now exist, but complete direct-text and first-party end-to-end proof, PostgreSQL execution, pending-operation recovery/reconciliation, and the Account lifecycle/authority-generation snapshot needed by final admission remain incomplete. Current Account gRPC membership, grant, and entitlement reads used by Game Session fail with `FAILED_PRECONDITION` before data access, including for the Game Session workload. Accordingly, a valid-route text `PLAY` reaching runtime admission returns `AUTH_UNAVAILABLE` before membership, grant, or roster evaluation, and direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity is called; neither is currently an actionable JOIN, roster, or PLAY path. The status and target admission contract are canonical in [Authentication](../../system-architecture-authentication.md#implementation-status). The local JOIN operation does not alter the target `JOIN` -> `CHARS`/character creation -> `PLAY` sequence. +The #2881 candidate now fails an otherwise valid first-party bare `LOGIN` with retryable `AUTH_UNAVAILABLE` before enqueue or authenticated session promotion because Game Session cannot yet obtain the required one-use Account delegation exchange. Existing invalid-context and mismatched-pointer checks retain their own denials; the unauthenticated bootstrap shell is not consumed merely by this unavailable result. Credential-bearing and email-code `LOGIN` keep their existing paths. This is containment, not proof that the current context verifier meets the complete target or that first-party login works end to end. + Target communication framing uses terminated sender `OK ` response frames and recipient `EVENT ` event frames, with structured-client `PlayerOutput` schema-version negotiation and `unsupported_schema_version` rejection. Telnet and generic text WebSocket clients consume the deterministic text projection without schema negotiation. These framing and compatibility behaviors are target behavior and remain unimplemented or unproved in full; current generic and first-party projections are narrower. The owner contract is [Input, Output, and Presentation](../../system-architecture-input-output-and-presentation.md#output-model). The current Unit 1B safety correction removes `PLAY`'s account/name/hash-derived actor fallback and performs account-scoped persisted Entity roster selection only after Account admission checks. That narrower roster is not yet namespace- and policy-qualified, and Account's current gRPC membership, grant, and entitlement reads fail with `FAILED_PRECONDITION` before data access even for the Game Session workload. Current text `PLAY` therefore fails closed with `AUTH_UNAVAILABLE` before Entity roster selection; direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity is called. These statuses do not establish whether a membership, grant, or character exists. Fresh first-party `PLAY` no longer treats a connect-context token alone as retained-context replay authority, and focused post-`LOGOUT` replay suppression is present; it still requests a fresh `LOOK`. Durable logout episode/generation fencing, delayed-race proof, effective resume-window enforcement, and namespace-scoped controller takeover remain open. diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index bb7a93fdb4..51afe6d4eb 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -22,6 +22,7 @@ For every private/playtest grant consequence, the exact Account target is `{acco - **Current gameplay authentication and transport boundary:** Current gameplay authentication supports `LOGIN ` / `LOGON ` to request a verified-email login code and `LOGIN ` / `LOGON ` for an immediate password-or-code attempt on raw Telnet and other non-WebSocket text clients. Bare raw-text `LOGIN`/`LOGON` prompt exchange is target-only and currently returns `PROMPT_LOGIN_UNSUPPORTED`. Control-plane clients use `/auth/login`. First-party gameplay uses `POST /auth/player-bootstrap` to establish the `player-bootstrap` identity, then uses `/auth/bootstrap/*` discovery/action routes and `/auth/connect-token` before the gameplay socket. Clients are stateless; current Account-owned legacy authentication session records persist `tokenHash` and session metadata under the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key, while gameplay bindings remain in Redis. These records never persist the raw delegation JWT; their runtime/data ownership is defined in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#session-and-token-model). Target issued-token registry issuance, storage, and consumer enforcement in Coordination Redis are unimplemented. The Game Session Service restores gameplay session state from Redis, while the Account Service validates the supplied login secret and issues the exact `control-ui`, `player-bootstrap`, or receiver-specific private player-delegation JWT profile required by the destination. Raw Telnet gameplay command streams never carry JWT authorization. Target browser and mobile-browser gameplay uses a `player-bootstrap` JWT for HTTPS bootstrap calls and a cookie-carried one-use connect token for the `/ws/game/**` handshake; target first-party native-mobile clients that use a cookie jar remain cookie-only. Public non-browser issuance and the dedicated handshake-header carrier are target-only and unavailable until a dedicated route is fully registered and its issuance, registry, profile, and carrier proof is complete; the target design uses protected secure storage plus `X-Firemud-Connect-Token`. First-party admin/creator UIs and backend services use their own permitted token profiles. Provider-specific HTTPS sign-in remains unavailable until the provider-specific verification, collision, recovery, and end-to-end proof required by [ADR 0049](./decisions/adr-0049-optional-provider-specific-external-identity-linking.md) is complete. - **Current first-party endpoint and runtime boundary:** The current first-party browser/mobile runtime includes dedicated `POST /auth/player-bootstrap` and `POST /auth/connect-token` surfaces, Gateway rejection for missing, expired, replayed, or scope-mismatched connect tokens, and Game Session validation of the signed connect context before bare `LOGIN`, but these remain partial implementation surfaces rather than proof of the complete target flow. Current `PLAY` resolves the admissible `gameInstanceId` from realm routing and binds the legacy `{tenantId, gameInstanceId, characterId}` identity; that per-instance binding is implementation drift. Target `PLAY` binds the controller identity `{tenantId, playableStateNamespaceId, characterId}`, carries server-derived `playableStateScope`, and retains `{gameInstanceId, sessionId, bindingGeneration}` as runtime/value evidence. Current behavior does not claim authoritative `regionId`, `regionEpoch`, lease-owner, or lease-fence resolution. Public non-browser issuance and the dedicated handshake-header carrier remain unavailable. +- **Current bare first-party `LOGIN` containment:** The #2881 candidate retains malformed-context and pointer-mismatch rejection, then returns retryable `AUTH_UNAVAILABLE` for an otherwise valid bare `LOGIN` before command enqueue or authenticated Game Session state is saved. The unauthenticated bootstrap shell remains available for a later explicit retry. Gateway context or a connect-token `jti` alone does not authenticate Account; the Account-owned one-use exchange, committed issuance, private delegation, and recovery proof remain unimplemented. Credential-bearing `LOGIN` is unchanged. - **Current realm-identity gap:** Current discovery, admission-pointer mutation/read models, gameplay-connect claims, and the Gateway signed context do not carry and prove durable `realmId` end to end; several runtime surfaces still key or resolve routes directly from `worldSlug`/`realmSlug`. The target resolves those selectors to `{tenantId, realmId}` before pointer lookup and carries `realmId` in the exact selected-target snapshot and signed context. - **Current provider-specific sign-in boundary:** Optional provider-specific HTTPS sign-in is permitted only after complete provider proof; password and verified-email code remain the Account-owned baseline and fallback, and Telnet never carries provider credentials. See [ADR 0049](./decisions/adr-0049-optional-provider-specific-external-identity-linking.md). - **Current raw-text challenge semantics:** The current raw-text email-code challenge is two commands: `LOGIN ` (or `LOGON `) requests an Account-owned, server-side verified-email challenge bound to the normalized account/email and its configured expiry without authenticating the session, then `LOGIN ` (or `LOGON `) submits that code. The separate immediate-auth form is `LOGIN ` (or `LOGON `) with one secret. Account selects the `EMAIL_OTP` validator first when the supplied secret matches the live challenge; otherwise it verifies `PASSWORD` when that account mode is enabled. The client does not select the validator, and a code is not valid outside its server-side challenge and expiry. 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 1bd3ecba71..3ea646dda6 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -32,6 +32,8 @@ The current Unit 1B draft's conditional Game Session `PLAY` branch now distingui The approved first-party bare-`LOGIN` private-delegation exchange is not live. 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 or key-ring deployment. The separate V37 storage candidate binds one exchange request to a committed V35 source, preserves first-writer request identity and digest, and permits only an atomic write-once pending-evidence to terminal-success transition with an exact purpose-bound envelope; it does not mint, decrypt, or return a delegation JWT. Its seven PostgreSQL cases compile but skipped without Docker; database execution, caller lost-response recovery, current-authority revalidation, exact Game Session caller proof, and the complete producer/consumer path remain open. 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 #2881 candidate also contains Game Session's fail-closed bare-`LOGIN` guard: otherwise valid first-party context returns `AUTH_UNAVAILABLE` before enqueue or authenticated session promotion while the Account exchange is unwired, without changing credential-bearing `LOGIN`. Focused handler tests exercise no enqueue, no save, and retained unauthenticated bootstrap context. The Account CI matrix now disables Gradle build-cache reuse and requires exact JOIN-map and exchange-transaction JUnit cases to execute without skips; synthetic strict-inspector contracts pass, while local XML correctly fails that gate because Docker is unavailable. This does not make the V37 storage a live exchange, or prove Account/Gateway context verification and lost-response recovery. + 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. diff --git a/dev-tools/README.md b/dev-tools/README.md index 2a4bee6ed9..965872c7ce 100644 --- a/dev-tools/README.md +++ b/dev-tools/README.md @@ -15,7 +15,7 @@ Keep the root of `dev-tools/` small. Only canonical human-facing entrypoints and - `build-local-smoke-images.sh` – builds the pinned local base and service images for a 40-character commit tag after rebuilding the service boot jars. - `verify-compose-health.sh` – shared health gate used by the smoke entrypoints. - `validation/run-locked-gradle.sh` – canonical local verification wrapper that prevents overlapping service-level Gradle runs from writing the same test-result trees at once. For example: `bash dev-tools/validation/run-locked-gradle.sh :account-service:test`. -- `validation/inspect-test-results.sh` – read-only JUnit XML summary helper for diagnosing quiet post-suite Gradle tails without guessing at process state. For example: `bash dev-tools/validation/inspect-test-results.sh account-service`. This is diagnostic evidence only and does not prove that the Gradle invocation completed cleanly. +- `validation/inspect-test-results.sh` – read-only JUnit XML helper for diagnosing quiet post-suite Gradle tails without guessing at process state. For example: `bash dev-tools/validation/inspect-test-results.sh account-service`. Its default mode is diagnostic only and does not prove that the Gradle invocation completed cleanly. CI may use `--strict` with repeated `--require-suite ` and `--require-case ` arguments to fail closed on missing, duplicate, malformed, empty, skipped, or failing JUnit proof; strict output contains only counts, requested names, and outcomes. - `pr-review` – the sole review controller. Use `dev-tools/pr-review stack set ...` and `stack show` for the repository review stack, `status [--pr ]` for fail-closed live state, `run hosted|cli [--expect-pr ]` for a complete checkpoint, `evidence []` for anchored evidence, and `decide ...` for explicit judgments. The complete review, status, checkpoint, and disposition policy is owned by [PR lifecycle: Review and Status](../design/developer-workflows/pr-lifecycle.md#review-and-status). The controller stores only stack configuration, exact policy overrides, explicit judgments (including summary-only finding dispositions), and reconciliation decisions in a locked private common-directory state file; live PR, CI, checkpoint, and review evidence is derived when requested. For hands-on acceptance, pass the paired global options `--acceptance-fixture ` and `--state-path `; these use synthetic fixture adapters in a dedicated private directory and never contact GitHub or consume review quota. The implementation and focused contracts live in `pr_review/` and `tests/pr-review-controller-contract.sh`. An acceptance fixture is a JSON object containing `repository`, `default_base_ref`, `default_base_tip`, `branch_heads`, `pull_requests`, `ancestors`, `merge_bases`, `patch_ids`, and optional `ordered_prs` and `evidence`. Pull requests provide exact `base_ref`, `base_tip`, `head`, and `head_repository` identities; `head_repository` must explicitly match the fixture's `repository`. They may also provide `head_ref`, state, mergeability, and merge flags; Git relationships and patch identities are explicit so missing or stale facts fail closed. Create a dedicated private directory with `review_acceptance_dir=$(mktemp -d)`, place the fixture there, then run `dev-tools/pr-review --acceptance-fixture "$review_acceptance_dir/fixture.json" --state-path "$review_acceptance_dir/state.json" status --json`. The state directory must already exist, be owned by the caller, and have mode `0700`; the canonical state directory is forbidden. diff --git a/dev-tools/tests/gradle-proof-tooling-contract.sh b/dev-tools/tests/gradle-proof-tooling-contract.sh index 6f7b487f35..35b4ae8b3e 100644 --- a/dev-tools/tests/gradle-proof-tooling-contract.sh +++ b/dev-tools/tests/gradle-proof-tooling-contract.sh @@ -77,6 +77,170 @@ grep -q "Most recent XML on disk:" <<<"$inspection_output" grep -q "Failing XML files:" <<<"$inspection_output" grep -q "Diagnostic only:" <<<"$inspection_output" +JOIN_SUITE="net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest" +EXCHANGE_SUITE="integration.net.firedevops.firemud.accountservice.AccountBareLoginExchangeRepositoryIntegrationTest" +JOIN_CASE="$JOIN_SUITE#positiveMembershipSnapshotRejectsScalarAndWrongTenantVersionMaps()" +EXCHANGE_CASE="$EXCHANGE_SUITE#claimOnlyTransactionRollsBackPendingExchange()" + +inspect_strict() { + bash "$INSPECTOR" --root "$1" --strict \ + --require-suite "$JOIN_SUITE" \ + --require-suite "$EXCHANGE_SUITE" \ + --require-case "$JOIN_CASE" \ + --require-case "$EXCHANGE_CASE" \ + account-service +} + +new_strict_fixture() { + mkdir -p "$1/services/account-service/build/test-results/integrationTest" +} + +STRICT_GREEN_ROOT="$TMP_DIR/strict-green" +new_strict_fixture "$STRICT_GREEN_ROOT" +cat >"$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" < + + + STRICT_OUTPUT_SENTINEL + +XML +cat >"$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" < + + +XML +strict_green_output="$(inspect_strict "$STRICT_GREEN_ROOT")" +grep -q '^Strict JUnit proof: passed$' <<<"$strict_green_output" +grep -Fq "Suite $JOIN_SUITE: tests=2 skipped=0 failures=0 errors=0 outcome=passed" <<<"$strict_green_output" +grep -Fq "Case $JOIN_CASE: executions=1 outcome=passed" <<<"$strict_green_output" +grep -Fq "Case $EXCHANGE_CASE: executions=1 outcome=passed" <<<"$strict_green_output" +! grep -q "STRICT_OUTPUT_SENTINEL" <<<"$strict_green_output" + +STRICT_MISSING_SUITE_ROOT="$TMP_DIR/strict-missing-suite" +new_strict_fixture "$STRICT_MISSING_SUITE_ROOT" +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" \ + "$STRICT_MISSING_SUITE_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" +if missing_suite_output="$(inspect_strict "$STRICT_MISSING_SUITE_ROOT" 2>&1)"; then + echo "Strict inspection unexpectedly accepted a missing suite." >&2 + exit 1 +fi +grep -Fq "Missing required suite: $EXCHANGE_SUITE" <<<"$missing_suite_output" + +STRICT_NO_REPORTS_ROOT="$TMP_DIR/strict-no-reports" +new_strict_fixture "$STRICT_NO_REPORTS_ROOT" +if no_reports_output="$(inspect_strict "$STRICT_NO_REPORTS_ROOT" 2>&1)"; then + echo "Strict inspection unexpectedly accepted an empty report directory." >&2 + exit 1 +fi +grep -Fq "No JUnit XML reports were found." <<<"$no_reports_output" + +STRICT_MISSING_CASE_ROOT="$TMP_DIR/strict-missing-case" +new_strict_fixture "$STRICT_MISSING_CASE_ROOT" +cat >"$STRICT_MISSING_CASE_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" < + + +XML +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" \ + "$STRICT_MISSING_CASE_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" +if missing_case_output="$(inspect_strict "$STRICT_MISSING_CASE_ROOT" 2>&1)"; then + echo "Strict inspection unexpectedly accepted a missing case." >&2 + exit 1 +fi +grep -Fq "Missing required case: $JOIN_CASE" <<<"$missing_case_output" + +STRICT_ZERO_TESTS_ROOT="$TMP_DIR/strict-zero-tests" +new_strict_fixture "$STRICT_ZERO_TESTS_ROOT" +cat >"$STRICT_ZERO_TESTS_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" < +XML +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" \ + "$STRICT_ZERO_TESTS_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" +if zero_tests_output="$(inspect_strict "$STRICT_ZERO_TESTS_ROOT" 2>&1)"; then + echo "Strict inspection unexpectedly accepted an empty required suite." >&2 + exit 1 +fi +grep -Fq "Required suite has zero tests: $JOIN_SUITE" <<<"$zero_tests_output" + +STRICT_SKIPPED_ROOT="$TMP_DIR/strict-skipped" +new_strict_fixture "$STRICT_SKIPPED_ROOT" +cat >"$STRICT_SKIPPED_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" < + + +XML +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" \ + "$STRICT_SKIPPED_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" +if skipped_output="$(inspect_strict "$STRICT_SKIPPED_ROOT" 2>&1)"; then + echo "Strict inspection unexpectedly accepted a skipped suite." >&2 + exit 1 +fi +grep -Fq "Required suite is failing, errored, or skipped: $JOIN_SUITE" <<<"$skipped_output" +grep -Fq "Case $JOIN_CASE: executions=1 outcome=skipped" <<<"$skipped_output" + +STRICT_FAILING_ROOT="$TMP_DIR/strict-failing" +new_strict_fixture "$STRICT_FAILING_ROOT" +cat >"$STRICT_FAILING_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" < + + SENSITIVE_FAILURE_SENTINEL + + SENSITIVE_STDOUT_SENTINEL + +XML +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" \ + "$STRICT_FAILING_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" +if failing_output="$(inspect_strict "$STRICT_FAILING_ROOT" 2>&1)"; then + echo "Strict inspection unexpectedly accepted a failing suite." >&2 + exit 1 +fi +grep -Fq "Required suite is failing, errored, or skipped: $JOIN_SUITE" <<<"$failing_output" +grep -Fq "Case $JOIN_CASE: executions=1 outcome=failure" <<<"$failing_output" +! grep -q "SENSITIVE_" <<<"$failing_output" + +STRICT_DUPLICATE_SUITE_ROOT="$TMP_DIR/strict-duplicate-suite" +new_strict_fixture "$STRICT_DUPLICATE_SUITE_ROOT" +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" \ + "$STRICT_DUPLICATE_SUITE_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" \ + "$STRICT_DUPLICATE_SUITE_ROOT/services/account-service/build/test-results/integrationTest/TEST-join-copy.xml" +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" \ + "$STRICT_DUPLICATE_SUITE_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" +if duplicate_suite_output="$(inspect_strict "$STRICT_DUPLICATE_SUITE_ROOT" 2>&1)"; then + echo "Strict inspection unexpectedly accepted a duplicate suite report." >&2 + exit 1 +fi +grep -Fq "Duplicate required suite: $JOIN_SUITE (2 report(s))" <<<"$duplicate_suite_output" + +STRICT_DUPLICATE_CASE_ROOT="$TMP_DIR/strict-duplicate-case" +new_strict_fixture "$STRICT_DUPLICATE_CASE_ROOT" +cat >"$STRICT_DUPLICATE_CASE_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" < + + + +XML +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" \ + "$STRICT_DUPLICATE_CASE_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" +if duplicate_case_output="$(inspect_strict "$STRICT_DUPLICATE_CASE_ROOT" 2>&1)"; then + echo "Strict inspection unexpectedly accepted duplicate requested case execution." >&2 + exit 1 +fi +grep -Fq "Duplicate required case: $JOIN_CASE (2 execution(s))" <<<"$duplicate_case_output" + +STRICT_MALFORMED_ROOT="$TMP_DIR/strict-malformed" +new_strict_fixture "$STRICT_MALFORMED_ROOT" +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" \ + "$STRICT_MALFORMED_ROOT/services/account-service/build/test-results/integrationTest/TEST-join.xml" +cp "$STRICT_GREEN_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" \ + "$STRICT_MALFORMED_ROOT/services/account-service/build/test-results/integrationTest/TEST-exchange.xml" +printf '"$STRICT_MALFORMED_ROOT/services/account-service/build/test-results/integrationTest/TEST-malformed.xml" +if malformed_output="$(inspect_strict "$STRICT_MALFORMED_ROOT" 2>&1)"; then + echo "Strict inspection unexpectedly accepted malformed JUnit XML." >&2 + exit 1 +fi +grep -Fq "malformed reports: 1" <<<"$malformed_output" + bootstrap_validation_output="$( FIREMUD_SMOKE_COMPOSE_SERVICES=$'gateway\ngame-session-service\n' \ FIREMUD_SMOKE_NO_CACHE_SERVICES='gateway game-session-service' \ diff --git a/dev-tools/validation/inspect-test-results.sh b/dev-tools/validation/inspect-test-results.sh index 4cd95c4cce..94d11af3e3 100644 --- a/dev-tools/validation/inspect-test-results.sh +++ b/dev-tools/validation/inspect-test-results.sh @@ -5,15 +5,27 @@ ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" usage() { cat <<'EOF' >&2 -Usage: inspect-test-results.sh [--root ] +Usage: + inspect-test-results.sh [--root ] + inspect-test-results.sh --strict [--root ] \ + --require-suite ... \ + --require-case ... Summarize parsed JUnit XML currently on disk under services//build/test-results. This is diagnostic only; it helps explain quiet Gradle tails but does not prove the original Gradle invocation completed cleanly. + +Strict mode fails closed unless every named suite has exactly one non-empty, +green report and every named test case executed exactly once without a skip, +failure, or error. EOF exit 1 } +STRICT_MODE=0 +REQUIRED_SUITES=() +REQUIRED_CASES=() + while (($# > 0)); do case "$1" in --root) @@ -21,6 +33,20 @@ while (($# > 0)); do ROOT_DIR="$2" shift 2 ;; + --strict) + STRICT_MODE=1 + shift + ;; + --require-suite) + [[ $# -ge 2 ]] || usage + REQUIRED_SUITES+=("$2") + shift 2 + ;; + --require-case) + [[ $# -ge 2 ]] || usage + REQUIRED_CASES+=("$2") + shift 2 + ;; --help|-h) usage ;; @@ -32,6 +58,39 @@ done [[ $# -eq 1 ]] || usage +if [[ "$STRICT_MODE" == "1" ]]; then + ((${#REQUIRED_SUITES[@]} > 0 && ${#REQUIRED_CASES[@]} > 0)) || usage + + for ((i = 0; i < ${#REQUIRED_SUITES[@]}; i++)); do + suite_name="${REQUIRED_SUITES[$i]}" + [[ -n "$suite_name" && ! "$suite_name" =~ [[:cntrl:]] && "$suite_name" != *'#'* ]] || usage + for ((j = 0; j < i; j++)); do + [[ "$suite_name" != "${REQUIRED_SUITES[$j]}" ]] || usage + done + done + + for ((i = 0; i < ${#REQUIRED_CASES[@]}; i++)); do + case_name="${REQUIRED_CASES[$i]}" + [[ "$case_name" == *'#'* && "${case_name#*#}" != *'#'* && ! "$case_name" =~ [[:cntrl:]] ]] || usage + case_suite="${case_name%%#*}" + case_test="${case_name#*#}" + [[ -n "$case_test" ]] || usage + suite_is_required=0 + for required_suite in "${REQUIRED_SUITES[@]}"; do + if [[ "$case_suite" == "$required_suite" ]]; then + suite_is_required=1 + break + fi + done + [[ "$suite_is_required" == "1" ]] || usage + for ((j = 0; j < i; j++)); do + [[ "$case_name" != "${REQUIRED_CASES[$j]}" ]] || usage + done + done +elif ((${#REQUIRED_SUITES[@]} > 0 || ${#REQUIRED_CASES[@]} > 0)); then + usage +fi + SERVICE_NAME="$1" SERVICE_DIR="$ROOT_DIR/services/$SERVICE_NAME" @@ -40,7 +99,7 @@ if [[ ! -d "$SERVICE_DIR" ]]; then exit 1 fi -python3 - "$SERVICE_DIR" <<'PY' +python3 - "$SERVICE_DIR" "$STRICT_MODE" "${REQUIRED_SUITES[@]}" --required-cases "${REQUIRED_CASES[@]}" <<'PY' from __future__ import annotations import datetime as dt @@ -50,9 +109,213 @@ from collections import defaultdict from pathlib import Path service_dir = Path(sys.argv[1]) +strict_mode = sys.argv[2] == "1" +case_separator = sys.argv.index("--required-cases", 3) +required_suites = sys.argv[3:case_separator] +required_cases = sys.argv[case_separator + 1 :] service_name = service_dir.name result_root = service_dir / "build" / "test-results" + +def strict_inspection() -> None: + xml_files = sorted(result_root.glob("**/TEST-*.xml")) if result_root.exists() else [] + malformed_reports = 0 + parsed_suite_count = 0 + parsed_test_count = 0 + suite_reports: dict[str, list[dict[str, object]]] = defaultdict(list) + required_suite_set = set(required_suites) + + def non_negative_count(value: str | None) -> int | None: + if value is None or not value.isascii() or not value.isdecimal(): + return None + try: + count = int(value) + except ValueError: + return None + return count if count >= 0 else None + + for xml_file in xml_files: + try: + root = ET.parse(xml_file).getroot() + except (ET.ParseError, OSError, ValueError): + malformed_reports += 1 + continue + + if root.tag == "testsuite": + suites = [root] + elif root.tag == "testsuites": + suites = list(root.findall(".//testsuite")) + else: + malformed_reports += 1 + continue + + if not suites: + malformed_reports += 1 + continue + + file_is_malformed = False + file_suites: list[dict[str, object]] = [] + for suite in suites: + suite_name = suite.attrib.get("name") + tests = non_negative_count(suite.attrib.get("tests")) + failures = non_negative_count(suite.attrib.get("failures")) + errors = non_negative_count(suite.attrib.get("errors")) + skipped = non_negative_count(suite.attrib.get("skipped")) + disabled = non_negative_count(suite.attrib.get("disabled", "0")) + testcases = list(suite.findall("./testcase")) + + if ( + not suite_name + or tests is None + or failures is None + or errors is None + or skipped is None + or disabled is None + or tests != len(testcases) + ): + file_is_malformed = True + + parsed_cases: list[dict[str, object]] = [] + for testcase in testcases: + classname = testcase.attrib.get("classname") + name = testcase.attrib.get("name") + if not classname or not name: + file_is_malformed = True + continue + parsed_cases.append( + { + "identity": f"{classname}#{name}", + "failed": bool(testcase.findall("./failure")), + "errored": bool(testcase.findall("./error")), + "skipped": bool(testcase.findall("./skipped")), + } + ) + + suite_info: dict[str, object] = { + "name": suite_name, + "tests": tests, + "failures": failures, + "errors": errors, + "skipped": skipped, + "disabled": disabled, + "cases": parsed_cases, + } + file_suites.append(suite_info) + + if file_is_malformed: + malformed_reports += 1 + continue + + parsed_suite_count += len(file_suites) + parsed_test_count += sum(int(suite["tests"]) for suite in file_suites) + for suite in file_suites: + suite_name = str(suite["name"]) + if suite_name in required_suite_set: + suite_reports[suite_name].append(suite) + + problems: list[str] = [] + suite_status: dict[str, tuple[str, dict[str, object] | None]] = {} + for suite_name in required_suites: + matches = suite_reports.get(suite_name, []) + if not matches: + suite_status[suite_name] = ("missing", None) + problems.append(f"Missing required suite: {suite_name}") + continue + if len(matches) != 1: + suite_status[suite_name] = ("duplicate", None) + problems.append(f"Duplicate required suite: {suite_name} ({len(matches)} report(s))") + continue + + suite = matches[0] + suite_status[suite_name] = ("passed", suite) + if int(suite["tests"]) == 0: + suite_status[suite_name] = ("zero tests", suite) + problems.append(f"Required suite has zero tests: {suite_name}") + elif ( + int(suite["failures"]) > 0 + or int(suite["errors"]) > 0 + or int(suite["skipped"]) > 0 + or int(suite["disabled"]) > 0 + or any( + bool(case["failed"]) or bool(case["errored"]) or bool(case["skipped"]) + for case in suite["cases"] + ) + ): + suite_status[suite_name] = ("failed or skipped", suite) + problems.append(f"Required suite is failing, errored, or skipped: {suite_name}") + + for case_spec in required_cases: + case_suite, _ = case_spec.split("#", 1) + suite = suite_status[case_suite][1] + matching_cases = ( + [case for case in suite["cases"] if case["identity"] == case_spec] + if suite is not None + else [] + ) + if not matching_cases: + problems.append(f"Missing required case: {case_spec}") + continue + if len(matching_cases) != 1: + problems.append(f"Duplicate required case: {case_spec} ({len(matching_cases)} execution(s))") + continue + case = matching_cases[0] + if bool(case["failed"]) or bool(case["errored"]) or bool(case["skipped"]): + problems.append(f"Required case did not pass: {case_spec}") + + print("Strict JUnit proof: passed" if not problems and malformed_reports == 0 else "Strict JUnit proof: failed") + print( + f"Reports: {len(xml_files)}; suites: {parsed_suite_count}; tests: {parsed_test_count}; " + f"malformed reports: {malformed_reports}" + ) + + for suite_name in required_suites: + status, suite = suite_status[suite_name] + if suite is None: + print(f"Suite {suite_name}: outcome={status}") + else: + print( + f"Suite {suite_name}: tests={suite['tests']} skipped={int(suite['skipped']) + int(suite['disabled'])} " + f"failures={suite['failures']} errors={suite['errors']} outcome={status}" + ) + + for case_spec in required_cases: + case_suite, _ = case_spec.split("#", 1) + suite = suite_status[case_suite][1] + matching_cases = ( + [case for case in suite["cases"] if case["identity"] == case_spec] + if suite is not None + else [] + ) + if not matching_cases: + outcome = "missing" + elif len(matching_cases) != 1: + outcome = "duplicate" + elif bool(matching_cases[0]["failed"]): + outcome = "failure" + elif bool(matching_cases[0]["errored"]): + outcome = "error" + elif bool(matching_cases[0]["skipped"]): + outcome = "skipped" + else: + outcome = "passed" + print(f"Case {case_spec}: executions={len(matching_cases)} outcome={outcome}") + + if malformed_reports > 0: + problems.append(f"Malformed report(s): {malformed_reports}") + for problem in problems: + print(f"- {problem}") + + if not xml_files: + print("No JUnit XML reports were found.") + raise SystemExit(1) + if problems: + raise SystemExit(1) + + +if strict_mode: + strict_inspection() + raise SystemExit(0) + if not result_root.exists(): print(f"Service: {service_name}") print("No build/test-results directory exists yet.") diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java index 49ffa7c7b1..581eaf06e7 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java @@ -16,7 +16,6 @@ import net.firedevops.firemud.gamesession.presentation.PlayerOutput; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; import net.firedevops.firemud.gamesession.service.CommandService; -import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextResolution; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; @@ -39,6 +38,7 @@ public final class LoginCommandHandler { private static final Logger logger = LoggerFactory.getLogger(LoginCommandHandler.class); private static final String AUTHENTICATION_UNAVAILABLE_CODE = "UNAVAILABLE"; + private static final String AUTH_UNAVAILABLE_CODE = "AUTH_UNAVAILABLE"; private static final String RETRY_LATER_CODE = "RETRY_LATER"; private static final String ABUSE_CONTROL_UNAVAILABLE_CODE = "ABUSE_CONTROL_UNAVAILABLE"; private static final String RETRY_LATER_MESSAGE = "Too many failed attempts; try again later."; @@ -107,7 +107,7 @@ public LoginCommandHandlingResult handle( LoginCommandConstants.INVALID_ARGUMENTS_CODE, LoginCommandConstants.INVALID_ARGUMENTS_MESSAGE); } - return handleVerifiedFirstPartyLogin(sessionId, command, requiresSoloTick); + return handleVerifiedFirstPartyLogin(sessionId); } TextCommandPayload.Credentials credentials = maybeCredentials.orElseThrow(); String canonicalLoginName = EmailCanonicalization.normalize(credentials.loginName()); @@ -198,8 +198,7 @@ private LoginCommandHandlingResult handleEmailLoginChallenge( LoginCommandConstants.EMAIL_LOGIN_CODE_MESSAGE, "message.login.code-sent"))); } - private LoginCommandHandlingResult handleVerifiedFirstPartyLogin( - String sessionId, TextCommand command, boolean requiresSoloTick) { + private LoginCommandHandlingResult handleVerifiedFirstPartyLogin(String sessionId) { SessionIdParsing.ParsedSessionId parsedSessionId = parseSessionId(sessionId); if (!parsedSessionId.valid()) { return invalidSessionFailure(parsedSessionId.errorMessage()); @@ -264,26 +263,7 @@ private LoginCommandHandlingResult handleVerifiedFirstPartyLogin( return failure("CONNECT_SCOPE_MISMATCH", "Connect scope invalid"); } - CommandEnqueueResult enqueueResult = - commandService.enqueue(sessionId, command.rawLine(), requiresSoloTick); - if (!enqueueResult.accepted()) { - return fromCommandResult(enqueueResult); - } - persistSessionContext( - numericSessionId, - verifiedContext.tenantId(), - verifiedContext.accountId(), - "first-party:" + verifiedContext.accountId(), - null, - verifiedContext.gameInstanceId(), - verifiedContext); - return new LoginCommandHandlingResult( - enqueueResult, - List.of( - PlayerOutput.message( - "Logged in as first-party account " + verifiedContext.accountId(), - "message.login.first-party-success", - Map.of("accountId", Long.toString(verifiedContext.accountId()))))); + return failure(AUTH_UNAVAILABLE_CODE, "Authentication service unavailable"); } private void persistSessionContext( @@ -293,18 +273,6 @@ private void persistSessionContext( String loginName, String jwt, long bootstrapGameInstanceId) { - persistSessionContext( - sessionId, tenantId, accountId, loginName, jwt, bootstrapGameInstanceId, null); - } - - private void persistSessionContext( - long sessionId, - long tenantId, - long accountId, - String loginName, - String jwt, - long bootstrapGameInstanceId, - FirstPartyConnectContext verifiedBootstrapContext) { if (sessionContextService == null) { return; } @@ -333,14 +301,6 @@ private void persistSessionContext( retainedPointerVersion = existing.pointerVersion(); retainedPlayableStateScope = existing.playableStateScope(); } - if (verifiedBootstrapContext != null) { - retainedBootstrapGameInstanceId = verifiedBootstrapContext.gameInstanceId(); - retainedWorldSlug = verifiedBootstrapContext.worldSlug(); - retainedRealmSlug = verifiedBootstrapContext.realmSlug(); - retainedPointerVersion = verifiedBootstrapContext.pointerVersion(); - retainedConnectScopeId = verifiedBootstrapContext.connectScopeId(); - retainedConnectRequestId = verifiedBootstrapContext.connectRequestId(); - } // LOGIN promotes an unauthenticated shell while keeping only its server-derived bootstrap // context. Reauthentication under a different account clears that context with old gameplay // identity; only a same-account login may preserve a candidate gameplay binding for PLAY. @@ -575,6 +535,7 @@ private String loginErrorMessageKey(String code) { case "ACCOUNT_LOCKED" -> "error.login.account-locked"; case RETRY_LATER_CODE -> "error.login.retry-later"; case ABUSE_CONTROL_UNAVAILABLE_CODE -> "error.login.abuse-control-unavailable"; + case AUTH_UNAVAILABLE_CODE -> "error.login.unavailable"; case AUTHENTICATION_UNAVAILABLE_CODE -> "error.login.unavailable"; default -> null; }; diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java index c70a727985..d312f6615b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java @@ -379,10 +379,10 @@ void missingCredentialsReturnsPromptError() { } @Test - void bareLoginAcceptsVerifiedFirstPartyAccountDifferentFromGameOwner() { + void bareLoginDoesNotPromoteVerifiedFirstPartyContextWithoutAccountExchange() { TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); GameInstance instance = buildInstance(1L, 22L, 77L); - stubSessionContext( + SessionContext shell = new SessionContext( 1L, 22L, @@ -400,7 +400,8 @@ void bareLoginAcceptsVerifiedFirstPartyAccountDifferentFromGameOwner() { 7L, "SHARED", "shell-scope", - "shell-request")); + "shell-request"); + stubSessionContext(shell); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( @@ -419,23 +420,26 @@ void bareLoginAcceptsVerifiedFirstPartyAccountDifferentFromGameOwner() { LoginCommandHandlingResult result = handler.handle("1", command, false); - assertTrue(result.commandResult().accepted()); - assertEquals("Logged in as first-party account 99", joinedOutputText(result.outputs())); + assertFalse(result.commandResult().accepted()); + assertEquals("AUTH_UNAVAILABLE", result.commandResult().errorCode()); + assertEquals("Authentication service unavailable", result.commandResult().errorMessage()); + assertEquals( + "ERROR AUTH_UNAVAILABLE Authentication service unavailable", + joinedOutputText(result.outputs())); + assertEquals( + "error.login.unavailable", ((ErrorOutput) result.outputs().get(0).payload()).messageKey()); verify(accountClient, never()).authenticate(anyString(), anyString()); - verify(commandService).enqueue("1", "LOGIN", false); - ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); - verify(sessionContextService).save(captor.capture()); - SessionContext saved = captor.getValue(); - assertEquals(99L, saved.accountId()); - assertEquals(1L, saved.bootstrapGameInstanceId()); - assertEquals("demo", saved.worldSlug()); - assertEquals("production", saved.realmSlug()); - assertEquals(1L, saved.pointerVersion()); - assertEquals("SHARED", saved.playableStateScope()); - assertEquals("scope-1", saved.connectScopeId()); - assertEquals("req-1", saved.connectRequestId()); - assertEquals(0L, saved.characterId()); - assertEquals(0L, saved.gameInstanceId()); + verify(accountClient, never()).requestEmailLoginOtp(anyString()); + verify(commandService, never()).enqueue(anyString(), anyString(), anyBoolean()); + verify(sessionContextService, never()).save(any(SessionContext.class)); + verify(firstPartyConnectContextRegistry, never()).unregister(anyLong()); + assertEquals(0L, shell.accountId()); + assertNull(shell.jwt()); + assertEquals(1L, shell.bootstrapGameInstanceId()); + assertEquals("shell-world", shell.worldSlug()); + assertEquals("shell-realm", shell.realmSlug()); + assertEquals("shell-scope", shell.connectScopeId()); + assertEquals("shell-request", shell.connectRequestId()); assertEquals(77L, instance.getOwnerAccountId()); } @@ -490,7 +494,7 @@ void credentialLoginPreservesBootstrapTargetButDropsSubjectBoundConnectScope() { } @Test - void bareLoginFallsBackToPersistedFirstPartyContextWhenRegistryEntryIsMissing() { + void bareLoginFailsUnavailableForPersistedFirstPartyContextFallback() { TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); GameInstance instance = buildInstance(1L, 22L, 77L); SessionContext persisted = @@ -519,9 +523,11 @@ void bareLoginFallsBackToPersistedFirstPartyContextWhenRegistryEntryIsMissing() LoginCommandHandlingResult result = handler.handle("1", command, false); - assertTrue(result.commandResult().accepted()); - assertEquals("Logged in as first-party account 77", joinedOutputText(result.outputs())); - verify(commandService).enqueue("1", "LOGIN", false); + assertFalse(result.commandResult().accepted()); + assertEquals("AUTH_UNAVAILABLE", result.commandResult().errorCode()); + verify(accountClient, never()).authenticate(anyString(), anyString()); + verify(commandService, never()).enqueue(anyString(), anyString(), anyBoolean()); + verify(sessionContextService, never()).save(any(SessionContext.class)); } @Test From 25626210ca95a3b81d1116aab271608160c8a053 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 27 Sep 2026 15:36:39 +1300 Subject: [PATCH 03/14] Make strict JUnit contract leak assertions ShellCheck-safe --- dev-tools/tests/gradle-proof-tooling-contract.sh | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/dev-tools/tests/gradle-proof-tooling-contract.sh b/dev-tools/tests/gradle-proof-tooling-contract.sh index 35b4ae8b3e..040134df7b 100644 --- a/dev-tools/tests/gradle-proof-tooling-contract.sh +++ b/dev-tools/tests/gradle-proof-tooling-contract.sh @@ -114,7 +114,10 @@ grep -q '^Strict JUnit proof: passed$' <<<"$strict_green_output" grep -Fq "Suite $JOIN_SUITE: tests=2 skipped=0 failures=0 errors=0 outcome=passed" <<<"$strict_green_output" grep -Fq "Case $JOIN_CASE: executions=1 outcome=passed" <<<"$strict_green_output" grep -Fq "Case $EXCHANGE_CASE: executions=1 outcome=passed" <<<"$strict_green_output" -! grep -q "STRICT_OUTPUT_SENTINEL" <<<"$strict_green_output" +if grep -q "STRICT_OUTPUT_SENTINEL" <<<"$strict_green_output"; then + echo "Strict inspection leaked test output." >&2 + exit 1 +fi STRICT_MISSING_SUITE_ROOT="$TMP_DIR/strict-missing-suite" new_strict_fixture "$STRICT_MISSING_SUITE_ROOT" @@ -196,7 +199,10 @@ if failing_output="$(inspect_strict "$STRICT_FAILING_ROOT" 2>&1)"; then fi grep -Fq "Required suite is failing, errored, or skipped: $JOIN_SUITE" <<<"$failing_output" grep -Fq "Case $JOIN_CASE: executions=1 outcome=failure" <<<"$failing_output" -! grep -q "SENSITIVE_" <<<"$failing_output" +if grep -q "SENSITIVE_" <<<"$failing_output"; then + echo "Strict inspection leaked failure details." >&2 + exit 1 +fi STRICT_DUPLICATE_SUITE_ROOT="$TMP_DIR/strict-duplicate-suite" new_strict_fixture "$STRICT_DUPLICATE_SUITE_ROOT" From aa5d73c05a408ba152ac05f4298cadd52430b831 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 27 Sep 2026 16:37:56 +1300 Subject: [PATCH 04/14] Record bare LOGIN proof and CI activation gap --- .../implementation-tracking/player-access-and-session.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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 309a5f2a0e..57a0cd0a3d 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -10,7 +10,7 @@ The unmerged #2876 `account-auth-authority-event/v1` correction uses ADR 0030's Draft #2880's Account membership-snapshot child retains the exact one-tenant version map and assembles four canonically ordered two-field issuer/account/tenant/membership checkpoints with separate positive membership event ID/digest evidence. A never-joined pair returns nonadmitting sequence zero only from its durable positive pair baseline, absent membership/receipt/event history, and pristine upstream generation/source-version rows under the Account fence; advanced upstream authority without matching event proof remains denied. A later account-local issuance fence is retained rather than reset to one. Its new typed runtime wire and Account encoder carry the complete current-only snapshot with exact caller selector and request-ID echoes. Game Session has a fail-closed structural consumer for that carrier, but neither full event-content/current-authority verification nor live admission is proved; the Account RPC remains denied. The composed local module gate passed with 381 Account unit tests, 1,640 Game Session unit tests, and 43 common-test-support tests executed; all 78 Account integration cases, 112 of 130 Game Session integration cases, and 39 of 40 Game Session cross-service cases skipped without Docker. Thus PostgreSQL, cross-service, and live RPC proof for this new wire remain open. Hosted run `36282748942` executed 82 Account integration cases on the earlier draft head: 81 passed and one negative test failed because its expected message named the later pair-baseline check rather than the earlier correct rejection of an advanced membership generation without a source event. The corrected-code run `36283628361` executed the Account integration task and its job passed, but uploaded only JaCoCo artifacts, so the corrected method's individual result cannot be attested. Both earlier aggregate gates were red on a shared TLS-watcher test race, Ruff, and EA-3.1 checks outside #2880's then nine-file snapshot patch. Overseer resolved the ADR 0030 wording conflict: the closed v1 event is insufficient without a separately Account-authenticated same-snapshot checkpoint/source carrier bound to its exact event ID/digest; #2876 records that authority, and #2880's typed carrier remains disabled pending full producer/consumer proof. -V37's deferred database guard rejects an exchange transaction that would commit `PENDING` without its terminal envelope: a pre-commit crash rolls back the claim, while a post-commit exact retry reads the original operation and envelope. This is still storage-only until PostgreSQL executes the new cases and the caller proves that source validation, current authority, credential creation, and envelope completion use that same transaction. Deletion is denied until Account adds a proven receipt/envelope retention and safe-cleanup path; no fixed TTL, timeout, or absent row is interpreted as a terminal result. Lost-response producer/consumer proof remains an activation gate. +V37's deferred database guard rejects an exchange transaction that would commit `PENDING` without its terminal envelope: a pre-commit crash rolls back the claim, while a post-commit exact retry reads the original operation and envelope. The seven V37 PostgreSQL cases executed and passed on #2881 head `25626210c` in CI run `36289042648`, but this remains storage-only until a caller proves that source validation, current authority, credential creation, and envelope completion use that same transaction. Deletion is denied until Account adds a proven receipt/envelope retention and safe-cleanup path; no fixed TTL, timeout, or absent row is interpreted as a terminal result. Lost-response producer/consumer proof remains an activation gate. Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, explicit public-production JOIN, durable Account audit outbox and Logging receipt handling, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. Account now has a bounded readback-only worker for abandoned JOIN `PENDING` intents, but PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof are not claimed. Expiry and absent evidence do not create terminal outcomes. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and durable post-logout episode fencing remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. @@ -30,9 +30,9 @@ The in-progress #2873 tenant bridge now has a signed Game Design migration-manif 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 gives missing non-public grant a separate `REALM_ACCESS_DENIED` outcome. 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 live. 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 or key-ring deployment. The separate V37 storage candidate binds one exchange request to a committed V35 source, preserves first-writer request identity and digest, and permits only an atomic write-once pending-evidence to terminal-success transition with an exact purpose-bound envelope; it does not mint, decrypt, or return a delegation JWT. Its seven PostgreSQL cases compile but skipped without Docker; database execution, caller lost-response recovery, current-authority revalidation, exact Game Session caller proof, and the complete producer/consumer path remain open. 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 approved first-party bare-`LOGIN` private-delegation exchange is not live. 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 or key-ring deployment. The separate V37 storage candidate binds one exchange request to a committed V35 source, preserves first-writer request identity and digest, and permits only an atomic write-once pending-evidence to terminal-success transition with an exact purpose-bound envelope; it does not mint, decrypt, or return a delegation JWT. Its seven PostgreSQL cases passed in CI run `36289042648` on prior #2881 head `25626210c` and skipped locally without Docker; caller lost-response recovery, current-authority revalidation, exact Game Session caller proof, and the complete producer/consumer path remain open. 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 #2881 candidate also contains Game Session's fail-closed bare-`LOGIN` guard: otherwise valid first-party context returns `AUTH_UNAVAILABLE` before enqueue or authenticated session promotion while the Account exchange is unwired, without changing credential-bearing `LOGIN`. Focused handler tests exercise no enqueue, no save, and retained unauthenticated bootstrap context. The Account CI matrix now disables Gradle build-cache reuse and requires exact JOIN-map and exchange-transaction JUnit cases to execute without skips; synthetic strict-inspector contracts pass, while local XML correctly fails that gate because Docker is unavailable. This does not make the V37 storage a live exchange, or prove Account/Gateway context verification and lost-response recovery. +The #2881 candidate also contains Game Session's fail-closed bare-`LOGIN` guard: otherwise valid first-party context returns `AUTH_UNAVAILABLE` before enqueue or authenticated session promotion while the Account exchange is unwired, without changing credential-bearing `LOGIN`. Focused handler tests exercise no enqueue, no save, and retained unauthenticated bootstrap context. Seven first-party structured-output cross-service tests currently fail at their shared helper's old successful-bare-LOGIN assertion; there is no supported authenticated first-party fixture until the Account exchange works, and the internal text fixture cannot prove structured public output. They remain an explicit runtime proof gate rather than being disabled or counted as passing. The Account CI matrix now disables Gradle build-cache reuse and requires exact JOIN-map and exchange-transaction JUnit cases to execute without skips; synthetic strict-inspector contracts pass, while local XML correctly fails that gate because Docker is unavailable. This does not make the V37 storage a live exchange, or prove Account/Gateway context verification and lost-response recovery. 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. From 81955a0c4e4264af7b12dcb9fe5936344317fef4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 27 Sep 2026 16:44:11 +1300 Subject: [PATCH 05/14] Prove first-party bare LOGIN denial before gameplay admission --- ...ommunicationWebSocketCrossServiceTest.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java index 46bc398992..09d9ddb28a 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java @@ -496,6 +496,27 @@ void websocketFriendsVisibilityShowsCurrentPolicy() throws Exception { FriendPresenceVisibilityPolicy.FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE); } + @Test + void websocketFirstPartyBareLoginFailsClosedBeforeGameplayAdmission() throws Exception { + ensureTestServicesStarted(); + prepareGameInstance(); + + try (GameplayWebSocketDriver client = openFirstPartyClient("bare-login-unavailable")) { + client.send("LOGIN"); + JsonNode login = awaitStructuredCommand(client, 0, "LOGIN"); + GameplayStructuredCommandAssertions.requireStructuredCommand( + login, "LOGIN", "login", "META", "SESSION"); + assertThat(login.path("accepted").asBoolean()).isFalse(); + assertThat(login.path("errorCode").asText()).isEqualTo("AUTH_UNAVAILABLE"); + + int baseline = client.responses().size(); + client.send("PLAY demo"); + JsonNode play = awaitStructuredCommand(client, baseline, "PLAY"); + assertThat(play.path("accepted").asBoolean()).isFalse(); + assertThat(play.path("errorCode").asText()).isEqualTo("LOGIN_REQUIRED"); + } + } + @Test void websocketFirstPartySayUsesStructuredCommunicationMetadata() throws Exception { ensureTestServicesStarted(); From e39c31b1f42b202c26c34ba83ddf6e4c8247699e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 27 Sep 2026 17:00:59 +1300 Subject: [PATCH 06/14] Record composed bare LOGIN proof and remaining activation gate --- .../implementation-tracking/player-access-and-session.md | 2 ++ 1 file changed, 2 insertions(+) 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 5e2b91aec4..9944f12359 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -34,6 +34,8 @@ The approved first-party bare-`LOGIN` private-delegation exchange is not live. A The #2881 candidate also contains Game Session's fail-closed bare-`LOGIN` guard: otherwise valid first-party context returns `AUTH_UNAVAILABLE` before enqueue or authenticated session promotion while the Account exchange is unwired, without changing credential-bearing `LOGIN`. Focused handler tests exercise no enqueue, no save, and retained unauthenticated bootstrap context. Seven first-party structured-output cross-service tests currently fail at their shared helper's old successful-bare-LOGIN assertion; there is no supported authenticated first-party fixture until the Account exchange works, and the internal text fixture cannot prove structured public output. They remain an explicit runtime proof gate rather than being disabled or counted as passing. The Account CI matrix now disables Gradle build-cache reuse and requires exact JOIN-map and exchange-transaction JUnit cases to execute without skips; synthetic strict-inspector contracts pass, while local XML correctly fails that gate because Docker is unavailable. This does not make the V37 storage a live exchange, or prove Account/Gateway context verification and lost-response recovery. +Manual CI run `36292018666` on prior #2881 head `aa5d73c05a408ba152ac05f4298cadd52430b831` passed its strict Account evidence gate: all 24 JOIN PostgreSQL cases and seven V37 bare-LOGIN exchange cases executed with no skips or failures, including the required targeted map-shape and transaction tests. Its aggregate gate remained red: seven first-party success assertions still assume the disabled exchange, and four Game Session/TCP Proxy cross-service failures arose from #2880's incomplete `INACTIVE` carrier handling; ten hosted smoke-tool Ruff errors and the EA-3.1 proof-link rule also failed. The #2880 consumer/stub correction has been merged normally into #2881 with its unique non-tracker patch ID unchanged. A new signed-context wire-negative test for bare `LOGIN` and following `PLAY` compiles but skipped locally without Docker; the seven positive scenarios remain unchanged. The corrected composed local module/doc gate passed, with 381 Account and 1,641 Game Session unit tests executed, but all 87 Account PostgreSQL cases and 40/41 Game Session cross-service cases skipped. Corrected-head hosted proof remains necessary, and neither membership nor credential runtime path is enabled. + 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. From 93bc4a45fa940f600d8f4d97d9aefdf20b424f2a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 27 Sep 2026 17:07:21 +1300 Subject: [PATCH 07/14] Prove concurrent bare LOGIN exchange first writer --- ...oginExchangeRepositoryIntegrationTest.java | 88 +++++++++++++++++++ 1 file changed, 88 insertions(+) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java index de1852f5d8..52ab80a535 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java @@ -3,8 +3,15 @@ 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.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.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.repository.AccountBareLoginExchangeIdentity; @@ -144,6 +151,87 @@ void sourceMustBeCommittedAndFirstWriterOwnsTheExchangeIdentity() { .hasMessageContaining("not committed"); } + @Test + void concurrentExactExchangeClaimsHaveOneTerminalFirstWriter() throws Exception { + TestContext context = newTestContext(); + Source source = committedSource(context); + AccountBareLoginExchangeIdentity identity = source.exchangeIdentity(); + byte[] requestDigest = digest(70); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Callable exchange = + () -> { + ready.countDown(); + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Exchange claim race did not start together"); + } + return inTransaction( + context.transaction(), + () -> { + var claim = context.repository().claim(identity, requestDigest); + if (claim.disposition() + == AccountBareLoginExchangeRepository.ClaimDisposition.CLAIMED) { + AccountEnvelopeBinding binding = + binding(claim.operation().operationId(), identity, requestDigest, 71); + context + .repository() + .recordPendingEvidence( + claim, + requestDigest, + "delegation-jti-race", + digest(80), + binding.contextEvidenceDigest(), + binding.authorityTupleDigest(), + binding.issuanceFenceDigest(), + binding.postconditionDigest()); + context + .repository() + .completeWithEnvelope( + claim, + requestDigest, + "delegation-jti-race", + digest(80), + binding, + encryptedEnvelope(AccountEnvelopePurpose.BARE_LOGIN_RESPONSE)); + } + return claim; + }); + }; + Future first = executor.submit(exchange); + Future second = executor.submit(exchange); + 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(AccountBareLoginExchangeRepository.ClaimResult::disposition) + .containsExactlyInAnyOrder( + AccountBareLoginExchangeRepository.ClaimDisposition.CLAIMED, + AccountBareLoginExchangeRepository.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.COMMITTED); + AccountEnvelopeBinding binding = + binding(results.get(0).operation().operationId(), identity, requestDigest, 71); + assertThat( + inTransaction( + context.transaction(), + () -> + context.repository().readResponseEnvelope(identity, requestDigest, binding))) + .isPresent(); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + @Test void pendingEvidenceThenTerminalSuccessReadBacksExactPurposeBoundEnvelope() { TestContext context = newTestContext(); From 3272a1fe0e38a2d2d7fff19995f0075adf58b50a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 27 Sep 2026 17:15:12 +1300 Subject: [PATCH 08/14] Prove stored bare LOGIN envelope recovery across retry --- .../player-access-and-session.md | 2 + ...oginExchangeRepositoryIntegrationTest.java | 89 +++++++++++++++++++ 2 files changed, 91 insertions(+) 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 9944f12359..1e78acbb57 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -36,6 +36,8 @@ The #2881 candidate also contains Game Session's fail-closed bare-`LOGIN` guard: Manual CI run `36292018666` on prior #2881 head `aa5d73c05a408ba152ac05f4298cadd52430b831` passed its strict Account evidence gate: all 24 JOIN PostgreSQL cases and seven V37 bare-LOGIN exchange cases executed with no skips or failures, including the required targeted map-shape and transaction tests. Its aggregate gate remained red: seven first-party success assertions still assume the disabled exchange, and four Game Session/TCP Proxy cross-service failures arose from #2880's incomplete `INACTIVE` carrier handling; ten hosted smoke-tool Ruff errors and the EA-3.1 proof-link rule also failed. The #2880 consumer/stub correction has been merged normally into #2881 with its unique non-tracker patch ID unchanged. A new signed-context wire-negative test for bare `LOGIN` and following `PLAY` compiles but skipped locally without Docker; the seven positive scenarios remain unchanged. The corrected composed local module/doc gate passed, with 381 Account and 1,641 Game Session unit tests executed, but all 87 Account PostgreSQL cases and 40/41 Game Session cross-service cases skipped. Corrected-head hosted proof remains necessary, and neither membership nor credential runtime path is enabled. +Corrected #2881 head `e39c31b1f42b202c26c34ba83ddf6e4c8247699e` ran in CI `36293121086`: the strict Account gate passed all 26 JOIN and seven V37 PostgreSQL cases with zero skips/failures, including #2880's two new same-fence snapshot cases; the signed-context bare-`LOGIN` denial test executed and passed. Game Session's 41 cross-service cases had exactly seven failures, all existing first-party success scenarios awaiting the Account exchange. TCP Proxy and all other service Build/Test jobs passed. Python Script Validation and the EA-3.1 Dev Tool Contract Check remain red outside this unique change. Two additional V37 repository/crypto tests now locally compile: concurrent exact first-writer terminalization and decrypting the exact retained envelope after a simulated lost response. All 89 local Account integration cases skip without Docker, so these two new tests need hosted execution. They prove storage/recovery primitives only, not Account-issued JWT, caller-bound exchange, live ring custody, or activation. + 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. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java index 52ab80a535..51241ec70f 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java @@ -3,6 +3,10 @@ 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.util.Base64; import java.util.List; import java.util.Map; import java.util.UUID; @@ -22,6 +26,7 @@ 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; @@ -29,6 +34,7 @@ import org.jooq.exception.DataAccessException; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; @@ -232,6 +238,89 @@ void concurrentExactExchangeClaimsHaveOneTerminalFirstWriter() throws Exception } } + @Test + void lostExchangeResponseRecoversExactEncryptedResultFromDurableReadback( + @TempDir Path temporaryDirectory) throws Exception { + TestContext context = newTestContext(); + Source source = committedSource(context); + AccountBareLoginExchangeIdentity identity = source.exchangeIdentity(); + byte[] requestDigest = digest(72); + byte[] originalResult = "original-private-delegation-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, 73); + context + .repository() + .recordPendingEvidence( + claim, + requestDigest, + "delegation-jti-recovery", + digest(80), + issuedBinding.contextEvidenceDigest(), + issuedBinding.authorityTupleDigest(), + issuedBinding.issuanceFenceDigest(), + issuedBinding.postconditionDigest()); + context + .repository() + .completeWithEnvelope( + claim, + requestDigest, + "delegation-jti-recovery", + digest(80), + issuedBinding, + writer.encrypt( + AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, + issuedBinding, + originalResult)); + return issuedBinding; + }); + + var retry = + inTransaction( + context.transaction(), () -> context.repository().claim(identity, requestDigest)); + assertThat(retry.disposition()) + .isEqualTo(AccountBareLoginExchangeRepository.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.BARE_LOGIN_RESPONSE, stored.binding())) + .containsExactly(originalResult); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), () -> context.repository().find(identity, digest(74)))) + .isInstanceOf(AccountBareLoginExchangeRepository.IdempotencyConflictException.class); + } + @Test void pendingEvidenceThenTerminalSuccessReadBacksExactPurposeBoundEnvelope() { TestContext context = newTestContext(); From d4cc6654b5395086e09428d6f41658022eb87852 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 01:14:18 +1300 Subject: [PATCH 09/14] fix(game-session): clear stale subject on failed bare login --- .github/workflows/ci.yml | 1 + .../command/text/LoginCommandHandler.java | 33 ++++ .../command/text/LoginCommandHandlerTest.java | 182 ++++++++++++++++++ 3 files changed, 216 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5f5fda367f..e0c5c4b303 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -390,6 +390,7 @@ jobs: bash ./dev-tools/tests/secret-compliance-contract.sh bash ./dev-tools/tests/ensure-local-compose-env-contract.sh bash ./dev-tools/tests/smoke-image-env-contract.sh + bash ./dev-tools/tests/gradle-proof-tooling-contract.sh bash ./dev-tools/tests/architecture-doc-contracts.sh bash ./dev-tools/tests/lint-yaml-contract.sh python3 -m unittest discover -s dev-tools/validation -p 'test_*.py' diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java index 581eaf06e7..88b98a2d53 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java @@ -16,6 +16,7 @@ import net.firedevops.firemud.gamesession.presentation.PlayerOutput; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; import net.firedevops.firemud.gamesession.service.CommandService; +import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextResolution; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; @@ -263,9 +264,41 @@ private LoginCommandHandlingResult handleVerifiedFirstPartyLogin(String sessionI return failure("CONNECT_SCOPE_MISMATCH", "Connect scope invalid"); } + if (existingSession != null + && existingSession.accountId() > 0L + && (existingSession.accountId() != verifiedContext.accountId() + || existingSession.tenantId() != verifiedContext.tenantId())) { + clearPreviousSessionForVerifiedContext(numericSessionId, existingSession, verifiedContext); + } return failure(AUTH_UNAVAILABLE_CODE, "Authentication service unavailable"); } + private void clearPreviousSessionForVerifiedContext( + long sessionId, SessionContext existingSession, FirstPartyConnectContext verifiedContext) { + if (existingSession.hasGameplayBinding()) { + gameplayPresenceLifecycleService.clearGameplayBinding(existingSession, "LOGIN_FAILED"); + } + sessionContextService.save( + new SessionContext( + sessionId, + verifiedContext.tenantId(), + 0L, + null, + 0L, + null, + 0L, + null, + null, + existingSession.localeTag(), + verifiedContext.gameInstanceId(), + verifiedContext.worldSlug(), + verifiedContext.realmSlug(), + verifiedContext.pointerVersion(), + null, + verifiedContext.connectScopeId(), + verifiedContext.connectRequestId())); + } + private void persistSessionContext( long sessionId, long tenantId, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java index d312f6615b..dc195b540f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java @@ -17,10 +17,14 @@ import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.util.List; import java.util.Optional; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AuthenticateResponse; import net.firedevops.firemud.account.v1.RequestEmailLoginOtpResponse; import net.firedevops.firemud.gamesession.client.AccountClient; +import net.firedevops.firemud.gamesession.client.EntityManagementClient; +import net.firedevops.firemud.gamesession.client.ModerationPolicyClient; +import net.firedevops.firemud.gamesession.config.GameLogicProperties; import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.presentation.ErrorOutput; @@ -33,6 +37,7 @@ import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; +import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.service.SessionContextService; @@ -443,6 +448,147 @@ void bareLoginDoesNotPromoteVerifiedFirstPartyContextWithoutAccountExchange() { assertEquals(77L, instance.getOwnerAccountId()); } + @Test + void bareLoginForDifferentVerifiedSubjectClearsOldAccountBeforeReturningUnavailable() { + TextCommand loginCommand = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); + SessionContext accountA = staleGameplayContext(1L); + stubMutableSessionContext(accountA); + FirstPartyConnectContext verifiedAccountBContext = + new FirstPartyConnectContext( + 99L, + 33L, + "demo", + "production", + 2L, + 1L, + "scope-account-b", + "jti-account-b", + "request-account-b", + "gateway-account-b"); + when(firstPartyConnectContextRegistry.find(1L)) + .thenReturn(Optional.of(verifiedAccountBContext)); + GameInstance instance = buildInstance(2L, 33L, 77L); + when(gameInstanceRepository.findById(2L)).thenReturn(Optional.of(instance)); + when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(33L, 2L)) + .thenReturn(List.of(pointer("demo", "production", 33L, 2L, 1L))); + + LoginCommandHandlingResult result = handler.handle("1", loginCommand, false); + + assertFalse(result.commandResult().accepted()); + assertEquals("AUTH_UNAVAILABLE", result.commandResult().errorCode()); + ArgumentCaptor savedContext = ArgumentCaptor.forClass(SessionContext.class); + verify(sessionContextService).save(savedContext.capture()); + SessionContext accountBShell = savedContext.getValue(); + assertEquals(33L, accountBShell.tenantId()); + assertEquals(0L, accountBShell.accountId()); + assertNull(accountBShell.loginName()); + assertNull(accountBShell.jwt()); + assertFalse(accountBShell.hasGameplayBinding()); + assertEquals(2L, accountBShell.bootstrapGameInstanceId()); + assertEquals("demo", accountBShell.worldSlug()); + assertEquals("production", accountBShell.realmSlug()); + assertEquals(1L, accountBShell.pointerVersion()); + assertNull(accountBShell.playableStateScope()); + assertEquals("scope-account-b", accountBShell.connectScopeId()); + assertEquals("request-account-b", accountBShell.connectRequestId()); + verify(gameplayPresenceLifecycleService).clearGameplayBinding(accountA, "LOGIN_FAILED"); + verify(firstPartyConnectContextRegistry, never()).unregister(anyLong()); + assertEquals(Optional.of(verifiedAccountBContext), firstPartyConnectContextRegistry.find(1L)); + + PlayCommandHandlingResult playResult = + createPlayCommandHandler() + .handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertFalse(playResult.commandResult().accepted()); + assertEquals("LOGIN_REQUIRED", playResult.commandResult().errorCode()); + } + + @Test + void bareLoginForSameVerifiedSubjectPreservesRetryableSessionState() { + TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); + SessionContext existing = staleGameplayContext(1L); + stubSessionContext(existing); + when(firstPartyConnectContextRegistry.find(1L)) + .thenReturn( + Optional.of( + new FirstPartyConnectContext( + existing.accountId(), + existing.tenantId(), + "demo", + "production", + 1L, + 1L, + "scope-account-a", + "jti-account-a", + "request-account-a", + "gateway-account-a"))); + GameInstance instance = buildInstance(1L, 22L, 77L); + when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); + + LoginCommandHandlingResult result = handler.handle("1", command, false); + + assertFalse(result.commandResult().accepted()); + assertEquals("AUTH_UNAVAILABLE", result.commandResult().errorCode()); + verify(sessionContextService, never()).save(any(SessionContext.class)); + verify(gameplayPresenceLifecycleService, never()) + .clearGameplayBinding(any(SessionContext.class), anyString()); + verify(firstPartyConnectContextRegistry, never()).unregister(anyLong()); + assertEquals(77L, existing.accountId()); + assertEquals(AUTH_TOKEN, existing.jwt()); + assertTrue(existing.hasGameplayBinding()); + assertEquals("scope-stale", existing.connectScopeId()); + assertEquals("req-stale", existing.connectRequestId()); + } + + @Test + void bareLoginForSameAccountInDifferentTenantClearsOldTenantBeforeReturningUnavailable() { + TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); + SessionContext accountA = staleGameplayContext(1L); + stubMutableSessionContext(accountA); + FirstPartyConnectContext verifiedTenantBContext = + new FirstPartyConnectContext( + accountA.accountId(), + 33L, + "demo", + "production", + 2L, + 1L, + "scope-tenant-b", + "jti-tenant-b", + "request-tenant-b", + "gateway-tenant-b"); + when(firstPartyConnectContextRegistry.find(1L)).thenReturn(Optional.of(verifiedTenantBContext)); + when(gameInstanceRepository.findById(2L)) + .thenReturn(Optional.of(buildInstance(2L, 33L, accountA.accountId()))); + when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(33L, 2L)) + .thenReturn(List.of(pointer("demo", "production", 33L, 2L, 1L))); + + LoginCommandHandlingResult result = handler.handle("1", command, false); + + assertFalse(result.commandResult().accepted()); + assertEquals("AUTH_UNAVAILABLE", result.commandResult().errorCode()); + ArgumentCaptor savedContext = ArgumentCaptor.forClass(SessionContext.class); + verify(sessionContextService).save(savedContext.capture()); + SessionContext tenantBShell = savedContext.getValue(); + assertEquals(33L, tenantBShell.tenantId()); + assertEquals(0L, tenantBShell.accountId()); + assertNull(tenantBShell.jwt()); + assertFalse(tenantBShell.hasGameplayBinding()); + assertEquals(2L, tenantBShell.bootstrapGameInstanceId()); + assertEquals("scope-tenant-b", tenantBShell.connectScopeId()); + assertEquals("request-tenant-b", tenantBShell.connectRequestId()); + verify(gameplayPresenceLifecycleService).clearGameplayBinding(accountA, "LOGIN_FAILED"); + verify(firstPartyConnectContextRegistry, never()).unregister(anyLong()); + assertEquals(Optional.of(verifiedTenantBContext), firstPartyConnectContextRegistry.find(1L)); + + PlayCommandHandlingResult playResult = + createPlayCommandHandler() + .handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertFalse(playResult.commandResult().accepted()); + assertEquals("LOGIN_REQUIRED", playResult.commandResult().errorCode()); + } + @Test void credentialLoginPreservesBootstrapTargetButDropsSubjectBoundConnectScope() { TextCommand command = @@ -1409,6 +1555,42 @@ private GameInstance buildInstance(long id, long tenantId, long ownerAccountId) return instance; } + private void stubMutableSessionContext(SessionContext context) { + AtomicReference persistedContext = new AtomicReference<>(context); + when(sessionContextService.findBySessionId(1L)) + .thenAnswer(invocation -> Optional.ofNullable(persistedContext.get())); + when(sessionContextService.findByTenantAndSessionId(anyLong(), eq(1L))) + .thenAnswer( + invocation -> { + long requestedTenantId = invocation.getArgument(0); + return Optional.ofNullable(persistedContext.get()) + .filter(saved -> saved.tenantId() == requestedTenantId); + }); + Mockito.doAnswer( + invocation -> { + persistedContext.set(invocation.getArgument(0)); + return null; + }) + .when(sessionContextService) + .save(any(SessionContext.class)); + } + + private PlayCommandHandler createPlayCommandHandler() { + return new PlayCommandHandler( + sessionAuthenticationService, + sessionContextService, + sessionRoutingNormalizationService, + GameplayWorldCatalog.forWorldViews(List.of()), + new GameLogicProperties(), + accountClient, + Mockito.mock(EntityManagementClient.class), + Mockito.mock(ModerationPolicyClient.class), + firstPartyConnectContextRegistry, + gameplayPresenceLifecycleService, + Mockito.mock(ScriptEventPublisher.class), + meterRegistry); + } + private static String joinedOutputText(List outputs) { return outputs.stream() .map(PlayerOutput::text) From 9c2147039f47649580b6e607d3e09e55fe66be1b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 10:44:33 +1300 Subject: [PATCH 10/14] test(game-session): prove bare first-party login stays denied --- ...ommunicationWebSocketCrossServiceTest.java | 13 ++- ...essionWebSocketHandlerIntegrationTest.java | 92 ++++++++----------- 2 files changed, 50 insertions(+), 55 deletions(-) diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java index 09d9ddb28a..b080edd672 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java @@ -1071,9 +1071,18 @@ private GameplayWebSocketDriver openFirstPartyGameplayClient(String transportSes JsonNode login = awaitStructuredCommand(client, 0, "LOGIN"); GameplayStructuredCommandAssertions.requireStructuredCommand( login, "LOGIN", "login", "META", "SESSION"); - assertThat(login.path("accepted").asBoolean()).withFailMessage(login.toPrettyString()).isTrue(); + assertThat(login.path("accepted").asBoolean()).isFalse(); + assertThat(login.path("errorCode").asText()).isEqualTo("AUTH_UNAVAILABLE"); + + client.send("LOGIN emberline@example.com swordfish"); + JsonNode credentialLogin = awaitStructuredCommand(client, 1, "LOGIN"); + GameplayStructuredCommandAssertions.requireStructuredCommand( + credentialLogin, "LOGIN", "login", "META", "SESSION"); + assertThat(credentialLogin.path("accepted").asBoolean()) + .withFailMessage(credentialLogin.toPrettyString()) + .isTrue(); client.send("PLAY demo"); - JsonNode play = awaitStructuredCommand(client, 1, "PLAY"); + JsonNode play = awaitStructuredCommand(client, 2, "PLAY"); GameplayStructuredCommandAssertions.requireStructuredCommand( play, "PLAY", "play", "META", "SESSION"); assertThat(play.path("accepted").asBoolean()).withFailMessage(play.toPrettyString()).isTrue(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 3e4e43fc38..5bd1345f6b 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -791,7 +791,7 @@ void websocketMoveEnqueuesDurableCommandAfterPlay() throws Exception { } @Test - void websocketFirstPartyLoginConsumesVerifiedConnectContext() throws Exception { + void websocketFirstPartyBareLoginFailsClosedWithoutPromotingBootstrapShell() throws Exception { List payloads; try (GameplayWebSocketDriver client = openFirstPartyDriver("1", firstPartyClaims("demo", "production", "1", "1", "1"))) { @@ -804,36 +804,31 @@ void websocketFirstPartyLoginConsumesVerifiedConnectContext() throws Exception { payloads = client.responses(); } - JsonNode loginSuccess = json(payloads.get(0)); + JsonNode loginFailure = json(payloads.get(0)); GameplayStructuredCommandAssertions.requireStructuredCommand( - loginSuccess, "LOGIN", "login", "META", "SESSION"); - assertThat(loginSuccess.path("accepted").asBoolean()).isTrue(); + loginFailure, "LOGIN", "login", "META", "SESSION"); + assertThat(loginFailure.path("accepted").asBoolean()).isFalse(); + assertThat(loginFailure.path("errorCode").asText()).isEqualTo("AUTH_UNAVAILABLE"); assertThat(payloads) .anyMatch( payload -> GameplayStructuredCommandAssertions.isStructuredCommand( payload, "PLAY", "play", "META", "SESSION") - && json(payload).path("accepted").asBoolean()); - assertThat(payloads).anyMatch(payload -> json(payload).path("outputs").isArray()); - verify(accountClient) - .getTenantMembershipForRuntime( - argThat( - playerContext -> - "123".equals(playerContext.getAccountId()) - && "22".equals(playerContext.getTenantId()) - && !playerContext.getRequestId().isBlank())); - verify(accountClient) - .getTenantEntitlementsForRuntime(eq("22"), org.mockito.ArgumentMatchers.anyString()); + && !json(payload).path("accepted").asBoolean() + && "LOGIN_REQUIRED".equals(json(payload).path("errorCode").asText())); assertThat(sessionContextService.findByTenantAndSessionId(22L, 1L)) .hasValueSatisfying( context -> { + assertThat(context.accountId()).isZero(); + assertThat(context.gameInstanceId()).isZero(); + assertThat(context.characterId()).isZero(); assertThat(context.bootstrapGameInstanceId()).isEqualTo(1L); - assertThat(context.worldSlug()).isEqualTo("demo"); - assertThat(context.realmSlug()).isEqualTo("production"); - assertThat(context.pointerVersion()).isEqualTo(1L); - assertThat(context.connectScopeId()).isEqualTo("scope-1"); - assertThat(context.connectRequestId()).isEqualTo("connect-req-1"); }); + verify(accountClient, never()) + .getTenantMembershipForRuntime( + org.mockito.ArgumentMatchers.any( + net.firedevops.firemud.shared.v1.PlayerExecutionContext.class)); + verify(commandService, never()).enqueue(eq("1"), eq("LOGIN"), eq(false)); } @Test @@ -884,9 +879,7 @@ void websocketFirstPartyStructuredLobbyBrowseFailsClosedForCharacters() throws E List payloads; try (GameplayWebSocketDriver client = openFirstPartyDriver("1", firstPartyClaims("demo", "production", "1", "1", "browse-1"))) { - client.send("LOGIN"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); + loginFirstPartyWithCredentials(client); client.send("REALMS demo"); client.awaitMatching( payload -> isStructuredCommand(payload, "REALMS"), "structured REALMS result"); @@ -965,9 +958,7 @@ void websocketFirstPartyStructuredWhoIncludesActivityState() throws Exception { List payloads; try (GameplayWebSocketDriver client = openFirstPartyDriver("1", firstPartyClaims("demo", "production", "1", "1", "who-1"))) { - client.send("LOGIN"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); + loginFirstPartyWithCredentials(client); client.send("PLAY demo"); client.awaitMatching( payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); @@ -1030,9 +1021,7 @@ void websocketFirstPartyFreshPlayDoesNotReplayBufferedScreenAndPerformsFreshLook List payloads; try (GameplayWebSocketDriver client = openFirstPartyDriver("1", firstPartyClaims("demo", "production", "1", "1", "2"))) { - client.send("LOGIN"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); + loginFirstPartyWithCredentials(client); client.send("PLAY demo"); client.awaitMatching( payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); @@ -1092,9 +1081,7 @@ void websocketFirstPartyLogoutRetainsReplayStateButSuppressesReplayForFreshRecon GameplayWebSocketDriver.CloseEvent firstCloseEvent; try (GameplayWebSocketDriver client = openFirstPartyDriver("1", firstPartyClaims("demo", "production", "1", "1", "logout-1"))) { - client.send("LOGIN"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); + loginFirstPartyWithCredentials(client); client.send("PLAY demo"); client.awaitMatching( payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); @@ -1111,9 +1098,7 @@ void websocketFirstPartyLogoutRetainsReplayStateButSuppressesReplayForFreshRecon java.util.List secondPayloads; try (GameplayWebSocketDriver client = openFirstPartyDriver("2", firstPartyClaims("demo", "production", "1", "1", "logout-2"))) { - client.send("LOGIN"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); + loginFirstPartyWithCredentials(client); client.send("PLAY demo"); client.awaitMatching( payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); @@ -1356,9 +1341,7 @@ void websocketFirstPartyReconnectAfterCutoverFailsClosedWithoutLeakingOldGamepla try (GameplayWebSocketDriver first = openFirstPartyDriver( "2", firstPartyClaims("demo", "production", "1", "1", "resume-before-cutover"))) { - first.send("LOGIN"); - first.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); + loginFirstPartyWithCredentials(first); first.send("PLAY demo"); first.awaitMatching( payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); @@ -1385,9 +1368,7 @@ void websocketFirstPartyRouteChangeOnReusedTransportClearsOldGameplayBeforeRelog throws Exception { try (GameplayWebSocketDriver first = openFirstPartyDriver("2", firstPartyClaims("demo", "production", "1", "1", "route-a"))) { - first.send("LOGIN"); - first.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); + loginFirstPartyWithCredentials(first); first.send("PLAY demo"); first.awaitMatching( payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); @@ -1399,9 +1380,7 @@ void websocketFirstPartyRouteChangeOnReusedTransportClearsOldGameplayBeforeRelog List payloads; try (GameplayWebSocketDriver second = openFirstPartyDriver("2", firstPartyClaims("sandbox", "production", "2", "1", "route-b"))) { - second.send("LOGIN"); - second.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); + loginFirstPartyWithCredentials(second); second.send("LOOK"); second.awaitMatching( payload -> isStructuredCommand(payload, "LOOK"), "structured LOOK result"); @@ -1459,9 +1438,7 @@ void websocketFirstPartyPlayRejectsCutoverAfterLogin() throws Exception { GameplayWebSocketDriver.CloseEvent closeEvent; try (GameplayWebSocketDriver client = openFirstPartyDriver("2", firstPartyClaims("demo", "production", "1", "1", "stale-play"))) { - client.send("LOGIN"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); + loginFirstPartyWithCredentials(client); bumpProductionAdmissionPointer(CUTOVER_GAME_INSTANCE_ID, true); client.send("PLAY demo"); client.awaitMatching( @@ -1490,9 +1467,7 @@ void websocketFirstPartySelectorChangeOnReusedTransportClearsOldGameplayBeforeRe try (GameplayWebSocketDriver first = openFirstPartyDriver( "2", firstPartyClaims("demo", "production", "1", "1", "scope-selector-a"))) { - first.send("LOGIN"); - first.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); + loginFirstPartyWithCredentials(first); first.send("PLAY demo"); first.awaitMatching( payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); @@ -1508,9 +1483,7 @@ void websocketFirstPartySelectorChangeOnReusedTransportClearsOldGameplayBeforeRe second.send("LOOK"); second.awaitMatching( payload -> isStructuredCommand(payload, "LOOK"), "structured LOOK result"); - second.send("LOGIN"); - second.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); + loginFirstPartyWithCredentials(second); payloads = second.responses(); } @@ -1585,6 +1558,19 @@ private GameplayWebSocketDriver openFirstPartyDriver( connectClaims); } + private void loginFirstPartyWithCredentials(GameplayWebSocketDriver client) throws Exception { + client.send("LOGIN demo@example.com swordfish"); + client.awaitMatching( + payload -> isStructuredCommand(payload, "LOGIN"), "structured credential LOGIN result"); + JsonNode login = + client.responses().stream() + .filter(payload -> isStructuredCommand(payload, "LOGIN")) + .map(GameSessionWebSocketHandlerIntegrationTest::json) + .reduce((first, second) -> second) + .orElseThrow(); + assertThat(login.path("accepted").asBoolean()).isTrue(); + } + private java.util.Map firstPartyClaims( String worldSlug, String realmSlug, From 8399ddb0aca36c7a674bacde3fbad62c8c625471 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 18:56:20 +1300 Subject: [PATCH 11/14] docs(auth): state bare LOGIN fail-closed proof accurately --- .../microservices/game-session-service/protocols.md | 4 ++-- .../implementation-tracking/player-access-and-session.md | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index 492eda06b7..56c519e704 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -102,10 +102,10 @@ Current local `JOIN` availability and the membership-authority-generation gap ar Telnet and WebSocket clients share the line-based syntax, but transport context determines which `LOGIN` form is valid: - For Telnet and other non-WebSocket text clients, fresh public `WORLDS` discovery precedes `LOGIN`; `LOGIN ` requests a verified-email code and `LOGIN ` performs an immediate password-or-code authentication attempt. Bare `LOGIN` does not start an interactive prompt. -- For sessions on the Gateway-routed first-party WebSocket route `/ws/game/**` that already carry a validated Gateway connect context, bare `LOGIN` completes gameplay authentication from the pre-established bootstrap identity instead of prompting for credentials. First-party browser, mobile-browser, native-mobile, and other first-party non-browser clients use the protected connect-token cookie; only the target-only, explicitly classified `non_first_party_public` route variant may use the dedicated connect-token handshake header after its proof is complete. This bootstrap identity must not quietly reintroduce gameplay binding into `LOGIN`; `PLAY` remains the sole gameplay-admission and gameplay-scope binding step. Reauthentication as a different account clears every retained character, runtime-route, playable-scope, and connect-scope field before `PLAY`; only an exact same-account reconnect may retain its candidate gameplay context for fresh admission validation. +- For sessions on the Gateway-routed first-party WebSocket route `/ws/game/**` that already carry a validated Gateway connect context, target bare `LOGIN` completes gameplay authentication through Account's one-use, caller-bound delegation exchange instead of prompting for credentials. The current candidate returns `AUTH_UNAVAILABLE` before promotion because that exchange is not implemented; Gateway context alone is not Account authorization. First-party browser, mobile-browser, native-mobile, and other first-party non-browser clients use the protected connect-token cookie; only the target-only, explicitly classified `non_first_party_public` route variant may use the dedicated connect-token handshake header after its proof is complete. This bootstrap identity must not quietly reintroduce gameplay binding into `LOGIN`; `PLAY` remains the sole gameplay-admission and gameplay-scope binding step. Reauthentication as a different account clears every retained character, runtime-route, playable-scope, and connect-scope field before `PLAY`; only an exact same-account reconnect may retain its candidate gameplay context for fresh admission validation. - The same `OK ` and `ERROR ` response format applies to all transports so clients can react consistently. -Multi-line prompt exchanges are planned but not implemented for Telnet and non-bootstrap clients. On those transports, bare `LOGIN` currently returns `ERROR PROMPT_LOGIN_UNSUPPORTED Prompt-based login is not implemented yet; send LOGIN [secret].` First-party `/ws/game/**` sessions with a validated connect context are the exception: bare `LOGIN` consumes the bootstrap-backed context and must not ask the browser to resend credentials. +Multi-line prompt exchanges are planned but not implemented for Telnet and non-bootstrap clients. On those transports, bare `LOGIN` currently returns `ERROR PROMPT_LOGIN_UNSUPPORTED Prompt-based login is not implemented yet; send LOGIN [secret].` First-party `/ws/game/**` sessions with a validated connect context are the target exception: bare `LOGIN` must use the Account exchange without asking the browser to resend credentials, but currently returns `AUTH_UNAVAILABLE` without promoting an authenticated session. After `LOGIN` succeeds, an existing member normally issues `PLAY [realm] [character]`; a first-time public-production player must issue `JOIN ` once before `PLAY`. `REALMS` and `CHARS` remain available as lobby helper commands when the player's choice is ambiguous or when they want to browse. `PLAY` is the gameplay-admission and gameplay-binding step; it is not merely a continuation of authentication. This step binds the authenticated connection to a world-scoped gameplay session and enforces tenant authorization, realm routing, public-admission rules, and entitlements. 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 ef13216881..389dc04c9f 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -32,11 +32,11 @@ The current Unit 1B draft's conditional Game Session `PLAY` branch now distingui The approved first-party bare-`LOGIN` private-delegation exchange is not live. 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 or key-ring deployment. The separate V37 storage candidate binds one exchange request to a committed V35 source, preserves first-writer request identity and digest, and permits only an atomic write-once pending-evidence to terminal-success transition with an exact purpose-bound envelope; it does not mint, decrypt, or return a delegation JWT. Its seven PostgreSQL cases passed in CI run `36289042648` on prior #2881 head `25626210c` and skipped locally without Docker; caller lost-response recovery, current-authority revalidation, exact Game Session caller proof, and the complete producer/consumer path remain open. 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 #2881 candidate also contains Game Session's fail-closed bare-`LOGIN` guard: otherwise valid first-party context returns `AUTH_UNAVAILABLE` before enqueue or authenticated session promotion while the Account exchange is unwired, without changing credential-bearing `LOGIN`. Focused handler tests exercise no enqueue, no save, and retained unauthenticated bootstrap context. Seven first-party structured-output cross-service tests currently fail at their shared helper's old successful-bare-LOGIN assertion; there is no supported authenticated first-party fixture until the Account exchange works, and the internal text fixture cannot prove structured public output. They remain an explicit runtime proof gate rather than being disabled or counted as passing. The Account CI matrix now disables Gradle build-cache reuse and requires exact JOIN-map and exchange-transaction JUnit cases to execute without skips; synthetic strict-inspector contracts pass, while local XML correctly fails that gate because Docker is unavailable. This does not make the V37 storage a live exchange, or prove Account/Gateway context verification and lost-response recovery. +The #2881 candidate also contains Game Session's fail-closed bare-`LOGIN` guard: otherwise valid first-party context returns `AUTH_UNAVAILABLE` before enqueue or authenticated session promotion while the Account exchange is unwired, without changing credential-bearing `LOGIN`. Focused handler tests exercise no enqueue, no save, and retained unauthenticated bootstrap context. Seven first-party structured-output cross-service tests failed on an earlier head because their helper still expected bare-LOGIN success. The corrected helper now asserts `AUTH_UNAVAILABLE` and no promotion for that attempt, then uses credential-bearing LOGIN for supported gameplay coverage; the dedicated negative fixture expects following `PLAY` to require login. Both affected Docker-backed classes skipped locally, so this is a corrected assertion, not executed WebSocket end-to-end proof or a working Account exchange. Positive first-party bare-LOGIN proof remains an explicit activation gate. The Account CI matrix now disables Gradle build-cache reuse and requires exact JOIN-map and exchange-transaction JUnit cases to execute without skips; synthetic strict-inspector contracts pass, while local XML correctly fails that gate because Docker is unavailable. This does not make the V37 storage a live exchange, or prove Account/Gateway context verification and lost-response recovery. -Manual CI run `36292018666` on prior #2881 head `aa5d73c05a408ba152ac05f4298cadd52430b831` passed its strict Account evidence gate: all 24 JOIN PostgreSQL cases and seven V37 bare-LOGIN exchange cases executed with no skips or failures, including the required targeted map-shape and transaction tests. Its aggregate gate remained red: seven first-party success assertions still assume the disabled exchange, and four Game Session/TCP Proxy cross-service failures arose from #2880's incomplete `INACTIVE` carrier handling; ten hosted smoke-tool Ruff errors and the EA-3.1 proof-link rule also failed. The #2880 consumer/stub correction has been merged normally into #2881 with its unique non-tracker patch ID unchanged. A new signed-context wire-negative test for bare `LOGIN` and following `PLAY` compiles but skipped locally without Docker; the seven positive scenarios remain unchanged. The corrected composed local module/doc gate passed, with 381 Account and 1,641 Game Session unit tests executed, but all 87 Account PostgreSQL cases and 40/41 Game Session cross-service cases skipped. Corrected-head hosted proof remains necessary, and neither membership nor credential runtime path is enabled. +Manual CI run `36292018666` on prior #2881 head `aa5d73c05a408ba152ac05f4298cadd52430b831` passed its strict Account evidence gate: all 24 JOIN PostgreSQL cases and seven V37 bare-LOGIN exchange cases executed with no skips or failures, including the required targeted map-shape and transaction tests. Its aggregate gate remained red: seven first-party success assertions still assume the disabled exchange, and four Game Session/TCP Proxy cross-service failures arose from #2880's incomplete `INACTIVE` carrier handling; ten hosted smoke-tool Ruff errors and the EA-3.1 proof-link rule also failed. The #2880 consumer/stub correction has been merged normally into #2881 with its unique non-tracker patch ID unchanged. A new signed-context wire-negative test for bare `LOGIN` and following `PLAY` compiles but skipped locally without Docker; the seven positive scenarios still retained their obsolete success assertions at that checkpoint; the later fixture correction is described above. The corrected composed local module/doc gate passed, with 381 Account and 1,641 Game Session unit tests executed, but all 87 Account PostgreSQL cases and 40/41 Game Session cross-service cases skipped. Corrected-head hosted proof remains necessary, and neither membership nor credential runtime path is enabled. -Corrected #2881 head `e39c31b1f42b202c26c34ba83ddf6e4c8247699e` ran in CI `36293121086`: the strict Account gate passed all 26 JOIN and seven V37 PostgreSQL cases with zero skips/failures, including #2880's two new same-fence snapshot cases; the signed-context bare-`LOGIN` denial test executed and passed. Game Session's 41 cross-service cases had exactly seven failures, all existing first-party success scenarios awaiting the Account exchange. TCP Proxy and all other service Build/Test jobs passed. Python Script Validation and the EA-3.1 Dev Tool Contract Check remain red outside this unique change. Two additional V37 repository/crypto tests now locally compile: concurrent exact first-writer terminalization and decrypting the exact retained envelope after a simulated lost response. All 89 local Account integration cases skip without Docker, so these two new tests need hosted execution. They prove storage/recovery primitives only, not Account-issued JWT, caller-bound exchange, live ring custody, or activation. +Corrected #2881 head `e39c31b1f42b202c26c34ba83ddf6e4c8247699e` ran in CI `36293121086`: the strict Account gate passed all 26 JOIN and seven V37 PostgreSQL cases with zero skips/failures, including #2880's two new same-fence snapshot cases; the signed-context bare-`LOGIN` denial test executed and passed. Game Session's 41 cross-service cases had exactly seven failures from the then-current first-party success assertions; those assertions were subsequently corrected to the fail-closed behavior described above, while the Account exchange remains unimplemented. TCP Proxy and all other service Build/Test jobs passed. Python Script Validation and the EA-3.1 Dev Tool Contract Check remain red outside this unique change. Two additional V37 repository/crypto tests now locally compile: concurrent exact first-writer terminalization and decrypting the exact retained envelope after a simulated lost response. All 89 local Account integration cases skip without Docker, so these two new tests need hosted execution. They prove storage/recovery primitives only, not Account-issued JWT, caller-bound exchange, live ring custody, or activation. 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. From 61ca37fdeea8784448929dd5ce1716f7475fb00c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 20:12:14 +1300 Subject: [PATCH 12/14] test(auth): align WebSocket login expectations with guarded path --- .../GameSessionWebSocketHandlerIntegrationTest.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index ae73b65914..fb5beab359 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -484,7 +484,7 @@ void websocketLoginThenLookUsesAuthenticatedPath() throws Exception { assertThat(context.roomInstanceId()).isNotBlank(); }); - verify(commandService).enqueue("41", "LOGIN demo@example.com swordfish", false); + verify(commandService, never()).enqueue("41", "LOGIN demo@example.com swordfish", false); verify(commandService).enqueue("41", "LOOK", false); verify(gameLogicClient) .resolveLook( @@ -851,7 +851,7 @@ void websocketLoginCanBrowseRealmsWhileCharactersFailClosed() throws Exception { && payload.contains("Live Realm (production) [shared, allow_new]")); assertThat(payloads) .anyMatch(payload -> payload.startsWith("ERROR CHARACTER_LIST_UNAVAILABLE")); - verify(commandService).enqueue("41", "LOGIN demo@example.com swordfish", false); + verify(commandService, never()).enqueue("41", "LOGIN demo@example.com swordfish", false); verify(commandService, never()).enqueue("41", "REALMS demo", false); verify(commandService, never()).enqueue("41", "CHARS demo", false); verify(accountClient) @@ -1427,8 +1427,8 @@ void websocketFirstPartyRouteChangeOnReusedTransportClearsOldGameplayBeforeRelog assertThat(context.worldSlug()).isEqualTo("sandbox"); assertThat(context.realmSlug()).isEqualTo("production"); assertThat(context.pointerVersion()).isEqualTo(1L); - assertThat(context.connectScopeId()).isEqualTo("scope-route-b"); - assertThat(context.connectRequestId()).isEqualTo("connect-req-route-b"); + assertThat(context.connectScopeId()).isNull(); + assertThat(context.connectRequestId()).isNull(); }); } @@ -1514,8 +1514,8 @@ void websocketFirstPartySelectorChangeOnReusedTransportClearsOldGameplayBeforeRe assertThat(context.worldSlug()).isEqualTo("demo"); assertThat(context.realmSlug()).isEqualTo("production"); assertThat(context.pointerVersion()).isEqualTo(1L); - assertThat(context.connectScopeId()).isEqualTo("scope-scope-selector-b"); - assertThat(context.connectRequestId()).isEqualTo("connect-req-scope-selector-b"); + assertThat(context.connectScopeId()).isNull(); + assertThat(context.connectRequestId()).isNull(); }); assertThat(gameplayPresenceService.findConnectedBySessionId(2L)).isEmpty(); } From c6fa3ea9436c2cb69a6e13710da4db9a0e53cf3e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 21:52:06 +1300 Subject: [PATCH 13/14] Require executed Script Pin PostgreSQL retry proof in CI --- .github/workflows/ci.yml | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 116ab5656b..97903cc2e9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -943,7 +943,7 @@ jobs: id: checks run: | echo "::group::Run Module Validation" - if [[ "${{ matrix.module }}" == "account-service" ]]; then + if [[ "${{ matrix.module }}" == "account-service" || "${{ matrix.module }}" == "game-session-service" ]]; then ./gradlew :${{ matrix.module }}:check -PfullCheck --no-build-cache else ./gradlew :${{ matrix.module }}:check -PfullCheck @@ -961,6 +961,15 @@ jobs: --require-case 'integration.net.firedevops.firemud.accountservice.AccountBareLoginExchangeRepositoryIntegrationTest#claimOnlyTransactionRollsBackPendingExchange()' \ account-service + - name: 🔎 Verify Game Session PostgreSQL proof case + if: ${{ matrix.module == 'game-session-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.gamesession.repository.ScriptPinOperationRepositoryIntegrationTest \ + --require-case 'net.firedevops.firemud.gamesession.repository.ScriptPinOperationRepositoryIntegrationTest#pinAdmissionBaseMustStillMatchTheRowLockedRuntimeAndIsBoundToTheReceipt()' \ + game-session-service + - name: 📦 Build Runtime JAR if: ${{ contains(fromJSON(needs.changes.outputs.bootable_modules), matrix.module) }} run: ./gradlew :${{ matrix.module }}:bootJar -PfullCheck From 1f0577b1f348280c4c630502df9ad5faa0f416e4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 22:57:33 +1300 Subject: [PATCH 14/14] Require executed connect issuance recovery proof in Account CI Extend the existing strict PostgreSQL evidence gate to V35 source issuance, including concurrent first writer, exact lost-response recovery and deletion guards. Parent proof must be propagated before publication. Focused actionlint passes. --- .github/workflows/ci.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 97903cc2e9..9856c37a5f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -957,8 +957,12 @@ jobs: --strict \ --require-suite net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest \ --require-suite integration.net.firedevops.firemud.accountservice.AccountBareLoginExchangeRepositoryIntegrationTest \ + --require-suite integration.net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepositoryIntegrationTest \ --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#positiveMembershipSnapshotRejectsScalarAndWrongTenantVersionMaps()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountBareLoginExchangeRepositoryIntegrationTest#claimOnlyTransactionRollsBackPendingExchange()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepositoryIntegrationTest#concurrentExactIssuanceClaimsHaveOneTerminalFirstWriter()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepositoryIntegrationTest#lostIssuanceResponseRecoversExactEncryptedResultFromDurableReadback(Path)' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepositoryIntegrationTest#directDeletionOfIssuanceOperationOrResponseEnvelopeIsRejected()' \ account-service - name: 🔎 Verify Game Session PostgreSQL proof case