diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 741449f8f4..2444f40da4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -150,8 +150,8 @@ jobs: outputs.module_check_matrix = outputs.affected_modules.flatMap((module) => slowServicePartitionCounts[module] ? Array.from({ length: slowServicePartitionCounts[module] }, (_, index) => - ({ module, partition: String(index + 1), "java-version": 21 })) - : [{ module, partition: "full", "java-version": 21 }] + ({ module, partition: String(index + 1), "java-version": 25 })) + : [{ module, partition: "full", "java-version": 25 }] ); for (const [name, value] of Object.entries(outputs)) { core.setOutput( @@ -1304,7 +1304,7 @@ jobs: uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6 with: distribution: 'temurin' - java-version: 21 + java-version: 25 - name: ⚙️ Set Up Gradle for Account Coverage Aggregation uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6 @@ -1415,7 +1415,7 @@ jobs: uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6 with: distribution: 'temurin' - java-version: 21 + java-version: 25 - name: ⚙️ Set Up Gradle for Game Session Coverage Aggregation uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6 @@ -1467,6 +1467,16 @@ jobs: ref: ${{ github.event.pull_request.base.sha }} persist-credentials: false + - name: Explain validation lane + env: + FIREMUD_METADATA_ONLY: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }} + run: | + if [[ "$FIREMUD_METADATA_ONLY" == "true" ]]; then + printf '## Metadata-only PR edit\n\nHeavy validation jobs are skipped. Required CI is preserved only from qualified source validation for this comparison.\n' >> "$GITHUB_STEP_SUMMARY" + else + printf '## Source validation\n\nThis run executes the applicable source checks for the PR comparison.\n' >> "$GITHUB_STEP_SUMMARY" + fi + - name: Preserve successful required gate on metadata-only edit id: preserved_gate if: ${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }} diff --git a/.github/workflows/refresh-gradle-daemon-jvm.yml b/.github/workflows/refresh-gradle-daemon-jvm.yml index 0edf013646..6b1f6b76f8 100644 --- a/.github/workflows/refresh-gradle-daemon-jvm.yml +++ b/.github/workflows/refresh-gradle-daemon-jvm.yml @@ -165,10 +165,10 @@ jobs: add-paths: gradle/gradle-daemon-jvm.properties base: develop branch: codex/gradle-daemon-jdk-refresh - commit-message: 'chore(deps): refresh Gradle daemon Java 21 artifacts' - title: 'chore(deps): refresh Gradle daemon Java 21 artifacts' + commit-message: 'chore(deps): refresh Gradle daemon Java 25 artifacts' + title: 'chore(deps): refresh Gradle daemon Java 25 artifacts' labels: dependencies body: | - Regenerated by the repository Gradle wrapper from validated official Adoptium metadata with `updateDaemonJvm --jvm-version=21 --jvm-vendor=adoptium`. + Regenerated by the repository Gradle wrapper from validated official Adoptium metadata with `updateDaemonJvm --jvm-version=25 --jvm-vendor=adoptium`. - Java 21 and Adoptium remain fixed. Gradle serializes the six supported Linux/macOS/Windows x64/AArch64 download URLs; this update refreshes the JDK patch artifacts rather than editing the language version. The publishing App triggers ordinary pull-request checks, including the Smoke Gate. Review and human merge remain required. + Java 25 and Adoptium remain fixed. Gradle serializes five supported download URLs: Linux/macOS x64/AArch64 and Windows x64. Windows ARM automatic provisioning is excluded until a matching official artifact is available and explicitly qualified. This update refreshes the JDK patch artifacts rather than editing the language version. The publishing App triggers ordinary pull-request checks, including the Smoke Gate. Review and human merge remain required. diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 4593d89767..0fca72688d 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -1578,6 +1578,7 @@ jobs: cache-read-only: true - name: Build local PR runtime images + id: runtime-images-build env: MERGE_SHA: ${{ needs.image-meta.outputs.merge_sha }} run: | @@ -1600,6 +1601,16 @@ jobs: "ghcr.io/benhook1013/${service}:${SMOKE_IMAGE_TAG}" done + - name: Retain runtime bootJar compile-failure evidence + if: ${{ failure() && steps.runtime-images-build.outcome == 'failure' }} + continue-on-error: true + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: runtime-bootjar-compile-failure-${{ github.run_id }}-attempt-${{ github.run_attempt }} + path: ${{ steps.runtime-images-build.outputs.runtime_compile_failure_path || format('build/reports/compile-failure/runtime-bootjar/unavailable-{0}-{1}', github.run_id, github.run_attempt) }} + if-no-files-found: warn + retention-days: 3 + - name: Build PR backup verifier image run: | docker build \ diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 1d2faaa9ae..5e22468fea 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -599,7 +599,7 @@ jobs: } // One canonical producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "307dc85869c84ef771aeb82b232bd405eb2aa85c0c691a81cb95257ec013c8ef"; + const canonicalRuntimeWorkflowSha256 = "e939f7a6205e9626fdb6fbe1ab6b908bc8eb9f8912b919a1f5c5491ac6804936"; const canonicalSmokeJobName = "PR Full-Stack Smoke (runtime-required=true)"; const workflowPath = ".github/workflows/runtime-images.yml"; const repositoryName = `${owner}/${repo}`; diff --git a/build.gradle.kts b/build.gradle.kts index fffe82da38..d23b6f3112 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -50,7 +50,7 @@ node { java { toolchain { - languageVersion.set(JavaLanguageVersion.of(21)) + languageVersion.set(JavaLanguageVersion.of(25)) } } @@ -79,14 +79,14 @@ dependencies { } tasks.register("compileBufGeneratedJava") { - description = "Verify remote Buf Java output against the catalog runtimes on Java 21" + description = "Verify remote Buf Java output against the catalog runtimes on Java 25" group = "verification" source(fileTree(providers.gradleProperty("bufGeneratedJavaDir").getOrElse("protos/gen/java")) { include("**/*.java") }) classpath = bufGeneratedJavaClasspath destinationDirectory.set(layout.buildDirectory.dir("buf-generated-classes")) - options.release.set(21) + options.release.set(25) javaCompiler.set(javaToolchains.compilerFor { - languageVersion.set(JavaLanguageVersion.of(21)) + languageVersion.set(JavaLanguageVersion.of(25)) }) } @@ -146,7 +146,7 @@ subprojects { val libs = rootProject.extensions.getByType().named("libs") plugins.withId("java") { - the().toolchain.languageVersion.set(JavaLanguageVersion.of(21)) + the().toolchain.languageVersion.set(JavaLanguageVersion.of(25)) val sourceSets = the() sourceSets.named("test") { compileClasspath += sourceSets.named("main").get().output @@ -156,7 +156,7 @@ subprojects { val crossServiceTestsDir = file("src/test/java/crossservice") val categorizedTestRootsExist = integrationTestsDir.exists() || crossServiceTestsDir.exists() tasks.withType().configureEach { - options.release.set(21) + options.release.set(25) if (name.contains("Test")) { // Ignore the current @MockBean removal warnings until Spring Boot 4.0 lands so tests stay clean. options.compilerArgs.add("-Xlint:-removal") diff --git a/config/protobuf/README.md b/config/protobuf/README.md index df393a37f1..3fab355bf4 100644 --- a/config/protobuf/README.md +++ b/config/protobuf/README.md @@ -8,7 +8,7 @@ buf lint protos The active CI template pins each remote Java generator's upstream version **and** BSR rebuild revision. Renovate queries the public BSR `PluginCurationService/GetLatestCuratedPlugin` Connect GET endpoint, transforms its published versions and revisions with its supported custom datasource, and updates both fields atomically. A version alone would follow later BSR rebuilds. Registry publication can lag upstream Maven releases: the BSR listing, rather than GitHub tags, controls generator availability. -Renovate groups the protobuf generator with the catalog's protobuf runtimes/compiler and the gRPC generator with its gRPC runtimes/compiler. Updates are uncapped; the existing PR Validation Gate generates with the pinned remote plugins and compiles that exact output on Java 21 against the catalog runtimes using `compileBufGeneratedJava`. Service builds continue to use the authoritative Gradle `generateProto` path. Both boundaries must pass before a dependency update can merge. +Renovate groups the protobuf generator with the catalog's protobuf runtimes/compiler and the gRPC generator with its gRPC runtimes/compiler. Updates are uncapped; the existing PR Validation Gate generates with the pinned remote plugins and compiles that exact output on Java 25 against the catalog runtimes using `compileBufGeneratedJava`. Service builds continue to use the authoritative Gradle `generateProto` path. Both boundaries must pass before a dependency update can merge. Reproduce the remote generator compatibility proof from the repository root: diff --git a/design/architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md b/design/architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md index 50424d44fd..253d429116 100644 --- a/design/architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md +++ b/design/architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -Bootstrap, connect-token, and visible `LOGIN`/`PLAY` pieces exist, but the target sequence is not runtime-complete. `/auth/player-bootstrap` now authenticates account identity before tenant selection and accepts the account's configured password or verified-email OTP mode. The target browser and mobile-browser connect-token responses are metadata-only and carry the raw token only in the HttpOnly cookie; the current response still exposes the internal `jti` in its body, so the DTO/OpenAPI `jti` fields must be removed before the target response can be considered implemented; public non-browser connect-token issuance and dedicated header carriage are target-only and unavailable, and protected secure storage plus the header is target contract only. Explicit `POST /auth/bootstrap/join` before bootstrap character creation/connect-token work remains a gap. The target `JOIN_REQUIRED` outcome remains canonical only after the selected public-production target's joining policy permits public joining. If that policy denies public joining, admission and `JOIN` return `PUBLIC_PRODUCTION_ADMISSION_DENIED`, and `JOIN` cannot create or restore membership. Current connect-token issuance and text `PLAY` require the four-field Account admission response, never invoke an implicit membership writer, and may return non-actionable `JOIN_REQUIRED` for an eligible fresh authoritative public-production response with `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter cannot be classified specifically as `INACTIVE`, and explicit `JOIN` remains unavailable; the obsolete writer seam has been removed. The current response cannot distinguish `INACTIVE` from another existing non-admitting membership because `membershipLifecycleState` remains target-only. The exact `membershipLifecycleState=ACTIVE` admission check, complete `membershipAuthorityGeneration` live reread, independent `membershipVersion` issuance baseline, and complete ADR 0030 admission-lease commit remain unimplemented/unproven, and explicit `JOIN` remains unimplemented. The target first-party admission gate therefore remains incomplete until explicit `JOIN`, the joining-policy gate, the active-state check, the generation reread, the unchanged issuance baseline, and exact lease commit are implemented and proven. The first-party browser target sequence is `POST /auth/player-bootstrap` -> bootstrap discovery -> explicit `POST /auth/bootstrap/join` when a first public-production entry requires membership -> `CHARS`/bootstrap character creation as needed -> `POST /auth/connect-token` -> WebSocket `LOGIN` -> `PLAY`; returning browser members skip the join step after their existing membership passes the target checks. The separate text-protocol sequence is credential-bearing `LOGIN ` -> explicit `JOIN ` when public-production membership is missing or `INACTIVE` -> `CHARS`/character creation as needed -> `PLAY`; existing-member text clients may use the documented compatibility path. Neither sequence substitutes for the other, and text `LOGIN` does not use player-bootstrap or connect-token binding. Grant-backed private/playtest players require both a current grant and existing membership, skip `JOIN`, and never create membership through this flow. The route matrix records the unimplemented explicit-membership `JOIN` path; its `known_drift` must also explicitly name the missing joining-policy, active-state, membership-generation, and membership-version baseline checks. +The target sequence remains incomplete. Current Account responses emit membership lifecycle and authority generation, and text `PLAY` consumes them after fresh entitlement evaluation, before membership/grant and later actor/binding checks. Gameplay requires a coherent membership result and `ACTIVE` admitting membership; public repair is limited to missing or `INACTIVE` membership when the joining policy permits it. The current connect-token endpoint fails closed with `AUTH_UNAVAILABLE` before cached replay or membership, entitlement, grant, and routing-authority reads, so it does not currently validate those authorities. Explicit text `JOIN` remains unavailable. Full caller-target/atomic Account authority, `allowNewGameplayBindings`, grant lifecycle/expiry, and lease-commit behavior remain absent or held. Current implementation and proof limits are recorded in [Account Runtime and Data](../microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) and the [Player Access and Session tracker](../../project-management/implementation-tracking/player-access-and-session.md#capability-status); this record does not upgrade runtime proof. The current `GameplayHandshakeFilter` accepts one cookie or header, rejects simultaneous carriers, and consumes an untagged replay marker through the generic Cache-bound client, but does not implement ADR 0029's tagged Coordination Redis readiness/fence and quarantine contract. Target player-facing admission remains quarantined until that cutover and proof complete. That current parser support does not establish public non-browser issuance or an accepted target non-first-party route/carrier. @@ -19,7 +19,7 @@ That current parser support does not establish public non-browser issuance or an - Decision owner: FireMUD human product and architecture owner - Consultation: human-led adversarial review of `AUTH-02` - Human review status: Completed -- Human review date: 2026-07-18 +- Human review date: 2026-11-01 - Human review disposition: Revised - Review source: `AUTH-02` @@ -33,13 +33,14 @@ The staged design is partially implemented and tested. It keeps the first-party ### First-Party Browser Flow +`allowPublicJoin` is enrollment policy, not a gameplay-entitlement switch. It gates creation or restoration of missing or `INACTIVE` public-production membership; setting it to `false` does not by itself deny connect-token issuance or `PLAY` for an existing `ACTIVE` member. Existing members remain subject to every other current membership, entitlement, routing, grant, and binding gate. When missing or `INACTIVE` membership requires a join/repair, a closed enrollment policy returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, not `JOIN_REQUIRED`. + 1. `POST /auth/player-bootstrap` authenticates the platform account without requiring a tenant selection and issues only a short-lived player-bootstrap identity. 2. Bootstrap discovery lets the authenticated player select a visible world and realm context; the player-bootstrap profile authorizes only caller-bound discovery, bootstrap-authenticated character discovery and character creation, `POST /auth/bootstrap/join`, and `POST /auth/connect-token`. 3. A first public-production entry first evaluates two separate authorities: fresh Account entitlement evidence, whose `allowPublicJoin` field controls whether this caller may join, and fresh selected-target catalog/pointer evidence, whose catalog/policy revision proves the target is the visible public-production realm and whose pointer proves the current route. An entitlement outage returns `ENTITLEMENT_UNAVAILABLE`; a definitive Account policy denial returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`; missing, stale, ambiguous, or unavailable selected-target routing returns its canonical routing error. None of these outcomes becomes `JOIN_REQUIRED`, and `JOIN` cannot create or restore membership on any of them. Only when both authorities pass does the flow explicitly invoke `JOIN` or `Join & Play`. Missing membership creates one durable `ACTIVE` row; `INACTIVE` membership restores to `ACTIVE`, advances `membershipVersion`, and emits the required one transition audit/outbox event; `ACTIVE` membership remains event-free and idempotent, returning the exact current snapshot; every other lifecycle state rejects admission and is not restored by `JOIN`. Missing creation also advances `membershipVersion`, and `membershipAuthorityGeneration` advances independently only when the committed transition records `callerBoundAuthorityInvalidated=true`. Any non-`ACTIVE` membership never admits gameplay. If the caller lacks the required public-production membership after both authorities permit joining, connect-token issuance and `PLAY` return `JOIN_REQUIRED` until this operation succeeds. Grant-backed private/playtest realms require both the applicable current grant and existing membership, with lifecycle state exactly `ACTIVE`, skip `JOIN`, and never create membership through this flow. For the public-production join predicate, `JOIN_REQUIRED` is emitted only when fresh Account entitlement says `allowPublicJoin=true`, fresh selected-target catalog/pointer evidence identifies the public-production target, and caller-bound membership is missing or `INACTIVE`. `ACTIVE` is the only gameplay-admissible state; `JOIN` is idempotent for `ACTIVE` and restores only `INACTIVE` to `ACTIVE`. Every other lifecycle state is a join denial and is not restorable or transitioned by `JOIN`; those states must be resolved by their owning lifecycle or remediation contract rather than by public enrollment. - 4. Character discovery and any allowed character creation occur for the selected realm after the explicit join where one is required. -5. `POST /auth/connect-token` first locally validates the presented `player-bootstrap` profile, performs exactly one lookup of its active issued-token registry record, and performs exactly one complete `account-auth-evidence-bundle/v1` read from Account. The registry record and bundle must match the presented token and caller; bootstrap cache presence, token claims alone, or separately assembled reads cannot authorize the request. The selected-route membership evidence comes from that same Account snapshot. It also resolves the verified scope against fresh selected-target catalog/pointer evidence and captures the exact immutable `routingBaseline={connectScopeId, tenantId, worldSlug, realmSlug, gameInstanceId, catalogRevision, pointerVersion, evaluatedAt, connectScopeExpiresAt}`. Here `catalogRevision` is the routing record's reference to the authoritative separately versioned catalog/policy snapshot; it is not supplied by, or substituted for, Account entitlement evidence. For a selected public-production target, fresh Account entitlement is evaluated separately: `allowPublicJoin=false` returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, an entitlement outage returns `ENTITLEMENT_UNAVAILABLE`, and only a permitted target with missing or `INACTIVE` membership returns `JOIN_REQUIRED`. It requires exact `membershipLifecycleState=ACTIVE` for issuance and captures an immutable issuance baseline `{routingBaseline, membershipLifecycleState, membershipAuthorityGeneration, membershipVersion}` only for a successful `COMMITTED` issuance from those coherent snapshots. It issues a single-use connect token with a lifetime no longer than 30 seconds and never creates or restores membership. Deterministic failures persist terminal error evidence for that request digest as the applicable error, with no token and no issuance baseline. Only the newly minted `gameplay-connect` artifact uses the no-registry replay exception defined by ADR 0029; its minting request still requires the presented registry-backed `player-bootstrap` authorization above. +5. `POST /auth/connect-token` first locally validates the presented `player-bootstrap` profile, performs exactly one lookup of its active issued-token registry record, and performs exactly one complete `account-auth-evidence-bundle/v1` read from Account. The registry record and bundle must match the presented token and caller; bootstrap cache presence, token claims alone, or separately assembled reads cannot authorize the request. The selected-route membership evidence comes from that same Account snapshot. It also resolves the verified scope against fresh selected-target catalog/pointer evidence and captures the exact immutable `routingBaseline={connectScopeId, tenantId, worldSlug, realmSlug, gameInstanceId, catalogRevision, pointerVersion, evaluatedAt, connectScopeExpiresAt}`. Here `catalogRevision` is the routing record's reference to the authoritative separately versioned catalog/policy snapshot; it is not supplied by, or substituted for, Account entitlement evidence. For a selected public-production target, fresh Account entitlement is evaluated separately. If membership is missing or `INACTIVE`, `allowPublicJoin=false` returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`; `JOIN_REQUIRED` is returned only when the selected target is confirmed as public production, fresh entitlement permits joining, and membership is missing or `INACTIVE`. An entitlement outage returns `ENTITLEMENT_UNAVAILABLE`. If membership is already `ACTIVE`, `allowPublicJoin=false` alone does not deny issuance; the fresh runtime-entitlement decision and every other applicable admission check must still permit it. Issuance requires exact `membershipLifecycleState=ACTIVE` and captures an immutable issuance baseline `{routingBaseline, membershipLifecycleState, membershipAuthorityGeneration, membershipVersion}` only for a successful `COMMITTED` issuance from those coherent snapshots. It issues a single-use connect token with a lifetime no longer than 30 seconds and never creates or restores membership. Deterministic failures persist terminal error evidence for that request digest as the applicable error, with no token and no issuance baseline. Only the newly minted `gameplay-connect` artifact uses the no-registry replay exception defined by ADR 0029; its minting request still requires the presented registry-backed `player-bootstrap` authorization above. 6. Browser and mobile-browser clients receive that token only in a `Secure`, `HttpOnly`, appropriately scoped cookie. First-party native-mobile clients using a cookie jar remain cookie-only. The target contract for explicitly classified non-first-party/public native-mobile and other non-browser clients is protected secure storage plus the dedicated header, but public non-browser issuance and header carriage are target-only and unavailable until the dedicated route is fully registered and proven. Browser JavaScript receives non-secret connection metadata, not the token value. 7. Gateway validates expiry, signature, audience, scope, and one-time use before admitting `/ws/game/**`, then attaches a signed internal connect context. This is transport admission, not general Gateway-owned account authentication. The current filter's bounded signature/claim/expiry and one-time marker checks do not constitute the target readiness/fence/quarantine proof; this target transport-admission exception must not be treated as general Gateway-owned account authentication. @@ -55,7 +56,7 @@ Reconnect uses a fresh bootstrap/connect-token sequence where required by the ow ### Telnet and Non-WebSocket Text Protocol Flow -Telnet and other non-WebSocket text clients authenticate in-band through Account's canonical email login, `LOGIN ` (with the supported email-code challenge form where applicable). `LOGIN` establishes only the authenticated socket/account context; it does not select a tenant or character and does not create a gameplay binding. After that authentication, a first public-production entry requires fresh Account entitlement with `allowPublicJoin=true` plus fresh selected-target catalog/pointer/public-production evidence before returning `JOIN_REQUIRED` and allowing explicit `JOIN ` before `CHARS` and `PLAY`; an entitlement outage is `ENTITLEMENT_UNAVAILABLE`, while a policy or target denial is `PUBLIC_PRODUCTION_ADMISSION_DENIED`. The user-entered world value is only a selector that Game Session resolves server-side to the current catalog identity and verified `connectScopeId` before Account creates or restores membership. Raw world, realm, tenant, or scope text is never membership authority. `PLAY` alone performs gameplay admission and binding. Grant-backed private/playtest entry requires both the grant and existing membership with lifecycle state exactly `ACTIVE`, skips `JOIN`, and does not create membership. Account Service interprets the secret according to the account's enabled `PASSWORD` or verified-email `EMAIL_OTP` mode. Bare prompt-based login remains the target text-client experience, but its absence is an implementation gap rather than a different authentication contract. Only this credential-bearing text-client path may use the direct existing-member `LOGIN` plus `PLAY` compatibility exception; first-party/browser clients remain behind authenticated lobby gates. This text sequence is separate from the browser player-bootstrap/connect-token/WebSocket `LOGIN` sequence. +Telnet and other non-WebSocket text clients authenticate in-band through Account's canonical email login, `LOGIN ` (with the supported email-code challenge form where applicable). `LOGIN` establishes only the authenticated socket/account context; it does not select a tenant or character and does not create a gameplay binding. When membership is missing or `INACTIVE` on a selected public-production target, fresh Account entitlement must permit joining with `allowPublicJoin=true` and fresh selected-target catalog/pointer/public-production evidence must pass before returning `JOIN_REQUIRED` and allowing explicit `JOIN ` before `CHARS` and `PLAY`; an entitlement outage is `ENTITLEMENT_UNAVAILABLE`, while a closed joining policy or target denial is `PUBLIC_PRODUCTION_ADMISSION_DENIED`. An existing `ACTIVE` member skips `JOIN`; `allowPublicJoin=false` alone does not deny that member's `PLAY`, which remains subject to all independent fresh admission gates. The user-entered world value is only a selector that Game Session resolves server-side to the current catalog identity and verified `connectScopeId` before Account creates or restores membership. Raw world, realm, tenant, or scope text is never membership authority. `PLAY` alone performs gameplay admission and binding. Grant-backed private/playtest entry requires both the grant and existing membership with lifecycle state exactly `ACTIVE`, skips `JOIN`, and does not create membership. Account Service interprets the secret according to the account's enabled `PASSWORD` or verified-email `EMAIL_OTP` mode. Bare prompt-based login remains the target text-client experience, but its absence is an implementation gap rather than a different authentication contract. Only this credential-bearing text-client path may use the direct existing-member `LOGIN` plus `PLAY` compatibility exception; first-party/browser clients remain behind authenticated lobby gates. This text sequence is separate from the browser player-bootstrap/connect-token/WebSocket `LOGIN` sequence. Public non-browser WebSocket clients do not use this credential-bearing exception. Their scoped connect-token issuance and dedicated non-browser handshake header are target-only and unavailable until the route is fully registered and proven; the target flow uses protected secure storage and then bare `LOGIN` after Gateway has established the signed connect context. Direct Game Session WebSocket access remains an internal/test seam rather than a separate public authentication contract. @@ -96,7 +97,7 @@ This strengthens account takeover resistance but adds enrollment, recovery, supp - Ensure `PASSWORD` and `EMAIL_OTP` account modes both work through first-party bootstrap where configured. - Ensure every first-party browser/mobile-browser connect-token response carries the token only through the secure HttpOnly cookie, and first-party native-mobile clients using a cookie jar remain cookie-only. Target-only public non-browser issuance must first have a fully registered route and complete proof; only then may explicitly classified non-first-party/public native-mobile and other non-browser WebSocket clients receive the token through protected secure storage and present it through ADR 0029's dedicated handshake header. Raw Telnet and other non-WebSocket text clients use their separate in-band login flow. - Prove token expiry, replay, scope mismatch, missing signed context, account mismatch, and pre-`PLAY` gameplay commands fail closed with stable errors. -- Prove the selected public-production joining policy is evaluated before the membership predicate: fresh Account entitlement must say `allowPublicJoin=true`, fresh selected-target catalog/pointer evidence must identify the public-production target, an entitlement outage returns `ENTITLEMENT_UNAVAILABLE`, and a policy/target denial returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, never `JOIN_REQUIRED`. Prove `JOIN_REQUIRED` only when both authorities pass and membership is missing or `INACTIVE`; explicit `JOIN` is the only action that may create or restore public-production membership and resolves its selector to a verified `connectScopeId` before the Account write. Both missing creation and `INACTIVE` restoration advance `membershipVersion`, while `membershipAuthorityGeneration` advances only when the same committed snapshot records `callerBoundAuthorityInvalidated=true`. Prove the resulting exact Account snapshot, keep `ACTIVE` `JOIN` idempotent without an authority/version advance, and never admit a non-`ACTIVE` membership. Prove grant-backed private/playtest admission requires both its grant and existing membership with exact lifecycle state `ACTIVE` without creating membership. +- Prove the selected public-production join policy is evaluated before a join/repair outcome when membership is missing or `INACTIVE`: fresh Account entitlement and fresh selected-target catalog/pointer evidence must identify an eligible public-production target; an entitlement outage returns `ENTITLEMENT_UNAVAILABLE`, and a closed joining policy or target denial returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, never `JOIN_REQUIRED`. Prove `JOIN_REQUIRED` only when both authorities pass and membership is missing or `INACTIVE`; prove that `allowPublicJoin=false` alone does not deny connect-token issuance or `PLAY` for an existing `ACTIVE` member, while all other fresh entitlement and admission gates still apply. Explicit `JOIN` is the only action that may create or restore public-production membership and resolves its selector to a verified `connectScopeId` before the Account write. Both missing creation and `INACTIVE` restoration advance `membershipVersion`, while `membershipAuthorityGeneration` advances only when the same committed snapshot records `callerBoundAuthorityInvalidated=true`. Prove the resulting exact Account snapshot, keep `ACTIVE` `JOIN` idempotent without an authority/version advance, and never admit a non-`ACTIVE` membership. Prove grant-backed private/playtest admission requires both its grant and existing membership with exact lifecycle state `ACTIVE` without creating membership. - Prove `IssueConnectToken` locally validates the presented `player-bootstrap`, performs exactly one active issued-token registry lookup and exactly one `account-auth-evidence-bundle/v1` read, verifies the unchanged `routingBaseline={connectScopeId, tenantId, worldSlug, realmSlug, gameInstanceId, catalogRevision, pointerVersion, evaluatedAt, connectScopeExpiresAt}` against fresh selected-target catalog/pointer evidence, rejects mismatched or unavailable evidence, and persists the immutable `{routingBaseline, membershipLifecycleState=ACTIVE, membershipAuthorityGeneration, membershipVersion}` issuance baseline only with a successful `COMMITTED` token issuance. Prove deterministic failures including `PUBLIC_PRODUCTION_ADMISSION_DENIED`, `ENTITLEMENT_UNAVAILABLE`, and `JOIN_REQUIRED` persist terminal error evidence with no token or baseline; only the minted `gameplay-connect` artifact uses the no-registry replay exception. Prove `PLAY` compares current routing and membership snapshots to that committed baseline, and that the server-side Account admission and Game Session gameplay-binding CAS records carry the complete unchanged ADR 0030 lease `{authorityTuple, issuanceFence, outboxCheckpoints, membershipBaseline}` plus the unchanged routing baseline. Keep the binding provisional until Account commits that exact lease as `COMMITTED`, reject any change before commit, and never treat token-carried membership evidence as the final admission decision. - Prove browser and non-browser connect-token-backed WebSocket `LOGIN` never request credentials again and that Telnet credential login reaches the same authenticated pre-`PLAY` state. - Complete and prove the Telnet/non-WebSocket prompt-based login UX or continue reporting it as partial implementation. diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 911aea7dac..4fd432c78b 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -90,7 +90,7 @@ Account has unregistered individual Creator Party, hosted-terms catalog, and ind `CommitTenantCapacityAdmission` is target-only. Its canonical request contract requires the stable identity, expected complete applicable `authorityTuple`, separate expected `entitlementVersion`, exact expected billing stream/checkpoint evidence, capacity delta, and versioned `mutationDigest`, but no proto RPC, durable authority/usage ledger, caller integration, or reservation-finalization path is implemented. The target replay rule is exact identity-and-payload replay with any changed tuple, entitlement, checkpoint, delta, or digest producing an idempotency conflict; implementation and focused proof remain future capability work rather than a nonfunctional service seam. -The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` implementation is Account/profile-local, with identity projections governed by [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity). This is partial data, not the canonical target portable-data export lifecycle, which is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route and policy remain implementation drift pending direct convergence on tenant-qualified routes. The legacy profile selector and authorization consequences are recorded under [REST APIs](#rest-apis); membership-authority-generation validation remains unimplemented. Public registration follows the response identity contract below and writes that same public identity in its platform audit outbox row; it creates only global Account state and does not create a profile or tenant membership. Explicit public-production `JOIN` / `Join & Play` is implemented locally through `JoinPublicProductionMembership`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then evaluates current public-join entitlement. Only an authoritative `AVAILABLE` evaluation creates the versioned policy-bound operation digest and stores the exact `allowPublicJoin` and `entitlementVersion`; an unavailable attempt records its failure and availability and leaves the operation `PENDING` without invented policy evidence. A matching retry can re-evaluate that pending operation, and the membership commit gate revalidates the same digest and policy evidence. The operation, membership transition, and tenant audit outbox evidence are committed together. Focused local PostgreSQL retry/rollback proof is recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#account-email-verification-and-deferred-currency-containment); original-outcome observation after retry authority expires and direct-text end-to-end proof remain open. The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Current `/auth/connect-token` issuance returns `AUTH_UNAVAILABLE` after bootstrap and scope validation, before replay or admission-authority reads, token minting, or replay/session mutation; cached-success replay and current membership, entitlement, grant, and pointer checks do not execute on this path. For text `PLAY`, the consumer currently proceeds only when `membershipExists` and `gameplayAdmissionAllowed` are true; it does not enforce the emitted `membershipLifecycleState` or `membershipAuthorityGeneration`. For eligible public-production text `PLAY`, missing or existing non-admitting membership may currently produce `JOIN_REQUIRED`. This text consumer therefore does not distinguish `INACTIVE` from another existing non-admitting state even though Account emits the lifecycle field. Current non-public or non-visible target handling remains split across existing discovery, membership, and grant surfaces; the complete grant/entitlement admission predicate at connect-token issuance remains target-only. The obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware. The browser connect-token body and OpenAPI response are defined as metadata-only; any issued raw token is carried only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. The `player-bootstrap` credential/result profile uses the persisted Account UUID in its result `accountId` and matching JWT subject/Account claim; its Account-owned reader rejects noncanonical, numeric or mismatched identity before resolving the private storage row. The final ordinary receiving composition also carries UUID ordinary login results/credentials, UUID shared intake and forwarding, UUID internal selectors and UUID Account references in downstream consumers; tenant identifiers remain numeric. Full token-profile/registry qualification remains held. Derived `bootstrap-connect-scope` artifacts use the persisted Account UUID in their signed subject/Account claim, through the shared browser/direct-text producer and dedicated Account reader. Profile self-binding and REST caller identity use UUID `SessionContext`; private Account SQL rows remain numeric. The legacy GameInstance owner/StartSession boundary remains separately numeric and unqualified. The bounded response and REST selector identity contract is defined below. Scoped-role population and tenant-switching proof remain target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. +The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` implementation is Account/profile-local, with identity projections governed by [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity). This is partial data, not the canonical target portable-data export lifecycle, which is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route and policy remain implementation drift pending direct convergence on tenant-qualified routes. The legacy profile selector and authorization consequences are recorded under [REST APIs](#rest-apis); membership-authority-generation validation remains unimplemented. Public registration follows the response identity contract below and writes that same public identity in its platform audit outbox row; it creates only global Account state and does not create a profile or tenant membership. Explicit public-production `JOIN` / `Join & Play` is implemented locally through `JoinPublicProductionMembership`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then evaluates current public-join entitlement. Only an authoritative `AVAILABLE` evaluation creates the versioned policy-bound operation digest and stores the exact `allowPublicJoin` and `entitlementVersion`; an unavailable attempt records its failure and availability and leaves the operation `PENDING` without invented policy evidence. A matching retry can re-evaluate that pending operation, and the membership commit gate revalidates the same digest and policy evidence. The operation, membership transition, and tenant audit outbox evidence are committed together. Focused local PostgreSQL retry/rollback proof is recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#account-email-verification-and-deferred-currency-containment); original-outcome observation after retry authority expires and direct-text end-to-end proof remain open. The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Current `/auth/connect-token` issuance returns `AUTH_UNAVAILABLE` after bootstrap and scope validation, before replay or admission-authority reads, token minting, or replay/session mutation; cached-success replay and current membership, entitlement, grant, and pointer checks do not execute on this path. Current text `PLAY` validates the emitted `membershipLifecycleState` and independent `membershipAuthorityGeneration` and requires coherent `ACTIVE` admitting membership. Missing or `INACTIVE` public-production membership yields `JOIN_REQUIRED` only when fresh enrollment policy permits repair; an existing active but non-admitting response is not a join fallback. The implemented consumer limits remain in [Account runtime status](./runtime-and-data.md#implementation-status); these checks do not establish the complete caller-target and atomic-freshness contract. Current non-public or non-visible target handling remains split across existing discovery, membership, and grant surfaces; the complete grant/entitlement admission predicate at connect-token issuance remains target-only. The obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware. The browser connect-token body and OpenAPI response are defined as metadata-only; any issued raw token is carried only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. The `player-bootstrap` credential/result profile uses the persisted Account UUID in its result `accountId` and matching JWT subject/Account claim; its Account-owned reader rejects noncanonical, numeric or mismatched identity before resolving the private storage row. The final ordinary receiving composition also carries UUID ordinary login results/credentials, UUID shared intake and forwarding, UUID internal selectors and UUID Account references in downstream consumers; tenant identifiers remain numeric. Full token-profile/registry qualification remains held. Derived `bootstrap-connect-scope` artifacts use the persisted Account UUID in their signed subject/Account claim, through the shared browser/direct-text producer and dedicated Account reader. Profile self-binding and REST caller identity use UUID `SessionContext`; private Account SQL rows remain numeric. The legacy GameInstance owner/StartSession boundary remains separately numeric and unqualified. The bounded response and REST selector identity contract is defined below. Scoped-role population and tenant-switching proof remain target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. ### Account UUID Response and REST Selector Identity @@ -309,7 +309,7 @@ Implemented Account-valued REST selectors and response fields use canonical Acco | `PUT` | `/tenants/{tenantId}/profiles/{accountId}` | **Canonical target, `tenant_regular`.** `accountId` is the canonical lowercase non-nil Account UUID. Account live membership authority supplies current membership lifecycle, `membershipAuthorityGeneration`, and independent `membershipVersion`; caller subject and scoped role checks apply. The legacy `/profiles/{accountId}` route remains implementation drift and has no `platformAdmin` override. | | `GET` | `/tenants/{tenantId}/memberships/me` | Authoritative caller-bound membership and roles for billing-safe mutation guards | | `GET` | `/tenants/{tenantId}/memberships/{accountId}` | Cross-tenant membership lookup for billing/reporting roles (`billingAdmin`/`platformAdmin`) | -| `POST` | `/auth/connect-token` | **Target behavior, not current compatibility behavior:** issue a short-lived gameplay connect token for one discovery-selected realm target using caller-bound player-bootstrap identity after one fresh atomic caller-bound runtime membership snapshot, including lifecycle state, independent membership version, and membership authority generation, plus the applicable grant, entitlement, and admission-pointer validation. The complete first-party sequence and private/playtest grant-and-entitlement predicate are owned by [ADR 0021](../../decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md#first-party-browser-flow); this local row records only the Account issuance consequence. Account must reread that exact membership on every issuance, including the first issuance after explicit join, at the issuance commit gate and compare both the independent membership version and opaque authority generation before issuing; stale or cached bootstrap/discovery membership evidence cannot substitute. For a selected public-production target, `PUBLIC_PRODUCTION_ADMISSION_DENIED` takes precedence when the current joining policy disallows joining; `JOIN_REQUIRED` is returned only when that policy permits joining but fresh membership is missing or `INACTIVE`. An exact duplicate whose compact receipt remains after response-envelope recovery expiry returns typed `RESPONSE_RECOVERY_EXPIRED` and requires a fresh authorized request with a new `requestId`; a changed digest remains `IDEMPOTENCY_CONFLICT`. **Current implementation:** after bootstrap and connect-scope authentication, the endpoint returns `AUTH_UNAVAILABLE` before cached-success replay, membership/entitlement/target reads, minting, or replay/session mutation while the canonical producer is unavailable. `ConnectTokenResponse` retains a dormant `jti` field; no current successful response or cookie delivery is reachable. **Target delivery:** HTTP response delivery uses only the protected `Set-Cookie` field: the response body and custom response headers never expose the raw token or provide a header fallback. First-party browser/mobile-browser clients and first-party native-mobile or other first-party non-browser clients using a cookie jar remain cookie-only. A separately registered and proven route for explicitly classified public/non-first-party native-mobile and other non-browser clients may later return the token once for protected secure storage and permit only the dedicated handshake header; that route and header are target-only/unavailable now and are not a browser endpoint or a cookie fallback. | +| `POST` | `/auth/connect-token` | **Target behavior, not current compatibility behavior:** issue a short-lived gameplay connect token for one discovery-selected realm target using caller-bound player-bootstrap identity after one fresh atomic caller-bound runtime membership snapshot, including lifecycle state, independent membership version, and membership authority generation, plus the applicable grant, entitlement, and admission-pointer validation. The complete first-party sequence and private/playtest grant-and-entitlement predicate are owned by [ADR 0021](../../decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md#first-party-browser-flow); this local row records only the Account issuance consequence. Account must reread that exact membership on every issuance, including the first issuance after explicit join, at the issuance commit gate and compare both the independent membership version and opaque authority generation before issuing; stale or cached bootstrap/discovery membership evidence cannot substitute. For a selected public-production target, `allowPublicJoin` gates the required join/repair only when membership is missing or `INACTIVE`: a closed joining policy returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, and `JOIN_REQUIRED` is returned only when that policy permits joining and fresh target evidence passes. An existing `ACTIVE` member is not denied issuance solely because `allowPublicJoin=false`; fresh gameplay entitlement and every other applicable membership, routing, grant, and binding check still apply. An exact duplicate whose compact receipt remains after response-envelope recovery expiry returns typed `RESPONSE_RECOVERY_EXPIRED` and requires a fresh authorized request with a new `requestId`; a changed digest remains `IDEMPOTENCY_CONFLICT`. **Current implementation:** after bootstrap and connect-scope authentication, the endpoint returns `AUTH_UNAVAILABLE` before cached-success replay, membership/entitlement/target reads, minting, or replay/session mutation while the canonical producer is unavailable. `ConnectTokenResponse` retains a dormant `jti` field; no current successful response or cookie delivery is reachable. **Target delivery:** HTTP response delivery uses only the protected `Set-Cookie` field: the response body and custom response headers never expose the raw token or provide a header fallback. First-party browser/mobile-browser clients and first-party native-mobile or other first-party non-browser clients using a cookie jar remain cookie-only. A separately registered and proven route for explicitly classified public/non-first-party native-mobile and other non-browser clients may later return the token once for protected secure storage and permit only the dedicated handshake header; that route and header are target-only/unavailable now and are not a browser endpoint or a cookie fallback. | | `POST` | `/auth/bootstrap/join` | **Local Account controller and operation; complete production proof incomplete.** The local `JoinPublicProductionMembership` operation implements explicit caller-bound JOIN using the exact `connectScopeId` and `requestId`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then reads entitlement authority. Only an `AVAILABLE` authoritative result produces the versioned policy-bound request digest and stored `allowPublicJoin` / `entitlementVersion` evidence. An unavailable authority attempt records its failure and availability while keeping the operation `PENDING`, without a fabricated policy result, entitlement version, or final request digest; a matching retry can re-evaluate it. For a retained `PENDING` operation, an expired scope fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. Account revalidates the exact policy digest at the membership commit gate. The request accepts no caller-selected `playableStateScope`, storage key, or independently supplied runtime target. A changed scope, intent, or available policy returns the applicable deterministic error, including `CONNECT_SCOPE_MISMATCH` or `IDEMPOTENCY_CONFLICT`, without silently retargeting the join; an `ACTIVE` retry remains event-free. The Account route exists locally, but its exact public Gateway path is currently denied by the explicit route guard; this is an exposure restriction, not target-only controller status. Exact-final-head PostgreSQL proof and membership-generation snapshot proof remain open. Game Session text JOIN dispatch remains with #2898; recovery/reconciliation after an unknown commit outcome and Logging receipt receiver/readback remain #2848. Direct text-client proof remains open; the canonical JOIN contract remains with [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). | | `DELETE` | `/tenants/{tenantId}/memberships/me` | Leave a joined game using caller-bound membership authority; removes future membership-based discovery/admission while retained character, purchase, audit, and legal data follow their owning policies | | `GET` | `/internal/runtime/tenants/{tenantId}/entitlements` | Internal runtime/admission entitlement snapshot for gameplay-affecting services | diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index f43526c618..65a383ab8e 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -70,7 +70,7 @@ The current public registration path creates only a global Account row and a pla Account has source-only persistence for individual Creator Party identity, hosted-terms acceptance/environment-binding evidence, and (from V98) disclosure handoffs with immutable captured source evidence. The V98 database guards constrain handoff identity, result transitions, and source-evidence insertion. A passive Account source-fence seam now excludes unsettled World participation from applicable source mutation/abort settlement and hosted-terms disclosure preparation/dispatch admission; `HostedTermsDisclosureHandoff` and its repository use the existing V98 journal. The unregistered historical World-participation reader resolves retained participation coordinates from the complete unchanged original tuple, verifies the retained capture and source-child vector, and can read after lease expiry or immutable terminal settlement; it uses existing rows and introduces no migration or table. It does not establish currentness, renew or admit authorization, or classify an Account expiry or failed response as World `ABORTED`; only the World owner can produce that terminal outcome with its original commit/fence evidence. The handoff retains opaque authority evidence as supplied and does not authenticate it. No verifier, dispatcher, transport, registry/runtime binding, creator UI, or Game Design evidence binding is registered. Reserve, claim, and publication paths that require the hosted-terms workflow remain unavailable. The acceptance/currentness authority remains target-only under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md), with changed-terms continuity under [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md); local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner workflow is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled. -The live `GetTenantMembershipForRuntime` producer emits `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`; `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent from the proto and producer. Current consumers still rely on only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and do not enforce the complete atomic-freshness contract or consume the emitted lifecycle/generation fields. Account-first bootstrap and credential-bearing gameplay `Authenticate` authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Character discovery requires membership after applicable target and entitlement checks; on an eligible public-production target missing or `INACTIVE` membership returns non-actionable `JOIN_REQUIRED` when `allowPublicJoin` permits entry and `PUBLIC_PRODUCTION_ADMISSION_DENIED` otherwise, while other present non-admitting membership is denied as `CONNECT_TOKEN_REJECTED`. Current `POST /auth/connect-token` validates bootstrap identity and the retained connect scope, then returns `AUTH_UNAVAILABLE` before membership, entitlement, admission-pointer, cached-result, or token-issuance work; it does not currently return an issuance `JOIN_REQUIRED` or `CONNECT_TOKEN_REJECTED` result. Current text `PLAY` can still return non-actionable `JOIN_REQUIRED` for missing or present non-admitting membership before fresh entitlement and public-target-policy ordering is established; this remains the AA-2.1 / Unit 1B ordering gap. These flows do not create or restore membership. The Account-owned public-production `JOIN` writer is implemented locally with a v1 policy-bound digest and atomic membership, operation-outcome, and audit-outbox evidence. Its HTTP exposure remains blocked by the Gateway route guard; Game Session text `JOIN`/`Join & Play` dispatch remains with #2898, while durable recovery after an unknown database commit and Logging receipt receiver/readback remain with #2848. Exact-final-head PostgreSQL runtime proof remains unavailable locally without Docker; no live PostgreSQL runtime proof or direct text-client end-to-end proof is claimed. See [Account API Contracts](./api-contracts.md) for the public and internal API boundary and [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the canonical direct-text scope and JOIN contract. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The entitlement producer returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field) when a tenant has zero or multiple subscription rows; only one explicit row is projected through current status mapping. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and canonical snapshot fields/freshness remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof covers only that cardinality guard and retry boundary. `CommitTenantCapacityAdmission` has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. +The live `GetTenantMembershipForRuntime` producer emits `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`; `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent from the proto and producer. Current text `PLAY` consumes the emitted lifecycle and independent authority generation alongside version and admission evidence; this does not establish the complete atomic-freshness contract. Account-first bootstrap and credential-bearing gameplay `Authenticate` authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Character discovery requires membership after applicable target and entitlement checks; on an eligible public-production target missing or `INACTIVE` membership returns non-actionable `JOIN_REQUIRED` when `allowPublicJoin` permits entry and `PUBLIC_PRODUCTION_ADMISSION_DENIED` otherwise, while other present non-admitting membership is denied as `CONNECT_TOKEN_REJECTED`. Current `POST /auth/connect-token` validates bootstrap identity and the retained connect scope, then returns `AUTH_UNAVAILABLE` before membership, entitlement, admission-pointer, cached-result, or token-issuance work; it does not currently return an issuance `JOIN_REQUIRED` or `CONNECT_TOKEN_REJECTED` result. Current text `PLAY` evaluates fresh entitlement before membership/grant and later actor/binding checks; public `JOIN_REQUIRED` is limited to coherent missing or `INACTIVE` membership when enrollment permits repair. An active but non-admitting response is not a join fallback. Complete caller-target/atomic authority and the remaining AA-2.1 / Unit 1B boundaries remain open. These flows do not create or restore membership. The Account-owned public-production `JOIN` writer is implemented locally with a v1 policy-bound digest and atomic membership, operation-outcome, and audit-outbox evidence. Its HTTP exposure remains blocked by the Gateway route guard; Game Session text `JOIN`/`Join & Play` dispatch remains with #2898, while durable recovery after an unknown database commit and Logging receipt receiver/readback remain with #2848. Focused PostgreSQL/component proof and its limits are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#validation-and-proof); those controlled fixtures do not establish genuine deployed receiving custody or complete public admission. See [Account API Contracts](./api-contracts.md) for the public and internal API boundary and [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the canonical direct-text scope and JOIN contract. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The entitlement producer returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field) when a tenant has zero or multiple subscription rows; only one explicit row is projected through current status mapping. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and canonical snapshot fields/freshness remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof covers only that cardinality guard and retry boundary. `CommitTenantCapacityAdmission` has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. The current `application.yml` and `application-prod.yml` retain `GetTenantMembershipForRuntime`, `GetRealmAccessGrantForRuntime`, `GetTenantEntitlementsForRuntime`, and `ListPresenceVisibilityPolicies` in the gRPC bearer-validation bypass list. Their handlers independently require certificate-derived workload identity in the exact configured namespace: Game Session for membership and realm-grant reads, Game Session or World Management for entitlement reads, and Social & Groups for presence-policy reads. Handler and configured-interceptor tests cover permitted peers without bearer credentials and refusal of unauthorized or wrong-namespace peers. This workload-only bypass does not make the methods unauthenticated public APIs. Complete typed caller-context and tenant-binding qualification, membership/currentness consumption, and the remaining canonical admission and registry contracts remain separate gaps under the [Account API contract](./api-contracts.md); these workload checks alone do not establish readiness. @@ -193,7 +193,7 @@ The `player-bootstrap` token profile is distinct from both `control-ui` and priv - Audience is `player-bootstrap`. - It is issued only by `POST /auth/player-bootstrap` / `IssuePlayerBootstrapToken`. - `POST /auth/player-bootstrap` is the canonical first-party browser/mobile player-login endpoint. It authenticates player credentials directly under the same password, OTP, brute-force defense, and account-lock policy used for gameplay login rather than deriving bootstrap from a pre-existing admin/creator session. -- 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 runtime uses only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; world and realm discovery remain available before membership. On an eligible public-production target, character discovery returns non-actionable `JOIN_REQUIRED` for missing or `INACTIVE` membership when `allowPublicJoin` permits entry and `PUBLIC_PRODUCTION_ADMISSION_DENIED` otherwise; other present non-admitting membership is denied as `CONNECT_TOKEN_REJECTED`. Current connect-token issuance validates bootstrap identity and scope, then returns `AUTH_UNAVAILABLE` before membership, entitlement, target-authority, or cached-result processing. Text `PLAY` may still return non-actionable `JOIN_REQUIRED` for either absent or present non-admitting membership on an eligible public-production target before fresh entitlement and public-target-policy ordering is established; this remains the AA-2.1 / Unit 1B ordering gap. None of these paths creates or restores membership. The Account-owned public-production `JOIN` writer is implemented locally; first-party text `JOIN`/`Join & Play` dispatch and durable recovery after an unknown database commit outcome remain open. Non-public or non-visible targets remain subject to their realm-access and grant checks rather than using public onboarding semantics. +- 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. World and realm discovery remain available before membership. On an eligible public-production target, character discovery returns non-actionable `JOIN_REQUIRED` for missing or `INACTIVE` membership when `allowPublicJoin` permits entry and `PUBLIC_PRODUCTION_ADMISSION_DENIED` otherwise; other present non-admitting membership is denied as `CONNECT_TOKEN_REJECTED`. Current text `PLAY` consumes the emitted membership lifecycle and independent authority generation alongside existence, admission, version, and evaluation-time evidence; it checks fresh entitlement before membership/grant and later actor/binding checks. Its implemented checks follow the [canonical PLAY outcome matrix](../../system-architecture-authentication.md#play-current-and-target-failure-boundaries). This implemented field validation is not the complete atomic freshness contract. Current connect-token issuance validates bootstrap identity and scope, then returns `AUTH_UNAVAILABLE` before membership, entitlement, target-authority, or cached-result processing. None of these paths creates or restores membership. The Account-owned public-production `JOIN` writer is implemented locally; first-party text `JOIN`/`Join & Play` dispatch and durable recovery after an unknown database commit outcome remain open. 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. - 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. @@ -230,7 +230,7 @@ Runtime caller contract: - Minimum request fields: `accountId`, `tenantId`, `requestId`. - Target minimum response fields: `accountId`, `tenantId`, `membershipExists`, `membershipLifecycleState`, `authorityAvailability`, `roles[]`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, `authorityTuple`, `evaluatedAt`, and the applicable `outboxCheckpoints[]` entry for the membership authority stream. - `membershipAuthorityGeneration` is an opaque Account-owned value. Runtime callers compare it only for exact freshness/equality and must not infer ordering or authority from its representation. It is the authoritative generation for connect-token issuance, gameplay-token refresh, gameplay binding and reconnect validation, and membership revocation. -- `GetTenantMembershipForRuntime` requires `authorityAvailability=AVAILABLE` before its snapshot can authorize admission; `UNAVAILABLE` is an authority failure, not missing or `INACTIVE` membership and cannot produce `JOIN_REQUIRED`. The generated proto and Account producer emit `membershipLifecycleState` and the opaque generation, but current runtime callers do not enforce either field. `authorityAvailability`, roles, the complete tuple, and checkpoints remain absent; a fresh atomic target snapshot and fail-closed consumer proof remain implementation drift. +- `GetTenantMembershipForRuntime` requires `authorityAvailability=AVAILABLE` before its snapshot can authorize admission; `UNAVAILABLE` is an authority failure, not missing or `INACTIVE` membership and cannot produce `JOIN_REQUIRED`. The generated proto and Account producer emit `membershipLifecycleState` and the opaque generation, and current text `PLAY` validates those fields alongside membership existence, admission, and version evidence; its entitlement-first ordering, private-grant validation, and outcomes are summarized by the canonical [PLAY outcome matrix](../../system-architecture-authentication.md#play-current-and-target-failure-boundaries). `authorityAvailability`, roles, the complete tuple, and checkpoints remain absent; the complete fresh atomic target snapshot and fail-closed consumer proof remain implementation gaps. - `GetTenantEntitlementsForRuntime(tenantId, requestId)` is the authoritative internal entitlement surface for gameplay/runtime flows. Runtime callers may cache its positive result only under the strict-new-commitment and bounded-continuity rules in [ADR 0028](../../decisions/adr-0028-differentiated-entitlement-freshness.md); the cache never becomes a second writer. - Minimum request fields: `tenantId`, `requestId`. - For target player-admission calls only, the minimum request additionally carries `callerAccountId`, `verifiedConnectScopeId`, and the exact resolved target bundle. Game Session supplies these fields as trusted typed execution/request context; the private `game-session-account-delegation` JWT carries its declared Account authority but does not carry `verifiedConnectScopeId` or the complete runtime target bundle. Account requires `callerAccountId` to equal the authenticated delegation JWT's `accountId`/`sub` and the exact bound Game Session subject, then verifies the scope and target fields against the signed connect scope and current exact target before returning the already-declared caller/target-bound evidence. World Management's tenant/operation-bound lifecycle calls retain their separate operation context and do not fabricate player-binding fields. @@ -246,7 +246,7 @@ Runtime caller contract: - For actor discovery and creation, the exact catalog/pointer snapshot uses the existing canonical `stateScope` to `playableStateScope` resolver owned by [Multi-Tenancy](../../system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract). Account's REST bootstrap producer and Game Session's direct-text `CHARS`/creation producer apply that same server-derived projection at the actor-query boundary and delegate persistence to Entity Management; it is not a storage-key selector or a value inferred from `gameInstanceId`. Account creation/bootstrap never provisions a default actor. After explicit realm entry, Entity applies the realm's published versioned, generic entry policy and descriptor/template; missing or mismatched cross-path proof is implementation drift. Actor-query input remains defined by the [Entity Management API contract](../entity-management-service/api-contracts.md#grpc). - `IssueConnectToken` / `POST /auth/connect-token` is the target gameplay bootstrap token-issuance surface. - Target issuance requires the current caller-bound `membershipAuthorityGeneration` and exactly one selected-tenant `authorityTuple.tenantAuthorityGeneration` entry from the fresh Account entitlement authority, in addition to the live membership, entitlement, and admission-pointer checks; discovery output and a stale bootstrap decision are not sufficient authority. The `runtimeEntitlementAuthorityReference` carries that selected tenant generation, its snapshot/version and freshness evidence, and the Account commit fence; issuance conditionally commits only while that authority tuple remains unchanged. The membership generation must be revalidated by gameplay-token refresh, gameplay binding/reconnect validation, and membership-revocation handling. The successful Account issuance evidence boundary carries the unchanged routing baseline `{connectScopeId, tenantId, worldSlug, realmSlug, playableStateNamespaceId, playableStateScope, gameInstanceId, catalogRevision, pointerVersion, evaluatedAt, connectScopeExpiresAt}`, plus exact `playtestLifecycleId` and positive `playtestStateGeneration` for every non-public target and neither field for a non-grant public-production target, together with the exact selected-route entitlement and admission-pointer authority references alongside the Account evidence-bundle reference; each reference identifies its owning snapshot/version/fence and resolved target. - - For a selected target confirmed as public production, fresh Account entitlement (`allowPublicJoin`) and fresh selected-target catalog/pointer/public-production evidence are separate required gates. `PUBLIC_PRODUCTION_ADMISSION_DENIED` applies only when that selected public-production joining policy denies entry. Missing, malformed, stale, or ambiguous routing remains `ADMISSION_POINTER_UNAVAILABLE`; a deliberate `CLOSED` realm remains `REALM_UNAVAILABLE`; and failure to establish fresh entitlement authority remains `ENTITLEMENT_UNAVAILABLE`. A non-public target uses its applicable grant/access outcome rather than public-production denial. `JOIN_REQUIRED` is returned only when both gates pass but the fresh membership snapshot is missing or `INACTIVE`. + - For a selected target confirmed as public production, fresh Account entitlement and fresh selected-target catalog/pointer/public-production evidence remain separate admission gates. `allowPublicJoin` is the enrollment predicate only: when membership is missing or `INACTIVE`, `false` returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, while `JOIN_REQUIRED` is available only when fresh entitlement permits joining and the target evidence passes. An existing `ACTIVE` member is not denied connect-token issuance or `PLAY` solely because `allowPublicJoin=false`; the member must still pass all other fresh entitlement and admission checks, including `gameplayAvailable`. The target `allowNewGameplayBindings` field and enforcement are not currently available. Missing, malformed, stale, or ambiguous routing remains `ADMISSION_POINTER_UNAVAILABLE`; a deliberate `CLOSED` realm remains `REALM_UNAVAILABLE`; failure to establish fresh entitlement authority remains `ENTITLEMENT_UNAVAILABLE`. A non-public target uses its applicable grant/access outcome rather than public-production denial. - Target issuance also requires the shared replay-readiness record to be `OPEN` and binds its exact `replayAdmissionFence` into the signed token. Missing, unreadable, quarantined, or changing readiness fails closed before the token is exposed. - Minimum request fields: `connectScopeId`, `requestId`. - Target response fields for all clients are non-secret metadata only: `expiresAt`, `accountId`, `tenantId`, `realmSlug`, `playtestLifecycleId` and positive `playtestStateGeneration` when the selected target is non-public, `gameInstanceId`, and `issuedAt`; both playtest fields are absent for a non-grant public-production target. The token `jti` remains only in the dedicated issuance/replay record and access-controlled security audit evidence; it is not returned to clients. **Dormant DTO/source-shape drift:** `ConnectTokenResponse` declares `jti`, and `ConnectTokenResult`/`AccountServiceImpl` do not carry `playtestLifecycleId` or `playtestStateGeneration` required for target non-public response metadata. Current `/auth/connect-token` returns `AUTH_UNAVAILABLE` before constructing this response, so these fields are not a live HTTP response or token disclosure. @@ -326,7 +326,7 @@ Current `AccountRealmAccessGrant` persistence and internal grant reads are limit - Account's owner-local JOIN v2 model adds a closed canonical scope, stable intent digest, and policy-bound request digest to the existing persistence foundation. It does not change the current JoinPublicProductionMembership RPC or confer target authority by digest alone. Account login/public JOIN wiring, Game Session text JOIN dispatch (#2898), unknown-outcome recovery (#2848), PostgreSQL execution, and direct text-client proof remain outstanding. -- Account-first bootstrap now authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current Account connect-token issuance validates bootstrap identity and connect-scope binding, then returns `AUTH_UNAVAILABLE` before membership, entitlement, admission-pointer, cached-success, or token-minting work. Character discovery checks local membership existence/admission after fresh entitlement and target checks. On an eligible public-production target, missing or `INACTIVE` membership returns `JOIN_REQUIRED` when `allowPublicJoin` permits entry and `PUBLIC_PRODUCTION_ADMISSION_DENIED` otherwise; other present non-admitting membership is denied as `CONNECT_TOKEN_REJECTED`. Current text `PLAY` may still return non-actionable `JOIN_REQUIRED` for a missing or present non-admitting membership on an eligible public-production target before the fresh entitlement and public-target-policy ordering is established; this remains the AA-2.1 / Unit 1B ordering gap. The Account-owned explicit public-production JOIN writer and operation controller, including the local `POST /auth/bootstrap/join` REST route, exist locally; its public Gateway exposure remains blocked by the explicit route guard pending production proof. Game Session text `JOIN`/`Join & Play` dispatch remains with #2898; recovery after unknown JOIN commit outcomes and Logging receipt receiver/readback remain #2848. PostgreSQL exact-final-head proof and direct text-client end-to-end proof remain incomplete. The membership-authority-generation reread remains unenforced and is a prerequisite for any future connect-token producer. The current non-public character-discovery mapping returns `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay; connect-token issuance instead returns `AUTH_UNAVAILABLE` before membership processing. Text `PLAY` maps either membership case to `WORLD_ACCESS_DENIED`. This split is current behavior, not the target canonical outcome; target private/playtest admission uses `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing or non-`ACTIVE` membership and keeps grant denial separate. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling are also incomplete. +- Account-first bootstrap now authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current Account connect-token issuance validates bootstrap identity and connect-scope binding, then returns `AUTH_UNAVAILABLE` before membership, entitlement, admission-pointer, cached-success, or token-minting work. Character discovery checks local membership existence/admission after fresh entitlement and target checks. On an eligible public-production target, missing or `INACTIVE` membership returns `JOIN_REQUIRED` when `allowPublicJoin` permits entry and `PUBLIC_PRODUCTION_ADMISSION_DENIED` otherwise; other present non-admitting membership is denied as `CONNECT_TOKEN_REJECTED`. Current text `PLAY` implements lifecycle/generation validation and entitlement-first ordering under the [canonical PLAY outcome matrix](../../system-architecture-authentication.md#play-current-and-target-failure-boundaries); complete caller-target and atomic authority proof remains open. The Account-owned explicit public-production JOIN writer and operation controller, including the local `POST /auth/bootstrap/join` REST route, exist locally; its public Gateway exposure remains blocked by the explicit route guard pending production proof. Game Session text `JOIN`/`Join & Play` dispatch remains with #2898; recovery after unknown JOIN commit outcomes and Logging receipt receiver/readback remain #2848. PostgreSQL exact-final-head proof and direct text-client end-to-end proof remain incomplete. The target connect-token membership-authority-generation reread remains unenforced and is a prerequisite for any future connect-token producer. The current non-public character-discovery mapping returns `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay; connect-token issuance instead returns `AUTH_UNAVAILABLE` before membership processing. Text `PLAY` implements the private membership and grant checks covered by the canonical outcome matrix linked above; complete caller-target, grant-lifecycle/expiry, and atomic freshness proof remains open. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling are also incomplete. The current JOIN implementation re-reads Game Session routing/catalog/pointer evidence but does not ensure that the exact target remains valid through the Account commit. The strict ADR 0025 commit gate is incomplete; detailed implementation and proof status is tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#capability-status). diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index c37e3d1f4a..5d36f6efcf 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -202,7 +202,7 @@ The internal front-end to lease-owner path is a **target-state** fenced gameplay - Admission-pointer requests identify the durable `{tenantId, realmId}` route after selector resolution; read/audit responses carry `worldSlug`/`realmSlug` from the referenced catalog snapshot, the runtime route version separately from catalog/policy revision, and, for private/playtest targets, the positive `playtestStateGeneration`. Public-production admission and first-join membership creation consume current catalog visibility/public-production facts with entitlement checks instead of inferring behavior from `realmSlug`; display-only changes do not become runtime cutovers. - Admission-pointer audit/list responses now also expose the `preparedVersionUpgradeId` used by a cutover write so operator history preserves the same proof identity that the mutation validated; private/playtest audit/readback retains the applicable lifecycle ID and generation, while public-production responses omit them. -**Target state:** Gameplay admission uses `JOIN_REQUIRED` only as a next-step response when fresh authority confirms that the selected target is publicly visible and public-production joining is allowed, while the caller's membership is absent or `INACTIVE` under [Account's explicit membership lifecycle](../../decisions/adr-0025-explicit-open-enrollment-membership.md#decision). A public-production policy denial remains `PUBLIC_PRODUCTION_ADMISSION_DENIED`; unavailable, stale, malformed, or ambiguous authority uses the applicable unavailable or invalid-authority outcome instead. Private/playtest admission always requires an existing caller-bound membership, the current membership authority generation, and the applicable Account-owned realm grant; a grant never replaces membership. **Current implementation:** text `PLAY` also returns `JOIN_REQUIRED` when a membership exists but `gameplayAdmissionAllowed=false`. It enforces the current non-public realm grant, while current connect-token issuance does not validate that grant; target connect-token issuance adds the same fresh grant gate. +**Target state:** Gameplay admission uses `JOIN_REQUIRED` only as a next-step response when fresh authority confirms that the selected target is publicly visible and public-production joining is allowed, while the caller's membership is absent or `INACTIVE` under [Account's explicit membership lifecycle](../../decisions/adr-0025-explicit-open-enrollment-membership.md#decision). A public-production policy denial returns `PUBLIC_PRODUCTION_ADMISSION_DENIED` for the required join/repair; an existing `ACTIVE` member is not denied solely because `allowPublicJoin=false`, but remains subject to every other current admission gate. Unavailable, stale, malformed, or ambiguous authority uses the applicable unavailable or invalid-authority outcome instead. Private/playtest admission always requires an existing caller-bound membership, the current membership authority generation, and the applicable Account-owned realm grant; a grant never replaces membership. **Current implementation:** text `PLAY` consumes Account-emitted lifecycle/generation and evaluates fresh entitlement before membership/grant and later actor/binding checks. Eligible missing or `INACTIVE` public membership yields non-actionable `JOIN_REQUIRED` only when joining policy permits repair; private missing/non-`ACTIVE` membership yields `NON_PUBLIC_ENROLLMENT_REQUIRED`, and denied grant yields `REALM_ACCESS_DENIED`. Current connect-token issuance returns `AUTH_UNAVAILABLE` before cached replay or membership, entitlement, grant, and routing-authority reads, so it does not currently validate those authorities. Full caller-target/atomic authority, `allowNewGameplayBindings`, grant lifecycle/expiry, lease commit, and genuine custody/registration remain absent or held. - **Admission-pointer CAS inputs:** existing-row writes compare the exact `expectedPointerVersion` and `expectedCatalogRevision` pair. The current owner-local no-record insert requires `0/0` as its expected-absent precondition; because no row exists to version-check, insert-race safety comes from runtime-target locking and database uniqueness constraints, not a row-version CAS. Neither condition is proof of realm/catalog initialization or permission to create a pointer. The `SetAdmissionPointer` and `ExecutePreparedVersionCutover` control-plane RPCs remain fail-closed until their complete owner contracts are supported. Initial admission still requires the separate World lifecycle, canonical realm/catalog identity, pointer/audit transaction, and exact owner-readback proof described in [Initial admission bind](#initial-admission-bind). diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index 9d6c77f79f..bf23f0b46f 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -12,7 +12,7 @@ For bootstrap-backed direct-text `LOGIN` and first-party `/ws/game/**`, the [Gat ## Implementation Status -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 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. `JOIN` and first-party `Join & Play` are not yet implemented as explicit commands/actions. Current text `PLAY` may return non-actionable `JOIN_REQUIRED` for an eligible public-production target when `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter cannot be classified specifically as `INACTIVE`, and explicit `JOIN` remains unavailable, without creating or restoring membership; current text `PLAY` enforces the applicable non-public realm grant, while current connect-token issuance fails closed with `AUTH_UNAVAILABLE` before replay or admission-authority reads. Current consumers decide from `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt` plus the text `PLAY` grant check; Account already emits `membershipLifecycleState` and `membershipAuthorityGeneration`, but this consumer does not enforce them and therefore does not classify `ACTIVE` or `INACTIVE`. Current non-public membership/admission denial remains `WORLD_ACCESS_DENIED`; target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` is defined separately. The missing membership-authority-generation reread and target non-public grant check at connect-token issuance remain gaps. +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 eligible missing or `INACTIVE` public-production membership, while an existing `ACTIVE` member may play without repair and a grant-backed non-public path requires existing `ACTIVE` membership plus its grant. A grant never creates or substitutes for membership. Explicit text `JOIN` and first-party `Join & Play` remain unavailable. Current text `PLAY` consumes Account-emitted lifecycle and authority generation, evaluates fresh entitlement before membership/grant and later actor/binding checks, and admits only coherent `ACTIVE` and admitting membership. Eligible missing or `INACTIVE` public-production membership may return non-actionable `JOIN_REQUIRED` only when joining policy permits repair; a closed policy denies repair but does not by itself deny an existing `ACTIVE` member. Current private outcomes are `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing or known non-`ACTIVE` membership and `REALM_ACCESS_DENIED` for denied grants; unsafe or unavailable authority is `AUTH_UNAVAILABLE`. Current connect-token issuance fails closed with `AUTH_UNAVAILABLE` before cached replay or membership, entitlement, grant, and routing-authority reads. Full caller-target/atomic authority, `allowNewGameplayBindings`, grant lifecycle/expiry, lease commit, and genuine custody/registration remain absent or held; see [Authentication](../../system-architecture-authentication.md#implementation-status), [Account Runtime and Data](../account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention), and [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#capability-status). Current catalog receiving remains partial. Current direct-text world/realm presentation advertises stable slugs only, and text, typed catalog and admission APIs resolve exact canonical slugs, including numeric-only slugs. They do not advertise or interpret unsupported world/realm menu positions. The local direct-text UUID selection store is a separate, unregistered component and does not yet provide the complete target snapshot-bound selector flow or protected receiving custody. Current public/caller-free realm snapshots expose only public-production realms; authenticated private-realm discovery and retained scope are not available. See [Realm Routing and Playable State](../../../project-management/implementation-tracking/realm-routing-and-playable-state.md#capability-status) and [Game Session Runtime and Data](./runtime-and-data.md#implementation-status) for local implementation and proof status. The target selector rules below remain authoritative. @@ -41,7 +41,7 @@ At the protocol level, commands are split into two groups: The player-facing protocol is also stage-aware: - **Connected, not logged in** – players can use non-discovery `HELP` and the sole anonymous discovery command, `WORLDS`, but they are not yet authenticated. `REALMS` and `CHARS` are not anonymous discovery and require successful `LOGIN`. -- **Logged in, not yet playing** – target behavior allows existing members with confirmed `membershipLifecycleState=ACTIVE` durable membership to issue `PLAY` directly and requires a first-time public-production player to issue `JOIN` first. In the current runtime, `JOIN` is unavailable and `PLAY` applies only the Account-exposed `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt` fields plus existing grant checks; it does not classify `ACTIVE` or `INACTIVE` because it ignores the emitted lifecycle field. An eligible public-production denial may return non-actionable `JOIN_REQUIRED` when `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter remains non-admitting without a lifecycle classification, and explicit `JOIN` remains unavailable; non-public membership/admission denial returns `WORLD_ACCESS_DENIED`. Current public-only `REALMS` can help disambiguate selection; direct-text `CHARS` remains unavailable. +- **Logged in, not yet playing** – target behavior allows existing members with confirmed `membershipLifecycleState=ACTIVE` durable membership to issue `PLAY` directly and requires a public-production player with missing or `INACTIVE` membership to use explicit `JOIN` first when `allowPublicJoin=true`. An existing `ACTIVE` member is not denied `PLAY` solely because `allowPublicJoin=false`; all other fresh admission checks still apply. Current `PLAY` consumes Account lifecycle and generation evidence after fresh entitlement evaluation and before membership/grant and actor/binding checks. It requires coherent membership evidence and `ACTIVE` admitting membership; eligible missing or `INACTIVE` public membership may produce non-actionable `JOIN_REQUIRED` only when joining policy permits repair. Current private membership/admission denial is `NON_PUBLIC_ENROLLMENT_REQUIRED`, while denied grant is `REALM_ACCESS_DENIED`. Explicit `JOIN` remains unavailable. Current connect-token issuance fails with `AUTH_UNAVAILABLE` before cached replay or admission-authority reads. Current public-only `REALMS` can help disambiguate selection; direct-text `CHARS` remains unavailable. - **In-game** – gameplay commands such as `LOOK`, `SAY`, and movement are available. The target-only happy path for a direct-text human player should therefore be: @@ -68,7 +68,7 @@ For direct text/Telnet, `HELP` is non-discovery, `WORLDS` is the sole anonymous | `REALMS ` | Requires successful `LOGIN` and lists visible realms for a world, where `` is the stable `tenantSlug/worldSlug` selector or menu index returned by `WORLDS`. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world; a bare `worldSlug` is never resolved globally. The default public production realm may be visible before membership exists; additional realms require explicit grants. | `REALMS demo/demo` | | `JOIN ` | **Target-only; not currently implemented.** Explicitly joins the selected world's public production realm through the Account-owned idempotent membership writer. The resulting membership is durable and powers later return discovery. `` follows the same tenant-scoped selector rules as `REALMS`. | `JOIN demo/demo` | | `CHARS [realm]` | Requires successful `LOGIN` and presents Entity's persisted roster/policy result for the resolved realm. It is discovery evidence, not admission authority; `PLAY` revalidates the selected actor and current runtime fence. | `CHARS demo/demo production` | -| `PLAY [realm] [character]` | Binds the authenticated connection to a world, optional realm, and optional character after the discovery, `LOGIN`, and conditional membership/character gates, enforcing tenant authorization, realm routing, and entitlements. Players may omit `[realm]` or `[character]` only when the fresh target resolution is unambiguous; direct text never reuses the first-party WebSocket discovery snapshot. A first-time public player must complete `JOIN ` first; a grant-backed non-public path may proceed only when its required durable `membershipLifecycleState=ACTIVE` membership already exists. `PLAY` returns `JOIN_REQUIRED` for the current eligible public-production predicate and never creates or substitutes membership implicitly. | `PLAY demo/demo production Sora` | +| `PLAY [realm] [character]` | Binds the authenticated connection to a world, optional realm, and optional character after the discovery, `LOGIN`, and conditional membership/character gates, enforcing tenant authorization, realm routing, and entitlements. Players may omit `[realm]` or `[character]` only when the fresh target resolution is unambiguous; direct text never reuses the first-party WebSocket discovery snapshot. A public-production player with missing or `INACTIVE` membership must complete `JOIN ` first when fresh joining policy permits; a closed policy denies that required join/repair without changing membership. Existing `ACTIVE` membership skips `JOIN` and is not denied `PLAY` solely because `allowPublicJoin=false`. A grant-backed non-public path may proceed only when its required durable `membershipLifecycleState=ACTIVE` membership already exists. `PLAY` returns `JOIN_REQUIRED` only for the eligible missing/`INACTIVE` public-production predicate and never creates or substitutes membership implicitly. | `PLAY demo/demo production Sora` | | `LOOK` | Requests the current room snapshot aggregated from Game Logic plus World and Entity services. | `LOOK` | | `INVENTORY` / `INV HERE` | Lists carried items or the current room-ground item holder. The command is rendered by Game Session, but item state is read through Game Logic and Entity Management. | `INV HERE` | | `GET ` / `DROP ` | Moves a visible room-ground item into carried inventory, or a carried item into the current room. Game Session forwards the raw selector and quantity to Game Logic; Game Logic resolves names, visible refs, container refs, and stack refs before Entity Management mutates state. | `GET torch1` | @@ -84,7 +84,7 @@ Selector rules for `PLAY` match the lobby helpers. `WORLDS` returns the stable ` The canonical JOIN and membership-admission contract is defined in [Authentication & Authorization](../../system-architecture-authentication.md#normative-target-contract); this section keeps only Game Session's protocol translation and local handling. -The target Account membership operation is `JoinPublicProductionMembership`; it remains target-only and unimplemented, so there is no current implicit membership writer. When the explicit text action is implemented, Game Session translates `JOIN ` to the sole target operation `JoinPublicProductionMembership`; it does not create membership locally or use another join writer. +Account implements `JoinPublicProductionMembership` locally; its HTTP exposure remains blocked by Gateway, and Game Session text `JOIN` / `Join & Play` dispatch is unimplemented, as recorded by [Account API contracts](../account-service/api-contracts.md). This does not provide an implicit membership writer. When the explicit text action is implemented, Game Session translates `JOIN ` to the sole target operation `JoinPublicProductionMembership`; it does not create membership locally or use another join writer. - Game Session resolves `` from the exact `WORLDS` snapshot to the tenant-scoped `{tenantId, worldSlug}` pair, selects the unique visible player-addressable realm marked `publicProduction=true` in that catalog/policy snapshot, and resolves that realm to durable `realmId` plus its current admission-pointer target. The resolved slugs identify the operation target for people but are not independent client authority. - Authenticated caller identity and subject authority come only from the validated caller-bound `PlayerExecutionContext`; Account separately validates that context and never treats `connectScopeId` as caller authority. Game Session generates and owns the high-entropy join-attempt `requestId` for the direct-text `JOIN ` command; that command carries no client-selected request ID or `playableStateScope`, and Game Session retains the generated identity with the pending transport-local scope and passes the same identity to Account for retries. The resolved target's opaque `connectScopeId` selects and binds the target world/realm and routing snapshot. Account validates the target scope at its commit boundary; a client-supplied request ID, runtime ID, playable-state scope, or independently supplied slug cannot replace the retained scope or attempt identity. @@ -116,7 +116,7 @@ Canonical first-party `PLAY` scope errors on `/ws/game/**`: Target-only resume/admission rule: after resolving the current server-authoritative realm target, Game Session looks up the resumable controller key `{tenantId, playableStateNamespaceId, characterId}`, verifies the authenticated `accountId` separately as binding-owner evidence, retains server-derived `playableStateScope` as binding context, and validates the current runtime/region fence before admitting the binding. A stale or caller-replayed namespace or instance is never a lookup fallback. Authorized takeover applies the atomic monotonic `bindingGeneration` transfer owned by [Session Behavior](../../system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02). A newly opened transport still requires explicit `PLAY`; after eligible admission, Game Session exposes only the semantic-context and fresh-state reconstruction owned by [Reconnection](../../system-architecture-reconnection.md#client-reconnection-behaviour). -Current runtime still uses the per-instance controller lookup and does not prove the namespace-key binding CAS. It consumes only four admission-evidence fields from the Account response (`membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`) and cannot classify `ACTIVE` or `INACTIVE`. Current text `PLAY` may return non-actionable `JOIN_REQUIRED` for an otherwise eligible public-production request when `membershipExists=false` or an existing membership has `gameplayAdmissionAllowed=false`; the latter cannot currently be classified specifically as `INACTIVE` because the consumer ignores the emitted lifecycle state. Current non-public missing or non-admitting membership remains `WORLD_ACCESS_DENIED`. A fresh Telnet admission requires current entitlement, and current text `PLAY` checks the applicable private/playtest grant; current connect-token grant validation remains a gap. +Current runtime still uses the per-instance controller lookup and does not prove the namespace-key binding CAS. Text `PLAY` consumes Account-emitted lifecycle and authority generation in addition to membership version/admission evidence; it evaluates fresh entitlement before membership/grant and later actor/binding checks. Coherent missing membership requires `membershipExists=false` with zero version/generation; existing membership requires positive independent version/generation and known lifecycle, with `ACTIVE` plus admitting required for gameplay. Eligible missing or `INACTIVE` public membership may return non-actionable `JOIN_REQUIRED` only when joining policy permits repair; current private membership denial is `NON_PUBLIC_ENROLLMENT_REQUIRED`, denied grant is `REALM_ACCESS_DENIED`, and unsafe or unavailable authority is `AUTH_UNAVAILABLE`. Current text `PLAY` checks the applicable grant. Connect-token issuance fails closed with `AUTH_UNAVAILABLE` before cached replay or admission-authority reads, and full caller-target/atomic authority, `allowNewGameplayBindings`, grant lifecycle/expiry, lease commit, and namespace-key binding CAS remain gaps. If a client attempts gameplay commands before `LOGIN` succeeds, the service should return a stage-aware response such as `ERROR LOGIN_REQUIRED Use LOGIN [secret]`. If a client is logged in but has not yet completed `PLAY`, the service should return a stage-aware response such as `ERROR PLAY_REQUIRED Use PLAY [realm] [character]`. These are menu/progression mistakes, not gameplay-mechanics failures. @@ -166,9 +166,9 @@ Additional Game Session-specific login failures cover parsing and session-state - `PROMPT_LOGIN_UNSUPPORTED` – multi-line interactive `LOGIN`/`LOGON` exchanges are planned but not implemented yet on non-bootstrap transports, so those clients must send `LOGIN ` to request a code or `LOGIN ` to authenticate. - `INVALID_ACCOUNT` – Account Service returned an account identifier that could not be parsed into the expected format. - `ACCOUNT_MISMATCH` – **target-only** canonical result when bootstrap-backed `LOGIN` resolves to an account different from the validated connect-context subject; see the [Authentication and Authorization contract](../../system-architecture-authentication.md#first-party-websocket-admission-sequence-normative). The current implementation's persisted-credential identity versus scoped registry-context conflict is separate: it unregisters the stale registry context and returns `CONNECT_CONTEXT_INVALID`. -- `JOIN_REQUIRED` – the selected public-production target either has missing membership (`membershipExists=false`) or an existing but non-admitting membership (`gameplayAdmissionAllowed=false`) for the account, so the target client must complete explicit `JOIN`/`Join & Play`; a grant or cached discovery result is not a substitute. In the current runtime this is a fail-closed, non-actionable result because explicit `JOIN` is unavailable, and the existing non-admitting case cannot be classified as `INACTIVE` because the consumer ignores the lifecycle state that Account emits. -- `WORLD_ACCESS_DENIED` – current runtime behavior for a private, playtest, or other non-public target whose Account-exposed membership/admission predicate or existing grant check denies access; no public join action is offered. -- `NON_PUBLIC_ENROLLMENT_REQUIRED` – target-only replacement for that non-public missing/non-`ACTIVE` membership outcome; it never offers public `JOIN` and requires existing `membershipLifecycleState=ACTIVE` membership plus the applicable grant. +- `JOIN_REQUIRED` – target behavior uses this next-step outcome only for missing or `INACTIVE` public-production membership after fresh target and enrollment checks permit explicit `JOIN`/`Join & Play`; `allowPublicJoin=false` instead denies the required join/repair with `PUBLIC_PRODUCTION_ADMISSION_DENIED`. An existing `ACTIVE` member does not need `JOIN` and is not denied `PLAY` solely because enrollment is closed. A grant or cached discovery result is not a substitute for current authority. Current text `PLAY` emits non-actionable `JOIN_REQUIRED` only for eligible missing or `INACTIVE` public membership after its fresh entitlement and joining-policy checks; explicit `JOIN` remains unavailable. +- `WORLD_ACCESS_DENIED` – a separate authoritative world/tenant denial, not the current non-public membership or grant result. Current private/playtest membership denial is `NON_PUBLIC_ENROLLMENT_REQUIRED`, and denied grant is `REALM_ACCESS_DENIED`; see [Authentication](../../system-architecture-authentication.md#in-band-play-admission-boundary). +- `NON_PUBLIC_ENROLLMENT_REQUIRED` – current text `PLAY` result for non-public missing/non-`ACTIVE` membership; it never offers public `JOIN` and requires existing `membershipLifecycleState=ACTIVE` membership plus the applicable grant. - `SESSION_NOT_FOUND` – the supplied game instance identifier has no corresponding `GameInstance`. - `INVALID_ARGUMENT` – session ID parsing or other validation failed before the handler reached gameplay state. - `PLAY_REQUIRED` – a gameplay command that requires admitted gameplay scope was sent before `PLAY` completed successfully. diff --git a/design/architecture/microservices/tcp-proxy-service/api-contracts.md b/design/architecture/microservices/tcp-proxy-service/api-contracts.md index 6b6eda8337..c93e2e752a 100644 --- a/design/architecture/microservices/tcp-proxy-service/api-contracts.md +++ b/design/architecture/microservices/tcp-proxy-service/api-contracts.md @@ -6,7 +6,7 @@ After actual edge loss, the Telnet transport carries the owner-defined `WORLDS` ## Implementation Status -Current proxy routing and receiving-service behavior support an abbreviated returning-member `LOGIN` -> `PLAY` path when current membership and character gates pass. Current proxy routing still bootstraps a hidden default and does not enforce `WORLDS` as a prerequisite; Account emits lifecycle state and an independent membership-authority generation, but the current text `PLAY` consumer does not enforce those fields; see [Account runtime status](../account-service/runtime-and-data.md). The proxy does not classify membership lifecycle. `NotifyDisconnect` remains a best-effort, at-least-once advisory signal as described below. Its current Game Session receiver returns bounded acknowledgements after read-only metadata checks without suspending shared state or invoking presence effects; [Game Session runtime status](../game-session-service/runtime-and-data.md#reconnection-and-disconnect-handling) records that containment and its remaining binding-fence limits. +Current proxy routing and receiving-service behavior support an abbreviated returning-member `LOGIN` -> `PLAY` path when current membership and character gates pass. Current proxy routing still bootstraps a hidden default and does not enforce `WORLDS` as a prerequisite; Account emits lifecycle state and an independent membership-authority generation, and current text `PLAY` validates them after fresh entitlement evaluation and before later actor/binding checks; see [Game Session protocols](../game-session-service/protocols.md). The proxy does not classify membership lifecycle. `NotifyDisconnect` remains a best-effort, at-least-once advisory signal as described below. Its current Game Session receiver returns bounded acknowledgements after read-only metadata checks without suspending shared state or invoking presence effects; [Game Session runtime status](../game-session-service/runtime-and-data.md#reconnection-and-disconnect-handling) records that containment and its remaining binding-fence limits. ## Service Interactions diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index 51631b8830..c2aa76520f 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -31,14 +31,14 @@ For every private/playtest grant consequence, the exact Account target is `{acco - **Current fail-closed boundary:** Any route branch that requires the unavailable `privileged_control` window must reject that `platformAdmin` or cross-tenant `billingAdmin` authorization path. A separately declared tenant-role or unelevated `support` branch may remain available only when all of its own live checks pass. - Character selection and gameplay takeover target the one-controller identity `{tenantId, playableStateNamespaceId, characterId}` with an atomic monotonic `bindingGeneration`; server-derived `playableStateScope` remains binding context, and the current `{tenantId, gameInstanceId, characterId}` identity is implementation drift. - **Membership behavior (target):** Only an explicit public-production `JOIN` / `Join & Play` through `JoinPublicProductionMembership` may change the durable caller-bound `player` membership. The lifecycle is exact: missing -> `JOIN` creates `ACTIVE` and advances `membershipVersion`; `INACTIVE` -> `JOIN` restores `ACTIVE` and advances `membershipVersion`; `membershipAuthorityGeneration` advances independently only when the transition records `callerBoundAuthorityInvalidated=true`; `ACTIVE` -> `JOIN` returns the exact idempotent current snapshot; every other lifecycle state rejects. `JOIN_REQUIRED` covers missing or `INACTIVE` membership before a successful join. Game Session admission, connect-token issuance, character creation, and `PLAY` require existing `ACTIVE` membership and must never create or restore membership. -- Current connect-token issuance returns `AUTH_UNAVAILABLE` before membership or replay-cache reads while its canonical producer is unavailable. Supported text `PLAY` does not consult the connect-token replay cache and performs its fresh membership check and, for private/playtest targets, its fresh current realm-grant check. -- **Membership behavior (current versus target):** The local Account explicit join action is implemented through `JoinPublicProductionMembership`; the required `membershipAuthorityGeneration` reread at connect-token issuance remains a proof gap. Current text `PLAY` requires a fresh current Account membership adapter response identified by `accountId` and `tenantId`, with these four admission-evidence fields: `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; the first two must be true. Although the live producer now emits `membershipLifecycleState` and `membershipAuthorityGeneration` too, this text consumer still uses only the four fields above and does not enforce the complete atomic-freshness contract. Connect-token issuance cannot currently return a cached success because its fail-closed guard precedes replay reads; the target replay/persistence and revalidation contract is owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). Text `PLAY` separately reads the current realm grant for private/playtest targets. The current text consumer therefore cannot classify the returned membership as `INACTIVE`: `membershipExists=false` represents missing membership, while `membershipExists=true` and `gameplayAdmissionAllowed=false` represents existing but non-admitting membership without distinguishing lifecycle states. For eligible public-production text `PLAY`, missing or existing non-admitting membership may currently return `JOIN_REQUIRED`; an existing but non-admitting membership cannot be classified as `INACTIVE`. Current non-public text `PLAY` maps missing or non-admitting membership to `WORLD_ACCESS_DENIED`. Text `PLAY` returns `AUTH_UNAVAILABLE` for unavailable or unsafe membership authority. The current `JOIN_REQUIRED` result remains a fail-closed `PLAY` denial until the caller completes the local explicit join operation; it is not proof of the target lifecycle snapshot or final admission flow. The obsolete writer seam has been removed, while the complete first-party browser/mobile sequence remains partial and its PostgreSQL, recovery/reconciliation, direct text end-to-end, and downstream membership-generation proof remain open. Returning members on a supported text path may proceed when current runtime membership and character checks pass, but current behavior does not prove the target exact generation/version reread at connect-token issuance; the target requires lifecycle state, authority generation, and independent membership version from one fresh membership snapshot. The target character-creation membership precondition and required issuance proof remain implementation/proof gaps. Every target gameplay admission requires the applicable fresh tenant runtime entitlement. Public-production `JOIN` additionally consumes its public-enrollment `allowPublicJoin` policy; private/playtest admission never consumes that public-enrollment predicate and instead requires caller-bound `ACTIVE` membership plus the exact current Account-owned grant. Both paths require exact routing and the fresh membership snapshot. Target missing or non-`ACTIVE` private/playtest membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`, target missing or invalid grant is `REALM_ACCESS_DENIED`, and unavailable authority is `AUTH_UNAVAILABLE`. +- Current connect-token issuance returns `AUTH_UNAVAILABLE` before cached replay or membership, entitlement, grant, and routing-authority reads. Text `PLAY` is independent of that issuance path and evaluates fresh entitlement before membership/grant and later actor/binding checks; it consumes Account-emitted membership lifecycle and authority generation. +- **Membership behavior (current versus target):** Account emits `membershipLifecycleState` and `membershipAuthorityGeneration`, and current text `PLAY` consumes both alongside membership version and admission evidence. Gameplay requires coherent membership evidence: missing membership is represented by `membershipExists=false` with zero version/generation; existing membership requires positive independent version and generation plus known lifecycle. Only `ACTIVE` and admitting membership passes. Fresh entitlement is evaluated before membership and applicable grant checks; actor and binding checks follow. Public repair is limited to missing or `INACTIVE` membership on an eligible public-production target; `allowPublicJoin=false` denies that required repair only, not an existing `ACTIVE` member by itself. Current private outcomes are `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing or known non-`ACTIVE` membership, `REALM_ACCESS_DENIED` for denied grant, and `AUTH_UNAVAILABLE` for unsafe or unavailable authority. Explicit text `JOIN` remains unavailable. The required full caller-target/atomic authority, connect-token membership/version revalidation, and target `allowNewGameplayBindings`, grant-lifecycle/expiry, and lease-commit boundaries remain incomplete; see [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#capability-status). - **Target-only/currently unavailable public non-browser issuance:** Public non-browser connect-token issuance and `X-Firemud-Connect-Token` carriage are not current supported capabilities. They may be exposed only after a dedicated route is fully registered in the authorization matrix and its `gameplay-connect` issuance/replay record, `replayAdmissionFence`, quarantine/deny state, signed-context, response, and carrier proofs are complete. This path is exempt from the ordinary active issued-token registry, `tokenGeneration`, `issuanceFence`, and `session:auth:token:` record; its bounded selected-target `authorityTuple` and separate `membershipVersion` are immutable issuance evidence passed into the later exact-binding admission checks, not a registry lookup or standalone gameplay authority. Current clients must not be told that header support exists. - First-party browser and mobile-browser gameplay use the short-lived `player-bootstrap` JWT for HTTPS bootstrap calls and carry the resulting gameplay-connect token only in the `Firemud-Connect-Token` HttpOnly cookie. First-party native-mobile and other first-party non-browser clients using a cookie jar remain cookie-only. Telnet and other non-WebSocket text transports use credential-bearing `LOGIN` and do not carry public JWTs or connect tokens. - `/sessions/{sessionId}/refresh-roles` exists as an operational hook, but current role-refresh token regeneration and periodic active-session `game-session-account-delegation` rotation remain implementation gaps; the placeholder response is not proof of refresh. - The current Account `Authenticate` proto path still lacks the target `requestId`/immutable-digest replay envelope and orphan-token retirement contract described below; those fields and recovery semantics remain implementation/proof gaps rather than implied current behavior. - **Current reauthentication boundary:** After a gameplay binding is terminated by an authority cutoff or the bounded cleanup path, current restoration requires fresh `LOGIN` plus `PLAY` and current authoritative checks. Token refresh, replacement, revocation, fencing, and logout are owned by [JWT and Token Contracts](./system-architecture-jwt-and-token-contracts.md); gameplay binding continuity, reconnect, and resume orchestration remain in [Session Behavior](./system-architecture-session-behavior.md). Fresh `LOGIN` then `PLAY` remains the client-visible reauthentication path when required. -- Account's JWKS endpoint and conditional secret watcher are implemented, but asymmetric-profile validation, non-exportable signer delegation for asymmetric signing, rotation/convergence, issued-token registry issuance/storage/consumer enforcement, and Account-owned authority generations remain target-state and unimplemented. No authority-generation issuance, advancement, propagation, or validation proof is currently claimed. +- Account's JWKS endpoint and conditional secret watcher are implemented, but asymmetric-profile validation, non-exportable signer delegation for asymmetric signing, rotation/convergence, issued-token registry issuance/storage/consumer enforcement, and Account-owned authority generations remain target-state and unimplemented. No end-to-end authority-generation issuance, advancement, propagation, or atomic-freshness validation proof is currently claimed. ## Contract Decisions (Normative) @@ -324,8 +324,13 @@ Normative semantic split: - `LOGIN` establishes the authenticated socket/session account context only; it does not select a tenant or character and does not create a gameplay binding. Gameplay admission, binding, and finalization belong to `PLAY`. - When the selected public-production tenant has missing or `INACTIVE` caller-bound membership, `JOIN ` explicitly establishes `ACTIVE` membership after authenticated `REALMS` discovery and before `CHARS` or character creation. Either create or restore advances `membershipVersion`; `membershipAuthorityGeneration` advances independently only when `callerBoundAuthorityInvalidated=true`. An `ACTIVE` membership returns the exact idempotent current snapshot. Any other lifecycle state rejects. A caller with existing `ACTIVE` membership omits `JOIN` and continues to character selection and `PLAY`. First-party browser/mobile clients use the equivalent Account bootstrap join endpoint. - The direct-text `LOGIN` plus `PLAY` compatibility shortcut is limited to an existing `membershipLifecycleState=ACTIVE` member for the same target. It may omit `JOIN` only because membership is already active, and it may omit a separate `CHARS` round-trip only when fresh transport-local resolution supplies one valid current character; it never reuses a first-party WebSocket discovery snapshot. First-party/browser clients always use authenticated bootstrap, discovery, and lobby gates, including for returning members. + - `PLAY` binds the gameplay session to `{tenantId, playableStateNamespaceId, characterId}`, carries server-derived `playableStateScope`, and retains `{gameInstanceId, sessionId, bindingGeneration}` as runtime/value evidence. +### Public-production enrollment-only policy + +`allowPublicJoin` controls whether Account may create missing public-production membership or restore membership from `INACTIVE` through explicit `JOIN`/`Join & Play`. It is not a gameplay-entitlement switch: setting it to `false` does not by itself deny connect-token issuance or `PLAY` for an existing `ACTIVE` member. Existing members remain subject to all other fresh, applicable membership, entitlement, routing, grant, and binding checks. When missing or `INACTIVE` membership requires a join/repair, closed enrollment returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, not `JOIN_REQUIRED`; `JOIN_REQUIRED` is available only after fresh target and policy checks permit that membership transition. + ### In-Band `PLAY` Admission Boundary In-band `PLAY` on a Telnet or gameplay WebSocket command stream is not an ordinary HTTP/gRPC JWT-middleware route. `LOGIN` establishes the authenticated account and Game Session-owned socket/session context; `PLAY` validates that bound gameplay session context and does not run `AuthTokenInterceptor` or infer authority from a browser JWT. diff --git a/design/architecture/system-architecture-authz-route-matrix.md b/design/architecture/system-architecture-authz-route-matrix.md index 593864372a..ba17905378 100644 --- a/design/architecture/system-architecture-authz-route-matrix.md +++ b/design/architecture/system-architecture-authz-route-matrix.md @@ -25,7 +25,7 @@ Hosted creator-terms acceptance is an explicit current inventory gap. [ADR 0180] ## Implementation Status -- Public-production membership and entitlement authority are canonical in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority); realm catalog and pointer authority are canonical in [Multi-Tenancy](./system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract). Current `PLAY` returns `JOIN_REQUIRED` for the documented eligible public-production case when the Account runtime response reports missing membership (`membershipExists=false`) or an existing membership with `gameplayAdmissionAllowed=false`; Account now exposes `membershipLifecycleState` and `membershipAuthorityGeneration`, but the current Game Session `PLAY` consumer does not yet consume those fields, so the latter response is not classified specifically as `INACTIVE` and its lifecycle interpretation/repair path remains target-only. `ACTIVE` membership does not require `JOIN`, while policy denial and unavailable/invalid authority remain distinct outcomes. Account's explicit JOIN writer is implemented locally, but Game Session text dispatch and direct text-client end-to-end proof remain unavailable in this stage; first-party `Join & Play` and durable unknown-outcome recovery remain incomplete. +- Public-production membership and entitlement authority are canonical in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority); realm catalog and pointer authority are canonical in [Multi-Tenancy](./system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract). Current `PLAY` validates `membershipLifecycleState` and the independent `membershipAuthorityGeneration`, and requires coherent `ACTIVE` admitting membership. The documented eligible public-production case yields `JOIN_REQUIRED` only for missing membership (`membershipExists=false`) or `INACTIVE` membership when fresh enrollment policy permits repair; an existing `ACTIVE` non-admitting response is denied rather than treated as a join fallback. `ACTIVE` membership does not require `JOIN`, while policy denial and unavailable/invalid authority remain distinct outcomes. Account's explicit JOIN writer is implemented locally, but Game Session text dispatch and direct text-client end-to-end proof remain unavailable in this stage; first-party `Join & Play` and durable unknown-outcome recovery remain incomplete. - `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` remain target `internal_workload` routes. Their seed entries are Account Service `GetTenantMembershipForRuntime` / `GetRealmAccessGrant` / `ListRealmAccessGrantsForAccount` and Account Service `GetTenantEntitlementsForRuntime`; the latter records the exact Game Session or World Management caller alternatives. Current Account development and production configuration incorrectly lists both methods as public gRPC bypasses, and their handlers accept caller-supplied identifiers without typed workload context or tenant binding. Remove the bypass and add missing-token, wrong-workload, and cross-tenant denial proof before runtime readiness is claimed. - The current `IssueConnectToken` route requires existing caller-bound membership for every realm and never creates it; its required membership-authority-generation reread is missing. A realm grant never substitutes for membership. - `privileged_control` is target-only and currently unavailable; route branches that authorize through a global `platformAdmin` or cross-tenant `billingAdmin` role therefore fail closed, while the `support` branch of `cross_tenant_support_safe` does not require `privileged_control`. Operator mutation rows that require an Account-issued authorization reference or this privileged-control window are normative target rows, not current availability claims. diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index f9118f5479..29a692d5b4 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -113,7 +113,7 @@ The main [`ci.yml`](../../.github/workflows/ci.yml) workflow: - On the complete CI path, preserves every service test task and JaCoCo execution. Each Account Service and Game Session partition uploads its report to Codecov using GitHub OIDC; a separate read-only aggregate verifies every module partition’s selectors and JUnit results, then merges execution data from unit and every available categorized integration/cross-service task into the complete service report. Other modules retain one report from their module check; modules without categorized tests retain their unit-only report. Production classes remain in reports rather than being excluded to improve percentages. Lightweight documentation-only PR validation does not run these service checks or coverage reports. - Retains Gradle JUnit XML results from each affected-module `check`, including unit and categorized integration/cross-service outcomes, for 14 days. Account and Game Session retain them with their complete partition evidence in `slow-service-ci-partition---attempt---partition-`; other modules use `junit---results--attempt-`. Including the attempt keeps partial workflow reruns from colliding with earlier artifacts. The load-testing matrix entry uses its `dev-tools/load-testing` output; missing XML is reported as a warning so artifact retention does not change the test gate. - Runs the existing module check with Gradle's native `--profile` and retains `build/reports/profile/` from the repository root as `gradle-profile----attempt-` for 14 days. These reports expose startup, configuration, dependency and task durations without changing the selected checks, workers or recovery behavior. Missing reports warn rather than supplying timing evidence; cancelled or early-failed runs may not produce a report. Parallel task durations can overlap and must not be summed as elapsed time; JUnit results remain the separate source for individual test costs. -- Failed Java compile tasks additionally retain bounded generated Java, proto, and build/version inputs with hashes and an omissions manifest in the existing per-module profile artifact. Native `--info` compiler identity lines come from the original check; a separate offline diagnostic records Gradle/JVM identity, compiler selection and ordered compile classpath paths/lengths without copying JARs. Diagnostic selection is explicitly post-failure and cannot establish the original executed compiler or dependency bytes. Collection is limited to four failed tasks, 512 input files, 2 MiB per input, 16 MiB total inputs, 4096 visited directory entries across source enumeration, a 16 MiB streamed log tail, and 60 seconds per diagnostic; symlink paths are rejected. Source enumeration and diagnostic output limits report possible truncation, including an exactly full diagnostic output. Live output is forwarded while only the bounded log tail is buffered for capture; capture/forwarding failures still drain the original output. Missing facts and diagnostic failure remain explicit. Cancellation/signal exits (128 or above) skip collection and diagnostics. Collection never retries compilation or tests, changes dependency recovery, or replaces the original failing exit. No environment dump, credentials, whole cache, or unrelated workspace data is retained. +- Failed Java compile tasks additionally retain bounded generated Java, proto, and build/version inputs with hashes and an omissions manifest in the existing per-module profile artifact. The same collector covers the source-built Compose all-eleven-service `bootJar` boundary in `dev-tools/build-compose-service-jars.sh`, using a distinct invocation directory under `build/reports/compile-failure/runtime-bootjar/`. The read-only `pr-local-smoke` job retains only that invocation's evidence on build failure as `runtime-bootjar-compile-failure--attempt-` for three days; missing evidence warns and upload failure cannot replace the build result. Native `--info` compiler identity lines come from the original check or boot-jar build; a separate offline diagnostic records Gradle/JVM identity, compiler selection and ordered compile classpath paths/lengths without copying JARs. Diagnostic selection is explicitly post-failure and cannot establish the original executed compiler or dependency bytes. Diagnostics use the canonical locked Gradle wrapper, retaining local resource admission, verified inherited leases, and its existing CI bypass. Collection is limited to four failed tasks, 512 input files, 2 MiB per input, 16 MiB total inputs, 4096 visited directory entries across source enumeration, a 16 MiB streamed log tail, and 60 seconds per diagnostic; symlink paths are rejected. Source enumeration and diagnostic output limits report possible truncation, including an exactly full diagnostic output. Live output is forwarded while only the bounded log tail is buffered for capture; capture/forwarding failures still drain the original output. Missing facts and diagnostic failure remain explicit. Missing boot-jar capture scratch runs the original build once without evidence. Success, failures without a failed Java compile task, and cancellation/signal exits (128 or above) produce no compile-failure evidence; cancellation/signal exits skip diagnostics. A failed `compileJava` task may retain evidence even when the failure comes from classpath or dependency resolution rather than compiler diagnostics. Collection never retries compilation or tests, changes dependency recovery, or replaces the original exit. No environment dump, credentials, whole cache, or unrelated workspace data is retained. - Uses Node 24 to lint OpenAPI specs, run React linters, and execute an accessibility audit using headless Chrome. - Validates tracked Bash scripts across the repository with ShellCheck and validates every tracked Python script with `py_compile` plus repository-wide Ruff linting. - Invokes a dedicated `generate-erd` job that runs [`dev-tools/docs/generate-erd.sh`](../../dev-tools/docs/generate-erd.sh) to build ERD diagrams from service migrations and upload them as artifacts. diff --git a/design/architecture/system-architecture-protocol-bridging.md b/design/architecture/system-architecture-protocol-bridging.md index 1238e25880..8cbb879a83 100644 --- a/design/architecture/system-architecture-protocol-bridging.md +++ b/design/architecture/system-architecture-protocol-bridging.md @@ -6,7 +6,7 @@ This design is the canonical specification for protocol-specific gameplay carria ## Implementation Status -The target flow and delivery contracts below remain normative. The complete `WORLDS` -> `LOGIN` -> `REALMS` -> conditional public-production `JOIN` -> conditional `CHARS`/character creation -> `PLAY` sequence remains incomplete; held-admission smoke is bounded runtime proof, not full protocol or public-admission proof. Account already emits membership lifecycle and independent authority generation/version, but current text `PLAY` ignores lifecycle/generation, evaluates membership before entitlement, and can return non-actionable public `JOIN_REQUIRED` for missing or present non-admitting membership without distinguishing `INACTIVE`. Non-public text admission uses `WORLD_ACCESS_DENIED` for membership denial and separately requires the current realm grant. Explicit text JOIN is unavailable; the Account-local writer is distinct. Current connect-token issuance validates bootstrap identity/scope and returns `AUTH_UNAVAILABLE` before cached replay, membership, entitlement or pointer reads. The complete atomic snapshot and admission authority remain unproved; current producer/issuance details are owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md), with capability/proof status in [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md). This implementation drift does not relax the at-most-once delivery, authentication, admission, reconnect or close-taxonomy requirements. +The target flow and delivery contracts below remain normative. The complete `WORLDS` -> `LOGIN` -> `REALMS` -> conditional public-production `JOIN` -> conditional `CHARS`/character creation -> `PLAY` sequence remains incomplete; held-admission smoke is bounded runtime proof, not full protocol or public-admission proof. Account emits membership lifecycle and authority generation, and current text `PLAY` consumes them after fresh entitlement evaluation and before membership/grant and later actor/binding checks. It requires coherent membership evidence and an `ACTIVE`, admitting state. Public repair is limited to missing or `INACTIVE` public-production membership when joining policy permits it; private membership and grant failures retain their distinct current outcomes. Explicit text `JOIN` remains unavailable; the Account-local writer is separate. Current connect-token issuance returns `AUTH_UNAVAILABLE` before cached replay or membership, entitlement, grant, and routing-authority reads. Full caller-target/atomic authority, `allowNewGameplayBindings`, grant lifecycle/expiry, lease commit, and genuine custody/registration remain absent or held. See [Account Runtime and Data](./microservices/account-service/runtime-and-data.md) and [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md) for current implementation/proof status. This implementation drift does not relax the at-most-once delivery, authentication, admission, reconnect or close-taxonomy requirements. --- @@ -42,9 +42,9 @@ Despite their differences, both protocols are normalized into the same internal - `/ws/game/**` is the only gameplay WebSocket route. The canonical carrier, replay, handshake, and Gateway-to-Game-Session context rules are owned by [Gateway architecture](./system-architecture-gateway.md#gameplay-websocket-route) and [Authentication](./system-architecture-authentication.md#websocket-connect-token-contract-ws-game). - The supported `first_party_web` variant requires the protected `Firemud-Connect-Token` cookie; `CONNECT_TOKEN_MISSING` means no connect-token carrier is supplied, not merely that the cookie is absent. A target-only `non_first_party_public` variant may use `X-Firemud-Connect-Token` only after its dedicated route registration and issuance, replay, signed-context, response, and carrier proof; a header-only request on an unsupported or unregistered route is `CONNECT_TOKEN_REJECTED`, not `CONNECT_TOKEN_MISSING`. The header is not a fallback for the cookie route, and a present but invalid value uses the applicable expired, replayed, or rejected class. These handshake outcomes return HTTP `403`. TCP Proxy bridge traffic is admitted only through the authenticated internal mTLS and header-trust branch and consumes no gameplay connect token. - Browser clients cannot read failed WebSocket upgrade headers. Before the socket opens, they follow the canonical [browser failed-upgrade recovery rule](./system-architecture-reconnection.md#browser-failed-upgrade-recovery): exactly one fresh discovery/token retry per failed-upgrade episode with bounded backoff, then no automatic refresh or reconnect and recovery guidance. Detailed bounded classes remain available to capable non-browser callers and operator telemetry rather than becoming a second browser status API. -- All gameplay sessions require in-band `LOGIN` and `PLAY` before gameplay commands. `LOGIN` establishes socket/account authentication and `PLAY` performs gameplay admission and binding under [Authentication](./system-architecture-authentication.md#login-and-session-flow). The current implementation caveat remains: explicit join is unimplemented, current text `PLAY` consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and proceeds only when the two admission fields are true; an eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED` without creating membership; the latter cannot be classified as `INACTIVE`. Account connect-token issuance separately fails closed with `AUTH_UNAVAILABLE` before membership, entitlement, pointer, replay or token work; [Account runtime status](./microservices/account-service/runtime-and-data.md) owns the current endpoint boundary. +- All gameplay sessions require in-band `LOGIN` and `PLAY` before gameplay commands. `LOGIN` establishes socket/account authentication and `PLAY` performs gameplay admission and binding under [Authentication](./system-architecture-authentication.md#login-and-session-flow). Current text `PLAY` consumes Account-emitted lifecycle and authority generation, evaluates fresh entitlement before membership/grant and later actor/binding checks, and requires coherent membership evidence plus `ACTIVE` admitting membership. The current connect-token endpoint fails with `AUTH_UNAVAILABLE` before cached replay or admission-authority reads and does not currently validate membership or grant. Explicit text `JOIN` remains unavailable. -For target browser onboarding and reconnect, the realm-scoped character gate remains in the sequence: first-time public entry, or a returning flow whose selected character is missing, invalid, or no longer visible for the resolved realm, must complete `CHARS`/allowed character creation after target-only `ACTIVE` membership and before `POST /auth/connect-token` and WebSocket `PLAY`. Returning players use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate); the bridge must preserve its fresh same-target entitlement, current authority, independent `membershipAuthorityGeneration` and `membershipVersion`, and exact current Account-owned realm-grant requirements, along with the discovery-snapshot and valid-character prerequisites defined there. The bridge forwards that owner-defined order and does not treat discovery or token evidence as authorization proof. Current text `PLAY` does not consume the Account producer’s emitted lifecycle/generation fields; its boolean admission predicate does not prove the target lifecycle gate. Direct-text `CHARS` is unavailable, while the separate Account HTTP/bootstrap roster does not complete that command boundary. Current connect-token issuance is fail-closed rather than a completed shortcut/token path; successful target character, grant, pointer and issuance ordering remains incomplete. A connect token carries a short-lived discovery snapshot for edge admission; it does not bypass `CHARS` or turn stale character evidence into gameplay authority. +For target browser onboarding and reconnect, the realm-scoped character gate remains in the sequence: first-time public entry, or a returning flow whose selected character is missing, invalid, or no longer visible for the resolved realm, must complete `CHARS`/allowed character creation after target-only `ACTIVE` membership and before `POST /auth/connect-token` and WebSocket `PLAY`. Returning players use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate); the bridge must preserve its fresh same-target entitlement, current authority, independent `membershipAuthorityGeneration` and `membershipVersion`, and exact current Account-owned realm-grant requirements, along with the discovery-snapshot and valid-character prerequisites defined there. The bridge forwards that owner-defined order and does not treat discovery or token evidence as authorization proof. Current text `PLAY` consumes lifecycle and generation and evaluates entitlement before membership/grant and later actor/binding checks; it enforces the current private/playtest grant. Current connect-token issuance fails closed before cached replay or those authority reads, so it does not establish membership or grant validation. A character becomes mandatory before connect-token issuance and `PLAY`; explicit text `JOIN` and the complete first-party path remain unavailable. A connect token, when issued under the target contract, carries a short-lived discovery snapshot for edge admission; it does not bypass `CHARS` or turn stale character evidence into gameplay authority. Every target connect-token issuance and `LOGIN` -> `PLAY` path uses the canonical admission checks in [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary). This document retains only the transport consequence: the bridge forwards the protocol in order and does not create or restore membership. @@ -56,18 +56,18 @@ For public-production repair, clients follow the canonical [Authentication membe Game Session translates admission outcomes into the shared `ERROR ` form on the established gameplay protocol. This inventory owns the canonical `PLAY` precedence; it is not an inventory of every character or protocol-stage error. All listed admission outcomes preserve the authenticated pre-`PLAY` session and create no gameplay binding. -The precedence and error rows below are the normative target inventory. Current runtime mapping is narrower: an eligible public-production response with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED`; the latter cannot be classified specifically as `INACTIVE`, and explicit `JOIN` remains unavailable while explicit `JOIN` is unimplemented. Current text `PLAY` uses `WORLD_ACCESS_DENIED` only for missing or non-admitting membership on a non-public target (private/playtest); an eligible public-production request remains `JOIN_REQUIRED`. The separate Account connect-token endpoint currently returns `AUTH_UNAVAILABLE` before membership checks; target membership-dependent issuance outcomes are not current behavior. `CONNECT_TOKEN_REJECTED` is an Account/Gateway endpoint or pre-WebSocket handshake outcome and is never translated by the bridge into the client-level public-production `JOIN_REQUIRED` result. `JOIN_REQUIRED` is emitted only by the authenticated gameplay admission path after public-production target/policy and membership evaluation; it is not a synonym for endpoint rejection. The target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` row below is a `PLAY` outcome and must not be inferred from current Account endpoint behavior. +The precedence and error rows below are the normative target inventory. Current text `PLAY` evaluates fresh entitlement before membership/grant and later actor/binding checks, and consumes Account-emitted lifecycle and generation. It returns public `JOIN_REQUIRED` only for eligible missing or `INACTIVE` membership after joining policy permits repair; a closed policy denies that repair, not an existing `ACTIVE` member by itself. For private/playtest targets, current membership denial is `NON_PUBLIC_ENROLLMENT_REQUIRED`, denied grant is `REALM_ACCESS_DENIED`, and unsafe or unavailable authority is `AUTH_UNAVAILABLE`. Explicit text `JOIN` remains unavailable. Current connect-token issuance returns `AUTH_UNAVAILABLE` before cached replay or admission-authority reads and does not establish current membership/grant validation. Endpoint and text-protocol errors remain distinct; see [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary) and [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for their owners. -Admission precedence is deterministic and evaluated in stages: first classify current routing/pointer/catalog evidence (`ADMISSION_POINTER_UNAVAILABLE` for reachable incomplete, malformed, ambiguous, stale, or otherwise invalid evidence; `AUTH_UNAVAILABLE` for an unreachable or timed-out Account or routing authority; `REALM_UNAVAILABLE` for a complete `CLOSED` pointer); then evaluate verified connect scope (`CONNECT_SCOPE_MISMATCH`). Every admission then evaluates the applicable fresh tenant runtime entitlement. Public production additionally evaluates its enrollment policy, while private/playtest requires existing caller-bound `ACTIVE` membership and the exact current Account-owned realm grant without consuming `allowPublicJoin`. The remaining membership and authority outcomes follow [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary). A routing or pointer failure masks later results; a scope mismatch masks later results; and an entitlement outage or authoritative public denial masks public `JOIN_REQUIRED`. The local bridge does not create or restore membership. +Admission precedence is deterministic and evaluated in stages: first classify current routing/pointer/catalog evidence (`ADMISSION_POINTER_UNAVAILABLE` for reachable incomplete, malformed, ambiguous, stale, or otherwise invalid evidence; `AUTH_UNAVAILABLE` for an unreachable or timed-out Account or routing authority; `REALM_UNAVAILABLE` for a complete `CLOSED` pointer); then evaluate verified connect scope (`CONNECT_SCOPE_MISMATCH`). Every admission then evaluates the applicable fresh tenant runtime entitlement. For public production, `allowPublicJoin` is an enrollment gate only when missing or `INACTIVE` membership requires a join/repair; an existing `ACTIVE` member is not denied solely because public joining is closed, but must still pass every other fresh admission gate. Private/playtest requires existing caller-bound `ACTIVE` membership and the exact current Account-owned realm grant without consuming `allowPublicJoin`. The remaining membership and authority outcomes follow [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary). A routing or pointer failure masks later results; a scope mismatch masks later results; and an entitlement outage or authoritative public denial masks `JOIN_REQUIRED` for missing or `INACTIVE` membership. The local bridge does not create or restore membership. - `ADMISSION_POINTER_UNAVAILABLE` - Reachable catalog/pointer evidence is missing, malformed, ambiguous, stale, or otherwise contract-invalid. Preserve authentication, create no binding, rerun discovery or reconciliation, and retry only with fresh routing evidence. An unreachable or timed-out Account or routing authority is `AUTH_UNAVAILABLE`, not this code. - `REALM_UNAVAILABLE` - The resolved realm pointer is complete and `CLOSED`. Preserve authentication, create no binding, and wait for a fresh authoritative availability result rather than fast-looping a retry. - `CONNECT_SCOPE_MISMATCH` - For token-backed `/ws/game/**` admission, the verified connect scope no longer matches the server-resolved target. Preserve authentication, discard the entire discovery snapshot and all derived connect-token metadata including `catalogRevision`, then rediscover, request a fresh token, and use a new socket before retrying `PLAY`. - `ENTITLEMENT_UNAVAILABLE` - Fresh entitlement authority cannot be established for `PLAY` or the join/admission decision. Preserve authentication, create no gameplay binding or new membership, and retry with bounded backoff; last-known-good entitlement may supply input only for unchanged public-production binding continuity during an entitlement-only outage after the other resume predicates pass. It never authorizes fresh admission, private/playtest admission, `JoinPublicProductionMembership`, membership creation/restoration, or an expanded binding. This is distinct from `AUTH_UNAVAILABLE`, which covers unavailable membership, grant, registry, or other required non-routing, non-entitlement authority. - `TENANT_BILLING_BLOCKED` - Account has authoritatively denied the tenant for billing. Preserve authentication and the lobby/session, create no binding, and keep billing-safe operations available unless separately denied; do not use this code when entitlement authority is unavailable. -- `PUBLIC_PRODUCTION_ADMISSION_DENIED` - Current Account entitlement, including `allowPublicJoin=false`, or other authoritative public-production admission rules deny first entry for a nonbilling reason. Preserve authentication and membership state, create no binding, do not create or restore membership, present a nonbilling admission denial, and do not present billing recovery or retry automatically until the policy/target changes. -- `WORLD_ACCESS_DENIED` - Reachable authoritative world/tenant policy denies gameplay for the resolved target for a reason other than missing or `INACTIVE` public-production membership. Preserve authentication, create no binding, and do not use this outcome when the canonical public membership predicate is false; that case is `JOIN_REQUIRED` after the earlier precedence gates. -- `JOIN_REQUIRED` - Current public-production membership is missing or `INACTIVE` in the target-only Authentication flow. Preserve authentication and follow [Authentication](./system-architecture-authentication.md#login-and-session-flow) for the explicit `JOIN` or `Join & Play` action; current text reconnect instead stops with non-actionable `JOIN_REQUIRED` and performs no membership mutation because explicit `JOIN` is unavailable. Private/playtest membership or grant failure is not a public join fallback. +- `PUBLIC_PRODUCTION_ADMISSION_DENIED` - Current Account entitlement, including `allowPublicJoin=false`, denies a required public-production join/repair for missing or `INACTIVE` membership, or another authoritative public-production admission rule denies entry for a nonbilling reason. Preserve authentication and membership state, create no binding, do not create or restore membership, present a nonbilling admission denial, and do not present billing recovery or retry automatically until the policy/target changes. An existing `ACTIVE` member is not denied solely because `allowPublicJoin=false`; independent current admission rules still apply. +- `WORLD_ACCESS_DENIED` - Reachable authoritative world/tenant policy denies gameplay for the resolved target for a reason other than missing or `INACTIVE` public-production membership. Preserve authentication, create no binding, and do not use this outcome for missing or `INACTIVE` public-production membership. That case is `JOIN_REQUIRED` when fresh policy permits repair, and `PUBLIC_PRODUCTION_ADMISSION_DENIED` otherwise, after the earlier precedence gates. +- `JOIN_REQUIRED` - Current public-production membership is missing or `INACTIVE` in the target-only Authentication flow, and fresh public-production target and enrollment checks permit the explicit membership transition. Preserve authentication and follow [Authentication](./system-architecture-authentication.md#login-and-session-flow) for the explicit `JOIN` or `Join & Play` action; current text reconnect instead stops with non-actionable `JOIN_REQUIRED` and performs no membership mutation because explicit `JOIN` is unavailable. An existing `ACTIVE` member does not require `JOIN`; private/playtest membership or grant failure is not a public join fallback. - `NON_PUBLIC_ENROLLMENT_REQUIRED` - A private, playtest, or other non-public target has missing or non-`ACTIVE` caller membership. Preserve authentication, create no binding, present the stable non-public enrollment/membership requirement, and do not offer public `JOIN` or automatically retry. This is distinct from `REALM_ACCESS_DENIED` for a missing/revoked/expired grant and from `AUTH_UNAVAILABLE` for an authority outage. - `REALM_ACCESS_DENIED` - A private, playtest, or other non-public target lacks the current Account-owned realm-access grant. Preserve authentication, create no binding, present grant/access guidance, and do not treat the result as a membership-enrollment or authority-outage condition. - `AUTH_UNAVAILABLE` - A required current Account or routing authority, including membership, grant, registry, or realm-routing authority, is unreachable or times out. Preserve authentication, create no gameplay binding, and retry the affected admission with bounded backoff; unavailable authority cannot be interpreted as missing/`INACTIVE` membership and cached authority cannot authorize it. Reachable stale, regressed, malformed, revoked, or mismatched evidence is the applicable denial or revocation outcome; reachable invalid pointer evidence is `ADMISSION_POINTER_UNAVAILABLE`, and entitlement authority failures use `ENTITLEMENT_UNAVAILABLE` instead. @@ -82,7 +82,7 @@ Admission precedence is deterministic and evaluated in stages: first classify cu Direct text/Telnet clients must issue fresh anonymous `WORLDS` before credential-bearing `LOGIN`, then follow the authenticated `REALMS`-to-`JOIN` procedure in [Authentication](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). The bridge carries the resulting text flow and does not create or restore membership; Game Session retains pending JOIN transport state under the contract below. Reachable invalid or stale pointer evidence is `ADMISSION_POINTER_UNAVAILABLE`; an unreachable or timed-out Account or routing authority is `AUTH_UNAVAILABLE`; a complete `CLOSED` realm remains `REALM_UNAVAILABLE`. Direct text/Telnet reconnect is a fresh transport and discovery path described in [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour). The proxy does not reuse a browser/WebSocket bootstrap snapshot or prior transport-local scope. Current proxy routing still bootstraps a hidden default and does not enforce `WORLDS` as a prerequisite; explicit-join and membership-reread gaps remain those recorded in [Authentication](./system-architecture-authentication.md#implementation-status). -Target private/playtest reconnect does not use public `JOIN`; missing or non-`ACTIVE` membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`, and a missing or invalid grant is `REALM_ACCESS_DENIED`. Current text `PLAY` retains `WORLD_ACCESS_DENIED` only for missing or non-admitting membership on these non-public (private/playtest) targets; an eligible public-production request remains `JOIN_REQUIRED`. It also requires the current realm grant, while connect-token grant validation remains implementation drift. The separate current Account connect-token mappings are recorded in the implementation status above and are not text-protocol outcomes. +Target private/playtest reconnect does not use public `JOIN`; missing or non-`ACTIVE` membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`, and a missing or invalid grant is `REALM_ACCESS_DENIED`. Current text `PLAY` consumes lifecycle/generation and checks the applicable grant; its private membership and grant outcomes remain `NON_PUBLIC_ENROLLMENT_REQUIRED` and `REALM_ACCESS_DENIED`, with `AUTH_UNAVAILABLE` for unsafe or unavailable authority. Current connect-token issuance fails with `AUTH_UNAVAILABLE` before cached replay or admission-authority reads, so its grant validation remains unavailable. Public-production `JOIN_REQUIRED` applies only to eligible missing or `INACTIVE` membership after fresh joining policy permits repair; existing `ACTIVE` membership is not denied solely by `allowPublicJoin=false`. The separate Account connect-token failure is not a text-protocol outcome. A retained-edge upstream rebind is not a reconnect from the client's perspective. Gateway and the proxy may rebind the established edge to a replacement Game Session owner without repeating `LOGIN`, `JOIN`, or `PLAY`; unchanged public-production binding continuity may use bounded last-known-good entitlement only during an entitlement-only outage after current Account membership, routing, public policy, revocation, and resume-lease checks pass. This exception does not change the strict fresh-entitlement rules for a fresh gameplay binding/new admission, private/playtest admission, or a client-facing edge disconnect; an exact same-binding reconnect on a new transport does not receive this retained-edge exception and must use fresh admission rules. @@ -236,7 +236,7 @@ Backpressure and slow-client handling are split across layers so that the platfo - Game Session provides **domain-level backpressure**. For gameplay WebSocket sessions, it applies a per-session outbound queue limit and send-timeout budget on its side of the connection. If either is exceeded (for example because a client has stopped reading or a downstream hop between Game Session and the gateway is persistently slow), Game Session closes the session with an explicit close reason instead of allowing the queue to grow without bound or dropping frames while pretending the connection is healthy. - For inbound overload (for example, a misbehaving client sending commands far beyond expected rates), Game Session either rejects excess commands with visible error messages or terminates the session after sustained abuse; it does not accept and then silently discard gameplay input. Domain-level backpressure and abuse closures are surfaced via metrics such as `gamesession.connection.closed{reason="backpressure"|"rate_limit"}` and command‑level error counters. - **Client expectations** -- When WebSocket connections close due to slow-client behavior, abuse, network issues, or backend unavailability, only first-party token-backed WebSocket clients may use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate). The bridge forwards fresh discovery, token issuance, socket reconnect, bare `LOGIN`, and `PLAY` in that owner-defined order; it does not authorize the shortcut. Current browser/mobile clients have only partial bootstrap/connect-token surfaces and explicit `Join & Play` remains unavailable, so an eligible public-production membership that is missing (`membershipExists=false`) or existing but non-admitting (`gameplayAdmissionAllowed=false`) remains non-actionable `JOIN_REQUIRED` with no mutation; the latter cannot be classified specifically as `INACTIVE`; an existing non-admitting response cannot be classified as `INACTIVE` by the live adapter. In the target, where public joining policy permits repair, those clients complete HTTP `Join & Play` for missing or `INACTIVE` membership before any fresh connect-token issuance, socket reconnect, bare `LOGIN`, or `PLAY`, or rerun character discovery/creation when the character is invalid before those later steps. Credential-bearing text clients follow [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) and the Authentication-owned discovery/JOIN ordering; current text clients stop with the same non-actionable `JOIN_REQUIRED` fallback when repair is required. Game Session’s Redis-backed state determines whether gameplay resumes or starts fresh, per [Reconnection Strategy](./system-architecture-reconnection.md). +- When WebSocket connections close due to slow-client behavior, abuse, network issues, or backend unavailability, only first-party token-backed WebSocket clients may use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate). The bridge forwards fresh discovery, token issuance, socket reconnect, bare `LOGIN`, and `PLAY` in that owner-defined order; it does not authorize the shortcut. Current browser/mobile admission remains incomplete: connect-token issuance fails with `AUTH_UNAVAILABLE` before cached replay or admission reads, and explicit `Join & Play` is unavailable. Current text `PLAY` distinguishes emitted lifecycle states and returns non-actionable `JOIN_REQUIRED` only for eligible missing or `INACTIVE` public membership after the enrollment policy permits repair; it never creates membership or treats an active non-admitting response as inactive. In the target, where public joining policy permits repair, those clients complete HTTP `Join & Play` for missing or `INACTIVE` membership before any fresh connect-token issuance, socket reconnect, bare `LOGIN`, or `PLAY`, or rerun character discovery/creation when the character is invalid before those later steps. Credential-bearing text clients follow [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) and the Authentication-owned discovery/JOIN ordering; current text clients stop with the same non-actionable `JOIN_REQUIRED` fallback when repair is required. Game Session’s Redis-backed state determines whether gameplay resumes or starts fresh, per [Reconnection Strategy](./system-architecture-reconnection.md). This model favors **clear closures over silent drops** when a client cannot keep up and provides enough metrics at each layer for operators to identify whether the TCP Proxy, Gateway, or Game Session is enforcing backpressure in a given incident. diff --git a/design/architecture/system-architecture-reconnection.md b/design/architecture/system-architecture-reconnection.md index 152a8793c8..221df3a0b0 100644 --- a/design/architecture/system-architecture-reconnection.md +++ b/design/architecture/system-architecture-reconnection.md @@ -10,8 +10,8 @@ Proof and check selection follows [Validation and Runtime Proof](../developer-wo - **Session takeover and resume** – Game Session emits `gamesession.session.takeover` and `gamesession.session.resume` counters and rebinds Redis tick/command queues on reconnect/takeover. The target owner uniqueness key is `{tenantId, playableStateNamespaceId, characterId}` with atomic monotonic `bindingGeneration`; the current per-instance uniqueness key remains an implementation gap. Same-character target takeover fences further source input, preserves the identity of already-admitted source work, and switches the binding by CAS before target commands are admitted. Other source sessions follow the bounded drain in [ADR 0027](./decisions/adr-0027-single-realm-admission-target.md). See [Session Behavior](./system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02) for the owner contract. - **Replacement-state continuity** – [ADR 0122](./decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) adds a durable `playableStateNamespaceId` to the replacement/reconnect context without making `gameInstanceId` durable identity. Target reconnect and takeover use the exact controller key `{tenantId, playableStateNamespaceId, characterId}` with an atomic monotonic `bindingGeneration` CAS; server-derived `playableStateScope` remains binding context. They still require the namespace-bound active admission pointer and fresh active-instance authorization when replacing a runtime, reject stale/old-instance bindings, and preserve durable character state across replacement. Pointer validation is a replacement admission consequence, not a requirement for every gameplay command to reread the pointer. The pointer and binding generation provide the fence; replacement does not invent a second lease or identity or revoke every source session. [ADR 0123](./decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) keeps lifecycle state/epoch authoritative in the owner database while Temporal coordinates cleanup; existing restart/reconnect proof does not establish these replacement guarantees. -- **Telnet and WebSocket parity** – The target shared gameplay authentication and reconnect flow is owned by [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Direct text/Telnet starts with fresh `WORLDS` discovery before credential-bearing `LOGIN`, while first-party WebSocket starts with `POST /auth/player-bootstrap` and `/auth/bootstrap/*` discovery. Current Account connect-token issuance fails closed with `AUTH_UNAVAILABLE` before membership, entitlement, pointer, or replay work; see [Account runtime status](./microservices/account-service/runtime-and-data.md). Current text `PLAY` consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, but not the Account producer’s emitted `membershipLifecycleState` or independent `membershipAuthorityGeneration`. Its boolean admission predicate does not establish the target `ACTIVE` lifecycle requirement; missing or non-admitting public-production membership can produce non-actionable `JOIN_REQUIRED` before complete target ordering is enforced. Missing or non-admitting membership for a non-public target remains `WORLD_ACCESS_DENIED`. Target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` is not current behavior. Explicit `JOIN`/`Join & Play` and the required connect-token membership-authority/version rereads remain unimplemented/proof gaps. First-party WebSocket clients must obtain a fresh connect token before opening `/ws/game/**`. -- **Runtime authority checks** – `PLAY` now performs a first-pass runtime membership and tenant-entitlement check before fresh entry or resume/takeover. This closes the earlier gap where reconnect semantics relied only on Redis gameplay identity plus a fresh `LOGIN`. +- **Telnet and WebSocket parity** – The target shared gameplay authentication and reconnect flow is owned by [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Direct text/Telnet starts with fresh `WORLDS` discovery before credential-bearing `LOGIN`, while first-party WebSocket starts with `POST /auth/player-bootstrap` and `/auth/bootstrap/*` discovery. Current text `PLAY` consumes Account-emitted lifecycle and authority generation, evaluates fresh entitlement before membership/grant, and reaches actor/binding checks only after those gates pass. Public `JOIN_REQUIRED` applies to eligible missing or `INACTIVE` membership after joining policy permits repair; private membership and denied-grant outcomes are `NON_PUBLIC_ENROLLMENT_REQUIRED` and `REALM_ACCESS_DENIED`. Current connect-token issuance returns `AUTH_UNAVAILABLE` before cached replay or membership, entitlement, grant, and routing-authority reads. Explicit `JOIN`/`Join & Play` remains unavailable, and connect-token membership/version revalidation remains a gap. First-party WebSocket clients need a current token before opening `/ws/game/**`, but the issuance path is not currently successful. +- **Runtime authority checks** – Current text `PLAY` evaluates fresh tenant entitlement before membership and applicable grant checks, consumes the Account lifecycle/generation evidence, and performs actor/binding checks only after admission gates pass. Current connect-token issuance fails closed before cached replay and admission-authority reads; this is not proof of current membership/grant validation or a complete reconnect authority snapshot. - **Continuity configuration drift** – The target continuity policy caps `FIREMUD_AUTH_SESSION_EXPIRATION_MS` at five minutes independently of JWT lifetime. Current Game Session code still defaults this setting to one hour and does not enforce the target cap. - **Remaining work** – Ordered `resume_transcript_entry` persistence is live, but convergence on the complete bounded semantic recent-context contract remains partial: namespace migration to `{tenantId, playableStateNamespaceId, characterId}`, strict `hardMax` accounting for complete envelopes, and oversize omission/marker behavior remain unproved. Redis is a best-effort hot cache. Current WebSocket reconnect suppresses retained private-context presentation rather than retrieving or sending screen-buffer entries; rows remain stored while durable episode/generation eligibility is unqualified. It obtains a fresh authoritative `LOOK` when reconnect redraw is recommended or the exact mode is `first_party_web`, and emits a reconnect prompt only when both effective reconnect-prompt settings are enabled. The target reconnect sequence still renders eligible retained context after authorization, then obtains fresh `LOOK` and emits exactly one reconnect prompt when both settings are enabled (zero when either is disabled). Admin-driven forced session transfers remain planned future steps. FireMUD does not replay client input, transport bytes, or frames after edge loss; an in-flight command may be lost when it was not durably admitted, while durably admitted work remains tracked under its existing identity and requires ordinary reconciliation. Admission alone guarantees neither execution nor commit, and the client never recreates the input. Gateway upstream rebind and focused downstream-worker restart proof exist, but the complete authenticated real-Game-Session replacement sequence, lifecycle classification, presence convergence, authority continuation, elapsed-time bounds, and stalled-input behavior still require implementation and proof before ADR 0013's availability target can be claimed as complete. @@ -79,11 +79,11 @@ A retained-edge upstream rebind, including a qualifying hidden Game Session rest Reconnection uses two distinct client flows: - **Credential-bearing text lobby flow** – Telnet and other non-WebSocket text clients open a fresh TCP connection, perform public `WORLDS` discovery, then send `LOGIN ` / `LOGON ` or the applicable email-code `LOGIN` / `LOGON` forms. They then perform authenticated `REALMS `. For a public-production target, the Authentication-owned repair evaluates the applicable fresh entitlement before its target-only `JOIN` procedure; ordering and scope handling follow [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Direct-text REALMS-to-JOIN scope](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). Current text reconnect instead stops with non-actionable `JOIN_REQUIRED` and performs no membership mutation because explicit `JOIN` is unavailable. Realm-scoped `CHARS` or character creation is conditional on no valid selected character already being resolved, followed by `PLAY`. This flow does not use HTTP bootstrap, browser discovery snapshots, or connect tokens; authenticated `REALMS` supplies the text-flow scope that Game Session retains for the current transport. -- **Target first-party WebSocket flow** – The client reruns HTTP `player-bootstrap` and discovery, must evaluate fresh selected-target catalog/pointer evidence and the applicable fresh Account entitlement before completing `Join & Play` when public-production membership is missing or `INACTIVE`, performs realm-scoped character selection or creation, requests a fresh HTTP connect token, opens `/ws/game/**`, sends bare `LOGIN` using the verified bootstrap/connect context, and completes `PLAY`. `Join & Play` therefore precedes connect-token issuance, socket open, bare `LOGIN`, and `PLAY`; the explicit join endpoint remains unimplemented in the current runtime. A returning player may skip `Join & Play` only under the [canonical first-party reconnect-shortcut gate](#canonical-first-party-reconnect-shortcut-gate). A denied policy returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, preserves bootstrap authentication and membership state, creates no binding, and stops before character repair, token issuance, socket admission, bare `LOGIN`, or `PLAY`. A valid current character is additionally required before connect-token issuance or `PLAY`; otherwise the player proceeds through realm-scoped discovery or creation. Bare `LOGIN` never prompts for or replays credentials. +- **Target first-party WebSocket flow** – The client reruns HTTP `player-bootstrap` and discovery, must evaluate fresh selected-target catalog/pointer evidence and the applicable fresh Account entitlement before completing `Join & Play` when public-production membership is missing or `INACTIVE`, performs realm-scoped character selection or creation, requests a fresh HTTP connect token, opens `/ws/game/**`, sends bare `LOGIN` using the verified bootstrap/connect context, and completes `PLAY`. `Join & Play` therefore precedes connect-token issuance, socket open, bare `LOGIN`, and `PLAY`; Account implements the local `POST /auth/bootstrap/join` controller and membership operation, but Gateway blocks its public exposure and the complete `Join & Play` flow remains unavailable; see [Account API contracts](./microservices/account-service/api-contracts.md). A returning player may skip `Join & Play` only under the [canonical first-party reconnect-shortcut gate](#canonical-first-party-reconnect-shortcut-gate). If the required join/repair is denied by enrollment policy, the outcome is `PUBLIC_PRODUCTION_ADMISSION_DENIED`; it preserves bootstrap authentication and membership state, creates no binding, and stops before character repair, token issuance, socket admission, bare `LOGIN`, or `PLAY`. An existing `ACTIVE` member is not denied solely because `allowPublicJoin=false`, but must pass every other fresh admission gate. A valid current character is additionally required before connect-token issuance or `PLAY`; otherwise the player proceeds through realm-scoped discovery or creation. Bare `LOGIN` never prompts for or replays credentials. Text clients may use the `LOGIN` -> `PLAY` compatibility shortcut only after the fresh target-specific checks defined by [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary) pass. The shortcut may omit `JOIN` only for an existing `ACTIVE` member and may omit a separate `CHARS` round-trip only when one valid current character is resolved; it never reuses a first-party browser/WebSocket discovery snapshot. The text-flow scope is separate transport-local state from that browser snapshot, and a new transport obtains a new scope through `REALMS`. First-party WebSocket clients rerun bootstrap/discovery and obtain a fresh connect token before the new handshake. Gameplay commands are not admitted before `PLAY`, and Telnet attach hints remain advisory hidden MCP metadata only. -Private/playtest reconnect admission follows the [Authentication contract](./system-architecture-authentication.md#login-and-session-flow). Current non-public membership/admission denial from the available `membershipExists` and `gameplayAdmissionAllowed` fields remains `WORLD_ACCESS_DENIED`; current text `PLAY` also checks the current realm grant, while current connect-token grant validation remains incomplete. Target private/playtest reconnect requires the applicable fresh tenant runtime entitlement, existing caller-bound `ACTIVE` membership, and the exact current Account-owned realm grant; it does not consume the public-production enrollment predicate `allowPublicJoin`. The bounded last-known-good entitlement exception in [ADR 0028](./decisions/adr-0028-differentiated-entitlement-freshness.md#bounded-continuity-and-recovery) is limited to unchanged public-production binding continuity during an entitlement-only outage. Private/playtest reconnect therefore requires fresh entitlement and remains `ENTITLEMENT_UNAVAILABLE` when that evaluation is unavailable. Fresh entitlement also remains mandatory for new joins, membership creation, and `INACTIVE` restoration; a changed realm target or fresh gameplay binding remains strict. It also requires exact routing and one fresh atomic membership snapshot supplying `membershipLifecycleState`, `membershipAuthorityGeneration`, and independent `membershipVersion`; reachable invalid or stale pointer evidence is `ADMISSION_POINTER_UNAVAILABLE`, while an unreachable or timed-out Account or routing authority is `AUTH_UNAVAILABLE`. The target-only membership outcome is `NON_PUBLIC_ENROLLMENT_REQUIRED`, distinct from public `JOIN_REQUIRED`; target character discovery or allowed realm-local character creation follows only after `ACTIVE` membership and the current realm grant, with an invalid or missing grant returning `REALM_ACCESS_DENIED`. +Private/playtest reconnect admission follows the [Authentication contract](./system-architecture-authentication.md#login-and-session-flow). Current text `PLAY` consumes lifecycle and generation and checks fresh entitlement, membership, and the current realm grant; missing or known non-`ACTIVE` membership returns `NON_PUBLIC_ENROLLMENT_REQUIRED`, denied grant returns `REALM_ACCESS_DENIED`, and unsafe or unavailable authority returns `AUTH_UNAVAILABLE`. Connect-token issuance fails with `AUTH_UNAVAILABLE` before cached replay or admission-authority reads and does not currently validate membership or grant. Target private/playtest reconnect requires the applicable fresh tenant runtime entitlement, existing caller-bound `ACTIVE` membership, and the exact current Account-owned realm grant; it does not consume the public-production enrollment predicate `allowPublicJoin`. The bounded last-known-good entitlement exception in [ADR 0028](./decisions/adr-0028-differentiated-entitlement-freshness.md#bounded-continuity-and-recovery) is limited to unchanged public-production binding continuity during an entitlement-only outage. Private/playtest reconnect therefore requires fresh entitlement and remains `ENTITLEMENT_UNAVAILABLE` when that evaluation is unavailable. Fresh entitlement also remains mandatory for new joins, membership creation, and `INACTIVE` restoration; a changed realm target or fresh gameplay binding remains strict. Full caller-target/atomic authority, grant lifecycle/expiry, `allowNewGameplayBindings`, lease commit, and genuine custody/registration remain absent or held; see [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#capability-status). A client must not infer current membership or target identity from a stale Redis binding, cached tenant/realm fields, or an old `connectScopeId` after `CONNECT_SCOPE_MISMATCH`. For direct text, Game Session may use only the scope retained from the current authenticated `REALMS` exchange; it must not recreate that scope or authority from a stale selector after transport loss or scope failure. @@ -211,14 +211,14 @@ FireMUD treats actual edge reconnection as an explicit **client-visible recovery - `policy_pressure_retriable` (for example HTTP `429`) – retry with slower backoff and strict caps. - `policy_violation_non_retriable` (for example sustained abuse or malformed protocol outcomes) – every top-level `1008/policy_violation` close maps to this client class by default: stop auto-retry or switch to very long backoff and surface corrective action to the user. Diagnostic subreasons, including `edge_backpressure`, never make that top-level class retriable and do not change lifecycle or retry semantics. The sole documented exception is when the established protocol first emits `ERROR CONNECT_SCOPE_MISMATCH` and then closes `1008/policy_violation`; recovery is retriable, `CONNECT_SCOPE_MISMATCH` is not a close subreason, and the client must discard the stale scope, rerun discovery/token issuance, and open a new socket. Follow [Post-upgrade Game Session admission failures](#post-upgrade-game-session-admission-failures) for that flow. - **Scope of reconnection** -- Telnet clients reconnect by establishing a new TCP connection to the TCP Proxy Service and following the fresh-discovery and authenticated text procedure in [Authentication](./system-architecture-authentication.md#login-and-session-flow). Current text clients stop with non-actionable `JOIN_REQUIRED` and no membership mutation when an otherwise eligible public-production request reports `membershipExists=false` or `gameplayAdmissionAllowed=false` and target-only public repair would be required. Direct text reconnect obtains a new transport-local scope from authenticated `REALMS`; it has no browser/WebSocket connect-token snapshot to reuse and must not select or attest a target from stale prior fields. `CHARS` or allowed character creation is conditional on no valid selected character being resolved. If smart-client attach hints return later, they should be re-sent as hidden MCP metadata on the new connection. +- Telnet clients reconnect by establishing a new TCP connection to the TCP Proxy Service and following the fresh-discovery and authenticated text procedure in [Authentication](./system-architecture-authentication.md#login-and-session-flow). Current text clients stop with non-actionable `JOIN_REQUIRED` and no membership mutation when the [current public-repair checks](./system-architecture-authentication.md#play-current-and-target-failure-boundaries) require explicit `JOIN`; lifecycle and policy evidence determine whether repair is eligible. Direct text reconnect obtains a new transport-local scope from authenticated `REALMS`; it has no browser/WebSocket connect-token snapshot to reuse and must not select or attest a target from stale prior fields. `CHARS` or allowed character creation is conditional on no valid selected character being resolved. If smart-client attach hints return later, they should be re-sent as hidden MCP metadata on the new connection. - Web clients reconnect by rerunning bootstrap discovery and, in the target when required, `Join & Play` plus realm-scoped `CHARS`/allowed character creation before obtaining a fresh connect token; they then open a new WebSocket to `/ws/game/**`, issue bare `LOGIN`, and issue `PLAY`. Current first-party browser/mobile bootstrap/connect-token surfaces are partial and the complete flow, including `Join & Play`, remains target-only. The target `Join & Play` and any required character repair therefore precede connect-token issuance and bare `LOGIN`. The token-backed WebSocket flow uses the fresh, short-lived discovery snapshot only for its selected edge target and discards it on expiry or scope mismatch. A valid snapshot is not a substitute for current `ACTIVE` membership or a valid character, and an invalid character must be repaired before token issuance rather than discovered after the socket opens. Web clients must not assume that any prior MCP or hidden smart-client attach metadata has survived, as described in [Mud Client Protocol (MCP) Support](./system-architecture-mud-client-protocol.md#reconnection--session-recovery). ### Canonical first-party reconnect-shortcut gate A returning first-party browser/WebSocket player may skip `Join & Play` only when all of the following are established before connect-token issuance: fresh same-target entitlement, current authority, one fresh atomic Account membership snapshot confirming `membershipLifecycleState=ACTIVE` with independent `membershipAuthorityGeneration` and `membershipVersion`, the exact current Account-owned realm grant where applicable, an unexpired complete discovery snapshot, and one valid current character for the selected target. If the checks occur at `POST /auth/connect-token`, that endpoint must complete them before issuing the token; discovery state and cached authority are not substitutes. An unavailable exact realm grant fails closed for private/playtest admission. -For clarity, Telnet clients do not receive hidden recovery after their TCP socket or TCP Proxy-to-Gateway edge bridge is lost. Even if the proxy-wide admission circuit later returns to closed after such an edge outage, the affected Telnet client must reconnect on a fresh TCP socket and follow the applicable Authentication-owned `WORLDS`/credential-bearing `LOGIN`/authenticated `REALMS`/target-only conditional `JOIN`/conditional `CHARS` or character-creation/`PLAY` flow; current text stops with non-actionable `JOIN_REQUIRED` and no membership mutation only when an otherwise eligible public-production request reports `membershipExists=false` or `gameplayAdmissionAllowed=false` and explicit `JOIN` is required. This does not prevent Gateway from retaining a still-established proxy bridge while it performs ADR 0013's bounded rebind of its separate Game Session upstream. +For clarity, Telnet clients do not receive hidden recovery after their TCP socket or TCP Proxy-to-Gateway edge bridge is lost. Even if the proxy-wide admission circuit later returns to closed after such an edge outage, the affected Telnet client must reconnect on a fresh TCP socket and follow the applicable Authentication-owned `WORLDS`/credential-bearing `LOGIN`/authenticated `REALMS`/target-only conditional `JOIN`/conditional `CHARS` or character-creation/`PLAY` flow; current text stops with non-actionable `JOIN_REQUIRED` and no membership mutation under the [current public-repair boundary](./system-architecture-authentication.md#play-current-and-target-failure-boundaries). This does not prevent Gateway from retaining a still-established proxy bridge while it performs ADR 0013's bounded rebind of its separate Game Session upstream. Clients must also treat pre-disconnect input and output as non-resumable transport state. FireMUD does not replay client commands, raw transport bytes, prior WebSocket frames, unsent Telnet output, or partially delivered prompts onto a newly opened connection. A command durably admitted before edge loss remains tracked under its existing server-side command/effect identity and requires ordinary reconciliation; admission alone guarantees neither execution nor commit, and the client never recreates the input. Instead, after fresh `LOGIN` and `PLAY`, reconnect restores player-visible context in three distinct steps: diff --git a/design/architecture/system-architecture-session-behavior.md b/design/architecture/system-architecture-session-behavior.md index 2f2089da19..0d9202fddf 100644 --- a/design/architecture/system-architecture-session-behavior.md +++ b/design/architecture/system-architecture-session-behavior.md @@ -30,7 +30,7 @@ Retained per-sequence duplicate evidence is a separate same-snapshot carrier, no ## Implementation Status -Membership-change event delivery and generation-aware session consumption are not yet live. The current `GetTenantMembershipForRuntimeResponse` and `AccountGrpcService` producer expose `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, `evaluatedAt`, and `error`; current Game Session `PLAY` consumes only the admission booleans, version, and evaluation time, without enforcing the emitted lifecycle or independent generation. Roles, the target exact one-tenant `membershipVersion` map carrier, `authorityTuple`, `outboxCheckpoints`, Account event delivery, generation-aware consumers, same-stream reconciliation, remaining player-facing legacy mapping, and focused proof across admission/reconnect paths remain gaps. The versioned Account-owned token-registry rules and binding schema below are target state, not current runtime behavior: the current fallback uses the legacy Account session key rather than the canonical issued-token registry. Game Session must not treat the contract below as fully implemented until those fields, consumers, and proofs converge. The target Account-durable-intent-before-Gateway-marker logout ordering and final Account token-fence invalidation are also not currently proven; the current fallback is Account logout plus local cleanup and bounded expiry, not proof of complete logout. +Membership-change event delivery and event-driven generation-aware session invalidation are not yet live. The current `GetTenantMembershipForRuntimeResponse` and `AccountGrpcService` producer expose `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, `evaluatedAt`, and `error`; current Game Session text `PLAY` validates lifecycle and independent generation with the admission booleans, version, and evaluation time, after fresh entitlement evaluation and before later actor/binding checks. Roles, the target exact one-tenant `membershipVersion` map carrier, `authorityTuple`, `outboxCheckpoints`, Account event delivery, generation-aware consumers, same-stream reconciliation, remaining player-facing legacy mapping, and focused proof across admission/reconnect paths remain gaps. The versioned Account-owned token-registry rules and binding schema below are target state, not current runtime behavior: the current fallback uses the legacy Account session key rather than the canonical issued-token registry. Game Session must not treat the contract below as fully implemented until those fields, consumers, and proofs converge. The target Account-durable-intent-before-Gateway-marker logout ordering and final Account token-fence invalidation are also not currently proven; the current fallback is Account logout plus local cleanup and bounded expiry, not proof of complete logout. The current WebSocket reconnect path does not retrieve or send retained private screen-buffer/context entries; private-context presentation is temporarily suppressed while durable episode and `resumeContextGeneration` eligibility remains unqualified. The rows remain stored, so this is not deletion or proof of durable logout invalidation. When a reconnect redraw is recommended or the exact mode is `first_party_web`, reconnect obtains a fresh authoritative `LOOK`; it emits a reconnect prompt only when both effective reconnect-prompt settings are enabled. This is current implementation status, not a change to the target eligible-context sequence owned by [Reconnection](./system-architecture-reconnection.md) and [Input, Output, and Presentation](./system-architecture-input-output-and-presentation.md). diff --git a/design/developer-workflows/pr-lifecycle.md b/design/developer-workflows/pr-lifecycle.md index 3ddc008e47..eb49be81ef 100644 --- a/design/developer-workflows/pr-lifecycle.md +++ b/design/developer-workflows/pr-lifecycle.md @@ -36,7 +36,7 @@ FireMUD owns the project authority and safety requirements below. Follow the act - Re-review new functionality, changed contracts, materially broader risk, or fixes that introduce independently reviewable behavior. Direct, verified corrections need not trigger another whole-PR discovery round solely to accumulate clean results. - The configured channel controls belong to FireController and are not a quota target. Request work beyond a completed policy only for a concrete unresolved risk, coverage gap, or explicit human override. Repeated serious findings trigger focused investigation of their shared failure mechanism and appropriate proof rather than arbitrary clean-round accumulation. - Under an explicit Overseer arrangement, present the Hosted/CLI trend and a nonblocking recommendation when marginal utility is uncertain. The Overseer—not the implementing lane or controller—decides whether an additional deliberate round is justified and whether evidence is ready for the User's product-PR approval. -- A normal product-queue PR, including a mixed product and maintenance PR, is ready for User approval only after controller evidence shows zero unresolved current and outdated threads, all actionable summary-only and outside-diff findings are addressed, every open incoming route is dispositioned by the target owner, each fix is verified, every required channel has completed its policy through attributable provider results, required CI is green, and proportionate validation/runtime proof is complete. Open routes from this PR to other owners do not hold its merge readiness. An explicit human stop closes discovery only for its authorized scope; it remains a visible review limitation, not taper or merge-readiness proof. Before handoff, refresh stale title/body content and the generated marked LOC section with `python3 dev-tools/maintenance/cloc-report.py pr [--repo owner/name] --update-pr`. The section is informational, not a size gate. If tooling is unavailable, record the limitation instead of inventing counts. Zero threads or GitHub `CLEAN` alone is insufficient, and the final head must not be described as reviewed when it was not. The implementing worker reports readiness without taking merge action. Review closure, channel overrides, READY/CLEAN state, green CI, and a lane readiness handoff do not authorize any agent to merge or enable or schedule auto-merge. Only a traceable, explicit User instruction to get a specified product PR merged authorizes the designated Overseer to merge that PR after verifying the required proof. Separately authorized controller/private-website maintenance merges and closure of verified-superseded PRs remain limited to their existing scope. +- A normal product-queue PR, including a mixed product and maintenance PR, is ready for User approval only after controller evidence shows zero unresolved current and outdated threads, all actionable summary-only and outside-diff findings are addressed, every open incoming route is dispositioned by the target owner, each fix is verified, every required channel has completed its policy through attributable provider results, required CI is green, and proportionate validation/runtime proof is complete. Open routes from this PR to other owners do not hold its merge readiness. An explicit human stop closes discovery only for its authorized scope; it remains a visible review limitation, not taper or merge-readiness proof. Before handoff, update a stale title through a separate title edit. Refresh the descriptive body and generated marked LOC section with `python3 dev-tools/maintenance/cloc-report.py pr [--repo owner/name] --update-pr`; that command updates only the body. When the descriptive body also needs updating, add `--body-file /absolute/path/to/draft.md` to insert the generated LOC section into that draft and publish both through one guarded body edit. The section is informational, not a size gate. If tooling is unavailable, record the limitation instead of inventing counts. Zero threads or GitHub `CLEAN` alone is insufficient, and the final head must not be described as reviewed when it was not. The implementing worker reports readiness without taking merge action. Review closure, channel overrides, READY/CLEAN state, green CI, and a lane readiness handoff do not authorize any agent to merge or enable or schedule auto-merge. Only a traceable, explicit User instruction to get a specified product PR merged authorizes the designated Overseer to merge that PR after verifying the required proof. Separately authorized controller/private-website maintenance merges and closure of verified-superseded PRs remain limited to their existing scope. ## Change And Merge Policy diff --git a/design/developer-workflows/validation-and-runtime-proof.md b/design/developer-workflows/validation-and-runtime-proof.md index 0cdedd7ad3..aa4303a71c 100644 --- a/design/developer-workflows/validation-and-runtime-proof.md +++ b/design/developer-workflows/validation-and-runtime-proof.md @@ -4,6 +4,7 @@ Use this guide when selecting or reporting formatting, checks, documentation val ## Code And Documentation +- Java 25 is the build/test toolchain and compiler release, aligned with the production JRE major. Daemon automatic provisioning has the [platform boundary below](#daemon-jdk-artifact-maintenance); compiler and focused-test proof do not replace fresh-image/runtime qualification. Java 25 bytecode is not a Java 21 compatibility target. - The lane orchestrator selects required proof by changed boundary. Use focused affected formatting and tests for quick feedback on an implementation or fix, and an appropriate broader integration or merge gate when contract or runtime impact requires it. Independent lanes and helper handoffs alone do not broaden proof. - Use canonical commands as relevant: `./gradlew spotlessApply` with the relevant `spotlessCheck -PfullCheck` or `spotlessJavaCheck -PfullCheck` for formatting-sensitive files; these check tasks are disabled unless `fullCheck` is enabled. Use `./gradlew ::check -PfullCheck` or `./gradlew check` for an appropriate broader gate, and the [local Gradle wrapper](#local-gradle-execution) for heavy local checks. - Do not launch separate Gradle processes concurrently when tasks may share generated-source dependencies; use one combined Gradle invocation or the canonical `dev-tools/validation/run-locked-gradle.sh` serialized path. Independent read-only checks such as script linting may still run in parallel. @@ -30,7 +31,9 @@ Confirm the logs show actual repository initialization and dependency extraction ## Daemon JDK Artifact Maintenance -[Refresh Gradle Daemon JDK](../../.github/workflows/refresh-gradle-daemon-jvm.yml) runs weekly from the default branch and can be dispatched from `develop`. Its [bounded helper](../../dev-tools/maintenance/refresh-gradle-daemon-jvm.py) enters the existing `run-locked-gradle.sh --resource-session` before snapshotting outside edits, reading daemon criteria, or querying release metadata; nested Gradle generation reuses the verified resource lease. In `--check-only` mode, the helper derives one exact approved release from the six existing daemon criteria URLs, fetches official Java 21 GA metadata for that release on each supported platform, and validates the same full release/build, platform, vendor, and immutable URL constraints before generation. Exact-release queries request Adoptium's `DEFAULT`/`DESC` ordering in deterministic zero-based pages of at most 20 records; they stop at the first exact match, treat HTTP 404 as pagination exhaustion, and fail after ten pages or exhaustion. Each response remains limited to 8 MiB. An explicit refresh without `--check-only` uses official latest-per-platform metadata and fails closed when those latest artifacts do not share one release/build; it never selects an older common release automatically. Both modes pass the six validated URLs to Gradle's native `UpdateDaemonJvm.toolchainDownloadUrls`; Gradle generates the criteria file, and the helper verifies exact Java 21/Adoptium criteria and a one-file change boundary. The outside-artifact snapshot retains tracked changes and records contents/modes for Git-enumerated untracked regular files plus targets for Git-enumerated symlinks; it refuses an unsupported special file if Git enumerates one. The check-only workflow therefore proves the committed pin during a staggered upstream rollout, while an explicit refresh waits for all platform latests to converge. Unsupported FreeBSD and generic Unix aliases are not synthesized. This maintenance path avoids Foojay's observed missing Temurin 21 metadata; the configured resolver remains available for other Gradle toolchain uses. Renovate maintains the Gradle wrapper and resolver plugin; it does not maintain the generated daemon artifact IDs. Changing `toolchainVersion` alone does not refresh JDK patch artifacts. +[Refresh Gradle Daemon JDK](../../.github/workflows/refresh-gradle-daemon-jvm.yml) runs weekly from the default branch and can be dispatched from `develop`. Its [bounded helper](../../dev-tools/maintenance/refresh-gradle-daemon-jvm.py) enters the existing `run-locked-gradle.sh --resource-session` before snapshotting outside edits, reading daemon criteria, or querying release metadata; nested Gradle generation reuses the verified resource lease. In `--check-only` mode, the helper derives one exact approved release from the five existing daemon criteria URLs, fetches official Java 25 GA metadata for that release on each supported platform, and validates the same full release/build, platform, vendor, and immutable URL constraints before generation. Exact-release queries request Adoptium's `DEFAULT`/`DESC` ordering in deterministic zero-based pages of at most 20 records; they stop at the first exact match, treat HTTP 404 as pagination exhaustion, and fail after ten pages or exhaustion. Each response remains limited to 8 MiB. An explicit refresh without `--check-only` uses official latest-per-platform metadata and fails closed when those latest artifacts do not share one release/build; it never selects an older common release automatically. Both modes require exactly Linux and macOS on x64 and AArch64 plus Windows on x64, and pass all five validated URLs to Gradle's native `UpdateDaemonJvm.toolchainDownloadUrls`; Gradle generates the criteria file, and the helper verifies exact Java 25/Adoptium criteria and a one-file change boundary. The outside-artifact snapshot retains tracked changes and records contents/modes for Git-enumerated untracked regular files plus targets for Git-enumerated symlinks; it refuses an unsupported special file if Git enumerates one. Check-only validates the committed Java 25 pin during a staggered upstream rollout, while an explicit refresh waits for all supported platform latests to converge. Unsupported FreeBSD and generic Unix aliases, missing-platform URLs, signed redirect URLs, and mixed-release substitutions are not synthesized or accepted. This maintenance path uses immutable official release artifacts rather than resolver-generated download aliases; the configured resolver remains available for other Gradle toolchain uses. Renovate maintains the Gradle wrapper and resolver plugin; it does not maintain the generated daemon artifact IDs. Changing `toolchainVersion` alone does not refresh JDK patch artifacts. + +**Platform limit:** Windows ARM (AArch64) automatic daemon provisioning is explicitly excluded because official Temurin 25 metadata lacks a matching artifact. The helper neither synthesizes that URL nor accepts it in generated criteria; adding the platform requires a matching official artifact and explicit qualification. This is an automatic-provisioning limitation, not a blanket claim that Java 25 cannot run on Windows ARM with an independently supplied compatible JDK. The [daemon criteria](../../gradle/gradle-daemon-jvm.properties) pin the five supported immutable artifacts; mocked metadata tests do not establish publisher availability or execution on all five platforms. Native generation and check-only validate the pin, while actual compilation/tests and fresh-image runtime proof establish their separately named execution boundaries. **Setup required:** install a dedicated GitHub App on this repository with only repository Contents and Pull requests write access, store its private key first in repository secret `DEPENDENCY_MAINTENANCE_APP_PRIVATE_KEY`, then set repository variable `DEPENDENCY_MAINTENANCE_APP_CLIENT_ID` to its client ID. Setting the client ID deliberately enables scheduled publication; without it the scheduled publishing job skips. A manual dispatch from `develop` still runs the setup check and fails visibly if either field is missing, and enabled scheduled publication also fails on incomplete configuration. Keep private-key material in GitHub Secrets, never in chat or source. Its ordinary `GITHUB_TOKEN` has Contents and Pull requests read access; a short-lived, current-repository-only App token is minted only after successful generation for publication. The App-backed PR events trigger the existing exact-head Validation, Security, License, CodeQL, and Smoke gates. A `GITHUB_TOKEN` publisher would suppress those ordinary events; manual CI activation is not this workflow's maintenance contract. Credential provisioning and live hosted execution remain separate setup/proof steps. A separate path-filtered pull-request job in the same workflow runs the real generator and criteria guard with read-only permissions and no App credentials or publication steps; fork PRs cannot select the publishing job. `--check-only` generates and validates the candidate artifact without remote writes and preserves existing edits outside that artifact; publication requires a clean checkout. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 05b30450cf..ca7034e3e7 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -36,3 +36,9 @@ A small inbox for unresolved agent, tooling, environment, and workflow issues; s - `2026-11-01` (Pacific/Auckland): CI watch masked a proven failure while another required gate was missing. - The shared observer retained a failed required Smoke check for #3369 while another required Validation check was absent, but returned pending rather than waking for the failure. Root inspected the actual failed image-build log and reported the discrepancy to FireController Worker; the worker confirmed the precedence defect at 12:17pm NZDT and deployed correction `edc11a7b`, retaining the counts and source guards. Natural failure wakeup is now verified: the shared observer returned the #3365/4f25 Smoke failure while Validation and CodeQL were missing, preserving the required counts. This resolved component is available for Overseer stewardship retirement; the pending state never supplied success. A separate Hosted wait exited locally cancelled before the provider finished; Root recovered the original operation without reposting. The owner trace could not identify the signal sender, so no server timeout or evidence loss is established. + +- `2026-11-01` (Pacific/Auckland): Source-built smoke leaves root-owned configuration that obstructs worktree cleanup. + - After successful smoke and independently empty container/network/volume cleanup, retiring the clean #3038 proof worktree failed with `Permission denied`: its generated `docker/config` directory was owned by root with mode `0755`. Git removed the worktree registration but left the directory on disk. Scoped ownership recovery for that generated directory allowed removal; committed source and private proof were retained. Next: have the canonical smoke path create its disposable bind-mount configuration with the invoking user's ownership, or restore ownership of only material it created during teardown. Preserve externally managed configuration and avoid broad permission changes. + +- `2026-11-01` (Pacific/Auckland): Post-merge retargeting retained stale GitHub test-merge parents on two consecutive fronts. + - After #3367 and #3368 merged, their respective successors #3368 and #3369 still exposed test merges with the previous base parent on fresh observations four minutes apart, despite a stable live `develop` tip. Normal develop-history merges preserved each file tree and complete feature patch and established a new comparison for CI; identical base trees alone did not satisfy parent identity. Both occurrences were reported to Overseer. Gameplay also discovered #3368's merge late and had already published one parent-fix carry; that separate avoidable successor wave was a sequencing error, not attributed to GitHub. Next: verify the live parent state before receiving publication and retain the two source observations on recurrence so Overseer can assess the repeated CI/reconciliation cost; do not manufacture a no-op commit or waive current-comparison proof. diff --git a/design/project-management/design-alignment/consequential-decision-inventory.md b/design/project-management/design-alignment/consequential-decision-inventory.md index 916a164cd5..4e840ecd3d 100644 --- a/design/project-management/design-alignment/consequential-decision-inventory.md +++ b/design/project-management/design-alignment/consequential-decision-inventory.md @@ -149,7 +149,7 @@ No implementation-blocking import override is active. Record an override here wi ### Packet 2: Identity, Authority, And Security -Packet 2 checklist dispositions record the human review outcome, not an inventory status. For every checked Packet 2 entry, `accepted` maps to the canonical inventory status `accepted-explicit`; `revised` maps to the same status after the revised target was accepted; `superseded` records that the reviewed key was replaced by the linked decision(s), so the linked replacement row rather than the checklist label determines the canonical inventory status. Unchecked entries have no Packet 2 disposition; their canonical inventory status remains whatever the inventory records and is not inferred from this checklist. The `AUTH-02` and `AUTH-06` targets retain explicit `JOIN`/`Join & Play`, but `POST /auth/bootstrap/join` is target-state and not implemented; current text `PLAY` and connect-token issuance require existing caller-bound membership and return canonical `JOIN_REQUIRED` for eligible missing or `INACTIVE` public-production membership, while the obsolete implicit membership-writer RPC/client/service seam has been removed. The target admission contract retains `JOIN_REQUIRED` for policy-permitted missing or `INACTIVE` membership. `WORLD_ACCESS_DENIED` is reserved for another reachable authoritative world/tenant denial and is mutually exclusive with `JOIN_REQUIRED`. A realm grant never substitutes for membership, and the connect-token membership-version plus membership-authority-generation reread remains a gap. The accepted tenant-role boundary and tenantless control-login/tenant-switching decision are target choices, not proof claims: the owning [Player Access and Session implementation tracker](../implementation-tracking/player-access-and-session.md#capability-status) records the missing tenant-scoped roles, switching controls, and implementation state, while its [Validation and Proof](../implementation-tracking/player-access-and-session.md#validation-and-proof) section records focused evidence and remaining proof gaps. +Packet 2 checklist dispositions record the human review outcome, not an inventory status. For every checked Packet 2 entry, `accepted` maps to the canonical inventory status `accepted-explicit`; `revised` maps to the same status after the revised target was accepted; `superseded` records that the reviewed key was replaced by the linked decision(s), so the linked replacement row rather than the checklist label determines the canonical inventory status. Unchecked entries have no Packet 2 disposition; their canonical inventory status remains whatever the inventory records and is not inferred from this checklist. `AUTH-02` retains explicit target `JOIN`/`Join & Play`, but text dispatch remains unavailable. Current text `PLAY` consumes Account-emitted lifecycle and authority generation after fresh entitlement evaluation; coherent membership evidence and `ACTIVE` admitting membership are required before later actor/binding checks. Public `JOIN_REQUIRED` applies only to eligible missing or `INACTIVE` public-production membership; a closed joining policy denies that repair, not an existing `ACTIVE` member's `PLAY` by itself. Private missing/non-`ACTIVE` membership and denied grant have distinct `NON_PUBLIC_ENROLLMENT_REQUIRED` and `REALM_ACCESS_DENIED` outcomes. Current connect-token issuance returns `AUTH_UNAVAILABLE` before cached replay or membership, entitlement, grant, and routing-authority reads. Full caller-target/atomic authority and its proof remain gaps: see the owning [Player Access and Session implementation tracker](../implementation-tracking/player-access-and-session.md#capability-status) and its [Validation and Proof](../implementation-tracking/player-access-and-session.md#validation-and-proof) section. Packet 2 count reconciliation: the 31 reviewed decisions are covered by the checked dispositions for ADRs 0020-0050, excluding the historical service-scan alias. The Packet 2 disposition contains exactly those 31 reviewed decisions; the alias is navigation-only and is not a checked disposition row. @@ -158,7 +158,7 @@ Packet 2 historical-alias rule: `MS-AA-TOKEN-REVOCATION` is a superseded service #### Packet 2 P0 - [x] `ID-01` — `revised` on 2026-07-18; [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [canonical identifier contract](../../architecture/system-architecture-identifier-glossary.md) -- [x] `AUTH-02` — `revised` on 2026-07-18; [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md) +- [x] `AUTH-02` — `revised` on 2026-11-01; [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md) - [x] `AUTH-03` — `accepted` on 2026-07-18; [ADR 0022](../../architecture/decisions/adr-0022-account-authority-and-gameplay-session-ownership.md) - [x] `AUTH-04` — `revised` on 2026-07-18; [ADR 0023](../../architecture/decisions/adr-0023-central-route-authorization-governance.md) - [x] `AUTH-05` — `revised` on 2026-07-19; [ADR 0024](../../architecture/decisions/adr-0024-trusted-gameplay-workload-delegation.md) @@ -386,6 +386,10 @@ Packet 2 historical-alias rule: `MS-AA-TOKEN-REVOCATION` is a superseded service - [x] `EDGE-WITHDRAWAL-01` — `accepted` on 2026-09-24; human-approved emergency cutoff despite possible service interruption; [ADR 0184](../../architecture/decisions/adr-0184-emergency-tcp-proxy-identity-withdrawal.md) - [x] `TICK-20` — `accepted` on 2026-10-04; human owner delegated the technical choice to the Overseer, who selected acceptance; [ADR 0183](../../architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) +### Post-Archive Clarification Of Existing Decision + +`AUTH-02` was first reviewed and revised on 2026-07-18. Its further narrow revision on 2026-11-01 aligns ADR 0021 with the already accepted `AUTH-06` / ADR 0025 enrollment-only rule; it clarifies no other target decision and is not blanket acceptance of unrelated changes. The User’s exact resolution was: “Keep existing members’ access; block new joins/reactivation only.” Accordingly, `allowPublicJoin=false` blocks a required public-production join or `INACTIVE` restoration; an existing `ACTIVE` member must still pass every independent current admission gate. Immutable source: Overseer call `call_f17cf625f7d549abaf2e36bb25fd38df`, message `msg_9a1ec39e854b957746daeb6546528fc3`, timestamp `2026-11-01T01:13:36Z`. + ### Allocation Notes - `EDGE-06` and `MS-GW-DYNAMIC-ROUTES` describe the same dynamic-route boundary but remain separate authoritative keys and must be reviewed together. 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 f5f7d52d2c..0fcde6bd68 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -481,7 +481,9 @@ Account connect-token issuance retains its existing bootstrap and scope authenti | `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. Current WebSocket reconnect suppresses retained private-context presentation while durable episode/generation eligibility is unqualified; rows remain stored, so this is neither deletion nor proof of logout invalidation. R1424 executed bounded suppression/redraw proof (57 WebSocket-handler units, 20 integration cases and ten LOOK cross-service cases), separately attributed in [Reconnect and Continuity](#reconnect-and-continuity); this is not a fresh current-head image result or proof of eligible-context replay. The earlier first-party post-logout replay defect is historical: current first-party `LOGIN` and `PLAY` deny before legacy effects while the genuine context consumers remain unavailable. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. See AA-2.1 for the finite namespace controller-index migration-driver prefix, its implementation and proof anchors, and the unproved physical PostgreSQL/Redis, final-image, and trusted-bootstrap/execution gates. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisMovementEffectIdempotencyService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [RedisMovementEffectIdempotencyServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java); [SessionContextSecretAndPresenceRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/SessionContextSecretAndPresenceRedisIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. The [local secret/presence containment](#session-secret-and-presence-containment) prevents new raw delegation-JWT persistence and projects legacy values without rehydration; physical retained-value cleanup remains open; scoped receiving proof is recorded at that owner. | -The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary without claiming explicit JOIN completion. Account bootstrap character discovery requires membership permitting gameplay admission without an Entity read; connect-token issuance instead returns `AUTH_UNAVAILABLE` before membership or cached-success replay. Pre-membership world and realm discovery remains available. The canonical `JOIN_REQUIRED` eligibility and ordering contract is defined in [Authentication and authorization](../../architecture/system-architecture-authentication.md#play-current-and-target-failure-boundaries). Focused service proof now covers Account-before-roster ordering, strict persisted actor selection, and the Game Session-to-Entity peer allowlist across 124 focused tests. Deployment/mTLS and fresh-image proof remain incomplete, so the targeted `PLAY` ordering work does not complete AA-2.1, explicit JOIN, or `playableSmoke`. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject any `stateScope` other than exact `SHARED` or `ISOLATED`, so malformed authority cannot silently become shared-state admission. Account-owned explicit public-production JOIN writing and operation checks are implemented locally; first-party text JOIN dispatch, lifecycle-aware inactive membership, complete grant/entitlement authority, and target admission-pointer fields remain open as recorded above. +The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary without claiming explicit JOIN completion. Account bootstrap character discovery requires membership permitting gameplay admission without an Entity read; connect-token issuance returns `AUTH_UNAVAILABLE` before cached replay or membership, entitlement, grant, and routing-authority reads. Pre-membership world and realm discovery remains available. Current text `PLAY` implements the lifecycle/generation and admission checks covered by this receiving boundary. The canonical ordering contract is defined in [Authentication and authorization](../../architecture/system-architecture-authentication.md#play-current-and-target-failure-boundaries). Focused service proof covers Account-before-roster ordering, strict persisted actor selection, and the Game Session-to-Entity peer allowlist across 124 focused tests. Deployment/mTLS and fresh-image proof remain incomplete, so this targeted `PLAY` work does not complete AA-2.1, explicit JOIN, or `playableSmoke`. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject any `stateScope` other than exact `SHARED` or `ISOLATED`, so malformed authority cannot silently become shared-state admission. Account-owned explicit public-production JOIN writing and operation checks are implemented locally; first-party text JOIN dispatch, full caller-target/atomic authority, `allowNewGameplayBindings`, grant lifecycle/expiry, and lease-commit proof remain open as recorded above. + +At receiving source `6c14229c32`, consolidated focused proof passes 572 cases across 15 unit, PostgreSQL-backed WebSocket, physical Redis and cross-service WebSocket/communication/Telnet suites, with zero failures, errors or skips, plus affected Checkstyle, formatting and canonical documentation checks. The gate includes current-parent menu/dispatch corrections; unchanged tasks may reuse qualified Gradle results. Account authority is controlled or mocked in transport fixtures, so these results do not prove full caller-target atomic authority, grant lifecycle/expiry, exact lease commit, genuine custody or public admission. Earlier focused counts overlap and are not additive. Reconnect prompt-setting precedence remains owned by [Input, Output, and Presentation](../../architecture/system-architecture-input-output-and-presentation.md#prompt-behavior); this tracker records only the current reconnect capability and proof gaps. diff --git a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md index ac7fe6dd82..cb755924e4 100644 --- a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md +++ b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md @@ -50,7 +50,7 @@ This section records implementation and proof status only. The target command, p ### Admission, Commands, and Capabilities -Current text `WORLDS` remains an optional pre-login public browse and authenticated `REALMS` discovery remains supported. Direct-text `CHARS` currently returns unavailable without calling Entity's legacy roster adapter; the supported Account bootstrap/HTTP character roster is separate. `HELP`/`PLAY` guidance no longer recommends `CHARS` or numbered roster browsing; any known-character selector guidance identifies a selection only and does not establish membership or public admission. For existing members, `LOGIN` followed by an unambiguous eligible `PLAY [character]` remains the direct gameplay-binding path. Text `PLAY` returns non-actionable `JOIN_REQUIRED` for a publicly visible public-production target when fresh membership evidence reports missing membership (`membershipExists=false`) or existing but non-admitting membership (`gameplayAdmissionAllowed=false`); the latter cannot be classified specifically as `INACTIVE`. `PlayCommandHandler` does not read `allowPublicJoin`, does not currently emit `PUBLIC_PRODUCTION_ADMISSION_DENIED` for a policy denial, and validates entitlement with `gameplayAvailable` only. Account connect-token issuance instead validates bootstrap identity and retained scope, then fails closed with `AUTH_UNAVAILABLE` before membership, entitlement, pointer, replay, or token work; [Account runtime status](../../architecture/microservices/account-service/runtime-and-data.md) owns that current behavior. Target membership-authority-generation rereads and successful issuance remain gaps. Unavailable or invalid authority remains the applicable unavailable/invalid-authority outcome. Ambiguous or inaccessible `PLAY` selections return selection-oriented or explicit bounded errors rather than low-level gameplay failures. Wrong-stage input produces guidance such as `LOGIN_REQUIRED` or `PLAY_REQUIRED`. Canonical target admission policy and error mappings remain in [Authentication and authorization](../../architecture/system-architecture-authentication.md#login-and-session-flow) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). +Current text `WORLDS` remains an optional pre-login public browse. The catalog snapshot exposes caller-free public-production realm data, but the text `REALMS` command still requires `LOGIN` under command-stage gating; authenticated private-realm discovery/retention remains unavailable. Direct-text `CHARS` returns unavailable without calling Entity’s legacy roster adapter; the supported Account bootstrap/HTTP roster is separate. `HELP`/`PLAY` guidance uses known character names rather than numbered roster browsing. Current text `PLAY` implements lifecycle/generation and private-grant validation under the [canonical PLAY outcome matrix](../../architecture/system-architecture-authentication.md#play-current-and-target-failure-boundaries). Account connect-token issuance separately validates bootstrap identity and retained scope, then returns `AUTH_UNAVAILABLE` before admission-authority reads, cached replay, or token work; [Account runtime status](../../architecture/microservices/account-service/runtime-and-data.md) owns that boundary. Explicit `JOIN`, complete atomic freshness, and successful first-party issuance remain incomplete. Canonical target policy and mappings remain in [Authentication and authorization](../../architecture/system-architecture-authentication.md#login-and-session-flow) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). The current admission gaps are explicit `JOIN`, the unavailable direct-text `CHARS` boundary, and the connect-token membership-authority-generation reread. The supported Account bootstrap/HTTP roster is separate and does not complete text-command actor discovery. The local #2857 receiving change also uses exact stable slug-only text and typed selection, including canonical numeric-only slugs, without advertising or interpreting unsupported menu ordinals and uses one catalog snapshot for composed `PLAY`/`WORLDS` decisions, with focused R1430 proof recorded in the linked tracker; the separate exact-target UUID menu store is unregistered, and authenticated private `REALMS`, protected receiving, and `JOIN` remain held. See [Realm Routing and Playable State](./realm-routing-and-playable-state.md#capability-status) for the bounded behavior and proof status. The `PLAY`-side `JOIN_REQUIRED` behavior remains bounded current behavior; Account connect-token issuance remains unavailable before membership or policy evaluation. R1424 qualifies bounded HELP/PLAY and WebSocket containment, not successful issuance or target admission ordering. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index f4a2f2116e..67f290411f 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -59,7 +59,7 @@ All routing-sensitive bundles preserve `tenantId`, `worldSlug`, `realmSlug`, res ### Admission, Membership, and Selection -Account-to-tenant membership is an explicit runtime substrate rather than an `accounts.tenant_id` shortcut. The live Account producer emits lifecycle state and independent authority generation/version, but current text `PLAY` consumes only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`. It therefore still returns non-actionable `JOIN_REQUIRED` for eligible public-production missing or present non-admitting membership without distinguishing `INACTIVE`; entitlement/public-policy precedence and lifecycle/generation enforcement remain gaps. Non-public text `PLAY` denies missing/non-admitting membership with `WORLD_ACCESS_DENIED` before its separate current realm-grant check. Current connect-token issuance validates bootstrap identity/scope and returns `AUTH_UNAVAILABLE` before cached replay or admission-authority reads. The Account-local explicit JOIN writer exists, while text JOIN dispatch and public exposure remain unavailable. R1430 separately passes all 451 cases in the two selected Account service/RPC classes, including active, missing and inactive lifecycle/independent-generation producer mapping; these mocked cases do not prove a complete atomic snapshot or consumer enforcement. Current producer, writer and issuance details remain in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md); the target atomic snapshot, explicit join and admission contract remains in [Authentication](../../architecture/system-architecture-authentication.md#in-band-play-admission-boundary). +Account-to-tenant membership is an explicit runtime substrate rather than an `accounts.tenant_id` shortcut. The live Account producer emits lifecycle and independent generation/version evidence, and current text `PLAY` consumes it with private-grant validation under the [canonical PLAY outcome matrix](../../architecture/system-architecture-authentication.md#play-current-and-target-failure-boundaries). Current connect-token issuance returns `AUTH_UNAVAILABLE` before cached replay or membership, entitlement, grant, and routing-authority reads. The Account-local explicit JOIN writer exists, while text JOIN dispatch remains unavailable. R1430 separately passes all 451 cases in the two selected Account service/RPC classes, including active, missing and inactive lifecycle/independent-generation producer mapping; these mocked cases do not prove full caller-target/atomic authority or connect-token enforcement. Current producer, writer and issuance details remain in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md); the target atomic authority and explicit join contract remains in [Authentication](../../architecture/system-architecture-authentication.md#in-band-play-admission-boundary). Account bootstrap discovery has a supported HTTP character-roster capability, separate from unavailable direct-text `CHARS`; it does not establish gameplay admission. Current connect-token issuance is held before cached replay and fresh admission-authority processing. Its target persistence/replay and private-grant requirements remain owned by [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). Text `PLAY` retains its separate current private/playtest grant check. Neither a discovery snapshot nor a returning shortcut substitutes for complete current authority; invalid or expired scope requires fresh discovery rather than a cached target fallback. @@ -105,7 +105,7 @@ The full direct-text `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> co - Later gameplay-state families, especially loadouts, abilities, authored effects, richer resource tables, and any new character-creation or social/runtime consumer, still need explicit adoption of `{tenantId, gameInstanceId, playableStateScope}` before they become live. They must not reopen tenant-wide or bare-character shortcuts. - Entity Management owns actor rows and the Account relationship/projection to those rows remains an evolving Account/Entity seam. Actor rows carry account and tenant identity, but neither membership nor that relationship establishes one implicit gameplay namespace across realms. -- Text `JOIN`/`Join & Play` dispatch remains unimplemented; the Account-local explicit writer is separate. Text `PLAY` still ignores Account-emitted lifecycle/generation and evaluates membership before entitlement/public-policy gates. Current connect-token issuance remains held before replay/authority reads. Complete atomic snapshot authority, current lifecycle/generation consumption, and the canonical outcome order remain gaps; no membership is created implicitly. +- Text `JOIN`/`Join & Play` dispatch remains unimplemented; the Account-local explicit writer is separate. Text `PLAY` lifecycle/generation validation is implemented; its outcome rules remain with the canonical owner linked above. Current connect-token issuance remains held before replay and authority reads. Full caller-target/atomic authority, connect-token membership/version reread, `allowNewGameplayBindings`, grant lifecycle/expiry, and lease-commit boundaries remain gaps; no membership is created implicitly. - Future routing-sensitive delegated consumers, replay-sensitive caches, and new automation follow-up families need explicit proof that they preserve the complete bundle and fail closed; closed `09.1` seams do not imply unreviewed consumers are safe. - Blank-scope login/bootstrap command staging currently retains the normalized shell selection hint with `playableStateScope=UNSPECIFIED` when runtime-target authority is absent, ambiguous, or incomplete. The implementation still needs focused proof that this hint cannot be consumed as routing authority or downstream gameplay metadata, plus convergence if any consumer crosses that boundary. - Region-partitioned runtime ownership and broader region fencing are tracked separately from admission routing. Current runtime projections carry region hints where available but do not implement the final execution-partition topology. diff --git a/dev-tools/README.md b/dev-tools/README.md index ac578f83ba..8ee605d09e 100644 --- a/dev-tools/README.md +++ b/dev-tools/README.md @@ -10,7 +10,7 @@ Keep the root of `dev-tools/` small. Only canonical human-facing entrypoints and - `verify-fresh-bootstrap.sh` – canonical source-built Docker smoke proof from a clean state. It establishes a new claim when the expected project is empty, or reuses the exact matching claim/capability for the exact per-run ID/project binding defined in [Testing: player-flow smoke and reset boundaries](../design/architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) before destructive teardown, and defaults to the read-only `LOGIN -> PLAY -> LOOK` baseline over both transports. Defaults to a per-service serial build path for local reliability; set `FIREMUD_SMOKE_SERIAL_BUILD=0` to use a normal compose build and default `COMPOSE_PARALLEL_LIMIT=4`. Set `FIREMUD_SMOKE_NO_CACHE_SERVICES="service-a service-b"` when a smoke proof must force a fresh compose rebuild for specific Docker Compose service ids without turning the whole stack into a cold no-cache build; use `gateway`, not the Gradle module name `spring-cloud-gateway`. When running from WSL, keep Docker on a native Linux CLI pointed at `unix:///var/run/docker.sock`; Windows `docker.exe` wrappers can look healthy but break the bind mounts this proof depends on. The complete local proof shares the user-wide Gradle resource guard and cleans its owned stack before returning by default; intentional continuation requires `--keep-running`, the original capability, and the same owning resource session (see the [Docker lifecycle examples](../docker/README.md#canonical-commands)). - `verify-restart-state.sh` – canonical source-built Docker smoke proof with preserved local state. It requires/reuses an already-existing matching claim/capability for the exact per-run ID/project binding defined in [Testing: player-flow smoke and reset boundaries](../design/architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) before running. Default completion tears down the claimed project; use `--keep-running` only with an explicit owner of final teardown. - `verify-smoke-images.sh` – canonical GHCR/image-tag Docker smoke proof. Invoke it as `SMOKE_IMAGE_TAG= dev-tools/verify-smoke-images.sh`; see the [Docker guide](../docker/README.md#canonical-commands) for tag semantics and local-only mode. It establishes a new claim when the expected project is empty, or reuses the exact matching claim/capability for the exact per-run ID/project binding defined in [Testing: player-flow smoke and reset boundaries](../design/architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) before running; it defaults to the baseline and rejects shared-state mutation parity. The same default cleanup and explicit keep-running lifecycle applies. -- `build-compose-service-jars.sh` – rebuilds the service boot jars consumed by the source-built Compose stack. +- `build-compose-service-jars.sh` – rebuilds the service boot jars consumed by the source-built Compose stack, retaining invocation-specific failure-only compiler evidence under `build/reports/compile-failure/runtime-bootjar/`; see the [CI evidence contract](../design/architecture/system-architecture-cicd.md#workflow-structure). - `ensure-local-compose-env.sh` – creates or completes the local root `.env` from `.env.sample` and synchronizes `docker/.env` for Compose-based smoke commands. - `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. @@ -40,7 +40,7 @@ FireController is maintained outside this repository. Use the `firecontroller-us - `kreya/` – Kreya gRPC client assets. - `load-testing/` – Gatling load-testing module. - `maintenance/` – maintenance and analysis utilities, including `maintenance/cloc-report.py` for repository summaries and PR impact snippets. Report generation is read-only by default; `pr ... --update-pr` performs the guarded marked PR-body update defined by the [PR lifecycle](../design/developer-workflows/pr-lifecycle.md). Generated PR LOC blocks carry exact base, merge-base, and head metadata for freshness checks. Use `python3 dev-tools/maintenance/cloc-report.py --help` for invocation details; its focused proof is [cloc-report-contract.sh](tests/cloc-report-contract.sh). -- `maintenance/refresh-gradle-daemon-jvm.py` – validates official Adoptium metadata for six supported platforms and regenerates Java 21 daemon artifact URLs through Gradle's native generator and verifies the generated criteria and one-file boundary. The [daemon maintenance workflow](../design/developer-workflows/validation-and-runtime-proof.md#daemon-jdk-artifact-maintenance) owns scheduling, App setup, PR publication, and failure handling. +- `maintenance/refresh-gradle-daemon-jvm.py` – validates official Java 25 Adoptium metadata before handing daemon artifact URLs to Gradle's native generator and verifying the generated criteria and one-file boundary. Missing publisher artifacts fail closed; see [daemon maintenance](../design/developer-workflows/validation-and-runtime-proof.md#daemon-jdk-artifact-maintenance) for the current qualification limit, platform policy, scheduling, App setup, publication, and failure handling. - `maintenance/update-workflow-tool.py` – updates repository-frozen checksum tuples for GitHub CLI, Buf, Kubeconform, Trivy, and Lychee. Kubectl, Helm, and the Velero CLI instead keep one exact version in the repository and fetch the publisher's checksum for that exact version during installation; `maintenance/verify-publisher-checksum.sh` validates the sidecar format, exact asset filename where the publisher supplies one, and downloaded bytes before installation. This detects corruption and publisher-side mismatches but deliberately trusts the publisher's current HTTPS artifact and checksum together rather than retaining a separately reviewed hash. The Kubernetes 1.34 hosted cluster constrains Renovate's kubectl proposals to `<1.36.0`; advance that cap only with the corresponding cluster-version upgrade. Renovate groups the Velero CLI version with the digest-pinned verifier Dockerfile image, digest-pinned Terraform server image, and Terraform Helm chart. The independently promoted backup-verifier CronJob digest remains outside that group. - `observability/` – observability contract and evidence validators. diff --git a/dev-tools/build-compose-service-jars.sh b/dev-tools/build-compose-service-jars.sh index b123b141a2..33fd8dbb0d 100644 --- a/dev-tools/build-compose-service-jars.sh +++ b/dev-tools/build-compose-service-jars.sh @@ -19,11 +19,53 @@ GRADLE_TASKS=( echo "Building current boot jars for source-built Docker compose services." # Bound compiler memory for this all-module image build and avoid protobuf task cache-serialization failures. -bash "$ROOT_DIR/dev-tools/validation/run-gradle-with-dependency-recovery.sh" \ +BUILD_COMMAND=(bash "$ROOT_DIR/dev-tools/validation/run-gradle-with-dependency-recovery.sh" --runner "$ROOT_DIR/dev-tools/validation/run-locked-gradle.sh" -- \ --no-configuration-cache \ --max-workers=1 \ --no-parallel \ '-Dorg.gradle.jvmargs=-Xmx2560m -Dfile.encoding=UTF-8' \ -PincludeLoadTesting=false \ - "${GRADLE_TASKS[@]}" + "${GRADLE_TASKS[@]}" --info --console=plain) + +# Scratch allocation is best effort, never a prerequisite for the original build. +SCRATCH="" +if mkdir -p "$ROOT_DIR/build"; then + SCRATCH="$(mktemp -d "$ROOT_DIR/build/runtime-bootjar.XXXXXX")" || SCRATCH="" +fi +if [[ -z "$SCRATCH" ]]; then + echo "Compile-failure log unavailable; running the original build without capture" >&2 + exec "${BUILD_COMMAND[@]}" +fi +trap 'rm -f -- "$SCRATCH/build.log" || :; rmdir -- "$SCRATCH" || :' EXIT +trap 'exit 130' INT +trap 'exit 143' TERM +trap 'exit 129' HUP +EVIDENCE="$ROOT_DIR/build/reports/compile-failure/runtime-bootjar/${SCRATCH##*/}" +set +e +"${BUILD_COMMAND[@]}" 2>&1 | ( + python3 "$ROOT_DIR/dev-tools/validation/collect-gradle-compile-failure.py" --capture-log "$SCRATCH/build.log" + capture_status=$? + if (( capture_status != 0 )); then + cat >/dev/null + fi + exit "$capture_status" +) +build_status=${PIPESTATUS[0]} +set -e +if (( build_status > 0 && build_status < 128 )); then + # Refuse even a reused scratch-name collision; never upload existing evidence. + if [[ ! -e "$EVIDENCE" && ! -L "$EVIDENCE" ]] && \ + python3 "$ROOT_DIR/dev-tools/validation/collect-gradle-compile-failure.py" \ + --root "$ROOT_DIR" --log "$SCRATCH/build.log" --check-exit "$build_status" \ + --output "$EVIDENCE"; then + # Propagate only successfully collected evidence from this invocation. + if [[ -f "$EVIDENCE/manifest.json" && -n "${GITHUB_OUTPUT:-}" ]]; then + printf 'runtime_compile_failure_path=%s\n' "$EVIDENCE" >> "$GITHUB_OUTPUT" || \ + echo "Compile-failure artifact path unavailable" >&2 + fi + else + echo "Compile-failure evidence collection unavailable; preserving build exit $build_status" >&2 + fi +fi +exit "$build_status" diff --git a/dev-tools/maintenance/cloc-report.py b/dev-tools/maintenance/cloc-report.py index fb4fe4e2c6..3d641d9093 100644 --- a/dev-tools/maintenance/cloc-report.py +++ b/dev-tools/maintenance/cloc-report.py @@ -1020,6 +1020,18 @@ def validated_pr_body(body: str) -> str: return body +def read_pr_body_file(path: Path) -> str: + if not path.is_absolute(): + raise ReportError("--body-file must be an absolute path") + try: + body = path.read_text(encoding="utf-8") + except (OSError, UnicodeError) as error: + raise ReportError(f"could not read UTF-8 PR body file {path}: {error}") from error + if not body.strip(): + raise ReportError(f"PR body file {path} is empty; refusing to replace the PR body") + return body + + def replace_pr_report_block(body: str, snippet: str) -> str: start_count = body.count(PR_REPORT_START) end_count = body.count(PR_REPORT_END) @@ -1068,7 +1080,12 @@ def pull_request_update_state(root: Path, number: int, repository: str) -> tuple return body, valid_object_id(payload.get("baseRefOid"), "base"), valid_object_id(payload.get("headRefOid"), "head") -def update_pull_request_body(root: Path, number: int, report: dict[str, object]) -> bool: +def update_pull_request_body( + root: Path, + number: int, + report: dict[str, object], + body_draft: str | None = None, +) -> bool: repository = report.get("repository") base = report.get("base") head = report.get("head") @@ -1082,7 +1099,7 @@ def update_pull_request_body(root: Path, number: int, report: dict[str, object]) counted_merge_base = valid_object_id(base.get("merge_base"), "merge-base") counted_head = valid_object_id(head.get("oid"), "head") - body, current_base, current_head = pull_request_update_state(root, number, repository) + remote_body, current_base, current_head = pull_request_update_state(root, number, repository) if current_head != counted_head: raise ReportError("PR head changed while the LOC report was being generated; refusing body update") current_metadata = PullRequestMetadata( @@ -1098,8 +1115,9 @@ def update_pull_request_body(root: Path, number: int, report: dict[str, object]) raise ReportError("PR merge-base changed while the LOC report was being generated; refusing body update") current_report = {**report, "base": {**base, "oid": current_base}} - updated_body = replace_pr_report_block(body, render_pr_report(current_report)) - if updated_body.replace("\r\n", "\n") == body.replace("\r\n", "\n"): + body_base = remote_body if body_draft is None else body_draft + updated_body = replace_pr_report_block(body_base, render_pr_report(current_report)) + if updated_body.replace("\r\n", "\n") == remote_body.replace("\r\n", "\n"): return False body_path: Path | None = None try: @@ -1107,7 +1125,7 @@ def update_pull_request_body(root: Path, number: int, report: dict[str, object]) body_path = Path(body_file.name) body_file.write(updated_body) latest_state = pull_request_update_state(root, number, repository) - if latest_state != (body, current_base, current_head): + if latest_state != (remote_body, current_base, current_head): raise ReportError("PR body, base, or head changed before the LOC report update; refusing body update") run_command( ( @@ -1333,6 +1351,11 @@ def build_parser() -> argparse.ArgumentParser: pr.add_argument("--repo", help="GitHub repository in owner/name form (defaults to origin)") pr.add_argument("--json", action="store_true", help="emit structured JSON") pr.add_argument("--update-pr", action="store_true", help="replace the marked LOC section in the PR body") + pr.add_argument( + "--body-file", + type=Path, + help="use an absolute UTF-8 file as the complete draft PR body before inserting the marked LOC section", + ) classify = commands.add_parser("classify", help="show source/test classification for tracked files") classify.add_argument("--json", action="store_true", help="emit structured JSON") @@ -1372,6 +1395,12 @@ def main(argv: Sequence[str] | None = None) -> int: return 0 try: + body_draft = None + if args.command == "pr" and args.body_file is not None: + if not args.update_pr: + raise ReportError("--body-file requires --update-pr") + body_draft = read_pr_body_file(args.body_file) + root = repository_root() if args.command == "classify": rows = classify_inventory(tracked_inventory(root)) @@ -1389,8 +1418,22 @@ def main(argv: Sequence[str] | None = None) -> int: report = build_pr_report(root, args.number, args.repo) print_json(report) if args.json else print(render_pr_report(report)) if args.update_pr: - updated = update_pull_request_body(root, args.number, report) - status = "Updated the marked LOC section" if updated else "The marked LOC section is already up to date" + if args.body_file is not None: + updated = update_pull_request_body(root, args.number, report, body_draft) + else: + updated = update_pull_request_body(root, args.number, report) + if args.body_file is not None: + status = ( + "Updated the PR body with the marked LOC section" + if updated + else "The PR body draft and marked LOC section are already up to date" + ) + else: + status = ( + "Updated the marked LOC section" + if updated + else "The marked LOC section is already up to date" + ) print(f"{status} in PR #{args.number}.", file=sys.stderr) return 0 diff --git a/dev-tools/maintenance/refresh-gradle-daemon-jvm.py b/dev-tools/maintenance/refresh-gradle-daemon-jvm.py index c84972eb10..19c46ec4ed 100644 --- a/dev-tools/maintenance/refresh-gradle-daemon-jvm.py +++ b/dev-tools/maintenance/refresh-gradle-daemon-jvm.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Regenerate Java 21 Adoptium daemon URLs with Gradle's native generator.""" +"""Regenerate Java 25 Adoptium daemon URLs with Gradle's native generator.""" import argparse import hashlib @@ -17,12 +17,12 @@ ROOT = Path(__file__).resolve().parents[2] ARTIFACT = "gradle/gradle-daemon-jvm.properties" -LATEST_METADATA_URL = "https://api.adoptium.net/v3/assets/latest/21/hotspot" -FEATURE_RELEASES_URL = "https://api.adoptium.net/v3/assets/feature_releases/21/ga" +LATEST_METADATA_URL = "https://api.adoptium.net/v3/assets/latest/25/hotspot" +FEATURE_RELEASES_URL = "https://api.adoptium.net/v3/assets/feature_releases/25/ga" MAX_METADATA_BYTES = 8 * 1024 * 1024 MAX_FEATURE_RELEASES = 20 MAX_FEATURE_RELEASE_PAGES = 10 -ADOPTIUM_RELEASE_PREFIX = "/adoptium/temurin21-binaries/releases/download/" +ADOPTIUM_RELEASE_PREFIX = "/adoptium/temurin25-binaries/releases/download/" RESOURCE_SESSION_ENV = ( "FIREMUD_LOCAL_RESOURCE_SESSION_FD", "FIREMUD_LOCAL_RESOURCE_SESSION_PID", @@ -33,11 +33,13 @@ (os, arch): f"{gradle_os}.{gradle_arch}" for os, gradle_os in [("linux", "LINUX"), ("mac", "MAC_OS"), ("windows", "WINDOWS")] for arch, gradle_arch in [("x64", "X86_64"), ("aarch64", "AARCH64")] + # No official matching Windows ARM artifact: never synthesize a download URL. + if (os, arch) != ("windows", "aarch64") } def select_downloads(metadata): - """Require one official Java 21 release across the six supported platforms.""" + """Require one official Java 25 release across the five supported platforms.""" if not isinstance(metadata, list): raise TypeError("Adoptium metadata must be an array") urls = {} @@ -58,18 +60,18 @@ def select_downloads(metadata): package = binary.get("package") if (entry.get("vendor") != "eclipse" or binary.get("jvm_impl") != "hotspot" or binary.get("project") != "jdk" or not isinstance(version, dict) - or type(version.get("major")) is not int or version["major"] != 21 + or type(version.get("major")) is not int or version["major"] != 25 or not isinstance(release, str) - or not re.fullmatch(r"jdk-21\.\d+\.\d+(?:\.\d+)?\+\d+", release) + or not re.fullmatch(r"jdk-25\.\d+\.\d+(?:\.\d+)?\+\d+", release) or not isinstance(package, dict) or not isinstance(package.get("link"), str)): - raise ValueError("Expected official Java 21 Adoptium HotSpot JDK metadata") + raise ValueError("Expected official Java 25 Adoptium HotSpot JDK metadata") if (any(type(version.get(field)) is not int or version[field] < 0 for field in ["minor", "security", "build"]) or type(version.get("patch", 0)) is not int or version.get("patch", 0) < 0 or not isinstance(version.get("semver"), str) or not isinstance(version.get("openjdk_version"), str)): raise ValueError("Malformed Adoptium version") - release_version = f"21.{version['minor']}.{version['security']}" + release_version = f"25.{version['minor']}.{version['security']}" if version.get("patch", 0): release_version += f".{version['patch']}" release_version += f"+{version['build']}" @@ -91,12 +93,14 @@ def select_downloads(metadata): def validate_download_url(url, os_name, architecture, release, release_version): + if (os_name, architecture) not in PLATFORMS: + raise ValueError("Unsupported automatic daemon provisioning platform") parsed = urlsplit(url) prefix = f"{ADOPTIUM_RELEASE_PREFIX}{quote(release, safe='')}/" expected_suffix = ".zip" if os_name == "windows" else ".tar.gz" filename = parsed.path.removeprefix(prefix) expected_filename = ( - f"OpenJDK21U-jdk_{architecture}_{os_name}_hotspot_" + f"OpenJDK25U-jdk_{architecture}_{os_name}_hotspot_" f"{release_version.replace('+', '_')}{expected_suffix}" ) if (parsed.scheme != "https" or parsed.netloc != "github.com" @@ -118,22 +122,24 @@ def parse_criteria(text): def validate_criteria(text, expected_urls): + if set(expected_urls) != set(PLATFORMS.values()): + raise ValueError("Expected exactly the five supported daemon platform URLs") properties = parse_criteria(text) - expected = {"toolchainVersion": "21", "toolchainVendor": "ADOPTIUM"} + expected = {"toolchainVersion": "25", "toolchainVendor": "ADOPTIUM"} expected.update({f"toolchainUrl.{platform}": url for platform, url in expected_urls.items()}) if properties != expected: - raise ValueError("Gradle daemon criteria differ from the selected official Java 21 artifacts") + raise ValueError("Gradle daemon criteria differ from the selected official Java 25 artifacts") def pinned_release_and_urls(text): - """Derive one exact approved release from all six existing daemon criteria URLs.""" + """Derive one exact approved release from all five existing daemon criteria URLs.""" properties = parse_criteria(text) expected_keys = {"toolchainVersion", "toolchainVendor"} expected_keys.update(f"toolchainUrl.{platform}" for platform in PLATFORMS.values()) if set(properties) != expected_keys: - raise ValueError("Pinned daemon criteria must contain exactly the Java 21 properties and six platform URLs") - if properties["toolchainVersion"] != "21" or properties["toolchainVendor"] != "ADOPTIUM": - raise ValueError("Pinned daemon criteria must select Java 21 from Adoptium") + raise ValueError("Pinned daemon criteria must contain exactly the Java 25 properties and five platform URLs") + if properties["toolchainVersion"] != "25" or properties["toolchainVendor"] != "ADOPTIUM": + raise ValueError("Pinned daemon criteria must select Java 25 from Adoptium") releases = set() urls = {} @@ -147,7 +153,7 @@ def pinned_release_and_urls(text): release_segment, separator, _ = parsed.path[len(ADOPTIUM_RELEASE_PREFIX):].partition("/") release = unquote(release_segment) if (not separator or quote(release, safe="") != release_segment - or not re.fullmatch(r"jdk-21\.\d+\.\d+(?:\.\d+)?\+\d+", release)): + or not re.fullmatch(r"jdk-25\.\d+\.\d+(?:\.\d+)?\+\d+", release)): raise ValueError("Malformed pinned Adoptium release URL") release_version = release.removeprefix("jdk-") validate_download_url(url, os_name, architecture, release, release_version) @@ -351,7 +357,7 @@ def refresh(check_only=False): ) subprocess.run( ["bash", str(ROOT / "dev-tools/validation/run-locked-gradle.sh"), - "updateDaemonJvm", "--jvm-version=21", "--jvm-vendor=adoptium", + "updateDaemonJvm", "--jvm-version=25", "--jvm-vendor=adoptium", f"-PdaemonJvmDownloadUrlsFile={metadata_file}"], cwd=ROOT, check=True, diff --git a/dev-tools/maintenance/test_refresh_gradle_daemon_jvm.py b/dev-tools/maintenance/test_refresh_gradle_daemon_jvm.py index 91d4405446..ed2888c1a5 100644 --- a/dev-tools/maintenance/test_refresh_gradle_daemon_jvm.py +++ b/dev-tools/maintenance/test_refresh_gradle_daemon_jvm.py @@ -19,17 +19,18 @@ def metadata(): + # Synthetic five-platform fixtures exercise the guard, not publisher availability. records = [] for os_name, arch in refresh_daemon.PLATFORMS: suffix = ".zip" if os_name == "windows" else ".tar.gz" records.append({ - "vendor": "eclipse", "release_name": "jdk-21.0.12.1+1", - "version": {"major": 21, "minor": 0, "security": 12, "patch": 1, "build": 1, - "semver": "21.0.12+101.0.LTS", "openjdk_version": "21.0.12.1+1-LTS"}, + "vendor": "eclipse", "release_name": "jdk-25.0.12.1+1", + "version": {"major": 25, "minor": 0, "security": 12, "patch": 1, "build": 1, + "semver": "25.0.12+101.0.LTS", "openjdk_version": "25.0.12.1+1-LTS"}, "binary": {"os": os_name, "architecture": arch, "image_type": "jdk", "jvm_impl": "hotspot", "project": "jdk", "package": { - "link": "https://github.com/adoptium/temurin21-binaries/releases/download/" - f"jdk-21.0.12.1%2B1/OpenJDK21U-jdk_{arch}_{os_name}_hotspot_21.0.12.1_1{suffix}"}}, + "link": "https://github.com/adoptium/temurin25-binaries/releases/download/" + f"jdk-25.0.12.1%2B1/OpenJDK25U-jdk_{arch}_{os_name}_hotspot_25.0.12.1_1{suffix}"}}, }) return records @@ -37,7 +38,7 @@ def metadata(): def criteria_text(urls=None): if urls is None: urls = refresh_daemon.select_downloads(metadata()) - lines = ["toolchainVersion=21", "toolchainVendor=ADOPTIUM"] + lines = ["toolchainVersion=25", "toolchainVendor=ADOPTIUM"] lines.extend( "toolchainUrl.{}={}".format(platform, url.replace(":", r"\:")) for platform, url in urls.items() @@ -79,20 +80,20 @@ def read(self, limit=-1): def staggered_latest_metadata(): records = metadata() version = { - "major": 21, "minor": 0, "security": 13, "build": 9, - "semver": "21.0.13+9.0.LTS", "openjdk_version": "21.0.13+9-LTS", + "major": 25, "minor": 0, "security": 13, "build": 9, + "semver": "25.0.13+9.0.LTS", "openjdk_version": "25.0.13+9-LTS", } for entry in records: binary = entry["binary"] if binary["os"] not in {"linux", "mac"}: continue - entry["release_name"] = "jdk-21.0.13+9" + entry["release_name"] = "jdk-25.0.13+9" entry["version"] = copy.deepcopy(version) suffix = ".zip" if binary["os"] == "windows" else ".tar.gz" binary["package"]["link"] = ( - "https://github.com/adoptium/temurin21-binaries/releases/download/" - f"jdk-21.0.13%2B9/OpenJDK21U-jdk_{binary['architecture']}_{binary['os']}_" - f"hotspot_21.0.13_9{suffix}" + "https://github.com/adoptium/temurin25-binaries/releases/download/" + f"jdk-25.0.13%2B9/OpenJDK25U-jdk_{binary['architecture']}_{binary['os']}_" + f"hotspot_25.0.13_9{suffix}" ) return records @@ -134,22 +135,22 @@ def generator_download_urls(command): raise AssertionError("generator daemon URL metadata file is missing") values = json.loads(metadata_path.read_text()) if not isinstance(values, dict) or set(values) != set(refresh_daemon.PLATFORMS.values()): - raise AssertionError("generator daemon URL metadata does not contain exactly six platforms") + raise AssertionError("generator daemon URL metadata does not contain exactly five platforms") return values class DaemonCriteriaTest(unittest.TestCase): def test_accepts_one_release_and_exact_generated_artifact(self): urls = refresh_daemon.select_downloads(metadata()) - criteria = "toolchainVersion=21\ntoolchainVendor=ADOPTIUM\n" + "".join( + criteria = "toolchainVersion=25\ntoolchainVendor=ADOPTIUM\n" + "".join( "toolchainUrl.{}={}\n".format(platform, url.replace(":", r"\:")) for platform, url in urls.items() ) refresh_daemon.validate_criteria(criteria, urls) - for mutated in [criteria.replace("Version=21", "Version=25"), + for mutated in [criteria.replace("Version=25", "Version=21"), criteria.replace("Vendor=ADOPTIUM", "Vendor=OTHER"), criteria.replace("LINUX.X86_64", "FREE_BSD.X86_64"), - criteria.replace("https", "http"), criteria + "toolchainVersion=21\n", + criteria.replace("https", "http"), criteria + "toolchainVersion=25\n", criteria + "toolchainImplementation=J9\n", criteria.split("toolchainUrl")[0]]: with self.subTest(criteria=mutated), self.assertRaises(ValueError): refresh_daemon.validate_criteria(mutated, urls) @@ -164,11 +165,63 @@ def test_rejects_missing_duplicate_and_malformed_platforms(self): with self.subTest(case=case), self.assertRaises((TypeError, ValueError)): refresh_daemon.select_downloads(case) + def test_java25_metadata_endpoint_and_exact_supported_platforms(self): + records = metadata() + with patch.object(refresh_daemon.urllib.request, "urlopen", + return_value=JsonResponse(records)) as urlopen: + self.assertEqual(refresh_daemon.fetch_latest_metadata(), records) + request = urlopen.call_args.args[0] + self.assertEqual(request.full_url, "https://api.adoptium.net/v3/assets/latest/25/hotspot") + self.assertEqual(urlopen.call_args.kwargs, {"timeout": 30}) + self.assertEqual(set(refresh_daemon.PLATFORMS), { + ("linux", "x64"), ("linux", "aarch64"), + ("mac", "x64"), ("mac", "aarch64"), ("windows", "x64"), + }) + for platform in refresh_daemon.PLATFORMS: + incomplete = [entry for entry in records if ( + entry["binary"]["os"], entry["binary"]["architecture"] + ) != platform] + with self.subTest(platform=platform), self.assertRaisesRegex( + ValueError, "Missing supported Adoptium platform" + ): + refresh_daemon.select_downloads(incomplete) + + def test_windows_arm_is_not_synthesized_or_accepted_in_criteria(self): + urls = refresh_daemon.select_downloads(metadata()) + self.assertNotIn("WINDOWS.AARCH64", urls) + unsupported = {"binary": { + "image_type": "jdk", "os": "windows", "architecture": "aarch64", + "package": {"link": "https://example.invalid/not-a-qualified-artifact"}, + }} + self.assertEqual(refresh_daemon.select_downloads(metadata() + [unsupported]), urls) + text = criteria_text(urls) + "toolchainUrl.WINDOWS.AARCH64=https\\://example.invalid/unsupported\n" + with self.assertRaises(ValueError): + refresh_daemon.pinned_release_and_urls(text) + with self.assertRaises(ValueError): + refresh_daemon.validate_criteria(text, urls) + with self.assertRaisesRegex(ValueError, "Unsupported automatic"): + refresh_daemon.validate_download_url( + "https://example.invalid/unsupported", "windows", "aarch64", + "jdk-25.0.12.1+1", "25.0.12.1+1" + ) + for expected in [dict(list(urls.items())[:-1]), {**urls, "WINDOWS.AARCH64": "unsupported"}]: + with self.subTest(expected=expected), self.assertRaisesRegex(ValueError, "exactly the five"): + refresh_daemon.validate_criteria(criteria_text(expected), expected) + + def test_java21_pin_is_not_java25_qualification(self): + legacy = criteria_text().replace("Version=25", "Version=21").replace( + "temurin25-binaries", "temurin21-binaries" + ).replace("jdk-25.", "jdk-21.").replace("OpenJDK25U", "OpenJDK21U").replace( + "hotspot_25.", "hotspot_21." + ) + with self.assertRaisesRegex(ValueError, "must select Java 25"): + refresh_daemon.pinned_release_and_urls(legacy) + def test_rejects_mixed_major_release_vendor_and_url_authority(self): mutations = [ - ("version", "major", 25), ("version", "major", "21"), - ("version", "build", "1"), ("version", "openjdk_version", "25.0.1+1"), - (None, "release_name", "jdk-21.0.12.1+2"), (None, "vendor", "other"), + ("version", "major", 21), ("version", "major", "25"), + ("version", "build", "1"), ("version", "openjdk_version", "21.0.1+1"), + (None, "release_name", "jdk-25.0.12.1+2"), (None, "vendor", "other"), ("binary", "jvm_impl", "openj9"), ] for section, key, value in mutations: @@ -178,14 +231,17 @@ def test_rejects_mixed_major_release_vendor_and_url_authority(self): with self.subTest(key=key, value=value), self.assertRaises(ValueError): refresh_daemon.select_downloads(case) case = metadata() - case[0]["release_name"] = "jdk-21.0.12.1+2" + case[0]["release_name"] = "jdk-25.0.12.1+2" case[0]["version"]["build"] = 2 - case[0]["version"]["openjdk_version"] = "21.0.12.1+2-LTS" + case[0]["version"]["openjdk_version"] = "25.0.12.1+2-LTS" with self.assertRaises(ValueError): refresh_daemon.select_downloads(case) for old, new in [("github.com", "example.com"), ("adoptium/", "other/"), - ("temurin21-binaries", "temurin25-binaries"), - ("https://", "http://"), ("%2B1/", "%2B2/")]: + ("temurin25-binaries", "temurin21-binaries"), + ("https://", "http://"), ("%2B1/", "%2B2/"), + (".tar.gz", ".zip"), ("_x64_linux_", "_aarch64_linux_"), + (".tar.gz", ".tar.gz?signature=untrusted"), + (".tar.gz", ".tar.gz#fragment")]: case = metadata() package = case[0]["binary"]["package"] package["link"] = package["link"].replace(old, new) @@ -206,7 +262,7 @@ def test_pinned_proof_uses_committed_release_while_latest_is_staggered(self): patch.object(refresh_daemon, "fetch_latest_metadata", side_effect=AssertionError("check-only must not query latest")): self.assertEqual(refresh_daemon.select_refresh_downloads(check_only=True), expected_urls) - pinned_fetch.assert_called_once_with("jdk-21.0.12.1+1") + pinned_fetch.assert_called_once_with("jdk-25.0.12.1+1") with ( patch.object(refresh_daemon, "fetch_latest_metadata", @@ -224,7 +280,7 @@ def test_rejects_malformed_or_mixed_committed_pins(self): mixed_pin = text.replace(escaped_pinned_url, escaped_other_release, 1) malformed = [ text.replace("toolchainUrl.WINDOWS.X86_64=", "toolchainUrl.UNKNOWN=", 1), - text + "toolchainVersion=21\n", + text + "toolchainVersion=25\n", text.replace("github.com", "example.com", 1), mixed_pin, text.replace(".tar.gz", ".zip", 1), @@ -234,7 +290,7 @@ def test_rejects_malformed_or_mixed_committed_pins(self): with self.subTest(candidate=candidate), self.assertRaises((TypeError, ValueError)): refresh_daemon.pinned_release_and_urls(candidate) - def test_pinned_metadata_must_include_six_exact_official_assets(self): + def test_pinned_metadata_must_include_five_exact_official_assets(self): text = criteria_text() rows = feature_metadata(metadata()) expected = refresh_daemon.select_downloads(metadata()) @@ -265,19 +321,19 @@ def open_request(request, timeout): return responses[len(requests) - 1] with patch.object(refresh_daemon.urllib.request, "urlopen", side_effect=open_request): - fetched = refresh_daemon.fetch_release_metadata("jdk-21.0.12.1+1") + fetched = refresh_daemon.fetch_release_metadata("jdk-25.0.12.1+1") self.assertEqual( - refresh_daemon.select_release_downloads(fetched, "jdk-21.0.12.1+1"), + refresh_daemon.select_release_downloads(fetched, "jdk-25.0.12.1+1"), refresh_daemon.select_downloads(metadata()), ) - self.assertEqual(len(requests), 6) + self.assertEqual(len(requests), 5) observed_platforms = set() for request, (os_name, architecture) in zip(requests, refresh_daemon.PLATFORMS): parsed = urlsplit(request.full_url) self.assertEqual(parsed.scheme, "https") self.assertEqual(parsed.netloc, "api.adoptium.net") - self.assertEqual(parsed.path, "/v3/assets/feature_releases/21/ga") + self.assertEqual(parsed.path, "/v3/assets/feature_releases/25/ga") query = parse_qs(parsed.query) self.assertEqual(query, { "architecture": [architecture], "heap_size": ["normal"], @@ -304,13 +360,13 @@ def open_request(request, timeout): return responses[len(requests) - 1] with patch.object(refresh_daemon.urllib.request, "urlopen", side_effect=open_request): - fetched = refresh_daemon.fetch_release_metadata("jdk-21.0.12.1+1") + fetched = refresh_daemon.fetch_release_metadata("jdk-25.0.12.1+1") self.assertEqual( - refresh_daemon.select_release_downloads(fetched, "jdk-21.0.12.1+1"), + refresh_daemon.select_release_downloads(fetched, "jdk-25.0.12.1+1"), refresh_daemon.select_downloads(metadata()), ) - self.assertEqual(len(requests), 12) + self.assertEqual(len(requests), 10) for offset in range(0, len(requests), 2): self.assertEqual(parse_qs(urlsplit(requests[offset].full_url).query)["page"], ["0"]) self.assertEqual(parse_qs(urlsplit(requests[offset + 1].full_url).query)["page"], ["1"]) @@ -322,7 +378,7 @@ def test_http_fetch_fails_closed_for_missing_duplicate_malformed_and_oversized_p ]), self.assertRaisesRegex(ValueError, "within 10 pages"), ): - refresh_daemon.fetch_release_metadata("jdk-21.0.12.1+1") + refresh_daemon.fetch_release_metadata("jdk-25.0.12.1+1") full_page = [{"release_name": f"unrelated-{index}", "binaries": []} for index in range(refresh_daemon.MAX_FEATURE_RELEASES)] @@ -332,7 +388,7 @@ def test_http_fetch_fails_closed_for_missing_duplicate_malformed_and_oversized_p for _ in range(refresh_daemon.MAX_FEATURE_RELEASE_PAGES)]) as urlopen, self.assertRaisesRegex(ValueError, "within 10 pages"), ): - refresh_daemon.fetch_release_metadata("jdk-21.0.12.1+1") + refresh_daemon.fetch_release_metadata("jdk-25.0.12.1+1") self.assertEqual(urlopen.call_count, refresh_daemon.MAX_FEATURE_RELEASE_PAGES) not_found = HTTPError("https://api.adoptium.net/page/1", 404, "Not Found", None, None) @@ -341,7 +397,7 @@ def test_http_fetch_fails_closed_for_missing_duplicate_malformed_and_oversized_p side_effect=[JsonResponse(full_page), not_found]) as urlopen, self.assertRaisesRegex(ValueError, "within 10 pages"), ): - refresh_daemon.fetch_release_metadata("jdk-21.0.12.1+1") + refresh_daemon.fetch_release_metadata("jdk-25.0.12.1+1") self.assertEqual(urlopen.call_count, 2) server_error = HTTPError("https://api.adoptium.net/page/0", 503, "Unavailable", None, None) @@ -349,7 +405,7 @@ def test_http_fetch_fails_closed_for_missing_duplicate_malformed_and_oversized_p patch.object(refresh_daemon.urllib.request, "urlopen", side_effect=server_error), self.assertRaises(HTTPError) as raised, ): - refresh_daemon.fetch_release_metadata("jdk-21.0.12.1+1") + refresh_daemon.fetch_release_metadata("jdk-25.0.12.1+1") self.assertEqual(raised.exception.code, 503) duplicate = feature_metadata(metadata())[0] @@ -358,19 +414,19 @@ def test_http_fetch_fails_closed_for_missing_duplicate_malformed_and_oversized_p return_value=JsonResponse([duplicate, copy.deepcopy(duplicate)])), self.assertRaisesRegex(ValueError, "Duplicate Adoptium release metadata"), ): - refresh_daemon.fetch_release_metadata("jdk-21.0.12.1+1") + refresh_daemon.fetch_release_metadata("jdk-25.0.12.1+1") with ( patch.object(refresh_daemon.urllib.request, "urlopen", return_value=JsonResponse([None])), self.assertRaisesRegex(TypeError, "Malformed Adoptium feature-release metadata"), ): - refresh_daemon.fetch_release_metadata("jdk-21.0.12.1+1") + refresh_daemon.fetch_release_metadata("jdk-25.0.12.1+1") with ( patch.object(refresh_daemon.urllib.request, "urlopen", return_value=OversizedResponse([])), self.assertRaisesRegex(ValueError, "exceeds the bounded size"), ): - refresh_daemon.fetch_release_metadata("jdk-21.0.12.1+1") + refresh_daemon.fetch_release_metadata("jdk-25.0.12.1+1") def test_check_only_preserves_preexisting_edits_outside_the_artifact(self): with tempfile.TemporaryDirectory() as directory: @@ -401,7 +457,14 @@ def run_or_generate(*args, **kwargs): self.assertEqual(artifact.read_text(), criteria_text()) self.assertEqual(len(generator_calls), 1) command = generator_calls[0] - self.assertEqual(command[2:5], ["updateDaemonJvm", "--jvm-version=21", "--jvm-vendor=adoptium"]) + self.assertEqual(command[2:5], ["updateDaemonJvm", "--jvm-version=25", "--jvm-vendor=adoptium"]) + + def test_publishing_refresh_still_requires_clean_checkout(self): + with patch.object(refresh_daemon.subprocess, "check_output", return_value=b" M build.gradle.kts\n"), \ + patch.object(refresh_daemon, "select_refresh_downloads") as select, \ + self.assertRaisesRegex(RuntimeError, "requires a clean checkout"): + refresh_daemon.refresh(check_only=False) + select.assert_not_called() def test_generator_inherits_only_the_existing_resource_session_descriptor(self): with tempfile.TemporaryDirectory() as directory: diff --git a/dev-tools/tests/ci-lightweight-scope-contract.sh b/dev-tools/tests/ci-lightweight-scope-contract.sh index 80135b586f..cf7d27fb5b 100644 --- a/dev-tools/tests/ci-lightweight-scope-contract.sh +++ b/dev-tools/tests/ci-lightweight-scope-contract.sh @@ -395,13 +395,13 @@ matrix_rows = evaluate_module_check_matrix( ci_compute_step, ["account-service", "game-session-service", "common-security"] ) expected_matrix_rows = [ - {"module": "account-service", "partition": "1", "java-version": 21}, - {"module": "account-service", "partition": "2", "java-version": 21}, - {"module": "game-session-service", "partition": "1", "java-version": 21}, - {"module": "game-session-service", "partition": "2", "java-version": 21}, - {"module": "game-session-service", "partition": "3", "java-version": 21}, - {"module": "game-session-service", "partition": "4", "java-version": 21}, - {"module": "common-security", "partition": "full", "java-version": 21}, + {"module": "account-service", "partition": "1", "java-version": 25}, + {"module": "account-service", "partition": "2", "java-version": 25}, + {"module": "game-session-service", "partition": "1", "java-version": 25}, + {"module": "game-session-service", "partition": "2", "java-version": 25}, + {"module": "game-session-service", "partition": "3", "java-version": 25}, + {"module": "game-session-service", "partition": "4", "java-version": 25}, + {"module": "common-security", "partition": "full", "java-version": 25}, ] expanded_jobs = [dict(row) for row in matrix_rows] if expanded_jobs != expected_matrix_rows or len({ @@ -424,7 +424,7 @@ for expected in ( 'Array.from({ length: slowServicePartitionCounts[module] }', 'partition: String(index + 1)', 'partition: "full"', - '"java-version": 21', + '"java-version": 25', ): require_contains(ci_compute_step, ("with", "script"), expected, "ci workflow") java_setup_step = find_step(ci, "build-and-test", "Set Up Java", "ci workflow") @@ -532,6 +532,9 @@ for module, job_id, display, prefix in ( "ci workflow", ) require_equal(aggregate_job, ("permissions",), {"actions": "read", "contents": "read"}, "ci workflow") + aggregate_java = find_step(ci, job_id, f"Set Up Java for {display} Coverage Aggregation", "ci workflow") + require_equal(aggregate_java, ("with", "java-version"), "25", "ci workflow") + require_equal(aggregate_java, ("with", "distribution"), "temurin", "ci workflow") capture = find_step(ci, job_id, f"Capture {display} partition job and artifact provenance", "ci workflow") require_equal(capture, ("env", "CI_MODULE"), module, "ci workflow") require_equal( @@ -915,6 +918,12 @@ require_equal( gradle_build = Path(sys.argv[6]).read_text(encoding="utf-8") root_configuration, subproject_configuration = gradle_build.split("subprojects {", 1) +if re.findall(r"JavaLanguageVersion\.of\((\d+)\)", gradle_build) != ["25", "25", "25"]: + raise SystemExit("build.gradle.kts: root, Buf, and subproject toolchains must all select Java 25") +if re.findall(r"options\.release\.set\((\d+)\)", gradle_build) != ["25", "25"]: + raise SystemExit("build.gradle.kts: Buf and subproject compilation must both target release 25") +buf_java_setup = find_step(ci, "buf-check", "Set up Java for remote generator compatibility proof", "ci workflow") +require_equal(buf_java_setup, ("with", "java-version"), "25", "ci workflow") for expected in ( 'val slowServiceCiPartitionCounts = mapOf("account-service" to 2, "game-session-service" to 4)', 'providers.gradleProperty("slowServiceCiPartitionModule").orNull', diff --git a/dev-tools/tests/cloc-report-contract.sh b/dev-tools/tests/cloc-report-contract.sh index a9bb2f0317..f312d632f4 100644 --- a/dev-tools/tests/cloc-report-contract.sh +++ b/dev-tools/tests/cloc-report-contract.sh @@ -246,6 +246,7 @@ import importlib.util import os import subprocess import sys +import textwrap from contextlib import contextmanager, redirect_stderr, redirect_stdout from io import StringIO from pathlib import Path @@ -1186,6 +1187,238 @@ finally: cloc_report.require_tool = original_require_tool cloc_report.run_command = original_run_command +native_gh_dir = repo.parent / "native-gh-bin" +native_gh_dir.mkdir() +native_gh = native_gh_dir / "gh" +native_gh.write_text( + textwrap.dedent( + """\ + #!/usr/bin/env python3 + import json + import os + from pathlib import Path + import sys + + args = sys.argv[1:] + state_path = Path(os.environ["FAKE_GH_STATE"]) + state = json.loads(state_path.read_text(encoding="utf-8")) + state["calls"].append(args) + if args[:2] == ["pr", "view"]: + state["views"] += 1 + if state.get("change_body_on_view") == state["views"]: + state["body"] = state["changed_body"] + state_path.write_text(json.dumps(state), encoding="utf-8") + print(json.dumps({ + "baseRefOid": state["baseRefOid"], + "headRefOid": state["headRefOid"], + "body": state["body"], + })) + elif args[:2] == ["pr", "edit"]: + body_path = Path(args[args.index("--body-file") + 1]) + state["edited_body"] = body_path.read_text(encoding="utf-8") + state["edits"] += 1 + state_path.write_text(json.dumps(state), encoding="utf-8") + else: + raise SystemExit("unexpected fake gh command: " + repr(args)) + """ + ), + encoding="utf-8", +) +native_gh.chmod(0o755) +native_gh_state = repo.parent / "native-gh-state.json" +native_gh_env = { + "FAKE_GH_STATE": str(native_gh_state), +} +previous_path = os.environ["PATH"] +os.environ.update(native_gh_env) +os.environ["PATH"] = f"{native_gh_dir}{os.pathsep}{previous_path}" + + +def reset_native_gh(body: str, *, change_body_on_view: int | None = None, changed_body: str | None = None) -> None: + native_gh_state.write_text( + json.dumps( + { + "baseRefOid": "a" * 40, + "headRefOid": "b" * 40, + "body": body, + "views": 0, + "edits": 0, + "calls": [], + "change_body_on_view": change_body_on_view, + "changed_body": changed_body, + } + ), + encoding="utf-8", + ) + + +def native_gh_calls() -> list[list[str]]: + calls = json.loads(native_gh_state.read_text(encoding="utf-8"))["calls"] + for args in calls: + assert args[:2] in (["pr", "view"], ["pr", "edit"]), args + assert args[2] == "2736", args + assert args.count("--repo") == 1, args + assert args[args.index("--repo") + 1] == "example/example", args + return calls + + +native_draft = repo.parent / "native-pr-body.md" +native_draft_text = ( + "Draft title\n\nLiteral shell-shaped text: $(not executed)\n\n" + + cloc_report.PR_REPORT_START + + "\nold generated LOC\n" + + cloc_report.PR_REPORT_END + + "\n\nDraft closing." +) +native_draft.write_text(native_draft_text, encoding="utf-8") +native_report_snippet = cloc_report.render_pr_report(impact) +native_original_functions = ( + cloc_report.repository_root, + cloc_report.build_pr_report, + cloc_report.pull_request_merge_base, +) +native_build_calls = [] +cloc_report.repository_root = lambda: repo + + +def native_build_pr_report(_root, number, requested_repository): + native_build_calls.append((number, requested_repository)) + return impact + + +cloc_report.build_pr_report = native_build_pr_report +cloc_report.pull_request_merge_base = lambda _root, _metadata: "c" * 40 + + +def run_native_pr(*extra_args: str) -> tuple[int, str, str]: + stdout = StringIO() + stderr = StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + status = cloc_report.main(["pr", "2736", *extra_args]) + return status, stdout.getvalue(), stderr.getvalue() + + +try: + reset_native_gh("Remote body that must not replace the supplied draft.") + status, stdout, stderr = run_native_pr( + "--update-pr", "--body-file", str(native_draft) + ) + native_state = json.loads(native_gh_state.read_text(encoding="utf-8")) + native_calls = native_gh_calls() + expected_native_draft = cloc_report.replace_pr_report_block( + native_draft_text, native_report_snippet + ) + assert status == 0 + assert cloc_report.PR_REPORT_START in stdout and cloc_report.PR_REPORT_END in stdout + assert native_state["edited_body"] == expected_native_draft + assert "Draft title" in native_state["edited_body"] + assert "Literal shell-shaped text: $(not executed)" in native_state["edited_body"] + assert "Remote body that must not replace" not in native_state["edited_body"] + assert native_state["edits"] == 1 + assert [call[:2] for call in native_calls] == [ + ["pr", "view"], + ["pr", "view"], + ["pr", "edit"], + ] + assert "Updated the PR body with the marked LOC section" in stderr + + reset_native_gh(expected_native_draft) + status, _stdout, stderr = run_native_pr( + "--update-pr", "--body-file", str(native_draft) + ) + native_state = json.loads(native_gh_state.read_text(encoding="utf-8")) + assert status == 0 + assert native_state["edits"] == 0 + assert len(native_gh_calls()) == 1 + assert "PR body draft and marked LOC section are already up to date" in stderr + + reset_native_gh("Existing remote body") + status, _stdout, stderr = run_native_pr("--update-pr") + native_state = json.loads(native_gh_state.read_text(encoding="utf-8")) + assert status == 0 + assert native_state["edited_body"] == cloc_report.replace_pr_report_block( + "Existing remote body", native_report_snippet + ) + assert native_state["edits"] == 1 + assert "Updated the marked LOC section" in stderr + assert "PR body draft" not in stderr + + build_calls_before_invalid_input = len(native_build_calls) + missing_draft = repo.parent / "missing-pr-body.md" + reset_native_gh("Must not be read") + status, _stdout, stderr = run_native_pr( + "--update-pr", "--body-file", str(missing_draft) + ) + assert status == 1 + assert len(native_build_calls) == build_calls_before_invalid_input + assert native_gh_calls() == [] + assert "could not read UTF-8 PR body file" in stderr + + for draft_name, draft_text in (("empty-pr-body.md", ""), ("blank-pr-body.md", " \t\n\r\n")): + empty_draft = repo.parent / draft_name + empty_draft.write_text(draft_text, encoding="utf-8") + reset_native_gh("Original remote body must remain untouched") + status, _stdout, stderr = run_native_pr( + "--update-pr", "--body-file", str(empty_draft) + ) + assert status == 1 + assert len(native_build_calls) == build_calls_before_invalid_input + assert native_gh_calls() == [] + assert "empty; refusing to replace the PR body" in stderr + + invalid_utf8_draft = repo.parent / "invalid-utf8-pr-body.md" + invalid_utf8_draft.write_bytes(b"\xff\xfe") + status, _stdout, stderr = run_native_pr( + "--update-pr", "--body-file", str(invalid_utf8_draft) + ) + assert status == 1 + assert len(native_build_calls) == build_calls_before_invalid_input + assert native_gh_calls() == [] + assert "could not read UTF-8 PR body file" in stderr + + relative_draft = os.path.relpath(native_draft, repo) + reset_native_gh("Must not be read") + status, _stdout, stderr = run_native_pr( + "--update-pr", "--body-file", relative_draft + ) + assert status == 1 + assert len(native_build_calls) == build_calls_before_invalid_input + assert native_gh_calls() == [] + assert "--body-file must be an absolute path" in stderr + + status, _stdout, stderr = run_native_pr("--body-file", str(native_draft)) + assert status == 1 + assert len(native_build_calls) == build_calls_before_invalid_input + assert native_gh_calls() == [] + assert "--body-file requires --update-pr" in stderr + + reset_native_gh( + "Original remote body", + change_body_on_view=2, + changed_body="Concurrent remote body change", + ) + status, _stdout, stderr = run_native_pr( + "--update-pr", "--body-file", str(native_draft) + ) + native_state = json.loads(native_gh_state.read_text(encoding="utf-8")) + assert status == 1 + assert native_state["body"] == "Concurrent remote body change" + assert native_state["edits"] == 0 + assert [call[:2] for call in native_gh_calls()] == [ + ["pr", "view"], + ["pr", "view"], + ] + assert "PR body, base, or head changed before the LOC report update" in stderr +finally: + ( + cloc_report.repository_root, + cloc_report.build_pr_report, + cloc_report.pull_request_merge_base, + ) = native_original_functions + os.environ["PATH"] = previous_path + for variable in native_gh_env: + os.environ.pop(variable, None) + real_source = Path(os.environ["REAL_PR_SOURCE"]) real_caller = Path(os.environ["REAL_PR_CALLER"]) @@ -1266,7 +1499,7 @@ pr_help_output = subprocess.check_output( [*script, "pr", "--help"], cwd=repo, env=help_env, text=True ) assert cloc_report.PR_COMMAND_DESCRIPTION in pr_help_output -for pr_argument in ("number", "--repo", "--json", "--update-pr"): +for pr_argument in ("number", "--repo", "--json", "--update-pr", "--body-file"): assert pr_argument in pr_help_output print("cloc report contract checks passed") diff --git a/dev-tools/tests/gradle-dependency-recovery-contract.sh b/dev-tools/tests/gradle-dependency-recovery-contract.sh index 65d2e8e47e..4819030968 100644 --- a/dev-tools/tests/gradle-dependency-recovery-contract.sh +++ b/dev-tools/tests/gradle-dependency-recovery-contract.sh @@ -486,7 +486,7 @@ BUILD FAILED in 17s LOG } -compose_expected="--no-configuration-cache --max-workers=1 --no-parallel -Dorg.gradle.jvmargs=-Xmx2560m -Dfile.encoding=UTF-8 -PincludeLoadTesting=false :account-service:bootJar :automation-scripting-service:bootJar :entity-management-service:bootJar :game-design-service:bootJar :game-logic-service:bootJar :game-session-service:bootJar :logging-admin-service:bootJar :social-groups-service:bootJar :spring-cloud-gateway:bootJar :tcp-proxy-service:bootJar :world-management-service:bootJar" +compose_expected="--no-configuration-cache --max-workers=1 --no-parallel -Dorg.gradle.jvmargs=-Xmx2560m -Dfile.encoding=UTF-8 -PincludeLoadTesting=false :account-service:bootJar :automation-scripting-service:bootJar :entity-management-service:bootJar :game-design-service:bootJar :game-logic-service:bootJar :game-session-service:bootJar :logging-admin-service:bootJar :social-groups-service:bootJar :spring-cloud-gateway:bootJar :tcp-proxy-service:bootJar :world-management-service:bootJar --info --console=plain" new_case runtime-jooq-classpath-resolution write_runtime_jooq_captured_cause # shellcheck disable=SC2016 diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 16556e1c0d..5434f2e111 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -100,6 +100,27 @@ if ! grep -Fq 'GH_TOKEN: ${{ github.token }}' "$ACTION" || exit 1 fi +python3 - "$ROOT_DIR/.github/workflows/ci.yml" <<'PY_LANE' +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import yaml + +workflow = yaml.safe_load(Path(sys.argv[1]).read_text()) +step = next(step for step in workflow["jobs"]["validation-gate"]["steps"] if step["name"] == "Explain validation lane") +assert step["env"]["FIREMUD_METADATA_ONLY"] == "${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null }}" +with tempfile.TemporaryDirectory(prefix="firemud-ci-lane-") as directory: + for value, heading in [("true", "## Metadata-only PR edit"), ("false", "## Source validation")]: + summary = Path(directory) / f"summary-{value}.md" + environment = dict(os.environ, FIREMUD_METADATA_ONLY=value, GITHUB_STEP_SUMMARY=str(summary)) + subprocess.run(["bash", "-e", "-c", step["run"]], check=True, env=environment) + text = summary.read_text() + assert text.startswith(heading + "\n"), text + assert "qualified source validation" in text if value == "true" else "applicable source checks" in text +PY_LANE + while IFS='|' read -r workflow gate_job_id gate workflow_name workflow_file workflow_path; do [[ -n "$workflow" ]] || continue path="$ROOT_DIR/.github/workflows/$workflow" diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 850040073e..2110584c9d 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -81,12 +81,16 @@ publisher_script="$fixture_dir/publisher.sh" runtime_script="$fixture_dir/runtime.sh" resolver_script="$fixture_dir/resolver.js" dispatch_script="$fixture_dir/dispatch.js" +smoke_scope_script="$fixture_dir/runtime-smoke-scope.js" +refresh_selector_script="$fixture_dir/runtime-refresh-selector.js" -python3 - "$WORKFLOW" "$RUNTIME_WORKFLOW" "$validation_script" "$publisher_script" "$runtime_script" "$resolver_script" "$dispatch_script" <<'PY' +python3 - "$WORKFLOW" "$RUNTIME_WORKFLOW" "$validation_script" "$publisher_script" "$runtime_script" "$resolver_script" "$dispatch_script" "$smoke_scope_script" "$refresh_selector_script" <<'PY' import re import sys from pathlib import Path +import yaml + workflow_path = Path(sys.argv[1]) runtime_workflow_path = Path(sys.argv[2]) validation_path = Path(sys.argv[3]) @@ -131,6 +135,15 @@ def javascript_step(text, name): Path(sys.argv[6]).write_text(javascript_step(workflow, "Resolve successful exact source run")) runtime_workflow = runtime_workflow_path.read_text(encoding="utf-8") Path(sys.argv[7]).write_text(javascript_step(runtime_workflow, "Dispatch exact runtime publication source")) +runtime_definition = yaml.load(runtime_workflow, Loader=yaml.BaseLoader) +image_meta = runtime_definition["jobs"]["image-meta"] +smoke_scope = next(step for step in image_meta["steps"] if step.get("name") == "Detect PR smoke scopes") +Path(sys.argv[8]).write_text(smoke_scope["with"]["script"], encoding="utf-8") +refresh_job = runtime_definition["jobs"]["dispatch-pr-base-refreshes"] +refresh_script = next(step["with"]["script"] for step in refresh_job["steps"] if "with" in step and "script" in step["with"]) +selector_start = refresh_script.index("const runtimePrefixes = [") +selector_end = refresh_script.index("const dependencyBotAuthors = new Set([", selector_start) +Path(sys.argv[9]).write_text(refresh_script[selector_start:selector_end], encoding="utf-8") handoff = runtime_workflow.split(" dispatch-pr-runtime-publication:\n", 1)[1].split(" smoke-full:\n", 1)[0] for required in ["needs: [image-meta, pr-local-smoke, pr-controller-smoke]", "github.event_name == 'repository_dispatch'", "github.event.action == 'pr-runtime-base-refresh'", "github.ref == format('refs/heads/{0}', github.event.repository.default_branch)", "needs.image-meta.result == 'success'", "needs.pr-local-smoke.result == 'success'", "needs.pr-controller-smoke.result == 'success'", "needs.image-meta.outputs.controller_smoke_required == 'false'", "needs.pr-controller-smoke.result == 'skipped'", "contents: write"]: if required not in handoff: @@ -155,12 +168,14 @@ runtime_path.write_text( ) PY -node - "$resolver_script" "$dispatch_script" "$RUNTIME_WORKFLOW" "$WORKFLOW" "$fixture_dir/download-inputs.json" <<'JS' +node - "$resolver_script" "$dispatch_script" "$RUNTIME_WORKFLOW" "$WORKFLOW" "$fixture_dir/download-inputs.json" "$smoke_scope_script" "$refresh_selector_script" <<'JS' const fs = require("fs"); const assert = require("assert/strict"); const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor; const resolver = new AsyncFunction("github", "context", "core", "Date", "setTimeout", fs.readFileSync(process.argv[2], "utf8")); const dispatch = new AsyncFunction("github", "context", fs.readFileSync(process.argv[3], "utf8")); +const smokeScope = new AsyncFunction("github", "context", "core", fs.readFileSync(process.argv[7], "utf8")); +const refreshSelector = new AsyncFunction("github", "context", "core", `${fs.readFileSync(process.argv[8], "utf8")}\nreturn hasRuntimeChange;`); const sha = character => character.repeat(40); const title = `Build Runtime Images secure-pr-artifact pr-42 base-${sha("b")} head-${sha("a")} merge-${sha("c")} mode-required`; const repository = { full_name: "benhook1013/FireMUD", default_branch: "develop" }; @@ -180,6 +195,31 @@ async function resolve({ context = baseContext, runs = [source], workflow = { id return {reads, output}; } const runtimeWorkflow = fs.readFileSync(process.argv[4], "utf8"); +const diagnosticPaths = [ + "dev-tools/validation/collect-gradle-compile-failure.py", + "dev-tools/validation/compile-failure-facts.init.gradle", +]; +async function smokeDecision(paths) { + const entries = paths.map(filename => ({filename})); + const outputs = {}; + await smokeScope( + {rest: {pulls: {listFiles: "listFiles"}}, paginate: async () => entries}, + {eventName: "pull_request", repo: {}, payload: {pull_request: {number: 42, changed_files: entries.length}}}, + {warning: () => {}, setOutput: (key, value) => {outputs[key] = value;}}, + ); + return outputs.runtime_smoke_required; +} +const refreshEntries = []; +const runtimeSelector = refreshSelector( + {rest: {pulls: {listFiles: "listFiles"}}, paginate: async () => refreshEntries}, + {repo: {}, payload: {}}, + {warning: () => {}}, +); +async function refreshDecision(paths) { + refreshEntries.splice(0, refreshEntries.length, ...paths.map(filename => ({filename}))); + const hasRuntimeChange = await runtimeSelector; + return hasRuntimeChange({number: 42, changed_files: refreshEntries.length}); +} const handoffCondition = runtimeWorkflow.split(" dispatch-pr-runtime-publication:\n")[1].match(/^ if: \$\{\{ (.*) \}\}$/m)[1] .replace(/needs\.([a-z-]+)/g, (_, key) => `needs[${JSON.stringify(key)}]`); const admitted = new Function("github", "needs", "always", "cancelled", "format", `return ${handoffCondition};`); @@ -198,6 +238,16 @@ assert.equal(admits(trigger, {...success, "image-meta": {result: "success", outp assert.equal(admits(trigger, {...success, "image-meta": {result: "success", outputs: {}}}), false); assert.equal(admits(trigger, success, true), false); (async () => { + for (const path of diagnosticPaths) { + assert.equal(await smokeDecision([path]), "false", `${path} must not require runtime smoke`); + assert.equal(await refreshDecision([path]), false, `${path} must not select a runtime refresh`); + } + assert.equal(await smokeDecision(diagnosticPaths), "false", "diagnostics-only changes must not require runtime smoke"); + assert.equal(await refreshDecision(diagnosticPaths), false, "diagnostics-only changes must not select a runtime refresh"); + for (const path of ["services/game-session-service/Dockerfile", "dev-tools/build-local-smoke-images.sh"]) { + assert.equal(await smokeDecision([path]), "true", `${path} must continue to require runtime smoke`); + assert.equal(await refreshDecision([path]), true, `${path} must continue to select a runtime refresh`); + } let dispatched; await dispatch({rest: {repos: {createDispatchEvent: async payload => {dispatched = payload;}}}}, baseContext); assert.deepEqual(dispatched, {...baseContext.repo, event_type: "pr-runtime-image-publication", client_payload: {source_run_id: "4242"}}); @@ -496,12 +546,28 @@ assert len(gradle_setup) == 1 and gradle_setup[0]["with"]["cache-read-only"] == build_step = next(step for step in job["steps"] if step.get("name") == "Build local PR runtime images") assert build_step["env"]["MERGE_SHA"] == "${{ needs.image-meta.outputs.merge_sha }}" assert 'bash ./dev-tools/build-local-smoke-images.sh "$MERGE_SHA"' in build_step["run"] +assert build_step["id"] == "runtime-images-build" +evidence = next(step for step in job["steps"] if step.get("name") == "Retain runtime bootJar compile-failure evidence") +assert evidence["if"] == "${{ failure() && steps.runtime-images-build.outcome == 'failure' }}" +assert evidence["continue-on-error"] == "true" +assert evidence["uses"] == "actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9" +assert evidence["with"]["name"] == "runtime-bootjar-compile-failure-${{ github.run_id }}-attempt-${{ github.run_attempt }}" +assert "steps.runtime-images-build.outputs.runtime_compile_failure_path" in evidence["with"]["path"] +assert evidence["with"]["if-no-files-found"] == "warn" +assert evidence["with"]["retention-days"] == "3" +for dependency in ("collect-gradle-compile-failure.py", "compile-failure-facts.init.gradle"): + path = "dev-tools/validation/" + dependency + assert path not in workflow["on"]["pull_request"]["paths"] +for source_path in ("services/**", "dev-tools/build-local-smoke-images.sh", "dev-tools/build-compose-service-jars.sh"): + assert source_path in workflow["on"]["pull_request"]["paths"] source_tree = fixture / "stacked-source" (source_tree / "dev-tools/validation").mkdir(parents=True) (source_tree / "fake-bin").mkdir() for name in ("build-local-smoke-images.sh", "build-compose-service-jars.sh"): shutil.copyfile(root / "dev-tools" / name, source_tree / "dev-tools" / name) +for name in ("collect-gradle-compile-failure.py", "compile-failure-facts.init.gradle"): + shutil.copyfile(root / "dev-tools/validation" / name, source_tree / "dev-tools/validation" / name) services = [ "account-service", "automation-scripting-service", "entity-management-service", "game-design-service", "game-logic-service", "game-session-service", @@ -534,6 +600,7 @@ if kind == "gradle": "--no-configuration-cache", "--max-workers=1", "--no-parallel", "-Dorg.gradle.jvmargs=-Xmx2560m -Dfile.encoding=UTF-8", "-PincludeLoadTesting=false", *[f":{service}:bootJar" for service in services], + "--info", "--console=plain", ], args for service in services: libs = root / "services" / service / "build/libs" diff --git a/dev-tools/tests/runtime-base-image-apt-contract.sh b/dev-tools/tests/runtime-base-image-apt-contract.sh index 8f17ca6105..6bb4a0101a 100644 --- a/dev-tools/tests/runtime-base-image-apt-contract.sh +++ b/dev-tools/tests/runtime-base-image-apt-contract.sh @@ -124,7 +124,8 @@ if [[ "$command" == update ]]; then case "$APT_EXPECTED_LAYOUT" in archive) grep -Fqx "URIs: mirror+file:$FIREMUD_APT_MIRROR_LIST_FILE" "$FIREMUD_APT_SOURCE_FILE" - grep -Eq '^URIs:[[:space:]]*https://security\.ubuntu\.com/ubuntu/?[[:space:]]*$' "$FIREMUD_APT_SOURCE_FILE" + [[ $(grep -Fc "URIs: mirror+file:$FIREMUD_APT_MIRROR_LIST_FILE" "$FIREMUD_APT_SOURCE_FILE") -eq 1 ]] + grep -Fqx 'URIs: https://security.ubuntu.com/ubuntu/' "$FIREMUD_APT_SOURCE_FILE" grep -Fqx 'Suites: resolute-security' "$FIREMUD_APT_SOURCE_FILE" grep -Fqx 'Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg' "$FIREMUD_APT_SOURCE_FILE" test -s "$FIREMUD_APT_MIRROR_LIST_FILE" diff --git a/dev-tools/tests/test_gradle_compile_failure.py b/dev-tools/tests/test_gradle_compile_failure.py index 31bd034fa2..2c37ce5d85 100644 --- a/dev-tools/tests/test_gradle_compile_failure.py +++ b/dev-tools/tests/test_gradle_compile_failure.py @@ -3,6 +3,7 @@ import importlib.util import io import json +import os import shutil import subprocess import sys @@ -21,7 +22,8 @@ class CaptureTests(unittest.TestCase): def setUp(self): - self.temp = tempfile.TemporaryDirectory() + (ROOT / 'build').mkdir(exist_ok=True) + self.temp = tempfile.TemporaryDirectory(dir=ROOT / 'build', prefix='compile-failure-test-') self.addCleanup(self.temp.cleanup) self.root = Path(self.temp.name) self.log = self.root / 'check.log' @@ -29,6 +31,9 @@ def setUp(self): 'Compiling with toolchain /jdk21\n' 'SECRET=do-not-retain\nBad.java:1: error: bad\n') self.output = self.root / 'evidence' + self.write('dev-tools/validation/run-locked-gradle.sh', '#!/bin/bash\n' + 'printf "%s\\n" "$@" > locked-args\n' + 'exec "$(dirname "$0")/../../gradlew" "$@"\n') def write(self, relative, content='source'): path = self.root / relative @@ -117,12 +122,37 @@ def test_diagnostic_retains_only_structured_facts_and_no_check_command(self): self.assertEqual('complete', result['status']) self.assertEqual({'attribution': 'post-failure'}, json.loads(target.read_text())) arguments = (self.root / 'diagnostic-args').read_text().splitlines() + self.assertEqual(arguments, (self.root / 'locked-args').read_text().splitlines()) self.assertIn('--offline', arguments) self.assertIn('--no-configuration-cache', arguments) self.assertEqual(':common-saga:firemudCompileFailureFacts', arguments[-1]) self.assertFalse(any(arg.endswith(':check') for arg in arguments)) self.assertNotIn('--refresh-dependencies', arguments) + def test_diagnostic_preserves_only_the_inherited_resource_descriptor(self): + runner = self.write('gradlew', f'#!{sys.executable}\n' + 'import json, os\n' + 'fd = int(os.environ["FIREMUD_LOCAL_RESOURCE_SESSION_FD"])\n' + 'os.fstat(fd)\n' + 'other = int(os.environ["FIXTURE_UNRELATED_FD"])\n' + 'try:\n' + ' os.fstat(other)\n' + 'except OSError:\n' + ' pass\n' + 'else:\n' + ' raise SystemExit("unrelated descriptor inherited")\n' + 'print("FIREMUD_COMPILE_FACTS=" + json.dumps({"lease_descriptor_open": True}))\n') + runner.chmod(0o755) + with (self.root / 'lease').open('w') as lease, (self.root / 'unrelated').open('w') as other: + os.set_inheritable(other.fileno(), True) + with patch.dict(os.environ, { + 'FIREMUD_LOCAL_RESOURCE_SESSION_FD': str(lease.fileno()), + 'FIXTURE_UNRELATED_FD': str(other.fileno())}): + target = self.root / 'facts.json' + result = CAPTURE.diagnostic(self.root, ':common-saga:compileJava', target) + self.assertEqual('complete', result['status']) + self.assertEqual({'lease_descriptor_open': True}, json.loads(target.read_text())) + def test_output_symlink_escape_rejected(self): external = self.root / 'outside' external.mkdir() @@ -426,5 +456,223 @@ def fixture_wrapper_with_early_capture_failure(self, exit_code, root, lastpipe=F capture_output=True, text=True, check=False) +class RuntimeBootJarTests(unittest.TestCase): + """Run the real entrypoint/recovery/collector against inert Gradle launchers.""" + + write = CaptureTests.write + + def setUp(self): + (ROOT / 'build').mkdir(exist_ok=True) + self.temp = tempfile.TemporaryDirectory(dir=ROOT / 'build', prefix='runtime-compile-test-') + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + for relative in ['dev-tools/build-compose-service-jars.sh', + 'dev-tools/validation/run-gradle-with-dependency-recovery.sh', + 'dev-tools/validation/collect-gradle-compile-failure.py']: + destination = self.root / relative + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(ROOT / relative, destination) + launcher = self.write('dev-tools/validation/run-locked-gradle.sh', '#!/bin/bash\n' + 'printf "%s\\n" "$@" >> locked-args\n' + 'exec "$(dirname "$0")/../../gradlew" "$@"\n') + launcher.chmod(0o755) + self.env = {**os.environ, 'TMPDIR': str(self.root), 'RUNNER_TEMP': str(self.root), + 'GITHUB_OUTPUT': str(self.root / 'step-output')} + self.env.pop('FIREMUD_LOCAL_RESOURCE_SESSION_FD', None) + + def run_build(self, status=0, output='', producer='', lastpipe=False, signal_number=None): + runner = self.write('gradlew', f'#!{sys.executable}\n' + 'import json, os, sys\nfrom pathlib import Path\n' + 'with open("calls", "a") as calls:\n' + ' calls.write(json.dumps(sys.argv[1:]) + "\\n")\n' + 'if any(arg.endswith(":firemudCompileFailureFacts") for arg in sys.argv):\n' + ' print(\'SECRET=not-retained\')\n' + ' print(\'FIREMUD_COMPILE_FACTS={"attribution":"post-failure",' + '"gradleVersion":"fixture", "jvm":"fixture",' + '"compiler":"fixture", "classpath":[]}\')\n' + ' raise SystemExit(0)\n' + + producer + '\n' + f'print({output!r}, flush=True)\n' + 'Path("producer-ended").write_text("drained")\n' + + (f'os.kill(os.getpid(), {signal_number})\n' if signal_number else '') + + f'raise SystemExit({status})\n') + runner.chmod(0o755) + return subprocess.run(['bash', *(['-O', 'lastpipe'] if lastpipe else []), + 'dev-tools/build-compose-service-jars.sh'], cwd=self.root, + env=self.env, capture_output=True, check=False, start_new_session=True) + + def calls(self): + return [json.loads(line) for line in (self.root / 'calls').read_text().splitlines()] + + def evidence(self): + return list((self.root / 'build/reports/compile-failure').rglob('manifest.json')) + + def assert_original_command(self, arguments): + services = ['account-service', 'automation-scripting-service', 'entity-management-service', + 'game-design-service', 'game-logic-service', 'game-session-service', + 'logging-admin-service', 'social-groups-service', 'spring-cloud-gateway', + 'tcp-proxy-service', 'world-management-service'] + self.assertEqual(['--no-configuration-cache', '--max-workers=1', '--no-parallel', + '-Dorg.gradle.jvmargs=-Xmx2560m -Dfile.encoding=UTF-8', + '-PincludeLoadTesting=false', + *[f':{service}:bootJar' for service in services], + '--info', '--console=plain'], arguments) + + def test_success_preserves_all_eleven_tasks_and_flags_once(self): + result = self.run_build(output='> Task :common-saga:compileJava FAILED') + self.assertEqual(0, result.returncode) + self.assertEqual(1, len(self.calls())) + self.assert_original_command(self.calls()[0]) + self.assertEqual([], self.evidence()) + + def test_noncompiler_and_signal_exits_never_collect(self): + for status, signal_number, output in [(19, None, '> Task :account-service:bootJar FAILED'), + (130, None, '> Task :common-saga:compileJava FAILED'), + (143, 15, '> Task :common-saga:compileJava FAILED'), + (129, 1, '> Task :common-saga:compileJava FAILED')]: + with self.subTest(status=status): + result = self.run_build(status, output, signal_number=signal_number) + self.assertEqual(status, result.returncode) + self.assertEqual([], self.evidence()) + self.assertEqual(4, len(self.calls())) + for arguments in self.calls(): + self.assert_original_command(arguments) + + def test_bounded_useful_compiler_capture_without_compiler_retry(self): + self.write('services/common-saga/build/generated/Bad.java', 'bad source') + self.write('services/common-saga/build/generated/Huge.java', 'x' * (CAPTURE.MAX_FILE_BYTES + 1)) + self.write('protos/owner/service.proto', 'schema') + self.write('build.gradle.kts', 'build inputs') + result = self.run_build(17, '> Task :common-saga:compileJava FAILED\n' + 'Compiling with toolchain /jdk25\nBad.java:1: error: bad\n' + 'SECRET=not-retained', + 'os.write(1, b"x" * (17 * 1024 * 1024) + b"\\n")') + self.assertEqual(17, result.returncode) + calls = self.calls() + self.assertEqual(2, len(calls)) + self.assert_original_command(calls[0]) + self.assertEqual(':common-saga:firemudCompileFailureFacts', calls[1][-1]) + self.assertIn('--offline', calls[1]) + self.assertIn('--no-daemon', calls[1]) + self.assertNotIn('--refresh-dependencies', calls[1]) + self.assertFalse(any(arg.startswith(':') and arg.endswith((':check', ':test', ':compileJava')) + for arg in calls[1])) + manifest_path, = self.evidence() + manifest = json.loads(manifest_path.read_text()) + self.assertEqual(17, manifest['check_exit']) + self.assertEqual(['Compiling with toolchain /jdk25'], manifest['original_compiler_info']) + self.assertIn('post-failure', manifest['attribution']) + self.assertTrue(manifest['log_tail_possibly_truncated']) + self.assertEqual(1, manifest['omitted']) + self.assertLessEqual(manifest['captured_bytes'], CAPTURE.MAX_BYTES) + paths = [entry['path'] for entry in manifest['files']] + self.assertIn('services/common-saga/build/generated/Bad.java', paths) + self.assertIn('protos/owner/service.proto', paths) + self.assertIn('build.gradle.kts', paths) + diagnostic, = manifest_path.parent.glob('*-diagnostic.json') + self.assertEqual('fixture', json.loads(diagnostic.read_text())['gradleVersion']) + self.assertNotIn('SECRET', manifest_path.read_text() + diagnostic.read_text()) + self.assertFalse(list((self.root / 'build').glob('runtime-bootjar.*'))) + + def test_wrapper_group_interrupts_preserve_signal_exit_without_diagnostics(self): + for signal_number, expected in [(2, 130), (15, 143), (1, 129)]: + with self.subTest(signal=signal_number): + result = self.run_build(producer='print("> Task :common-saga:compileJava FAILED", flush=True)\n' + f'os.killpg(os.getpgrp(), {signal_number})') + self.assertEqual(expected, result.returncode) + self.assertEqual([], self.evidence()) + self.assertEqual(3, len(self.calls())) + + def test_capture_early_exit_drains_for_all_original_statuses_and_lastpipe(self): + collector = self.root / 'dev-tools/validation/collect-gradle-compile-failure.py' + collector.write_text('import sys\n' + 'if "--capture-log" in sys.argv:\n' + ' sys.stdin.buffer.read(1)\n' + 'raise SystemExit(23)\n') + for status in [0, 17, 130, 143]: + for lastpipe in [False, True]: + with self.subTest(status=status, lastpipe=lastpipe): + result = self.run_build(status, producer='os.write(1, b"x" * 1048576)', lastpipe=lastpipe) + self.assertEqual(status, result.returncode) + self.assertEqual('drained', (self.root / 'producer-ended').read_text()) + self.assertEqual([], self.evidence()) + self.assertEqual(8, len(self.calls())) + + def test_capture_write_failure_drains_and_preserves_original_exit(self): + collector = self.root / 'dev-tools/validation/collect-gradle-compile-failure.py' + collector.write_text(collector.read_text().replace( + 'return capture_log(sys.stdin.buffer', + 'args.capture_log.mkdir()\n return capture_log(sys.stdin.buffer')) + for status in [0, 17]: + with self.subTest(status=status): + result = self.run_build(status, '> Task :common-saga:compileJava FAILED', + 'os.write(1, b"x" * 1048576)') + self.assertEqual(status, result.returncode) + self.assertIn(b'original output drained', result.stderr) + self.assertIn(b'> Task :common-saga:compileJava FAILED', result.stdout) + self.assertEqual('drained', (self.root / 'producer-ended').read_text()) + self.assertEqual(2, len(self.calls())) + self.assertEqual([], self.evidence()) + + def test_missing_scratch_runs_original_build_once_without_evidence(self): + mktemp = self.write('bin/mktemp', '#!/bin/bash\n' + 'case "$*" in *runtime-bootjar*) exit 1;; esac\n' + f'exec "{shutil.which("mktemp")}" "$@"\n') + mktemp.chmod(0o755) + self.env['PATH'] = str(mktemp.parent) + os.pathsep + os.environ['PATH'] + for status in [0, 17, 143]: + with self.subTest(status=status): + result = self.run_build(status, '> Task :common-saga:compileJava FAILED') + self.assertEqual(status, result.returncode) + self.assertIn(b'without capture', result.stderr) + self.assertEqual(3, len(self.calls())) + self.assertEqual([], self.evidence()) + self.assertFalse((self.root / 'step-output').exists()) + + def test_collection_failure_preserves_original_exit_without_retry(self): + collector = self.root / 'dev-tools/validation/collect-gradle-compile-failure.py' + collector.write_text(collector.read_text().replace( + 'collect(args.root, args.log, args.output, args.check_exit)', + 'raise OSError("fixture collection unavailable")')) + result = self.run_build(23, '> Task :common-saga:compileJava FAILED') + self.assertEqual(23, result.returncode) + self.assertIn(b'preserving build exit 23', result.stderr) + self.assertEqual(1, len(self.calls())) + self.assertEqual([], self.evidence()) + + def test_repeated_invocations_never_select_stale_evidence(self): + self.env.update(GITHUB_RUN_ID='123', GITHUB_RUN_ATTEMPT='2') + paths = [] + for status in [17, 0, 19, 17]: + step_output = self.root / 'step-output' + step_output.write_text('') + result = self.run_build(status, '> Task :common-saga:compileJava FAILED' if status == 17 else '') + self.assertEqual(status, result.returncode) + output = step_output.read_text() + self.assertEqual(status == 17, bool(output)) + if output: + paths.append(Path(output.strip().split('=', 1)[1])) + self.assertEqual(2, len(set(paths))) + self.assertTrue(all((path / 'manifest.json').exists() for path in paths)) + self.assertEqual(6, len(self.calls())) + + def test_reused_scratch_name_never_publishes_existing_evidence(self): + stale = self.write('build/reports/compile-failure/runtime-bootjar/runtime-bootjar.reused/manifest.json', + 'stale evidence') + mktemp = self.write('bin/mktemp', '#!/bin/bash\n' + 'case "$*" in *runtime-bootjar*)\n' + f' mkdir -p "{self.root}/build/runtime-bootjar.reused"\n' + f' printf "%s\\n" "{self.root}/build/runtime-bootjar.reused"; exit 0;; esac\n' + f'exec "{shutil.which("mktemp")}" "$@"\n') + mktemp.chmod(0o755) + self.env['PATH'] = str(mktemp.parent) + os.pathsep + os.environ['PATH'] + result = self.run_build(17, '> Task :common-saga:compileJava FAILED') + self.assertEqual(17, result.returncode) + self.assertIn(b'preserving build exit 17', result.stderr) + self.assertEqual('stale evidence', stale.read_text()) + self.assertFalse((self.root / 'step-output').exists()) + self.assertEqual(1, len(self.calls())) + + if __name__ == '__main__': unittest.main() diff --git a/dev-tools/validation/collect-gradle-compile-failure.py b/dev-tools/validation/collect-gradle-compile-failure.py index 0ffceb11a5..0466db2ea5 100644 --- a/dev-tools/validation/collect-gradle-compile-failure.py +++ b/dev-tools/validation/collect-gradle-compile-failure.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Failure-only, bounded module-CI evidence; never reruns a check or compiler.""" +"""Failure-only, bounded Gradle evidence; never reruns a build or compiler.""" import argparse import hashlib @@ -107,14 +107,18 @@ def diagnostic(root, task, output): if task_match is None: raise ValueError('Diagnostic compile task path is invalid') facts_task = task_match.group(1) + ':firemudCompileFailureFacts' + # Preserve the existing lease descriptor; the canonical runner verifies its authority. + session_fd = os.environ.get('FIREMUD_LOCAL_RESOURCE_SESSION_FD') + session_fds = (int(session_fd),) if session_fd is not None else () process = subprocess.Popen( - [str(root / 'gradlew'), '--offline', '--no-daemon', '--no-configuration-cache', + ['bash', str(root / 'dev-tools/validation/run-locked-gradle.sh'), + '--offline', '--no-daemon', '--no-configuration-cache', '--console=plain', '--max-workers=2', '-Dorg.gradle.java.installations.auto-download=false', '-I', str(root / 'dev-tools/validation/compile-failure-facts.init.gradle'), '-PfiremudFailedCompile=' + task, facts_task], cwd=root, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, - start_new_session=True, bufsize=0, + start_new_session=True, bufsize=0, pass_fds=session_fds, ) captured = bytearray() limited = False diff --git a/gradle/gradle-daemon-jvm.properties b/gradle/gradle-daemon-jvm.properties index dacaae5229..8f02d303ae 100644 --- a/gradle/gradle-daemon-jvm.properties +++ b/gradle/gradle-daemon-jvm.properties @@ -1,9 +1,8 @@ #This file is generated by :updateDaemonJvm -toolchainUrl.LINUX.AARCH64=https\://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.12.1%2B1/OpenJDK21U-jdk_aarch64_linux_hotspot_21.0.12.1_1.tar.gz -toolchainUrl.LINUX.X86_64=https\://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.12.1%2B1/OpenJDK21U-jdk_x64_linux_hotspot_21.0.12.1_1.tar.gz -toolchainUrl.MAC_OS.AARCH64=https\://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.12.1%2B1/OpenJDK21U-jdk_aarch64_mac_hotspot_21.0.12.1_1.tar.gz -toolchainUrl.MAC_OS.X86_64=https\://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.12.1%2B1/OpenJDK21U-jdk_x64_mac_hotspot_21.0.12.1_1.tar.gz -toolchainUrl.WINDOWS.AARCH64=https\://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.12.1%2B1/OpenJDK21U-jdk_aarch64_windows_hotspot_21.0.12.1_1.zip -toolchainUrl.WINDOWS.X86_64=https\://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.12.1%2B1/OpenJDK21U-jdk_x64_windows_hotspot_21.0.12.1_1.zip +toolchainUrl.LINUX.AARCH64=https\://github.com/adoptium/temurin25-binaries/releases/download/jdk-25.0.5%2B8/OpenJDK25U-jdk_aarch64_linux_hotspot_25.0.5_8.tar.gz +toolchainUrl.LINUX.X86_64=https\://github.com/adoptium/temurin25-binaries/releases/download/jdk-25.0.5%2B8/OpenJDK25U-jdk_x64_linux_hotspot_25.0.5_8.tar.gz +toolchainUrl.MAC_OS.AARCH64=https\://github.com/adoptium/temurin25-binaries/releases/download/jdk-25.0.5%2B8/OpenJDK25U-jdk_aarch64_mac_hotspot_25.0.5_8.tar.gz +toolchainUrl.MAC_OS.X86_64=https\://github.com/adoptium/temurin25-binaries/releases/download/jdk-25.0.5%2B8/OpenJDK25U-jdk_x64_mac_hotspot_25.0.5_8.tar.gz +toolchainUrl.WINDOWS.X86_64=https\://github.com/adoptium/temurin25-binaries/releases/download/jdk-25.0.5%2B8/OpenJDK25U-jdk_x64_windows_hotspot_25.0.5_8.zip toolchainVendor=ADOPTIUM -toolchainVersion=21 +toolchainVersion=25 diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java index c7847510ce..bf39db3a85 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java @@ -350,4 +350,61 @@ private static GetTenantMembershipForRuntimeRequest membershipRequest( .setRequestId("membership-request") .build(); } + + @Test + void runtimeMembershipSnapshotsKeepLifecycleAndAuthorityCountersIndependent() throws Exception { + Instant evaluatedAt = Instant.parse("2026-10-30T12:34:56Z"); + String accountId = AccountRuntimeStubServer.accountUuidForTestFixture(7L); + try (AccountRuntimeStubServer server = + new AccountRuntimeStubServer(0, Clock.fixed(evaluatedAt, ZoneOffset.UTC))) { + server.mapAccountId("demo@example.com", 7L); + server.setMembershipVersion(9L); + server.setMembershipAuthorityGeneration(4L); + ManagedChannel channel = + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); + try { + AccountServiceGrpc.AccountServiceBlockingStub stub = + AccountServiceGrpc.newBlockingStub(channel); + GetTenantMembershipForRuntimeRequest request = + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId(accountId) + .setTenantId("11") + .setRequestId("membership-request-1") + .build(); + + server.denyGameplayAdmission(); + var activeDenied = stub.getTenantMembershipForRuntime(request); + assertThat(activeDenied.getMembershipExists()).isTrue(); + assertThat(activeDenied.getGameplayAdmissionAllowed()).isFalse(); + assertThat(activeDenied.getMembershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(activeDenied.getMembershipVersion()).isEqualTo(9L); + assertThat(activeDenied.getMembershipAuthorityGeneration()).isEqualTo(4L); + + server.setMembershipInactive(); + var inactive = stub.getTenantMembershipForRuntime(request); + assertThat(inactive.getMembershipExists()).isTrue(); + assertThat(inactive.getGameplayAdmissionAllowed()).isFalse(); + assertThat(inactive.getMembershipLifecycleState()).isEqualTo("INACTIVE"); + assertThat(inactive.getMembershipVersion()).isEqualTo(9L); + assertThat(inactive.getMembershipAuthorityGeneration()).isEqualTo(4L); + + server.setMembershipExists(false); + server.setGameplayAdmissionAllowed(true); + var missing = stub.getTenantMembershipForRuntime(request); + assertThat(missing.getMembershipExists()).isFalse(); + assertThat(missing.getGameplayAdmissionAllowed()).isFalse(); + assertThat(missing.getMembershipLifecycleState()).isEqualTo("MISSING"); + assertThat(missing.getMembershipVersion()).isZero(); + assertThat(missing.getMembershipAuthorityGeneration()).isZero(); + + for (var response : List.of(activeDenied, inactive, missing)) { + assertThat(response.getAccountId()).isEqualTo(accountId); + assertThat(response.getTenantId()).isEqualTo("11"); + assertThat(response.getEvaluatedAt()).isEqualTo(evaluatedAt.toString()); + } + } finally { + channel.shutdownNow(); + } + } + } } diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java index 4074574476..811e3fb37f 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java @@ -110,6 +110,7 @@ void authenticationCanonicalizesMappedEmailAndMissingMembershipDeniesAdmission() assertThat(accountUuid).isEqualTo(AccountRuntimeStubServer.accountUuidForTestFixture(7L)); server.setMembershipExists(false); + server.setGameplayAdmissionAllowed(true); var membership = stub.getTenantMembershipForRuntime( @@ -120,6 +121,42 @@ void authenticationCanonicalizesMappedEmailAndMissingMembershipDeniesAdmission() .build()); assertThat(membership.getMembershipExists()).isFalse(); assertThat(membership.getGameplayAdmissionAllowed()).isFalse(); + assertThat(membership.getMembershipLifecycleState()).isEqualTo("MISSING"); + assertThat(membership.getMembershipVersion()).isZero(); + assertThat(membership.getMembershipAuthorityGeneration()).isZero(); + assertThat(membership.getAccountId()).isEqualTo(accountUuid); + assertThat(membership.getTenantId()).isEqualTo("1"); + } finally { + channel.shutdownNow(); + } + } + } + + @Test + void inactiveMembershipCannotBeAdmittedWhenAdmissionFlagIsEnabled() throws Exception { + try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { + ManagedChannel channel = + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); + try { + AccountServiceGrpc.AccountServiceBlockingStub stub = + AccountServiceGrpc.newBlockingStub(channel); + String accountUuid = authenticate(stub); + server.setMembershipInactive(); + server.setGameplayAdmissionAllowed(true); + + var membership = + stub.getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId(accountUuid) + .setTenantId("1") + .setRequestId("inactive-membership-request") + .build()); + + assertThat(membership.getMembershipExists()).isTrue(); + assertThat(membership.getMembershipLifecycleState()).isEqualTo("INACTIVE"); + assertThat(membership.getMembershipVersion()).isPositive(); + assertThat(membership.getMembershipAuthorityGeneration()).isPositive(); + assertThat(membership.getGameplayAdmissionAllowed()).isFalse(); } finally { channel.shutdownNow(); } diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java index d404d76493..7a132094fa 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java @@ -16,6 +16,7 @@ import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.account.v1.AccountServiceGrpc; import net.firedevops.firemud.account.v1.AuthenticateRequest; import net.firedevops.firemud.account.v1.AuthenticateResponse; @@ -56,8 +57,10 @@ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountSe private final Server server; private final Clock clock; private final List authenticateRequests = new CopyOnWriteArrayList<>(); - private final AtomicBoolean membershipExists = new AtomicBoolean(true); + private final AtomicReference membershipLifecycleState = new AtomicReference<>("ACTIVE"); private final AtomicBoolean gameplayAdmissionAllowed = new AtomicBoolean(true); + private final AtomicLong membershipVersion = new AtomicLong(1L); + private final AtomicLong membershipAuthorityGeneration = new AtomicLong(1L); private final AtomicBoolean gameplayAvailable = new AtomicBoolean(true); private final AtomicBoolean allowPublicJoin = new AtomicBoolean(true); private final AtomicBoolean realmAccessGranted = new AtomicBoolean(true); @@ -122,10 +125,23 @@ public void setGameplayAdmissionAllowed(boolean allowed) { } public void setMembershipExists(boolean exists) { + membershipLifecycleState.set(exists ? "ACTIVE" : "MISSING"); if (!exists) { gameplayAdmissionAllowed.set(false); } - membershipExists.set(exists); + } + + public void setMembershipInactive() { + membershipLifecycleState.set("INACTIVE"); + gameplayAdmissionAllowed.set(false); + } + + public void setMembershipVersion(long version) { + membershipVersion.set(version); + } + + public void setMembershipAuthorityGeneration(long generation) { + membershipAuthorityGeneration.set(generation); } public void allowGameplayAdmission() { @@ -152,8 +168,10 @@ public void setRealmAccessGranted(boolean granted) { public void resetRuntimeState() { authenticateRequests.clear(); - membershipExists.set(true); + membershipLifecycleState.set("ACTIVE"); gameplayAdmissionAllowed.set(true); + membershipVersion.set(1L); + membershipAuthorityGeneration.set(1L); gameplayAvailable.set(true); allowPublicJoin.set(true); realmAccessGranted.set(true); @@ -192,16 +210,18 @@ public void authenticate( public void getTenantMembershipForRuntime( GetTenantMembershipForRuntimeRequest request, StreamObserver responseObserver) { - boolean exists = membershipExists.get(); + String lifecycleState = membershipLifecycleState.get(); + boolean exists = !lifecycleState.equals("MISSING"); responseObserver.onNext( GetTenantMembershipForRuntimeResponse.newBuilder() .setAccountId(request.getAccountId()) .setTenantId(request.getTenantId()) .setMembershipExists(exists) - .setGameplayAdmissionAllowed(gameplayAdmissionAllowed.get()) - .setMembershipVersion(exists ? 1L : 0L) - .setMembershipLifecycleState(exists ? "ACTIVE" : "MISSING") - .setMembershipAuthorityGeneration(exists ? 1L : 0L) + .setGameplayAdmissionAllowed( + exists && "ACTIVE".equals(lifecycleState) && gameplayAdmissionAllowed.get()) + .setMembershipVersion(exists ? membershipVersion.get() : 0L) + .setMembershipLifecycleState(lifecycleState) + .setMembershipAuthorityGeneration(exists ? membershipAuthorityGeneration.get() : 0L) .setEvaluatedAt(clock.instant().toString()) .build()); responseObserver.onCompleted(); @@ -349,7 +369,7 @@ public void joinPublicProductionMembership( .setTenantId(caller.getTenantId()) .build()); } else { - membershipExists.set(true); + membershipLifecycleState.set("ACTIVE"); gameplayAdmissionAllowed.set(true); responseObserver.onNext( JoinPublicProductionMembershipResponse.newBuilder() diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java index eaa5b07d51..0f495ed83c 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java @@ -22,6 +22,15 @@ public final class GameplayStageCommandConstants { public static final String WORLD_ACCESS_DENIED_MESSAGE = "You are not allowed to enter that world."; public static final String JOIN_REQUIRED_CODE = "JOIN_REQUIRED"; + public static final String PUBLIC_PRODUCTION_ADMISSION_DENIED_CODE = + "PUBLIC_PRODUCTION_ADMISSION_DENIED"; + public static final String PUBLIC_PRODUCTION_ADMISSION_DENIED_MESSAGE = + "Public enrollment is closed for that world."; + public static final String NON_PUBLIC_ENROLLMENT_REQUIRED_CODE = "NON_PUBLIC_ENROLLMENT_REQUIRED"; + public static final String NON_PUBLIC_ENROLLMENT_REQUIRED_MESSAGE = + "Active membership is required for that non-public realm."; + public static final String REALM_ACCESS_DENIED_CODE = "REALM_ACCESS_DENIED"; + public static final String REALM_ACCESS_DENIED_MESSAGE = "You do not have access to that realm."; public static final String JOIN_REQUIRED_MESSAGE = "Membership is required before PLAY; joining this world is not available yet."; public static final String TENANT_BILLING_BLOCKED_CODE = "TENANT_BILLING_BLOCKED"; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index fcd2e0f9af..9bc88481bc 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -59,6 +59,8 @@ public class PlayCommandHandler { "gamesession.session.fresh_entry_fallback"; private static final Duration AUTHORITY_REPLY_MAX_FUTURE_SKEW = Duration.ofSeconds(5); private static final Duration AUTHORITY_REPLY_MAX_AGE = Duration.ofMinutes(5); + // The five-second skew subtraction leaves a conservative 10-second reply-age limit. + private static final Duration ENTITLEMENT_REPLY_MAX_AGE = Duration.ofSeconds(15); private final SessionAuthenticationService sessionAuthenticationService; private final SessionContextService sessionContextService; @@ -632,6 +634,20 @@ private Optional validateRuntimeAdmission( String tenantTag, long requestedCharacterId) { String requestId = context.sessionId() + ":" + UUID.randomUUID(); + GetTenantEntitlementsForRuntimeResponse entitlementResponse = + accountClient.getTenantEntitlementsForRuntime( + Long.toString(selectedRealm.tenantId()), requestId); + Optional entitlementFailure = + validateEntitlementsResponse( + entitlementResponse, + context, + tenantTag, + selectedWorld, + selectedRealm, + requestedCharacterId); + if (entitlementFailure.isPresent()) { + return entitlementFailure; + } GetTenantMembershipForRuntimeResponse membershipResponse = accountClient.getTenantMembershipForRuntime( context.accountId(), Long.toString(selectedRealm.tenantId()), requestId); @@ -643,21 +659,9 @@ private Optional validateRuntimeAdmission( selectedWorld, selectedRealm, requestedCharacterId, - requestId); - if (membershipFailure.isPresent()) { - return membershipFailure; - } - - GetTenantEntitlementsForRuntimeResponse entitlementResponse = - accountClient.getTenantEntitlementsForRuntime( - Long.toString(selectedRealm.tenantId()), requestId); - return validateEntitlementsResponse( - entitlementResponse, - context, - tenantTag, - selectedWorld, - selectedRealm, - requestedCharacterId); + requestId, + entitlementResponse.getAllowPublicJoin()); + return membershipFailure; } private long requireResolvedCharacterId(String characterId) { @@ -694,10 +698,17 @@ private Optional validateMembershipResponse( GameplayWorldCatalog.WorldView selectedWorld, GameplayWorldCatalog.RealmView selectedRealm, long requestedCharacterId, - String requestId) { + String requestId, + boolean allowPublicJoin) { + if (response == null) { + return Optional.of( + authorityUnavailableFailure( + tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); + } Optional maybeError = extractError(response.getError()); if (maybeError.isPresent()) { - if (!isAuthorityUnavailable(maybeError.orElseThrow())) { + String code = maybeError.orElseThrow().getCode(); + if ("PERMISSION_DENIED".equalsIgnoreCase(code) || "NOT_FOUND".equalsIgnoreCase(code)) { return Optional.of( worldAccessDeniedFailure( context, tenantTag, selectedWorld, selectedRealm, requestedCharacterId)); @@ -711,8 +722,24 @@ private Optional validateMembershipResponse( authorityUnavailableFailure( tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); } - if (!response.getMembershipExists() || !response.getGameplayAdmissionAllowed()) { - if (isPublicProductionRealm(selectedRealm)) { + boolean repairable = + "MISSING".equals(response.getMembershipLifecycleState()) + || "INACTIVE".equals(response.getMembershipLifecycleState()); + if (isPublicProductionRealm(selectedRealm) && repairable && !allowPublicJoin) { + return Optional.of( + admissionDeniedFailure( + context, + tenantTag, + selectedWorld, + selectedRealm, + requestedCharacterId, + GameplayStageCommandConstants.PUBLIC_PRODUCTION_ADMISSION_DENIED_CODE, + GameplayStageCommandConstants.PUBLIC_PRODUCTION_ADMISSION_DENIED_MESSAGE, + "error.play.public-production-admission-denied")); + } + if (!"ACTIVE".equals(response.getMembershipLifecycleState()) + || !response.getGameplayAdmissionAllowed()) { + if (isPublicProductionRealm(selectedRealm) && repairable) { recordResumeDeniedIfApplicable( context, selectedWorld.slug(), @@ -733,6 +760,19 @@ private Optional validateMembershipResponse( Long.toString(requestedCharacterId), null)); } + if (!isPublicProductionRealm(selectedRealm) + && !"ACTIVE".equals(response.getMembershipLifecycleState())) { + return Optional.of( + admissionDeniedFailure( + context, + tenantTag, + selectedWorld, + selectedRealm, + requestedCharacterId, + GameplayStageCommandConstants.NON_PUBLIC_ENROLLMENT_REQUIRED_CODE, + GameplayStageCommandConstants.NON_PUBLIC_ENROLLMENT_REQUIRED_MESSAGE, + "error.play.non-public-enrollment-required")); + } return Optional.of( worldAccessDeniedFailure( context, tenantTag, selectedWorld, selectedRealm, requestedCharacterId)); @@ -745,6 +785,11 @@ private Optional validateMembershipResponse( selectedWorld.slug(), selectedRealm.slug(), requestId); + if (grantResponse == null) { + return Optional.of( + authorityUnavailableFailure( + tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); + } Optional grantError = extractError(grantResponse.getError()); if (grantError.isPresent() && isAuthorityUnavailable(grantError.get())) { return Optional.of( @@ -752,8 +797,14 @@ private Optional validateMembershipResponse( tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); } if (grantError.isPresent()) { + String code = grantError.orElseThrow().getCode(); + if (!"PERMISSION_DENIED".equalsIgnoreCase(code) && !"NOT_FOUND".equalsIgnoreCase(code)) { + return Optional.of( + authorityUnavailableFailure( + tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); + } return Optional.of( - worldAccessDeniedFailure( + realmAccessDeniedFailure( context, tenantTag, selectedWorld, selectedRealm, requestedCharacterId)); } if (!isSafeRealmGrantResponse(grantResponse, context, selectedWorld, selectedRealm)) { @@ -763,7 +814,7 @@ private Optional validateMembershipResponse( } if (!grantResponse.getGranted()) { return Optional.of( - worldAccessDeniedFailure( + realmAccessDeniedFailure( context, tenantTag, selectedWorld, selectedRealm, requestedCharacterId)); } return Optional.empty(); @@ -781,6 +832,7 @@ private boolean isSafeRealmGrantResponse( || !Long.toString(selectedRealm.tenantId()).equals(response.getTenantId()) || !selectedWorld.slug().equals(response.getWorldSlug()) || !selectedRealm.slug().equals(response.getRealmSlug()) + || response.getGrantVersion() < 0L || (response.getGranted() && response.getGrantVersion() <= 0L) || !StringUtils.hasText(response.getEvaluatedAt())) { return false; @@ -801,12 +853,55 @@ static boolean isWithinAuthorityReplyWindow(Instant evaluatedAt, Instant now) { && !evaluatedAt.isBefore(now.minus(AUTHORITY_REPLY_MAX_AGE)); } + static boolean isWithinEntitlementReplyWindow(Instant evaluatedAt, Instant now) { + return !evaluatedAt.isAfter(now.plus(AUTHORITY_REPLY_MAX_FUTURE_SKEW)) + && now.isBefore( + evaluatedAt.plus(ENTITLEMENT_REPLY_MAX_AGE).minus(AUTHORITY_REPLY_MAX_FUTURE_SKEW)); + } + + private PlayCommandHandlingResult realmAccessDeniedFailure( + SessionContext context, + String tenantTag, + GameplayWorldCatalog.WorldView selectedWorld, + GameplayWorldCatalog.RealmView selectedRealm, + long requestedCharacterId) { + return admissionDeniedFailure( + context, + tenantTag, + selectedWorld, + selectedRealm, + requestedCharacterId, + GameplayStageCommandConstants.REALM_ACCESS_DENIED_CODE, + GameplayStageCommandConstants.REALM_ACCESS_DENIED_MESSAGE, + "error.play.realm-access-denied"); + } + private PlayCommandHandlingResult worldAccessDeniedFailure( SessionContext context, String tenantTag, GameplayWorldCatalog.WorldView selectedWorld, GameplayWorldCatalog.RealmView selectedRealm, long requestedCharacterId) { + return admissionDeniedFailure( + context, + tenantTag, + selectedWorld, + selectedRealm, + requestedCharacterId, + GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE, + GameplayStageCommandConstants.WORLD_ACCESS_DENIED_MESSAGE, + "error.play.world-access-denied"); + } + + private PlayCommandHandlingResult admissionDeniedFailure( + SessionContext context, + String tenantTag, + GameplayWorldCatalog.WorldView selectedWorld, + GameplayWorldCatalog.RealmView selectedRealm, + long requestedCharacterId, + String code, + String message, + String messageKey) { recordResumeDeniedIfApplicable( context, selectedWorld.slug(), @@ -817,9 +912,9 @@ private PlayCommandHandlingResult worldAccessDeniedFailure( tenantTag, "access_denied"); return failure( - GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE, - GameplayStageCommandConstants.WORLD_ACCESS_DENIED_MESSAGE, - "error.play.world-access-denied", + code, + message, + messageKey, Map.of(), tenantTag, Long.toString(selectedRealm.gameInstanceId()), @@ -834,21 +929,37 @@ private Optional validateEntitlementsResponse( GameplayWorldCatalog.WorldView selectedWorld, GameplayWorldCatalog.RealmView selectedRealm, long requestedCharacterId) { + if (response == null) { + return Optional.of( + entitlementUnavailableFailure( + tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); + } Optional maybeError = extractError(response.getError()); if (maybeError.isPresent()) { - if (isEntitlementUnavailable(maybeError.get())) { + if (!GameplayStageCommandConstants.TENANT_BILLING_BLOCKED_CODE.equalsIgnoreCase( + maybeError.orElseThrow().getCode())) { return Optional.of( entitlementUnavailableFailure( tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); } - if (isAuthorityUnavailable(maybeError.get())) { + return Optional.of( + tenantBillingBlockedFailure( + context, tenantTag, selectedWorld, selectedRealm, requestedCharacterId)); + } + try { + if (!Long.toString(selectedRealm.tenantId()).equals(response.getTenantId()) + || response.getEntitlementVersion() <= 0L + || response.getTenantBillingSequence() <= 0L + || !isWithinEntitlementReplyWindow( + Instant.parse(response.getEvaluatedAt()), Instant.now())) { return Optional.of( - authorityUnavailableFailure( + entitlementUnavailableFailure( tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); } + } catch (DateTimeParseException ex) { return Optional.of( - tenantBillingBlockedFailure( - context, tenantTag, selectedWorld, selectedRealm, requestedCharacterId)); + entitlementUnavailableFailure( + tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); } if (!response.getGameplayAvailable()) { return Optional.of( @@ -951,11 +1062,6 @@ private boolean isAuthorityUnavailable(ErrorDetail error) { return GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE.equalsIgnoreCase(code); } - private boolean isEntitlementUnavailable(ErrorDetail error) { - String code = Optional.ofNullable(error.getCode()).orElse(""); - return GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_CODE.equalsIgnoreCase(code); - } - private boolean isSafeMembershipAuthorityResponse( GetTenantMembershipForRuntimeResponse response, SessionContext context, @@ -978,9 +1084,19 @@ private boolean isSafeMembershipAuthorityResponse( } catch (DateTimeParseException | IllegalArgumentException ex) { return false; } - return response.getMembershipExists() - ? response.getMembershipVersion() > 0L - : response.getMembershipVersion() == 0L; + if (!response.getMembershipExists()) { + return "MISSING".equals(response.getMembershipLifecycleState()) + && !response.getGameplayAdmissionAllowed() + && response.getMembershipVersion() == 0L + && response.getMembershipAuthorityGeneration() == 0L; + } + return response.getMembershipVersion() > 0L + && response.getMembershipAuthorityGeneration() > 0L + && switch (response.getMembershipLifecycleState()) { + case "ACTIVE" -> true; + case "INACTIVE", "LEGACY_UNVERIFIED" -> !response.getGameplayAdmissionAllowed(); + default -> false; + }; } private boolean maybeRecordFreshEntryFallback( @@ -1127,7 +1243,7 @@ private void recordResumeDeniedIfApplicable( Long.toString(context.tenantId()).equals(tenantTag) && sameSlug(context.worldSlug(), requestedWorldSlug) && sameSlug(context.realmSlug(), requestedRealmSlug); - if (!sameGameplayIdentity && !sameVisibleRealm) { + if (!context.hasGameplayBinding() || (!sameGameplayIdentity && !sameVisibleRealm)) { return; } meterRegistry.counter(RESUME_DENIED_METRIC, "reason", reason).increment(); @@ -1136,13 +1252,13 @@ && sameSlug(context.worldSlug(), requestedWorldSlug) new SessionContext( context.sessionId(), context.tenantId(), - null, - null, + context.accountId(), + context.loginName(), 0L, null, 0L, null, - null, + context.jwt(), context.localeTag(), context.bootstrapGameInstanceId(), requestedWorldSlug, diff --git a/services/game-session-service/src/main/resources/presentation-messages.properties b/services/game-session-service/src/main/resources/presentation-messages.properties index 0b38c3c6a3..2d224c41ea 100644 --- a/services/game-session-service/src/main/resources/presentation-messages.properties +++ b/services/game-session-service/src/main/resources/presentation-messages.properties @@ -21,6 +21,9 @@ error.chars.unavailable=Character browsing is unavailable. Use PLAY [rea error.play.connect-context-invalid=Connect context invalid. error.play.connect-scope-mismatch=Connect scope mismatch. error.play.world-access-denied=You are not allowed to enter that world. +error.play.public-production-admission-denied=Public enrollment is closed for that world. +error.play.non-public-enrollment-required=Active membership is required for that non-public realm. +error.play.realm-access-denied=You do not have access to that realm. error.play.join-required=Membership is required before PLAY; joining this world is not available yet. error.play.authority-unavailable=Gameplay authority is temporarily unavailable. Retry PLAY shortly. error.play.admission-pointer-unavailable=Gameplay admission pointer is temporarily unavailable. Retry PLAY shortly. diff --git a/services/game-session-service/src/main/resources/presentation-messages_fr.properties b/services/game-session-service/src/main/resources/presentation-messages_fr.properties index dbe946600d..110bdb1f48 100644 --- a/services/game-session-service/src/main/resources/presentation-messages_fr.properties +++ b/services/game-session-service/src/main/resources/presentation-messages_fr.properties @@ -21,6 +21,9 @@ error.chars.unavailable=La consultation des personnages n’est pas disponible. error.play.connect-context-invalid=Contexte de connexion invalide. error.play.connect-scope-mismatch=Le perimetre de connexion ne correspond pas. error.play.world-access-denied=Vous n’êtes pas autorisé à entrer dans ce monde. +error.play.public-production-admission-denied=Les inscriptions publiques sont fermées pour ce monde. +error.play.non-public-enrollment-required=Une adhésion active est requise pour ce royaume non public. +error.play.realm-access-denied=Vous n’avez pas accès à ce royaume. error.play.join-required=Une adhésion est requise avant PLAY ; rejoindre ce monde n’est pas encore disponible. error.play.authority-unavailable=L’autorité de jeu est temporairement indisponible. Réessayez PLAY sous peu. error.play.admission-pointer-unavailable=Le pointeur d’admission au jeu est temporairement indisponible. Réessayez PLAY sous peu. diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java index 8d6c89cc22..676f06fb27 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java @@ -19,6 +19,8 @@ import net.firedevops.firemud.test.TestContainerImages; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -269,8 +271,10 @@ void websocketMovedPlayerStaysInGameAcrossGameLogicRestart() throws Exception { } } - @Test - void websocketReconnectAfterRevocationFailsClosed() throws Exception { + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void websocketReconnectDistinguishesActiveDenialFromInactiveRepair(boolean inactive) + throws Exception { ensureTestServicesStarted(); accountStub().allowGameplayAdmission(); long sessionId = prepareGameInstance(); @@ -284,11 +288,19 @@ void websocketReconnectAfterRevocationFailsClosed() throws Exception { LookTestFixtures.DESTINATION_ROOM_ID) .test(response.trim())); - accountStub().denyGameplayAdmission(); - List reconnectResponses = runPlayAfterReconnect(sessionId); + if (inactive) { + accountStub().setMembershipInactive(); + } else { + accountStub().denyGameplayAdmission(); + } + accountStub().setMembershipVersion(12L); + accountStub().setMembershipAuthorityGeneration(9L); + String expectedCode = inactive ? "JOIN_REQUIRED" : "WORLD_ACCESS_DENIED"; + List reconnectResponses = runPlayAfterReconnect(sessionId, expectedCode); assertThat(reconnectResponses).hasSizeGreaterThanOrEqualTo(2); assertThat(reconnectResponses).anyMatch(response -> response.startsWith("OK LOGIN")); - assertThat(reconnectResponses).anyMatch(response -> response.startsWith("ERROR JOIN_REQUIRED")); + assertThat(reconnectResponses) + .anyMatch(response -> response.startsWith("ERROR " + expectedCode)); } @Test @@ -427,7 +439,7 @@ private List runLookAfterReconnect(long sessionId, String expectedRoomId } } - private List runPlayAfterReconnect(long sessionId) throws Exception { + private List runPlayAfterReconnect(long sessionId, String expectedCode) throws Exception { try (GameplayWebSocketScenarios.LoginThenPlayScenario scenario = GameplayWebSocketScenarios.loginThenAttemptPlay( ignored -> @@ -437,7 +449,7 @@ private List runPlayAfterReconnect(long sessionId) throws Exception { READY_LOOK_TEXT, client -> client.awaitMatching( - response -> response.startsWith("ERROR JOIN_REQUIRED"), + response -> response.startsWith("ERROR " + expectedCode), "revoked membership admission denial"))) { return scenario.responses(); } 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 ea58aac339..c6499a3147 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 @@ -271,6 +271,8 @@ void setUp() { .setMembershipExists(true) .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) + .setMembershipLifecycleState("ACTIVE") + .setMembershipAuthorityGeneration(9L) .setEvaluatedAt(java.time.Instant.now().toString()) .build()) .when(accountClient) @@ -278,14 +280,16 @@ void setUp() { org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.nullable(String.class)); - org.mockito.Mockito.doReturn( - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") - .setGameplayAvailable(true) - .setEntitlementVersion(1L) - .setTenantBillingSequence(1L) - .setEvaluatedAt(java.time.Instant.now().toString()) - .build()) + org.mockito.Mockito.doAnswer( + invocation -> + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("22") + .setGameplayAvailable(true) + .setAllowPublicJoin(true) + .setEntitlementVersion(1L) + .setTenantBillingSequence(1L) + .setEvaluatedAt(java.time.Instant.now().toString()) + .build()) .when(accountClient) .getTenantEntitlementsForRuntime( org.mockito.ArgumentMatchers.anyString(), diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java index 88aea73f47..b10193f3d5 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java @@ -48,6 +48,7 @@ import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; @@ -912,6 +913,9 @@ void runtimeMembershipRejectsUncorrelatedAccountResult(String returnedAccount) t .setTenantId("7") .setMembershipExists(true) .setGameplayAdmissionAllowed(true) + .setMembershipLifecycleState("ACTIVE") + .setMembershipVersion(12L) + .setMembershipAuthorityGeneration(9L) .build()); AccountClient client = newClient(stub); assertThat( @@ -974,6 +978,8 @@ void runtimeMembershipCallerUsesCanonicalAccountTenantRequest() throws Exception .setMembershipExists(true) .setGameplayAdmissionAllowed(true) .setMembershipVersion(12L) + .setMembershipLifecycleState("ACTIVE") + .setMembershipAuthorityGeneration(9L) .setEvaluatedAt("2026-07-31T00:00:00Z") .build(); when(stub.getTenantMembershipForRuntime(any(GetTenantMembershipForRuntimeRequest.class))) @@ -990,6 +996,9 @@ void runtimeMembershipCallerUsesCanonicalAccountTenantRequest() throws Exception assertThat(captor.getValue().getTenantId()).isEqualTo("7"); assertThat(captor.getValue().getRequestId()).isEmpty(); assertThat(actual).isEqualTo(expected); + assertThat(actual.getMembershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(actual.getMembershipVersion()).isEqualTo(12L); + assertThat(actual.getMembershipAuthorityGeneration()).isEqualTo(9L); } @Test @@ -1001,6 +1010,37 @@ void runtimeMembershipReturnsCanonicalUnavailableWhenStubIsMissing() throws Exce assertThat(response.getError().getMessage()).isEqualTo("Membership authority unavailable"); } + @ParameterizedTest + @CsvSource({ + "ACTIVE,true,true,44,9", "ACTIVE,true,false,44,9", + "INACTIVE,true,false,23,41", "LEGACY_UNVERIFIED,true,false,7,19", + "MISSING,false,false,0,0" + }) + void runtimeMembershipPassesThroughIndependentEmittedFields( + String lifecycle, boolean exists, boolean admitting, long version, long generation) + throws Exception { + AccountServiceGrpc.AccountServiceBlockingStub stub = + mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + var expected = + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setTenantId("7") + .setMembershipExists(exists) + .setGameplayAdmissionAllowed(admitting) + .setMembershipLifecycleState(lifecycle) + .setMembershipVersion(version) + .setMembershipAuthorityGeneration(generation) + .setEvaluatedAt("2026-11-01T00:00:00Z") + .build(); + when(stub.getTenantMembershipForRuntime(any(GetTenantMembershipForRuntimeRequest.class))) + .thenReturn(expected); + + var actual = newClient(stub).getTenantMembershipForRuntime(ACCOUNT_UUID, "7", "request-1"); + + assertThat(actual).isEqualTo(expected); + } + @Test void realmAccessGrantReturnsCanonicalUnavailableWhenStubIsMissing() throws Exception { GetRealmAccessGrantForRuntimeResponse response = @@ -1025,6 +1065,8 @@ void runtimeMembershipRetriesOnceAfterUnavailableAndPreservesSuccess() throws Ex .setMembershipExists(true) .setGameplayAdmissionAllowed(true) .setMembershipVersion(12L) + .setMembershipLifecycleState("ACTIVE") + .setMembershipAuthorityGeneration(9L) .build(); when(fixture .retryStub() diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index b0adc2abd1..f97868fd5b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -119,17 +119,21 @@ void setUp() { .setMembershipExists(true) .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) + .setMembershipLifecycleState("ACTIVE") + .setMembershipAuthorityGeneration(9L) .setEvaluatedAt(Instant.now().toString()) .build()); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") - .setGameplayAvailable(true) - .setEntitlementVersion(1L) - .setTenantBillingSequence(1L) - .setEvaluatedAt(Instant.now().toString()) - .build()); + .thenAnswer( + invocation -> + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("22") + .setGameplayAvailable(true) + .setAllowPublicJoin(true) + .setEntitlementVersion(1L) + .setTenantBillingSequence(1L) + .setEvaluatedAt(Instant.now().toString()) + .build()); when(accountClient.getRealmAccessGrantForRuntime( Mockito.anyString(), Mockito.anyString(), @@ -540,11 +544,11 @@ void playPromotesSessionIntoGameplay() { var admissionOrder = Mockito.inOrder(accountClient, entityManagementClient); admissionOrder .verify(accountClient) - .getTenantMembershipForRuntime( - Mockito.eq(ACCOUNT_ID), Mockito.eq("22"), Mockito.anyString()); + .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); admissionOrder .verify(accountClient) - .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); + .getTenantMembershipForRuntime( + Mockito.eq(ACCOUNT_ID), Mockito.eq("22"), Mockito.anyString()); admissionOrder .verify(entityManagementClient) .listCharactersByAccount( @@ -1476,6 +1480,8 @@ void playDeniedByMembershipReturnsWorldAccessDenied() { .setMembershipExists(true) .setGameplayAdmissionAllowed(false) .setMembershipVersion(2L) + .setMembershipLifecycleState("ACTIVE") + .setMembershipAuthorityGeneration(9L) .setEvaluatedAt(Instant.now().toString()) .build()); @@ -1526,12 +1532,14 @@ void playDeniedDoesNotClearCrossTenantBindingForSameVisibleRealm() { .setMembershipExists(false) .setGameplayAdmissionAllowed(false) .setMembershipVersion(0L) + .setMembershipLifecycleState("MISSING") + .setMembershipAuthorityGeneration(0L) .setEvaluatedAt(Instant.now().toString()) .build()); PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); - assertThat(result.commandResult().errorCode()).isEqualTo("WORLD_ACCESS_DENIED"); + assertThat(result.commandResult().errorCode()).isEqualTo("NON_PUBLIC_ENROLLMENT_REQUIRED"); Mockito.verify(gameplayPresenceLifecycleService, never()) .clearGameplayBinding(Mockito.any(), Mockito.anyString()); Mockito.verify(sessionContextService, never()).save(Mockito.any()); @@ -1556,7 +1564,9 @@ void playNonPublicRealmRequiresExistingAdmissibleMembership() { .setAccountId(ACCOUNT_ID) .setTenantId("22") .setMembershipExists(false) - .setGameplayAdmissionAllowed(true) + .setGameplayAdmissionAllowed(false) + .setMembershipLifecycleState("MISSING") + .setMembershipAuthorityGeneration(0L) .setEvaluatedAt(Instant.now().toString()) .build()); @@ -1570,7 +1580,7 @@ void playNonPublicRealmRequiresExistingAdmissibleMembership() { assertThat(result.commandResult().accepted()).isFalse(); assertThat(result.commandResult().errorCode()) - .isEqualTo(GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE); + .isEqualTo(GameplayStageCommandConstants.NON_PUBLIC_ENROLLMENT_REQUIRED_CODE); Mockito.verify(accountClient, Mockito.never()) .getRealmAccessGrantForRuntime( Mockito.anyString(), @@ -1620,7 +1630,7 @@ void playVisibleNonPublicRealmRequiresGrantedAccess() { PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); assertThat(result.commandResult().errorCode()) - .isEqualTo(GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE); + .isEqualTo(GameplayStageCommandConstants.REALM_ACCESS_DENIED_CODE); Mockito.verify(accountClient) .getRealmAccessGrantForRuntime( Mockito.eq(ACCOUNT_ID), @@ -1646,7 +1656,7 @@ void playInvisibleRealmWithDeniedGrantClearsBinding() { PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); assertThat(result.commandResult().errorCode()) - .isEqualTo(GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE); + .isEqualTo(GameplayStageCommandConstants.REALM_ACCESS_DENIED_CODE); Mockito.verify(gameplayPresenceLifecycleService).clearGameplayBinding(context, "access_denied"); } @@ -1673,7 +1683,7 @@ void playInvisibleRealmWithNonAuthorityGrantClearsBinding() { PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); assertThat(result.commandResult().errorCode()) - .isEqualTo(GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE); + .isEqualTo(GameplayStageCommandConstants.REALM_ACCESS_DENIED_CODE); Mockito.verify(gameplayPresenceLifecycleService).clearGameplayBinding(context, "access_denied"); } @@ -1785,8 +1795,10 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsMissing() { .setAccountId(ACCOUNT_ID) .setTenantId("22") .setMembershipExists(false) - .setGameplayAdmissionAllowed(true) + .setGameplayAdmissionAllowed(false) .setMembershipVersion(0L) + .setMembershipLifecycleState("MISSING") + .setMembershipAuthorityGeneration(0L) .setEvaluatedAt(Instant.now().toString()) .build()); PlayCommandHandlingResult result = @@ -1817,6 +1829,8 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsInactive() { .setMembershipExists(true) .setGameplayAdmissionAllowed(false) .setMembershipVersion(4L) + .setMembershipLifecycleState("INACTIVE") + .setMembershipAuthorityGeneration(9L) .setEvaluatedAt(Instant.now().toString()) .build()); @@ -1855,6 +1869,8 @@ void playWhenMembershipAuthorityAccountDoesNotExactlyMatchFailsClosed(String res .setMembershipExists(true) .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) + .setMembershipLifecycleState("ACTIVE") + .setMembershipAuthorityGeneration(9L) .setEvaluatedAt(Instant.now().toString()) .build()); @@ -1886,6 +1902,355 @@ void authorityReplyWindowIncludesExactBoundsAndRejectsOneNanosecondOutside() { .isFalse(); } + @Test + void entitlementFreshnessExpiresAtConservativeDeadlineAndGuardsFutureSkew() { + Instant now = Instant.parse("2026-11-01T00:00:00Z"); + assertThat( + PlayCommandHandler.isWithinEntitlementReplyWindow( + now.minusSeconds(10).plusNanos(1), now)) + .isTrue(); + assertThat(PlayCommandHandler.isWithinEntitlementReplyWindow(now.minusSeconds(10), now)) + .isFalse(); + assertThat( + PlayCommandHandler.isWithinEntitlementReplyWindow( + now.minusSeconds(10).minusNanos(1), now)) + .isFalse(); + assertThat(PlayCommandHandler.isWithinEntitlementReplyWindow(now.plusSeconds(5), now)).isTrue(); + assertThat( + PlayCommandHandler.isWithinEntitlementReplyWindow(now.plusSeconds(5).plusNanos(1), now)) + .isFalse(); + } + + @ParameterizedTest + @CsvSource({ + "22,1,1,-5,true", "22,1,1,-11,false", "22,1,1,-299,false", + "22,1,1,4,true", "22,1,1,6,false", "23,1,1,0,false", + "022,1,1,0,false", "22,0,1,0,false", "22,1,0,0,false", + "22,-1,1,0,false", "22,1,-1,0,false" + }) + void entitlementEvidenceHasItsOwnStrictFreshnessAndTenantVersionGuards( + String tenantId, long version, long sequence, long secondsFromNow, boolean accepted) { + SessionContext context = + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + entitlementResponse(true).toBuilder() + .setTenantId(tenantId) + .setEntitlementVersion(version) + .setTenantBillingSequence(sequence) + .setEvaluatedAt(Instant.now().plusSeconds(secondsFromNow).toString()) + .build()); + + var result = handler.handle("1", new TextCommandParser().parse("PLAY demo")); + + assertThat(result.commandResult().accepted()).isEqualTo(accepted); + if (!accepted) { + assertThat(result.commandResult().errorCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + verify(accountClient, never()) + .getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + verifyNoGameplayBindingSideEffects(); + Mockito.verifyNoInteractions(entityManagementClient, moderationPolicyClient); + } + } + + @ParameterizedTest + @ValueSource(strings = {"", "not-a-timestamp"}) + void malformedEntitlementTimestampStopsBeforeMembership(String timestamp) { + SessionContext context = + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(entitlementResponse(true).toBuilder().setEvaluatedAt(timestamp).build()); + + var result = handler.handle("1", new TextCommandParser().parse("PLAY demo")); + + assertThat(result.commandResult().errorCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + verify(accountClient, never()) + .getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + verifyNoGameplayBindingSideEffects(); + Mockito.verifyNoInteractions(entityManagementClient, moderationPolicyClient); + } + + @ParameterizedTest + @CsvSource({ + "MISSING,false,false,0,0,true,JOIN_REQUIRED", + "MISSING,false,false,0,0,false,PUBLIC_PRODUCTION_ADMISSION_DENIED", + "INACTIVE,true,false,12,9,true,JOIN_REQUIRED", + "INACTIVE,true,false,12,9,false,PUBLIC_PRODUCTION_ADMISSION_DENIED", + "ACTIVE,true,false,12,9,true,WORLD_ACCESS_DENIED", + "ACTIVE,true,false,12,9,false,WORLD_ACCESS_DENIED", + "LEGACY_UNVERIFIED,true,false,12,9,true,WORLD_ACCESS_DENIED", + "LEGACY_UNVERIFIED,true,false,12,9,false,WORLD_ACCESS_DENIED", + "UNKNOWN,true,false,12,9,true,AUTH_UNAVAILABLE", + "'',true,false,12,9,true,AUTH_UNAVAILABLE", + "MISSING,false,true,0,0,true,AUTH_UNAVAILABLE", + "MISSING,false,false,1,0,true,AUTH_UNAVAILABLE", + "MISSING,false,false,0,1,true,AUTH_UNAVAILABLE", + "ACTIVE,false,false,0,0,true,AUTH_UNAVAILABLE", + "MISSING,true,false,12,9,true,AUTH_UNAVAILABLE", + "INACTIVE,true,true,12,9,true,AUTH_UNAVAILABLE", + "LEGACY_UNVERIFIED,true,true,12,9,true,AUTH_UNAVAILABLE", + "ACTIVE,true,true,0,9,true,AUTH_UNAVAILABLE", + "ACTIVE,true,true,12,0,true,AUTH_UNAVAILABLE", + "ACTIVE,true,true,-1,9,true,AUTH_UNAVAILABLE", + "ACTIVE,true,true,12,-1,true,AUTH_UNAVAILABLE" + }) + void publicMembershipUsesLifecycleAndIndependentVersionGenerationWithoutRepairingDenial( + String lifecycle, + boolean exists, + boolean admitting, + long version, + long generation, + boolean allowPublicJoin, + String expectedCode) { + SessionContext context = + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(entitlementResponse(allowPublicJoin)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(membershipResponse(lifecycle, exists, admitting, version, generation)); + + var result = handler.handle("1", new TextCommandParser().parse("PLAY demo")); + + assertThat(result.commandResult().errorCode()).isEqualTo(expectedCode); + verify(accountClient, never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + verifyNoGameplayBindingSideEffects(); + Mockito.verifyNoInteractions(entityManagementClient, moderationPolicyClient); + } + + @ParameterizedTest + @CsvSource({"12,9", "9,12"}) + void activeMemberRetainsAccessWhenPublicEnrollmentCloses(long version, long generation) { + SessionContext context = + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(entitlementResponse(false)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(membershipResponse("ACTIVE", true, true, version, generation)); + + var result = handler.handle("1", new TextCommandParser().parse("PLAY demo")); + + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + verify(moderationPolicyClient).evaluateGameplayAdmission(22L, ACCOUNT_ID); + } + + @ParameterizedTest + @ValueSource(strings = {"MISSING", "INACTIVE", "LEGACY_UNVERIFIED"}) + void privateNonActiveMembershipRequiresEnrollmentWithoutGrantOrPublicJoin(String lifecycle) { + SessionContext context = + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); + boolean exists = !"MISSING".equals(lifecycle); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(entitlementResponse(false)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + membershipResponse(lifecycle, exists, false, exists ? 12L : 0L, exists ? 9L : 0L)); + + var result = handler.handle("1", previewRealmPlayCommand()); + + assertThat(result.commandResult().errorCode()).isEqualTo("NON_PUBLIC_ENROLLMENT_REQUIRED"); + verify(accountClient, never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + verifyNoGameplayBindingSideEffects(); + Mockito.verifyNoInteractions(entityManagementClient, moderationPolicyClient); + } + + @ParameterizedTest + @CsvSource({ + "MISSING,false,ENTITLEMENT_UNAVAILABLE", "INACTIVE,true,ENTITLEMENT_UNAVAILABLE", + "MISSING,false,TENANT_BILLING_BLOCKED", "INACTIVE,true,TENANT_BILLING_BLOCKED" + }) + void entitlementFailureMasksPublicRepairBeforeMembershipRead( + String lifecycle, boolean exists, String errorCode) { + SessionContext context = + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + membershipResponse(lifecycle, exists, false, exists ? 12L : 0L, exists ? 9L : 0L)); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setError( + net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder().setCode(errorCode)) + .build()); + + var result = handler.handle("1", new TextCommandParser().parse("PLAY demo")); + + assertThat(result.commandResult().errorCode()).isEqualTo(errorCode); + verify(accountClient, never()) + .getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + verifyNoGameplayBindingSideEffects(); + Mockito.verifyNoInteractions(entityManagementClient, moderationPolicyClient); + } + + @Test + void sameTargetActiveDenialClearsOnlyGameplayAndRetainsAuthenticatedUuidContext() { + SessionContext context = previewRealmContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(membershipResponse("ACTIVE", true, false, 12L, 9L)); + + var result = handler.handle("1", previewRealmPlayCommand()); + + assertThat(result.commandResult().errorCode()).isEqualTo("WORLD_ACCESS_DENIED"); + var saved = org.mockito.ArgumentCaptor.forClass(SessionContext.class); + verify(sessionContextService).save(saved.capture()); + assertThat(saved.getValue().accountId()).isEqualTo(ACCOUNT_ID); + assertThat(saved.getValue().loginName()).isEqualTo(context.loginName()); + assertThat(saved.getValue().jwt()).isEqualTo(context.jwt()); + assertThat(saved.getValue().tenantId()).isEqualTo(context.tenantId()); + assertThat(saved.getValue().hasGameplayBinding()).isFalse(); + verify(gameplayPresenceLifecycleService).clearGameplayBinding(context, "access_denied"); + Mockito.verifyNoInteractions( + entityManagementClient, moderationPolicyClient, scriptEventPublisher); + verify(accountClient, never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + } + + private static GetTenantMembershipForRuntimeResponse membershipResponse( + String lifecycle, boolean exists, boolean admitting, long version, long generation) { + return GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId(ACCOUNT_ID) + .setTenantId("22") + .setMembershipExists(exists) + .setGameplayAdmissionAllowed(admitting) + .setMembershipLifecycleState(lifecycle) + .setMembershipVersion(version) + .setMembershipAuthorityGeneration(generation) + .setEvaluatedAt(Instant.now().toString()) + .build(); + } + + @ParameterizedTest + @ValueSource( + strings = { + "denied", + "outage", + "malformed-error", + "account", + "tenant", + "world", + "realm", + "timestamp", + "version", + "negative-version" + }) + void privateGrantOutcomeNeverFallsBackToJoinOrInvokesLaterAdmission(String scenario) { + SessionContext context = + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(entitlementResponse(false)); + var grant = realmGrantResponse(true).toBuilder(); + switch (scenario) { + case "denied" -> grant.setGranted(false).setGrantVersion(0L); + case "outage" -> + grant.setError( + net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() + .setCode("AUTH_UNAVAILABLE")); + case "malformed-error" -> + grant.setError( + net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() + .setMessage("unclassified failure")); + case "account" -> grant.setAccountId("00000000-0000-4000-8000-000000000043"); + case "tenant" -> grant.setTenantId("23"); + case "world" -> grant.setWorldSlug("other"); + case "realm" -> grant.setRealmSlug("other"); + case "timestamp" -> grant.setEvaluatedAt("not-a-timestamp"); + case "version" -> grant.setGrantVersion(0L); + case "negative-version" -> grant.setGranted(false).setGrantVersion(-1L); + default -> throw new IllegalArgumentException(scenario); + } + when(accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString())) + .thenReturn(grant.build()); + + var result = handler.handle("1", previewRealmPlayCommand()); + + assertThat(result.commandResult().errorCode()) + .isEqualTo("denied".equals(scenario) ? "REALM_ACCESS_DENIED" : "AUTH_UNAVAILABLE"); + var order = Mockito.inOrder(accountClient); + order + .verify(accountClient) + .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); + order + .verify(accountClient) + .getTenantMembershipForRuntime( + Mockito.eq(ACCOUNT_ID), Mockito.eq("22"), Mockito.anyString()); + order + .verify(accountClient) + .getRealmAccessGrantForRuntime( + Mockito.eq(ACCOUNT_ID), + Mockito.eq("22"), + Mockito.eq("sandbox"), + Mockito.eq("preview"), + Mockito.anyString()); + verifyNoGameplayBindingSideEffects(); + Mockito.verifyNoInteractions(entityManagementClient, moderationPolicyClient); + } + + @Test + void deniedSelectedRealmDoesNotClearUnrelatedSameTenantGameplayBinding() { + SessionContext context = previewRealmContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(membershipResponse("ACTIVE", true, false, 12L, 9L)); + + var result = handler.handle("1", new TextCommandParser().parse("PLAY demo")); + + assertThat(result.commandResult().errorCode()).isEqualTo("WORLD_ACCESS_DENIED"); + verify(gameplayPresenceLifecycleService, never()) + .clearGameplayBinding(Mockito.any(), Mockito.anyString()); + verifyNoGameplayBindingSideEffects(); + Mockito.verifyNoInteractions(entityManagementClient, moderationPolicyClient); + } + + private static GetTenantEntitlementsForRuntimeResponse entitlementResponse( + boolean allowPublicJoin) { + return GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("22") + .setGameplayAvailable(true) + .setAllowPublicJoin(allowPublicJoin) + .setEntitlementVersion(12L) + .setTenantBillingSequence(9L) + .setEvaluatedAt(Instant.now().toString()) + .build(); + } + @ParameterizedTest @CsvSource({ "membership,-301,false", "membership,-299,true", "membership,4,true", "membership,6,false", @@ -1906,6 +2271,8 @@ void membershipAndRealmGrantApplyTheSameTimestampWindow( .setMembershipExists(true) .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) + .setMembershipLifecycleState("ACTIVE") + .setMembershipAuthorityGeneration(9L) .setEvaluatedAt(evaluatedAt) .build()); } else { @@ -1947,6 +2314,8 @@ void playWhenMembershipAuthorityTimestampIsMalformedFailsClosed() { .setMembershipExists(true) .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) + .setMembershipLifecycleState("ACTIVE") + .setMembershipAuthorityGeneration(9L) .setEvaluatedAt("not-a-timestamp") .build()); @@ -2094,8 +2463,17 @@ void playWhenMembershipAuthorityUnavailableFailsClosed() { Mockito.verify(sessionContextService, Mockito.never()).save(Mockito.any()); } - @Test - void playWhenEntitlementAuthorityUnavailablePreservesExistingBinding() { + @ParameterizedTest + @ValueSource( + strings = { + "ENTITLEMENT_UNAVAILABLE", + "AUTH_UNAVAILABLE", + "UNAVAILABLE", + "DEADLINE_EXCEEDED", + "UNKNOWN", + "" + }) + void playWhenEntitlementAuthorityUnavailablePreservesExistingBinding(String unavailableCode) { SessionContext context = new SessionContext( 1L, 22L, ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); @@ -2105,7 +2483,7 @@ void playWhenEntitlementAuthorityUnavailablePreservesExistingBinding() { GetTenantEntitlementsForRuntimeResponse.newBuilder() .setError( net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() - .setCode(GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_CODE) + .setCode(unavailableCode) .setMessage(GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_MESSAGE)) .build()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index 7abc0816a1..9b04f0e80c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -174,6 +174,8 @@ void setUp() { .setMembershipExists(true) .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) + .setMembershipLifecycleState("ACTIVE") + .setMembershipAuthorityGeneration(9L) .setEvaluatedAt(java.time.Instant.now().toString()) .build()); when(accountClient.getRealmAccessGrantForRuntime( @@ -189,14 +191,16 @@ void setUp() { .setAllowed(true) .build()); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") - .setGameplayAvailable(true) - .setEntitlementVersion(1L) - .setTenantBillingSequence(1L) - .setEvaluatedAt(java.time.Instant.now().toString()) - .build()); + .thenAnswer( + invocation -> + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("22") + .setGameplayAvailable(true) + .setAllowPublicJoin(true) + .setEntitlementVersion(1L) + .setTenantBillingSequence(1L) + .setEvaluatedAt(java.time.Instant.now().toString()) + .build()); when(entityManagementClient.listCharactersByAccount( Mockito.anyString(), Mockito.anyString(), @@ -463,6 +467,8 @@ void deniedReconnectPlayClearsStaleGameplayBinding() { .setMembershipExists(true) .setGameplayAdmissionAllowed(false) .setMembershipVersion(2L) + .setMembershipLifecycleState("INACTIVE") + .setMembershipAuthorityGeneration(9L) .setEvaluatedAt(java.time.Instant.now().toString()) .build()); @@ -475,7 +481,7 @@ void deniedReconnectPlayClearsStaleGameplayBinding() { TextCommandInterpretationResult lookAfterDeniedReconnect = interpreter.interpret("1", LOOK_PAYLOAD, false); assertFalse(lookAfterDeniedReconnect.commandResult().accepted()); - assertEquals("LOGIN_REQUIRED", lookAfterDeniedReconnect.commandResult().errorCode()); + assertEquals("PLAY_REQUIRED", lookAfterDeniedReconnect.commandResult().errorCode()); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index fb5bb0e772..4d10a006c7 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -175,6 +175,8 @@ void setUp() { .setMembershipExists(true) .setGameplayAdmissionAllowed(true) .setMembershipVersion(1L) + .setMembershipLifecycleState("ACTIVE") + .setMembershipAuthorityGeneration(9L) .setEvaluatedAt(java.time.Instant.now().toString()) .build()); when(accountClient.getRealmAccessGrantForRuntime( @@ -190,14 +192,16 @@ void setUp() { .setAllowed(true) .build()); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") - .setGameplayAvailable(true) - .setEntitlementVersion(1L) - .setTenantBillingSequence(1L) - .setEvaluatedAt(java.time.Instant.now().toString()) - .build()); + .thenAnswer( + invocation -> + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("22") + .setGameplayAvailable(true) + .setAllowPublicJoin(true) + .setEntitlementVersion(1L) + .setTenantBillingSequence(1L) + .setEvaluatedAt(java.time.Instant.now().toString()) + .build()); when(gameLogicClient.queryInventory(Mockito.any(SessionContext.class))) .thenReturn( QueryInventoryResponse.newBuilder() diff --git a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java index 922791eb6a..d094b4989c 100644 --- a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java +++ b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java @@ -181,16 +181,12 @@ void telnetReconnectAfterRevocationFailsPlayAdmission() throws Exception { this::openTelnetClient, GameplayTelnetScenarios.demoAdmission(READY_LOOK_TEXT), client -> - assertThat(client.readLineContaining("ERROR JOIN_REQUIRED")) - .contains("ERROR JOIN_REQUIRED") - .contains( - "Membership is required before PLAY; joining this world is not available yet."))) { + assertThat(client.readLineContaining("ERROR WORLD_ACCESS_DENIED")) + .contains("ERROR WORLD_ACCESS_DENIED") + .contains("You are not allowed to enter that world."))) { assertThat(scenario.responses()) - .anyMatch(response -> response.contains("ERROR JOIN_REQUIRED")) - .anyMatch( - response -> - response.contains( - "Membership is required before PLAY; joining this world is not available yet.")); + .anyMatch(response -> response.contains("ERROR WORLD_ACCESS_DENIED")) + .anyMatch(response -> response.contains("You are not allowed to enter that world.")); } } @@ -479,23 +475,17 @@ void telnetItemLoopStillSucceedsAfterWebSocketLogoutOnSharedRuntime() throws Exc } @Test - void telnetReconnectAfterRevocationFailsClosed() throws Exception { + void telnetReconnectWithInactiveMembershipRequiresExplicitJoin() throws Exception { ensureTestServicesStarted(); - try (GameplayTelnetScenarios.ReconnectScenario scenario = - GameplayTelnetScenarios.reconnectAfterReady( - this::openTelnetClient, - READY_LOOK_TEXT, - LookTestFixtures.DESTINATION_ROOM_ID, - firstClient -> { - firstClient.sendLine("MOVE north"); - assertThat(firstClient.readBlockContainingOrTimeout("OK LOOK")) - .contains(LookTestFixtures.DESTINATION_ROOM_ID); - })) { - assertThat(scenario.firstResponses()) - .anyMatch(response -> response.contains(LookTestFixtures.DESTINATION_ROOM_ID)); + try (GameplayTelnetDriver firstClient = openReadyTelnetClient()) { + firstClient.sendLine("MOVE north"); + assertThat(firstClient.readBlockContainingOrTimeout("OK LOOK")) + .contains(LookTestFixtures.DESTINATION_ROOM_ID); } - accountStub().setGameplayAdmissionAllowed(false); + accountStub().setMembershipInactive(); + accountStub().setMembershipVersion(12L); + accountStub().setMembershipAuthorityGeneration(9L); try (GameplayTelnetScenarios.LoginThenPlayScenario scenario = GameplayTelnetScenarios.loginThenAttemptPlay(